Просмотр исходного кода

Fruity Video Player: FL's state, the video through the user's ffmpeg, its sound track in sync with the song (WIP, not built yet)

Ka1-S 1 месяц назад
Родитель
Сommit
2ff1d6f87b

+ 2 - 0
CMakeLists.txt

@@ -92,6 +92,7 @@ add_library(lynx_core STATIC
     src/core/LowLifterFl.cpp
     src/core/VisualFx.cpp
     src/core/FlExtraFx.cpp
+    src/core/VideoPlayer.cpp
     src/core/FruityDance.cpp
     src/core/Reeverb2.cpp
     src/core/LuxeVerb.cpp
@@ -342,6 +343,7 @@ if(LYNX_BUILD_APP)
         src/ui/FlExtraEditors.cpp
         src/ui/VisualGl.cpp
         src/ui/DanceView.cpp
+        src/ui/VideoPlayerView.cpp
         src/ui/NewtoneEditor.cpp
         src/ui/ChannelSettings.cpp
         src/ui/LayerEditor.cpp

+ 38 - 0
resources/i18n/pt-BR.txt

@@ -5543,3 +5543,41 @@ countries: br
 "Flats (b)" = "Bemóis (b)"
 "Balance of the input before the de-esser hears it" = "Balanço da entrada antes de o de-esser ouvi-la"
 "Balance of the output" = "Balanço da saída"
+"Current time (H:M:S:MS)" = "Tempo atual (H:M:S:MS)"
+"Current time (right click to set)" = "Tempo atual (clique direito para definir)"
+"Delay playback (H:M:S:MS)" = "Atrasar a reprodução (H:M:S:MS)"
+"Delay playback by {0}" = "Reprodução atrasada em {0}"
+"Delay playback until the song position" = "Atrasar a reprodução até a posição da música"
+"Delay playback" = "Atrasar a reprodução"
+"Dock control panel" = "Fixar o painel de controle"
+"Enable audio" = "Ativar o áudio"
+"End time (H:M:S:MS)" = "Tempo final (H:M:S:MS)"
+"End time (click to go to, right click to set)" = "Tempo final (clique para ir até ele, clique direito para definir)"
+"Extracting the sound..." = "Extraindo o som..."
+"Host" = "Host"
+"Hours:Minutes:Seconds:Ms" = "Horas:Minutos:Segundos:Ms"
+"Ignore tempo changes" = "Ignorar mudanças de andamento"
+"Keep aspect ratio" = "Manter a proporção"
+"Load a video file (or drop one here)" = "Carregue um arquivo de vídeo (ou solte um aqui)"
+"Load video file..." = "Carregar arquivo de vídeo..."
+"Mute audio" = "Silenciar o áudio"
+"No delay" = "Sem atraso"
+"No video" = "Sem vídeo"
+"Plugin options" = "Opções do plugin"
+"Send audio to playlist" = "Enviar o áudio para a playlist"
+"Set current position as end time" = "Usar a posição atual como tempo final"
+"Set current position as start time" = "Usar a posição atual como tempo inicial"
+"Set..." = "Definir..."
+"Show the video in its own window (double-click the video)" = "Mostrar o vídeo numa janela própria (clique duplo no vídeo)"
+"Slave playback to host: the song position drives the video (off: the player's own Play / Stop)" = "Reprodução escrava do host: a posição da música conduz o vídeo (desligado: o Play / Stop do próprio player)"
+"Start time (H:M:S:MS)" = "Tempo inicial (H:M:S:MS)"
+"Start time (click to go to, right click to set)" = "Tempo inicial (clique para ir até ele, clique direito para definir)"
+"The video is in its own window" = "O vídeo está na sua própria janela"
+"The video starts when the song reaches this time." = "O vídeo começa quando a música chega a este tempo."
+"The video was not found:" = "O vídeo não foi encontrado:"
+"Time display" = "Exibição do tempo"
+"Video position (use left/right keys for previous/next frame)" = "Posição do vídeo (setas esquerda/direita para o quadro anterior/seguinte)"
+"audio" = "áudio"
+"ffmpeg could not read a video in this file" = "O ffmpeg não conseguiu ler um vídeo neste arquivo"
+"ffmpeg was not found. LYNX plays videos with ffmpeg: install it or locate it." = "O ffmpeg não foi encontrado. O LYNX reproduz vídeos com o ffmpeg: instale-o ou localize-o."
+"no sound" = "sem som"

Разница между файлами не показана из-за своего большого размера
+ 0 - 0
scripts/build-local.sh


+ 1 - 1
scripts/build-windows-zig.sh

@@ -148,7 +148,7 @@ APP_SOURCES+=(src/core/CrashReport.cpp src/ui/CrashReporter.cpp)
 # visual plugins: Wave Candy, Visualizer, video export (round 164c)
 APP_SOURCES+=(src/core/VisualFx.cpp src/ui/VisualEditors.cpp)
 # FL plugins LYNX lacked: Mute 2, Big Clock, Tuner, HTML NoteBook (round 165g)
-APP_SOURCES+=(src/core/FlExtraFx.cpp src/ui/FlExtraEditors.cpp)
+APP_SOURCES+=(src/core/FlExtraFx.cpp src/ui/FlExtraEditors.cpp src/core/VideoPlayer.cpp src/ui/VideoPlayerView.cpp)
 APP_SOURCES+=(src/core/VisualFx.cpp src/core/FruityDance.cpp src/ui/VisualEditors.cpp src/ui/VisualGl.cpp src/ui/DanceView.cpp)
 
 echo "WavPack (decoder, C)..."

+ 60 - 0
src/Main.cpp

@@ -4,6 +4,7 @@
 #include "core/LoadTrace.h"
 #include "core/Patcherize.h"
 #include "core/Performance.h"
+#include "core/VideoPlayer.h"
 #include "core/Effects.h"
 #include "core/MixSuite.h"
 #include "core/HardwareInsert.h"
@@ -31,6 +32,7 @@
 #include "engine/Text.h"
 #include "platform/FileTypes.h"
 #include "platform/Package.h"
+#include "ui/VideoPlayerView.h"
 #include "ui/PatcherEditor.h"
 #include "ui/VisualEditors.h"
 #include "ui/FlExtraEditors.h"
@@ -906,6 +908,16 @@ public:
             return;
         }
 
+        if (args.contains ("--videoshot") && args.indexOf ("--videoshot") + 2 < args.size())
+        {
+            // LYNX.exe --videoshot prefix video: the Video Player's editor (round 165g) at a few song positions, with
+            // the user's ffmpeg, as PNGs + report.txt (frames decoded, the sound track)
+            const auto i = args.indexOf ("--videoshot");
+            runVideoShot (args[i + 1].unquoted(), args[i + 2].unquoted());
+            quit();
+            return;
+        }
+
         if (args.contains ("--vfxshot"))
         {
             // LYNX.exe --vfxshot prefix: the VFX note effects' editors (round 164b), on channels and in a Patcher, as PNGs
@@ -1102,6 +1114,7 @@ public:
     {
         startupTrace.mark ("before the audio engine");
         engine = std::make_unique<lynx::AudioEngine>();
+        lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
         startupTrace.mark ("audio engine + device");
         crashEngine = engine.get();
         lynx::crashreporter::watchAudioDevice (engine->getDeviceManager()); // (the session file names the device: crash reports)
@@ -3438,6 +3451,7 @@ private:
     {
         startupOptions = lynx::StartupOptions::load();
         engine = std::make_unique<lynx::AudioEngine>();
+        lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
         crashEngine = engine.get();
         createMainWindow();
         mainWindow->reveal();
@@ -3612,6 +3626,7 @@ private:
     {
         startupOptions = lynx::StartupOptions::load();
         engine = std::make_unique<lynx::AudioEngine>();
+        lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
         crashEngine = engine.get();
         // the user's saved device stays as it was: this run's choices are undone before quitting
         savedDeviceState = engine->getDeviceManager().createStateXml();
@@ -3735,6 +3750,7 @@ private:
                         const juce::String& inputName, int mode, int pdcSamples, int bufferSize)
     {
         engine = std::make_unique<lynx::AudioEngine>();
+        lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
         savedDeviceState = engine->getDeviceManager().createStateXml();
         auto text = std::make_shared<juce::String>();
         auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
@@ -3956,6 +3972,7 @@ private:
                           const juce::String& inputName, int bufferSize, bool inPatcher = false, juce::File bounceFile = {})
     {
         engine = std::make_unique<lynx::AudioEngine>();
+        lynx::videoview::install (*engine); // (Fruity Video Player channels: their sound tracks)
         savedDeviceState = engine->getDeviceManager().createStateXml();
         auto text = std::make_shared<juce::String>();
         auto step = [report, text] (const juce::String& line) { *text << line << "\n"; report.replaceWithText (*text); };
@@ -5153,6 +5170,49 @@ private:
         quit();
     }
 
+    void runVideoShot (const juce::String& prefix, const juce::String& videoPath)
+    {
+        juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);
+        lynx::AudioEngine offline (false);
+        lynx::videoview::install (offline);
+        lynx::Song song;
+        song.mixer = lynx::Song::defaultMixer (2);
+        lynx::ChannelDef c;
+        c.name = "Fruity Video Player";
+        c.instrument = lynx::InstrumentKind::videoplayer;
+        lynx::video::Settings vs;
+        vs.path = juce::File (videoPath).getFullPathName().toStdString();
+        vs.delay = lynx::video::unitsPerSecond / 2; // the video starts at 0.5 s
+        c.pluginState = lynx::video::write (vs);
+        song.channels.push_back (c);
+        song.patterns.emplace_back();
+        offline.setSong (std::move (song));
+        offline.dispatchPendingMessages();
+        juce::String report;
+        report << "ffmpeg: " << lynx::findFfmpeg().getFullPathName() << "\n";
+        report << lynx::videoview::report (vs.path).fromFirstOccurrenceOf ("Input #0", true, false).upToFirstOccurrenceOf ("At least", false, false) << "\n";
+        auto editor = lynx::makeChannelSettingsPanel (offline, 0);
+        if (editor == nullptr)
+            return;
+        juce::Component holder;
+        holder.setSize (editor->getWidth(), editor->getHeight());
+        holder.addAndMakeVisible (*editor);
+        auto pump = [] (int ms) {
+            const auto end = juce::Time::getMillisecondCounter() + (juce::uint32) ms;
+            while (juce::Time::getMillisecondCounter() < end)
+                juce::MessageManager::getInstance()->runDispatchLoopUntil (20);
+        };
+        const double times[] = { 0.0, 1.5, 3.25 };
+        int k = 0;
+        for (const auto t : times)
+        {
+            offline.getTransport().positionTicks.store (t * offline.getSong().bpm / 60.0 * lynx::ppq);
+            pump (1500);
+            savePng (editor->createComponentSnapshot (editor->getLocalBounds()), prefix + "-" + juce::String (k++) + ".png");
+        }
+        juce::File (prefix + "-report.txt").replaceWithText (report);
+    }
+
     void runDanceShot (const juce::String& prefix)
     {
         juce::LookAndFeel::setDefaultLookAndFeel (&lookAndFeel);

+ 0 - 2
src/core/FlExtraFx.cpp

@@ -715,8 +715,6 @@ std::string inertPluginNote (const std::string& flPluginName)
         return "FL Studio Mobile Rack FX (its modules are not reproduced; the slot is left out)";
     if (flPluginName == "FL Studio Mobile" || flPluginName == "FL Studio Mobile Rack")
         return flPluginName + " (its instruments are not reproduced; played with a LYNX synth preset)";
-    if (flPluginName == "Fruity Video Player")
-        return "Fruity Video Player (the video is not played; the channel is left silent)";
     return {};
 }
 } // namespace lynx::flextra

+ 16 - 1
src/core/FlpImport.cpp

@@ -4,6 +4,7 @@
 #include "core/VoltageController.h"
 #include "core/XyController.h"
 #include "core/Vfx.h"
+#include "core/VideoPlayer.h"
 #include "core/Patcher.h"
 #include <filesystem>
 #include "core/EditorPolish.h"
@@ -1618,6 +1619,19 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
                     adoptedFromPlugin = true;
                 }
             }
+            else if (name == "fruity video player")
+            {
+                // FL's state as it is (round 165g, core/VideoPlayer.h); the video's path through FL's folder names
+                if (auto vs = video::read (c.pluginState))
+                {
+                    if (vs->path.find ('%') != std::string::npos)
+                        if (const auto resolved = resolveFlPath (vs->path, options.roots); ! resolved.empty())
+                            vs->path = resolved;
+                    def.instrument = InstrumentKind::videoplayer;
+                    def.pluginState = video::write (*vs);
+                    adoptedFromPlugin = true;
+                }
+            }
             else if (name == "fruity dance")
             {
                 // a visual plugin: notes change the dance, its Gen_Render writes nothing (REA_rodada68 §8)
@@ -1918,6 +1932,7 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
                      || def.instrument == InstrumentKind::sawer || def.instrument == InstrumentKind::flkeys
                      || def.instrument == InstrumentKind::granulizer || def.instrument == InstrumentKind::drumaxx
                      || def.instrument == InstrumentKind::slayer || def.instrument == InstrumentKind::fruitydance
+                     || def.instrument == InstrumentKind::videoplayer
                      || def.instrument == InstrumentKind::directwave || def.instrument == InstrumentKind::soundfont)
                 ++r.converted[c.pluginName]; // FL's own engine rebuilt from the plugin state
             else if ((plugin == "harmless" && def.instrument != InstrumentKind::harmless) || (plugin == "harmor" && def.instrument != InstrumentKind::harmor && adoptedFromPlugin) || (plugin == "minisynth" && def.instrument != InstrumentKind::minisynth) || plugin == "fruity dx10" || plugin == "dx10" || (plugin == "fruit kick" && def.instrument != InstrumentKind::fruitkick)
@@ -1943,7 +1958,7 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
                      && def.instrument == InstrumentKind::synth)
             {
                 const auto note = flextra::inertPluginNote (c.pluginName); // round 165g: ReWired, Video Player, FL Studio Mobile
-                if (c.pluginName == "ReWired" || c.pluginName == "Fruity Video Player")
+                if (c.pluginName == "ReWired")
                     def.muted = true; // no sound of their own in LYNX: the stand-in synth must not play their notes
                 ++r.unsupported[note.empty() ? c.pluginName : note]; // (Keyboard Controller only sends notes to other channels)
             }

+ 4 - 0
src/core/Instruments.cpp

@@ -3,6 +3,7 @@
 #include "core/ControlSurface.h"
 #include "core/VoltageController.h"
 #include "core/Vfx.h"
+#include "core/VideoPlayer.h"
 #include "core/Scheduler.h"
 
 #include "core/DirectWave.h"
@@ -238,6 +239,7 @@ private:
             case InstrumentKind::dashboard:
             case InstrumentKind::voltage:
             case InstrumentKind::vfx:
+            case InstrumentKind::videoplayer:
             case InstrumentKind::patcher:
             case InstrumentKind::sakura:
             case InstrumentKind::drumpad:
@@ -2974,6 +2976,8 @@ std::unique_ptr<Instrument> makeInstrument (InstrumentKind kind, std::shared_ptr
         return voltage::makeInstrument();
     if (kind == InstrumentKind::vfx)
         return std::make_unique<VfxInstrument>();
+    if (kind == InstrumentKind::videoplayer) // the video's sound, in sync with the song (round 165g)
+        return video::makeInstrument();
 
     if (kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip)
         return std::make_unique<SamplerInstrument> (std::move (sample), kind == InstrumentKind::audioClip);

+ 3 - 1
src/core/Song.h

@@ -84,7 +84,9 @@ enum class InstrumentKind : std::uint8_t
     dashboard,  // FL's Dashboard (REA_rodada164a, core/ControlSurface.h): no sound; a panel of controls in patcher.surface
     voltage,    // FL's Voltage Controller (REA_rodada164a, core/VoltageController.h): its notes as control voltages; FL's
                 // state in pluginState
-    vfx         // FL's VFX note processors (round 164b, core/Vfx.h): kind, output port and FL's state in pluginState; no sound
+    vfx,        // FL's VFX note processors (round 164b, core/Vfx.h): kind, output port and FL's state in pluginState; no sound
+    videoplayer // FL's Fruity Video Player (round 165g, core/VideoPlayer.h): FL's state (with the video's path) in
+                // pluginState; plays the video's sound in sync with the song, the video is shown by its editor
 };
 
 // External plugin: format identifier (the app knows how to find the file) + saved state.

+ 563 - 0
src/core/VideoPlayer.cpp

@@ -0,0 +1,563 @@
+#include "core/VideoPlayer.h"
+
+#include <algorithm>
+#include <cctype>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+#include <mutex>
+
+#include "core/Instruments.h"
+#include "core/Song.h"
+
+namespace lynx::video
+{
+namespace
+{
+struct Reader
+{
+    const std::vector<std::uint8_t>& b;
+    std::size_t p = 0;
+    bool ok = true;
+
+    template <typename T>
+    T get()
+    {
+        T v {};
+        if (p + sizeof (T) > b.size())
+        {
+            ok = false;
+            return v;
+        }
+        std::memcpy (&v, b.data() + p, sizeof (T));
+        p += sizeof (T);
+        return v;
+    }
+};
+
+template <typename T>
+void put (std::vector<std::uint8_t>& out, T v)
+{
+    const auto* p = reinterpret_cast<const std::uint8_t*> (&v);
+    out.insert (out.end(), p, p + sizeof (T));
+}
+
+// UTF-16 ↔ UTF-8 (the path)
+std::string utf8 (const std::vector<char16_t>& w)
+{
+    std::string s;
+    for (std::size_t i = 0; i < w.size(); ++i)
+    {
+        std::uint32_t c = w[i];
+        if (c >= 0xd800 && c < 0xdc00 && i + 1 < w.size() && w[i + 1] >= 0xdc00 && w[i + 1] < 0xe000)
+            c = 0x10000 + ((c - 0xd800) << 10) + (std::uint32_t) (w[++i] - 0xdc00);
+        if (c < 0x80)
+            s += (char) c;
+        else if (c < 0x800)
+        {
+            s += (char) (0xc0 | (c >> 6));
+            s += (char) (0x80 | (c & 0x3f));
+        }
+        else if (c < 0x10000)
+        {
+            s += (char) (0xe0 | (c >> 12));
+            s += (char) (0x80 | ((c >> 6) & 0x3f));
+            s += (char) (0x80 | (c & 0x3f));
+        }
+        else
+        {
+            s += (char) (0xf0 | (c >> 18));
+            s += (char) (0x80 | ((c >> 12) & 0x3f));
+            s += (char) (0x80 | ((c >> 6) & 0x3f));
+            s += (char) (0x80 | (c & 0x3f));
+        }
+    }
+    return s;
+}
+
+std::vector<char16_t> utf16 (const std::string& s)
+{
+    std::vector<char16_t> w;
+    for (std::size_t i = 0; i < s.size();)
+    {
+        const auto c0 = (unsigned char) s[i];
+        std::uint32_t c = c0;
+        int more = 0;
+        if (c0 >= 0xf0) { c = c0 & 0x07; more = 3; }
+        else if (c0 >= 0xe0) { c = c0 & 0x0f; more = 2; }
+        else if (c0 >= 0xc0) { c = c0 & 0x1f; more = 1; }
+        ++i;
+        for (int k = 0; k < more && i < s.size(); ++k, ++i)
+            c = (c << 6) | ((unsigned char) s[i] & 0x3f);
+        if (c >= 0x10000)
+        {
+            c -= 0x10000;
+            w.push_back ((char16_t) (0xd800 + (c >> 10)));
+            w.push_back ((char16_t) (0xdc00 + (c & 0x3ff)));
+        }
+        else
+            w.push_back ((char16_t) c);
+    }
+    return w;
+}
+
+constexpr char lynxTag[8] = { 'L', 'Y', 'N', 'X', 'v', 'p', '1', 0 };
+
+AudioProvider& provider()
+{
+    static AudioProvider p;
+    return p;
+}
+std::mutex& providerLock()
+{
+    static std::mutex m;
+    return m;
+}
+} // namespace
+
+const char* timeDisplayName (int mode) noexcept
+{
+    switch (mode)
+    {
+        case smpte23976: return "SMPTE (23.976 fps NONDROP)";
+        case smpte24: return "SMPTE (24 fps NONDROP)";
+        case smpte25: return "SMPTE (25 fps NONDROP)";
+        case smpte2997drop: return "SMPTE (29.97 fps DROP)";
+        case smpte30: return "SMPTE (30 fps NONDROP)";
+        case smpteAuto: return "SMPTE (Auto)";
+        case smpte2997: return "SMPTE (29.97 fps NONDROP)";
+        case smpte48: return "SMPTE (48 fps NONDROP)";
+        case smpte50: return "SMPTE (50 fps NONDROP)";
+        case smpte5994drop: return "SMPTE (59.94 fps DROP)";
+        case smpte5994: return "SMPTE (59.94 fps NONDROP)";
+        case smpte60: return "SMPTE (60 fps NONDROP)";
+        case smpte72: return "SMPTE (72 fps NONDROP)";
+        case smpte120: return "SMPTE (120 fps NONDROP)";
+        default: return "Hours:Minutes:Seconds:Ms";
+    }
+}
+
+double timeDisplayFps (int mode, double videoFps) noexcept
+{
+    switch (mode)
+    {
+        case smpte23976: return 23.976;
+        case smpte24: return 24.0;
+        case smpte25: return 25.0;
+        case smpte2997drop: case smpte2997: return 29.97;
+        case smpte30: return 30.0;
+        case smpteAuto: return videoFps > 0.0 ? videoFps : 0.0;
+        case smpte48: return 48.0;
+        case smpte50: return 50.0;
+        case smpte5994drop: case smpte5994: return 59.94;
+        case smpte60: return 60.0;
+        case smpte72: return 72.0;
+        case smpte120: return 120.0;
+        default: return 0.0;
+    }
+}
+
+bool timeDisplayDrops (int mode) noexcept
+{
+    return mode == smpte2997drop || mode == smpte5994drop;
+}
+
+std::string formatTime (double seconds, int mode, double videoFps)
+{
+    char buf[48];
+    const auto negative = seconds < 0.0;
+    auto t = std::abs (seconds);
+    const auto fps = timeDisplayFps (mode, videoFps);
+    const char* sign = negative ? "-" : "";
+    if (fps <= 0.0)
+    {
+        // FL: whole milliseconds of the 100 ns time
+        const auto ms = (std::int64_t) std::floor (t * 1000.0 + 1e-6);
+        std::snprintf (buf, sizeof (buf), "%s%d:%02d:%02d:%03d", sign, (int) (ms / 3600000), (int) (ms / 60000 % 60),
+                       (int) (ms / 1000 % 60), (int) (ms % 1000));
+        return buf;
+    }
+    const auto drops = timeDisplayDrops (mode);
+    const auto nominal = (std::int64_t) std::llround (fps);
+    auto frame = (std::int64_t) std::floor (t * fps + 1e-6);
+    if (drops)
+    {
+        // drop-frame: frame numbers 0 and 1 (2 and 3 at 59.94) are skipped every minute except every tenth
+        const std::int64_t dropped = nominal == 60 ? 4 : 2;
+        const auto perTen = nominal * 600 - dropped * 9;
+        const auto perMinute = nominal * 60 - dropped;
+        const auto tens = frame / perTen;
+        auto rest = frame % perTen;
+        frame += dropped * 9 * tens;
+        if (rest > dropped)
+            frame += dropped * ((rest - dropped) / perMinute);
+    }
+    const auto ff = frame % nominal;
+    const auto total = frame / nominal;
+    std::snprintf (buf, sizeof (buf), "%s%d:%02d:%02d%c%02d", sign, (int) (total / 3600), (int) (total / 60 % 60),
+                   (int) (total % 60), drops ? ';' : ':', (int) ff);
+    return buf;
+}
+
+std::vector<std::uint8_t> write (const Settings& s)
+{
+    std::vector<std::uint8_t> out;
+    put<std::int32_t> (out, 3);
+    std::uint32_t flags = 0;
+    if (s.loop) flags |= 1;
+    if (s.keepAspect) flags |= 2;
+    flags |= (std::uint32_t) (std::clamp (s.transport, 0, 3) & 3) << 2;
+    if (s.enableAudio) flags |= 0x10;
+    if (s.ignoreTempo) flags |= 0x40;
+    if (s.slave) flags |= 0x80;
+    if (s.dock) flags |= 0x100;
+    put<std::uint32_t> (out, flags);
+    put<std::int32_t> (out, std::clamp (s.timeDisplay, 0, timeDisplayCount - 1));
+    put<std::int32_t> (out, 3);
+    put<std::int32_t> (out, std::clamp (s.volume, 0, 127));
+    put<std::int32_t> (out, s.mute ? 1 : 0);
+    put<std::int32_t> (out, s.play ? 1 : 0);
+    const auto w = utf16 (s.path);
+    if (w.size() < 0xff)
+        out.push_back ((std::uint8_t) w.size());
+    else
+    {
+        out.push_back (0xff);
+        put<std::uint32_t> (out, (std::uint32_t) w.size());
+    }
+    for (const auto c : w)
+        put<std::uint16_t> (out, (std::uint16_t) c);
+    put<std::int32_t> (out, s.width);
+    put<std::int32_t> (out, s.height);
+    if (! w.empty())
+    {
+        put<std::int64_t> (out, s.start);
+        put<std::int64_t> (out, s.end);
+    }
+    out.insert (out.end(), lynxTag, lynxTag + 8);
+    put<std::int64_t> (out, s.delay);
+    return out;
+}
+
+std::optional<Settings> read (const std::vector<std::uint8_t>& state)
+{
+    Reader r { state };
+    const auto version = r.get<std::int32_t>();
+    if (! r.ok || version < 1 || version > 3)
+        return std::nullopt;
+    Settings s;
+    const auto flags = r.get<std::uint32_t>();
+    if (version > 2)
+        s.timeDisplay = std::clamp (r.get<std::int32_t>(), 0, timeDisplayCount - 1);
+    auto count = 2;
+    if (version > 2)
+        count = r.get<std::int32_t>();
+    if (! r.ok || count < 0 || count > 16)
+        return std::nullopt;
+    for (int i = 0; i < count; ++i)
+    {
+        const auto v = r.get<std::int32_t>();
+        if (i == 0) s.volume = std::clamp (v, 0, 127);
+        if (i == 1) s.mute = v != 0;
+        if (i == 2) s.play = v != 0;
+    }
+    // the path: version 3 UTF-16 (byte length, 0xFF + int when longer); before, an ANSI string with the same lengths
+    std::uint32_t length = r.get<std::uint8_t>();
+    if (length == 0xff)
+        length = r.get<std::uint32_t>();
+    if (! r.ok || length > 32768)
+        return std::nullopt;
+    if (version > 2)
+    {
+        std::vector<char16_t> w;
+        for (std::uint32_t i = 0; i < length; ++i)
+            w.push_back ((char16_t) r.get<std::uint16_t>());
+        s.path = utf8 (w);
+    }
+    else
+        for (std::uint32_t i = 0; i < length; ++i)
+            s.path += (char) r.get<std::uint8_t>();
+    if (! r.ok)
+        return std::nullopt;
+    if (! s.path.empty() || version > 1)
+    {
+        s.width = r.get<std::int32_t>();
+        s.height = r.get<std::int32_t>();
+    }
+    if (! s.path.empty())
+    {
+        s.start = std::max<std::int64_t> (0, r.get<std::int64_t>());
+        s.end = std::max<std::int64_t> (0, r.get<std::int64_t>());
+    }
+    if (! r.ok)
+        return std::nullopt;
+    s.loop = (flags & 1) != 0;
+    s.keepAspect = (flags & 2) != 0;
+    s.transport = (int) ((flags >> 2) & 3);
+    s.enableAudio = (flags & 0x30) != 0;
+    s.ignoreTempo = (flags & 0x40) != 0;
+    s.slave = version < 3 || (flags & 0x80) != 0;
+    s.dock = (flags & 0x100) != 0;
+    if (r.p + 16 <= state.size() && std::memcmp (state.data() + r.p, lynxTag, 8) == 0)
+    {
+        r.p += 8;
+        s.delay = r.get<std::int64_t>();
+    }
+    return s;
+}
+
+Settings readOrDefault (const std::vector<std::uint8_t>& state)
+{
+    if (auto s = read (state))
+        return *s;
+    return {};
+}
+
+Info parseFfmpegReport (const std::string& report)
+{
+    Info info;
+    if (const auto d = report.find ("Duration: "); d != std::string::npos)
+    {
+        int h = 0, m = 0;
+        double sec = 0.0;
+        if (std::sscanf (report.c_str() + d + 10, "%d:%d:%lf", &h, &m, &sec) == 3)
+            info.duration = h * 3600.0 + m * 60.0 + sec;
+    }
+    std::size_t at = 0;
+    while ((at = report.find ("Stream #", at)) != std::string::npos)
+    {
+        const auto lineEnd = report.find ('\n', at);
+        const auto line = report.substr (at, lineEnd == std::string::npos ? std::string::npos : lineEnd - at);
+        at = lineEnd == std::string::npos ? report.size() : lineEnd;
+        if (line.find ("Audio:") != std::string::npos)
+            info.hasAudio = true;
+        if (line.find ("Video:") == std::string::npos || info.hasVideo)
+            continue;
+        if (line.find ("attached pic") != std::string::npos)
+            continue;
+        // "…, 1920x1080 [SAR 1:1 DAR 16:9], …, 29.97 fps, …" (the size: the first "<digits>x<digits>")
+        for (std::size_t i = 0; i + 2 < line.size(); ++i)
+        {
+            if (line[i] < '1' || line[i] > '9' || (i > 0 && std::isalnum ((unsigned char) line[i - 1])))
+                continue;
+            int w = 0, h = 0, used = 0;
+            if (std::sscanf (line.c_str() + i, "%dx%d%n", &w, &h, &used) == 2 && w > 0 && h > 0 && used > 2)
+            {
+                info.width = w;
+                info.height = h;
+                break;
+            }
+        }
+        for (const char* key : { " fps", " tbr" })
+            if (const auto f = line.find (key); f != std::string::npos && info.fps <= 0.0)
+            {
+                auto b = line.rfind (' ', f - 1);
+                if (b != std::string::npos)
+                    info.fps = std::atof (line.c_str() + b + 1);
+            }
+        info.hasVideo = info.width > 0;
+    }
+    return info;
+}
+
+double Clock::videoTime (double songSeconds, const Settings& s, double duration) noexcept
+{
+    const auto delay = (double) s.delay / (double) unitsPerSecond;
+    auto t = songSeconds - delay;
+    if (t < 0.0)
+        return t;
+    const auto start = (double) s.start / (double) unitsPerSecond;
+    auto end = s.end > 0 ? (double) s.end / (double) unitsPerSecond : duration;
+    if (duration > 0.0)
+        end = std::min (end, duration);
+    t += start;
+    if (end > start && t >= end)
+    {
+        if (s.loop)
+            t = start + std::fmod (t - start, end - start);
+        else
+            t = end;
+    }
+    return t;
+}
+
+void setAudioProvider (AudioProvider p)
+{
+    std::lock_guard<std::mutex> lock (providerLock());
+    provider() = std::move (p);
+}
+
+namespace
+{
+std::shared_ptr<const AudioTrack> provide (const std::string& path, bool wait)
+{
+    AudioProvider p;
+    {
+        std::lock_guard<std::mutex> lock (providerLock());
+        p = provider();
+    }
+    return p ? p (path, wait) : nullptr;
+}
+
+class VideoInstrument final : public Instrument, public Player
+{
+public:
+    void prepare (double sampleRate) noexcept override { rate = sampleRate > 0.0 ? sampleRate : 44100.0; }
+    void noteOn (int, float) noexcept override {}
+    void noteOff (int) noexcept override {}
+    void allNotesOff() noexcept override {}
+    void transportStopped() noexcept override { songRunning.store (false, std::memory_order_relaxed); }
+    void panic() noexcept override { ownStop(); }
+
+    // UI thread
+    void configure (const ChannelDef& def, double bpm) noexcept override
+    {
+        const auto s = readOrDefault (def.pluginState);
+        loop.store (s.loop, std::memory_order_relaxed);
+        enableAudio.store (s.enableAudio, std::memory_order_relaxed);
+        ignoreTempo.store (s.ignoreTempo, std::memory_order_relaxed);
+        slave.store (s.slave, std::memory_order_relaxed);
+        gain.store (s.mute ? 0.0f : (float) s.volume / 100.0f, std::memory_order_relaxed);
+        delay.store ((double) s.delay / (double) unitsPerSecond, std::memory_order_relaxed);
+        start.store ((double) s.start / (double) unitsPerSecond, std::memory_order_relaxed);
+        end.store ((double) s.end / (double) unitsPerSecond, std::memory_order_relaxed);
+        if (bpm > 0.0)
+            songBpm.store (bpm, std::memory_order_relaxed);
+        if (s.path != path || (track == nullptr && ! s.path.empty()))
+        {
+            path = s.path;
+            auto fresh = s.path.empty() || ! s.enableAudio ? nullptr : provide (s.path, offlineRendering());
+            if (fresh != track)
+            {
+                if (track != nullptr)
+                    retired.push_back (track); // (the audio thread may still read it; freed with the instrument)
+                track = std::move (fresh);
+                audio.store (track.get(), std::memory_order_release);
+            }
+        }
+        else if (s.enableAudio && track == nullptr && ! path.empty())
+        {
+            track = provide (path, offlineRendering());
+            audio.store (track.get(), std::memory_order_release);
+        }
+    }
+
+    void setSongPosition (double ticks) noexcept override
+    {
+        const auto bpm = songBpm.load (std::memory_order_relaxed);
+        const auto beatSeconds = ticks / (double) ppq * 60.0 / bpm;
+        const auto moved = lastTicks >= 0.0 && ticks != lastTicks;
+        const auto expected = lastTicks + lastBlock * lastTps;
+        const auto jumped = ! moved || std::abs (ticks - expected) > std::max (1.0, lastBlock * lastTps * 0.5) || ticks < lastTicks;
+        if (moved && lastBlock > 0)
+            lastTps = (ticks - lastTicks) / (double) lastBlock;
+        lastTicks = ticks;
+        if (ignoreTempo.load (std::memory_order_relaxed) && moved && ! jumped)
+            songSeconds += (double) lastBlock / rate; // real time
+        else
+            songSeconds = beatSeconds;
+        songRunning.store (moved, std::memory_order_relaxed);
+    }
+
+    bool idle() const noexcept override
+    {
+        if (audio.load (std::memory_order_acquire) == nullptr || ! enableAudio.load (std::memory_order_relaxed)
+            || gain.load (std::memory_order_relaxed) <= 0.0f)
+            return true;
+        return slave.load (std::memory_order_relaxed) ? ! songRunning.load (std::memory_order_relaxed) : ! ownRunning.load (std::memory_order_relaxed);
+    }
+
+    void render (float* left, float* right, int n, float gainLeft, float gainRight) noexcept override
+    {
+        lastBlock = n;
+        const auto slaved = slave.load (std::memory_order_relaxed);
+        if (! slaved && ownRequest.load (std::memory_order_acquire))
+        {
+            ownSeconds = ownTarget.load (std::memory_order_relaxed);
+            ownRequest.store (false, std::memory_order_release);
+        }
+        const auto running = slaved ? songRunning.load (std::memory_order_relaxed) : ownRunning.load (std::memory_order_relaxed);
+        Settings s;
+        s.loop = loop.load (std::memory_order_relaxed);
+        s.delay = (std::int64_t) std::llround (delay.load (std::memory_order_relaxed) * unitsPerSecond);
+        s.start = (std::int64_t) std::llround (start.load (std::memory_order_relaxed) * unitsPerSecond);
+        s.end = (std::int64_t) std::llround (end.load (std::memory_order_relaxed) * unitsPerSecond);
+        const auto* a = audio.load (std::memory_order_acquire);
+        const auto duration = a != nullptr && a->rate > 0.0 ? (double) a->frames() / a->rate : 0.0;
+        const auto base = slaved ? songSeconds : ownSeconds;
+        const auto t0 = slaved ? Clock::videoTime (base, s, duration) : base;
+        now.store (t0, std::memory_order_relaxed);
+        isRunning.store (running, std::memory_order_relaxed);
+        if (! slaved && running)
+            ownSeconds += (double) n / rate;
+        if (! running || a == nullptr || ! enableAudio.load (std::memory_order_relaxed))
+            return;
+        const auto g = gain.load (std::memory_order_relaxed);
+        if (g <= 0.0f)
+            return;
+        const auto frames = a->frames();
+        const auto* data = a->samples.data();
+        // per sample: the clock moves in real time inside the block (the loop / end applies at each sample)
+        for (int i = 0; i < n; ++i)
+        {
+            const auto songT = base + (double) i / rate;
+            const auto t = slaved ? Clock::videoTime (songT, s, duration) : songT;
+            if (t < 0.0 || (! s.loop && s.end <= 0 && t >= duration))
+                continue;
+            const auto pos = t * a->rate;
+            const auto k = (std::int64_t) pos;
+            if (k < 0 || k + 1 >= frames)
+                continue;
+            const auto f = (float) (pos - (double) k);
+            const auto l = (float) data[k * 2] + f * (float) (data[k * 2 + 2] - data[k * 2]);
+            const auto r = (float) data[k * 2 + 1] + f * (float) (data[k * 2 + 3] - data[k * 2 + 1]);
+            left[i] += l * (g * gainLeft / 32768.0f);
+            right[i] += r * (g * gainRight / 32768.0f);
+        }
+    }
+
+    double currentTime() const noexcept override { return now.load (std::memory_order_relaxed); }
+    bool running() const noexcept override { return isRunning.load (std::memory_order_relaxed); }
+    void ownPlay (double seconds) noexcept override
+    {
+        ownTarget.store (seconds, std::memory_order_relaxed);
+        ownRequest.store (true, std::memory_order_release);
+        ownRunning.store (true, std::memory_order_relaxed);
+    }
+    void ownPause() noexcept override { ownRunning.store (false, std::memory_order_relaxed); }
+    void ownStop() noexcept override
+    {
+        ownRunning.store (false, std::memory_order_relaxed);
+        ownTarget.store (start.load (std::memory_order_relaxed), std::memory_order_relaxed);
+        ownRequest.store (true, std::memory_order_release);
+    }
+
+private:
+    double rate = 44100.0;
+    std::atomic<double> songBpm { 130.0 };
+    std::atomic<bool> loop { false }, enableAudio { true }, ignoreTempo { false }, slave { true };
+    std::atomic<float> gain { 1.0f };
+    std::atomic<double> delay { 0.0 }, start { 0.0 }, end { 0.0 };
+    std::atomic<const AudioTrack*> audio { nullptr };
+    std::shared_ptr<const AudioTrack> track; // (UI thread)
+    std::vector<std::shared_ptr<const AudioTrack>> retired;
+    std::string path;
+
+    // audio thread
+    double lastTicks = -1.0, lastTps = 0.0, songSeconds = 0.0, ownSeconds = 0.0;
+    int lastBlock = 0;
+    std::atomic<bool> songRunning { false }, ownRunning { false }, ownRequest { false }, isRunning { false };
+    std::atomic<double> ownTarget { 0.0 }, now { 0.0 };
+};
+} // namespace
+
+std::unique_ptr<Instrument> makeInstrument()
+{
+    return std::make_unique<VideoInstrument>();
+}
+
+Player* playerOf (Instrument* instrument) noexcept
+{
+    return dynamic_cast<VideoInstrument*> (instrument);
+}
+} // namespace lynx::video

+ 129 - 0
src/core/VideoPlayer.h

@@ -0,0 +1,129 @@
+#pragma once
+
+// LYNX Video Player (round 165g, docs/analise/REA_rodada165g.md §7): FL's Fruity Video Player — a generator channel that
+// shows a video in sync with the song (and plays its sound). The video is decoded by the user's own ffmpeg (ui/VideoPlayer
+// View); this part holds FL's saved state, the clock that turns the song position into the video's time, and the
+// instrument that plays the video's sound track. No JUCE here (tests/VideoPlayer165Tests.inc).
+//
+// FL's behaviour, read in its plugin (Fruity Video Player_x64.dll, SaveRestoreState 0x72d9b0, the options menu and its
+// handlers, the time display 0x72bb50) [DECOMP]:
+// - state version 3: int version; int flags (bit 0 Loop, bit 1 Keep aspect ratio, bits 2-3 the player's own transport
+//   (0 stopped, 1 playing, 2 playing the start…end range, 3 paused), bit 4 Enable audio (bits 4|5 in older states),
+//   bit 6 Ignore tempo changes, bit 7 Slave playback to host, bit 8 Dock control panel); int time display; int count (3)
+//   and the three parameters (Volume 0…127, default 100; Mute; Play); the video's path (a byte length — 0xFF then an
+//   int when ≥ 255 — and UTF-16 characters); two ints (the video window's size); with a path, the start and end times
+//   (int64, 100 ns units).
+// - FL's default state (Default.fst): flags 0x92 (Keep aspect ratio, Enable audio, Slave playback to host), time display
+//   0, Volume 100.
+// - "Delay playback until that time" (form +0x770) is not part of FL's state: LYNX appends it after FL's fields
+//   ("LYNXvp1" + int64), where FL's reader stops.
+
+#include <atomic>
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace lynx
+{
+class Instrument;
+}
+
+namespace lynx::video
+{
+constexpr std::int64_t unitsPerSecond = 10000000; // FL's times (100 ns)
+
+// FL's time display modes (the menu's tags)
+enum TimeDisplay : int
+{
+    hms = 0, smpte23976 = 1, smpte24 = 2, smpte25 = 3, smpte2997drop = 4, smpte30 = 5, smpteAuto = 6, smpte2997 = 7,
+    smpte48 = 8, smpte50 = 9, smpte5994drop = 10, smpte5994 = 11, smpte60 = 12, smpte72 = 13, smpte120 = 14
+};
+constexpr int timeDisplayCount = 15;
+const char* timeDisplayName (int mode) noexcept; // English (the UI translates "Hours:Minutes:Seconds:Ms")
+// frames per second of a SMPTE mode (0 for H:M:S:Ms; the video's own rate for Auto) and whether it drops frames
+double timeDisplayFps (int mode, double videoFps) noexcept;
+bool timeDisplayDrops (int mode) noexcept;
+// FL's "0:00:00:000" (H:MM:SS:mmm) or "H:MM:SS:FF" (SMPTE; ";" before the frames when dropping)
+std::string formatTime (double seconds, int mode, double videoFps);
+
+struct Settings
+{
+    std::string path;            // the video (UTF-8)
+    bool loop = false;
+    bool keepAspect = true;
+    int transport = 0;           // FL's own player when not slaved: 0 stopped, 1 playing, 2 playing start…end, 3 paused
+    bool enableAudio = true;
+    bool ignoreTempo = false;
+    bool slave = true;           // Slave playback to host: the song position drives the video
+    bool dock = false;           // Dock control panel
+    int timeDisplay = hms;
+    int volume = 100;            // 0…127
+    bool mute = false;
+    bool play = false;           // the Play parameter (when not slaved)
+    int width = 375, height = 0; // FL's video window size (kept for FL)
+    std::int64_t start = 0, end = 0; // 100 ns; end 0 = the video's end
+    std::int64_t delay = 0;      // LYNX: the song time where the video starts (100 ns)
+
+    bool operator== (const Settings&) const = default;
+};
+
+std::vector<std::uint8_t> write (const Settings& s); // FL's version-3 state + LYNX's tail
+std::optional<Settings> read (const std::vector<std::uint8_t>& state); // nullopt: not a Video Player state
+Settings readOrDefault (const std::vector<std::uint8_t>& state);
+
+// What the video looks like (ffmpeg's report)
+struct Info
+{
+    double duration = 0.0; // seconds
+    double fps = 0.0;
+    int width = 0, height = 0;
+    bool hasVideo = false, hasAudio = false;
+};
+// Parses ffmpeg's "-i" report (stderr): Duration, the first video stream's size and rate, an audio stream
+Info parseFfmpegReport (const std::string& report);
+
+// The video's time at a song position, FL's clock:
+// - slaved, following the tempo: the song's beats at the song's tempo (a tempo change changes the video's speed);
+// - slaved, Ignore tempo changes: real time since the play position (seconds), re-anchored at jumps;
+// then the delay (the video starts when the song reaches it), the start time, and the end / loop.
+struct Clock
+{
+    // videoSeconds for a song time (s) given as seconds since the song's start; < 0 before the delay
+    static double videoTime (double songSeconds, const Settings& s, double duration) noexcept;
+};
+
+// The decoded sound track (interleaved stereo int16 at `rate`), shared between the UI and the audio thread
+struct AudioTrack
+{
+    double rate = 48000.0;
+    std::vector<std::int16_t> samples; // L R L R …
+    std::int64_t frames() const noexcept { return (std::int64_t) samples.size() / 2; }
+};
+
+// The UI gives the instrument its sound track by path (ui/VideoPlayerView decodes it with ffmpeg; `wait` while
+// exporting). nullptr: not decoded (yet), no audio, or no ffmpeg.
+using AudioProvider = std::function<std::shared_ptr<const AudioTrack> (const std::string& path, bool wait)>;
+void setAudioProvider (AudioProvider provider);
+
+// The instrument: no notes; plays the sound track at the video's time while the song plays (or while its own
+// transport plays when not slaved). Its clock is published for the video window.
+class Player;
+std::unique_ptr<Instrument> makeInstrument();
+Player* playerOf (Instrument* instrument) noexcept;
+
+class Player
+{
+public:
+    virtual ~Player() = default;
+    // the video's time the audio thread is at (seconds; < 0 before the delay) and whether it moves
+    virtual double currentTime() const noexcept = 0;
+    virtual bool running() const noexcept = 0;
+    // the player's own transport (not slaved): play from `seconds`, pause, stop (UI thread)
+    virtual void ownPlay (double seconds) noexcept = 0;
+    virtual void ownPause() noexcept = 0;
+    virtual void ownStop() noexcept = 0;
+};
+} // namespace lynx::video

+ 2 - 1
src/engine/ProjectFile.cpp

@@ -119,6 +119,7 @@ const char* instrumentId (InstrumentKind k)
         case InstrumentKind::dashboard: return "dashboard";
         case InstrumentKind::voltage: return "voltage";
         case InstrumentKind::vfx: return "vfx";
+        case InstrumentKind::videoplayer: return "videoplayer";
     }
     return "synth";
 }
@@ -133,7 +134,7 @@ InstrumentKind instrumentFromId (const juce::String& id)
                     InstrumentKind::fruitkick, InstrumentKind::bassdrum, InstrumentKind::toxic,
                     InstrumentKind::threeosc, InstrumentKind::autogun, InstrumentKind::transistorbass,
                     InstrumentKind::simsynth, InstrumentKind::wasp, InstrumentKind::plucked, InstrumentKind::beepmap, InstrumentKind::sawer, InstrumentKind::flkeys,
-                    InstrumentKind::granulizer, InstrumentKind::drumaxx, InstrumentKind::slayer, InstrumentKind::fruitydance, InstrumentKind::directwave, InstrumentKind::midiOut, InstrumentKind::patcher, InstrumentKind::soundfont, InstrumentKind::layer, InstrumentKind::dashboard, InstrumentKind::voltage, InstrumentKind::vfx })
+                    InstrumentKind::granulizer, InstrumentKind::drumaxx, InstrumentKind::slayer, InstrumentKind::fruitydance, InstrumentKind::directwave, InstrumentKind::midiOut, InstrumentKind::patcher, InstrumentKind::soundfont, InstrumentKind::layer, InstrumentKind::dashboard, InstrumentKind::voltage, InstrumentKind::vfx, InstrumentKind::videoplayer })
         if (id == instrumentId (k))
             return k;
 

+ 11 - 0
src/ui/ChannelRackComponent.cpp

@@ -1,4 +1,5 @@
 #include "core/FruityDance.h"
+#include "core/VideoPlayer.h"
 #include "ui/ColourPicker.h"
 #include "ui/PatcherEditor.h"
 #include "ui/UiTrace.h"
@@ -89,6 +90,7 @@ juce::String instrumentName (InstrumentKind k)
         case InstrumentKind::dashboard: return "Dashboard";
         case InstrumentKind::voltage: return "Voltage Controller";
         case InstrumentKind::vfx: return "VFX";
+        case InstrumentKind::videoplayer: return "Fruity Video Player";
     }
     return "?";
 }
@@ -2176,6 +2178,15 @@ void ChannelRackComponent::addInstrumentItems (juce::PopupMenu& menu, int insert
         const auto added = add (c);
         openChannelSettings (engine, added);
     });
+    // FL's Fruity Video Player (round 165g): a video in sync with the song, decoded by the user's ffmpeg
+    menu.addItem ("Fruity Video Player", [this, add] {
+        ChannelDef c;
+        c.name = "Fruity Video Player";
+        c.instrument = InstrumentKind::videoplayer;
+        c.pluginState = video::write (video::Settings {});
+        const auto added = add (c);
+        openChannelSettings (engine, added);
+    });
     // FL's own instrument engines (round 142, issue #5): their editor opens
     {
         juce::PopupMenu engines;

+ 5 - 0
src/ui/ChannelSettings.cpp

@@ -48,6 +48,7 @@
 #include "ui/WaveformView.h"
 #include "ui/SoundFontEditor.h"
 #include "ui/VfxEditors.h"
+#include "ui/VideoPlayerView.h"
 
 namespace lynx
 {
@@ -3215,6 +3216,8 @@ std::unique_ptr<juce::Component> makeInstrumentPage (AudioEngine& engine, const
     const auto kind = def->instrument;
     if (kind == InstrumentKind::fruitydance && ref.index >= 0)
         return makeDanceEditor (engine, ref.index); // round 165e
+    if (kind == InstrumentKind::videoplayer)
+        return makeVideoPlayerEditor (engine, ref.locate, ref.index); // round 165g
     if (kind == InstrumentKind::synth)
         return std::make_unique<SynthPanel> (engine, ref);
     if (isModelKind (kind))
@@ -3421,6 +3424,8 @@ std::unique_ptr<juce::Component> makeChannelSettingsPanel (AudioEngine& engine,
         return makeVfxEditor (engine, channel);
     if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::fruitydance)
         return makeDanceEditor (engine, channel); // round 165e
+    if (engine.getSong().channels[(std::size_t) channel].instrument == InstrumentKind::videoplayer)
+        return makeVideoPlayerEditor (engine, channel); // round 165g
     if (const auto kind = engine.getSong().channels[(std::size_t) channel].instrument;
         kind == InstrumentKind::sakura || kind == InstrumentKind::drumpad || kind == InstrumentKind::boobass
                  || kind == InstrumentKind::drumsynth || kind == InstrumentKind::harmless || kind == InstrumentKind::harmor

+ 112 - 1
src/ui/I18nData.h

@@ -16545,6 +16545,117 @@ inline constexpr unsigned char ptBR[] = {
 110, 116, 114, 97, 100, 97, 32, 97, 110, 116, 101, 115, 32, 100, 101, 32, 111, 32, 100, 101, 45, 101, 115, 115,
 101, 114, 32, 111, 117, 118, 105, 45, 108, 97, 34, 10, 34, 66, 97, 108, 97, 110, 99, 101, 32, 111, 102, 32,
 116, 104, 101, 32, 111, 117, 116, 112, 117, 116, 34, 32, 61, 32, 34, 66, 97, 108, 97, 110, 195, 167, 111, 32,
-100, 97, 32, 115, 97, 195, 173, 100, 97, 34, 10,
+100, 97, 32, 115, 97, 195, 173, 100, 97, 34, 10, 34, 67, 117, 114, 114, 101, 110, 116, 32, 116, 105, 109, 101,
+32, 40, 72, 58, 77, 58, 83, 58, 77, 83, 41, 34, 32, 61, 32, 34, 84, 101, 109, 112, 111, 32, 97, 116,
+117, 97, 108, 32, 40, 72, 58, 77, 58, 83, 58, 77, 83, 41, 34, 10, 34, 67, 117, 114, 114, 101, 110, 116,
+32, 116, 105, 109, 101, 32, 40, 114, 105, 103, 104, 116, 32, 99, 108, 105, 99, 107, 32, 116, 111, 32, 115, 101,
+116, 41, 34, 32, 61, 32, 34, 84, 101, 109, 112, 111, 32, 97, 116, 117, 97, 108, 32, 40, 99, 108, 105, 113,
+117, 101, 32, 100, 105, 114, 101, 105, 116, 111, 32, 112, 97, 114, 97, 32, 100, 101, 102, 105, 110, 105, 114, 41,
+34, 10, 34, 68, 101, 108, 97, 121, 32, 112, 108, 97, 121, 98, 97, 99, 107, 32, 40, 72, 58, 77, 58, 83,
+58, 77, 83, 41, 34, 32, 61, 32, 34, 65, 116, 114, 97, 115, 97, 114, 32, 97, 32, 114, 101, 112, 114, 111,
+100, 117, 195, 167, 195, 163, 111, 32, 40, 72, 58, 77, 58, 83, 58, 77, 83, 41, 34, 10, 34, 68, 101, 108,
+97, 121, 32, 112, 108, 97, 121, 98, 97, 99, 107, 32, 98, 121, 32, 123, 48, 125, 34, 32, 61, 32, 34, 82,
+101, 112, 114, 111, 100, 117, 195, 167, 195, 163, 111, 32, 97, 116, 114, 97, 115, 97, 100, 97, 32, 101, 109, 32,
+123, 48, 125, 34, 10, 34, 68, 101, 108, 97, 121, 32, 112, 108, 97, 121, 98, 97, 99, 107, 32, 117, 110, 116,
+105, 108, 32, 116, 104, 101, 32, 115, 111, 110, 103, 32, 112, 111, 115, 105, 116, 105, 111, 110, 34, 32, 61, 32,
+34, 65, 116, 114, 97, 115, 97, 114, 32, 97, 32, 114, 101, 112, 114, 111, 100, 117, 195, 167, 195, 163, 111, 32,
+97, 116, 195, 169, 32, 97, 32, 112, 111, 115, 105, 195, 167, 195, 163, 111, 32, 100, 97, 32, 109, 195, 186, 115,
+105, 99, 97, 34, 10, 34, 68, 101, 108, 97, 121, 32, 112, 108, 97, 121, 98, 97, 99, 107, 34, 32, 61, 32,
+34, 65, 116, 114, 97, 115, 97, 114, 32, 97, 32, 114, 101, 112, 114, 111, 100, 117, 195, 167, 195, 163, 111, 34,
+10, 34, 68, 111, 99, 107, 32, 99, 111, 110, 116, 114, 111, 108, 32, 112, 97, 110, 101, 108, 34, 32, 61, 32,
+34, 70, 105, 120, 97, 114, 32, 111, 32, 112, 97, 105, 110, 101, 108, 32, 100, 101, 32, 99, 111, 110, 116, 114,
+111, 108, 101, 34, 10, 34, 69, 110, 97, 98, 108, 101, 32, 97, 117, 100, 105, 111, 34, 32, 61, 32, 34, 65,
+116, 105, 118, 97, 114, 32, 111, 32, 195, 161, 117, 100, 105, 111, 34, 10, 34, 69, 110, 100, 32, 116, 105, 109,
+101, 32, 40, 72, 58, 77, 58, 83, 58, 77, 83, 41, 34, 32, 61, 32, 34, 84, 101, 109, 112, 111, 32, 102,
+105, 110, 97, 108, 32, 40, 72, 58, 77, 58, 83, 58, 77, 83, 41, 34, 10, 34, 69, 110, 100, 32, 116, 105,
+109, 101, 32, 40, 99, 108, 105, 99, 107, 32, 116, 111, 32, 103, 111, 32, 116, 111, 44, 32, 114, 105, 103, 104,
+116, 32, 99, 108, 105, 99, 107, 32, 116, 111, 32, 115, 101, 116, 41, 34, 32, 61, 32, 34, 84, 101, 109, 112,
+111, 32, 102, 105, 110, 97, 108, 32, 40, 99, 108, 105, 113, 117, 101, 32, 112, 97, 114, 97, 32, 105, 114, 32,
+97, 116, 195, 169, 32, 101, 108, 101, 44, 32, 99, 108, 105, 113, 117, 101, 32, 100, 105, 114, 101, 105, 116, 111,
+32, 112, 97, 114, 97, 32, 100, 101, 102, 105, 110, 105, 114, 41, 34, 10, 34, 69, 120, 116, 114, 97, 99, 116,
+105, 110, 103, 32, 116, 104, 101, 32, 115, 111, 117, 110, 100, 46, 46, 46, 34, 32, 61, 32, 34, 69, 120, 116,
+114, 97, 105, 110, 100, 111, 32, 111, 32, 115, 111, 109, 46, 46, 46, 34, 10, 34, 72, 111, 115, 116, 34, 32,
+61, 32, 34, 72, 111, 115, 116, 34, 10, 34, 72, 111, 117, 114, 115, 58, 77, 105, 110, 117, 116, 101, 115, 58,
+83, 101, 99, 111, 110, 100, 115, 58, 77, 115, 34, 32, 61, 32, 34, 72, 111, 114, 97, 115, 58, 77, 105, 110,
+117, 116, 111, 115, 58, 83, 101, 103, 117, 110, 100, 111, 115, 58, 77, 115, 34, 10, 34, 73, 103, 110, 111, 114,
+101, 32, 116, 101, 109, 112, 111, 32, 99, 104, 97, 110, 103, 101, 115, 34, 32, 61, 32, 34, 73, 103, 110, 111,
+114, 97, 114, 32, 109, 117, 100, 97, 110, 195, 167, 97, 115, 32, 100, 101, 32, 97, 110, 100, 97, 109, 101, 110,
+116, 111, 34, 10, 34, 75, 101, 101, 112, 32, 97, 115, 112, 101, 99, 116, 32, 114, 97, 116, 105, 111, 34, 32,
+61, 32, 34, 77, 97, 110, 116, 101, 114, 32, 97, 32, 112, 114, 111, 112, 111, 114, 195, 167, 195, 163, 111, 34,
+10, 34, 76, 111, 97, 100, 32, 97, 32, 118, 105, 100, 101, 111, 32, 102, 105, 108, 101, 32, 40, 111, 114, 32,
+100, 114, 111, 112, 32, 111, 110, 101, 32, 104, 101, 114, 101, 41, 34, 32, 61, 32, 34, 67, 97, 114, 114, 101,
+103, 117, 101, 32, 117, 109, 32, 97, 114, 113, 117, 105, 118, 111, 32, 100, 101, 32, 118, 195, 173, 100, 101, 111,
+32, 40, 111, 117, 32, 115, 111, 108, 116, 101, 32, 117, 109, 32, 97, 113, 117, 105, 41, 34, 10, 34, 76, 111,
+97, 100, 32, 118, 105, 100, 101, 111, 32, 102, 105, 108, 101, 46, 46, 46, 34, 32, 61, 32, 34, 67, 97, 114,
+114, 101, 103, 97, 114, 32, 97, 114, 113, 117, 105, 118, 111, 32, 100, 101, 32, 118, 195, 173, 100, 101, 111, 46,
+46, 46, 34, 10, 34, 77, 117, 116, 101, 32, 97, 117, 100, 105, 111, 34, 32, 61, 32, 34, 83, 105, 108, 101,
+110, 99, 105, 97, 114, 32, 111, 32, 195, 161, 117, 100, 105, 111, 34, 10, 34, 78, 111, 32, 100, 101, 108, 97,
+121, 34, 32, 61, 32, 34, 83, 101, 109, 32, 97, 116, 114, 97, 115, 111, 34, 10, 34, 78, 111, 32, 118, 105,
+100, 101, 111, 34, 32, 61, 32, 34, 83, 101, 109, 32, 118, 195, 173, 100, 101, 111, 34, 10, 34, 80, 108, 117,
+103, 105, 110, 32, 111, 112, 116, 105, 111, 110, 115, 34, 32, 61, 32, 34, 79, 112, 195, 167, 195, 181, 101, 115,
+32, 100, 111, 32, 112, 108, 117, 103, 105, 110, 34, 10, 34, 83, 101, 110, 100, 32, 97, 117, 100, 105, 111, 32,
+116, 111, 32, 112, 108, 97, 121, 108, 105, 115, 116, 34, 32, 61, 32, 34, 69, 110, 118, 105, 97, 114, 32, 111,
+32, 195, 161, 117, 100, 105, 111, 32, 112, 97, 114, 97, 32, 97, 32, 112, 108, 97, 121, 108, 105, 115, 116, 34,
+10, 34, 83, 101, 116, 32, 99, 117, 114, 114, 101, 110, 116, 32, 112, 111, 115, 105, 116, 105, 111, 110, 32, 97,
+115, 32, 101, 110, 100, 32, 116, 105, 109, 101, 34, 32, 61, 32, 34, 85, 115, 97, 114, 32, 97, 32, 112, 111,
+115, 105, 195, 167, 195, 163, 111, 32, 97, 116, 117, 97, 108, 32, 99, 111, 109, 111, 32, 116, 101, 109, 112, 111,
+32, 102, 105, 110, 97, 108, 34, 10, 34, 83, 101, 116, 32, 99, 117, 114, 114, 101, 110, 116, 32, 112, 111, 115,
+105, 116, 105, 111, 110, 32, 97, 115, 32, 115, 116, 97, 114, 116, 32, 116, 105, 109, 101, 34, 32, 61, 32, 34,
+85, 115, 97, 114, 32, 97, 32, 112, 111, 115, 105, 195, 167, 195, 163, 111, 32, 97, 116, 117, 97, 108, 32, 99,
+111, 109, 111, 32, 116, 101, 109, 112, 111, 32, 105, 110, 105, 99, 105, 97, 108, 34, 10, 34, 83, 101, 116, 46,
+46, 46, 34, 32, 61, 32, 34, 68, 101, 102, 105, 110, 105, 114, 46, 46, 46, 34, 10, 34, 83, 104, 111, 119,
+32, 116, 104, 101, 32, 118, 105, 100, 101, 111, 32, 105, 110, 32, 105, 116, 115, 32, 111, 119, 110, 32, 119, 105,
+110, 100, 111, 119, 32, 40, 100, 111, 117, 98, 108, 101, 45, 99, 108, 105, 99, 107, 32, 116, 104, 101, 32, 118,
+105, 100, 101, 111, 41, 34, 32, 61, 32, 34, 77, 111, 115, 116, 114, 97, 114, 32, 111, 32, 118, 195, 173, 100,
+101, 111, 32, 110, 117, 109, 97, 32, 106, 97, 110, 101, 108, 97, 32, 112, 114, 195, 179, 112, 114, 105, 97, 32,
+40, 99, 108, 105, 113, 117, 101, 32, 100, 117, 112, 108, 111, 32, 110, 111, 32, 118, 195, 173, 100, 101, 111, 41,
+34, 10, 34, 83, 108, 97, 118, 101, 32, 112, 108, 97, 121, 98, 97, 99, 107, 32, 116, 111, 32, 104, 111, 115,
+116, 58, 32, 116, 104, 101, 32, 115, 111, 110, 103, 32, 112, 111, 115, 105, 116, 105, 111, 110, 32, 100, 114, 105,
+118, 101, 115, 32, 116, 104, 101, 32, 118, 105, 100, 101, 111, 32, 40, 111, 102, 102, 58, 32, 116, 104, 101, 32,
+112, 108, 97, 121, 101, 114, 39, 115, 32, 111, 119, 110, 32, 80, 108, 97, 121, 32, 47, 32, 83, 116, 111, 112,
+41, 34, 32, 61, 32, 34, 82, 101, 112, 114, 111, 100, 117, 195, 167, 195, 163, 111, 32, 101, 115, 99, 114, 97,
+118, 97, 32, 100, 111, 32, 104, 111, 115, 116, 58, 32, 97, 32, 112, 111, 115, 105, 195, 167, 195, 163, 111, 32,
+100, 97, 32, 109, 195, 186, 115, 105, 99, 97, 32, 99, 111, 110, 100, 117, 122, 32, 111, 32, 118, 195, 173, 100,
+101, 111, 32, 40, 100, 101, 115, 108, 105, 103, 97, 100, 111, 58, 32, 111, 32, 80, 108, 97, 121, 32, 47, 32,
+83, 116, 111, 112, 32, 100, 111, 32, 112, 114, 195, 179, 112, 114, 105, 111, 32, 112, 108, 97, 121, 101, 114, 41,
+34, 10, 34, 83, 116, 97, 114, 116, 32, 116, 105, 109, 101, 32, 40, 72, 58, 77, 58, 83, 58, 77, 83, 41,
+34, 32, 61, 32, 34, 84, 101, 109, 112, 111, 32, 105, 110, 105, 99, 105, 97, 108, 32, 40, 72, 58, 77, 58,
+83, 58, 77, 83, 41, 34, 10, 34, 83, 116, 97, 114, 116, 32, 116, 105, 109, 101, 32, 40, 99, 108, 105, 99,
+107, 32, 116, 111, 32, 103, 111, 32, 116, 111, 44, 32, 114, 105, 103, 104, 116, 32, 99, 108, 105, 99, 107, 32,
+116, 111, 32, 115, 101, 116, 41, 34, 32, 61, 32, 34, 84, 101, 109, 112, 111, 32, 105, 110, 105, 99, 105, 97,
+108, 32, 40, 99, 108, 105, 113, 117, 101, 32, 112, 97, 114, 97, 32, 105, 114, 32, 97, 116, 195, 169, 32, 101,
+108, 101, 44, 32, 99, 108, 105, 113, 117, 101, 32, 100, 105, 114, 101, 105, 116, 111, 32, 112, 97, 114, 97, 32,
+100, 101, 102, 105, 110, 105, 114, 41, 34, 10, 34, 84, 104, 101, 32, 118, 105, 100, 101, 111, 32, 105, 115, 32,
+105, 110, 32, 105, 116, 115, 32, 111, 119, 110, 32, 119, 105, 110, 100, 111, 119, 34, 32, 61, 32, 34, 79, 32,
+118, 195, 173, 100, 101, 111, 32, 101, 115, 116, 195, 161, 32, 110, 97, 32, 115, 117, 97, 32, 112, 114, 195, 179,
+112, 114, 105, 97, 32, 106, 97, 110, 101, 108, 97, 34, 10, 34, 84, 104, 101, 32, 118, 105, 100, 101, 111, 32,
+115, 116, 97, 114, 116, 115, 32, 119, 104, 101, 110, 32, 116, 104, 101, 32, 115, 111, 110, 103, 32, 114, 101, 97,
+99, 104, 101, 115, 32, 116, 104, 105, 115, 32, 116, 105, 109, 101, 46, 34, 32, 61, 32, 34, 79, 32, 118, 195,
+173, 100, 101, 111, 32, 99, 111, 109, 101, 195, 167, 97, 32, 113, 117, 97, 110, 100, 111, 32, 97, 32, 109, 195,
+186, 115, 105, 99, 97, 32, 99, 104, 101, 103, 97, 32, 97, 32, 101, 115, 116, 101, 32, 116, 101, 109, 112, 111,
+46, 34, 10, 34, 84, 104, 101, 32, 118, 105, 100, 101, 111, 32, 119, 97, 115, 32, 110, 111, 116, 32, 102, 111,
+117, 110, 100, 58, 34, 32, 61, 32, 34, 79, 32, 118, 195, 173, 100, 101, 111, 32, 110, 195, 163, 111, 32, 102,
+111, 105, 32, 101, 110, 99, 111, 110, 116, 114, 97, 100, 111, 58, 34, 10, 34, 84, 105, 109, 101, 32, 100, 105,
+115, 112, 108, 97, 121, 34, 32, 61, 32, 34, 69, 120, 105, 98, 105, 195, 167, 195, 163, 111, 32, 100, 111, 32,
+116, 101, 109, 112, 111, 34, 10, 34, 86, 105, 100, 101, 111, 32, 112, 111, 115, 105, 116, 105, 111, 110, 32, 40,
+117, 115, 101, 32, 108, 101, 102, 116, 47, 114, 105, 103, 104, 116, 32, 107, 101, 121, 115, 32, 102, 111, 114, 32,
+112, 114, 101, 118, 105, 111, 117, 115, 47, 110, 101, 120, 116, 32, 102, 114, 97, 109, 101, 41, 34, 32, 61, 32,
+34, 80, 111, 115, 105, 195, 167, 195, 163, 111, 32, 100, 111, 32, 118, 195, 173, 100, 101, 111, 32, 40, 115, 101,
+116, 97, 115, 32, 101, 115, 113, 117, 101, 114, 100, 97, 47, 100, 105, 114, 101, 105, 116, 97, 32, 112, 97, 114,
+97, 32, 111, 32, 113, 117, 97, 100, 114, 111, 32, 97, 110, 116, 101, 114, 105, 111, 114, 47, 115, 101, 103, 117,
+105, 110, 116, 101, 41, 34, 10, 34, 97, 117, 100, 105, 111, 34, 32, 61, 32, 34, 195, 161, 117, 100, 105, 111,
+34, 10, 34, 102, 102, 109, 112, 101, 103, 32, 99, 111, 117, 108, 100, 32, 110, 111, 116, 32, 114, 101, 97, 100,
+32, 97, 32, 118, 105, 100, 101, 111, 32, 105, 110, 32, 116, 104, 105, 115, 32, 102, 105, 108, 101, 34, 32, 61,
+32, 34, 79, 32, 102, 102, 109, 112, 101, 103, 32, 110, 195, 163, 111, 32, 99, 111, 110, 115, 101, 103, 117, 105,
+117, 32, 108, 101, 114, 32, 117, 109, 32, 118, 195, 173, 100, 101, 111, 32, 110, 101, 115, 116, 101, 32, 97, 114,
+113, 117, 105, 118, 111, 34, 10, 34, 102, 102, 109, 112, 101, 103, 32, 119, 97, 115, 32, 110, 111, 116, 32, 102,
+111, 117, 110, 100, 46, 32, 76, 89, 78, 88, 32, 112, 108, 97, 121, 115, 32, 118, 105, 100, 101, 111, 115, 32,
+119, 105, 116, 104, 32, 102, 102, 109, 112, 101, 103, 58, 32, 105, 110, 115, 116, 97, 108, 108, 32, 105, 116, 32,
+111, 114, 32, 108, 111, 99, 97, 116, 101, 32, 105, 116, 46, 34, 32, 61, 32, 34, 79, 32, 102, 102, 109, 112,
+101, 103, 32, 110, 195, 163, 111, 32, 102, 111, 105, 32, 101, 110, 99, 111, 110, 116, 114, 97, 100, 111, 46, 32,
+79, 32, 76, 89, 78, 88, 32, 114, 101, 112, 114, 111, 100, 117, 122, 32, 118, 195, 173, 100, 101, 111, 115, 32,
+99, 111, 109, 32, 111, 32, 102, 102, 109, 112, 101, 103, 58, 32, 105, 110, 115, 116, 97, 108, 101, 45, 111, 32,
+111, 117, 32, 108, 111, 99, 97, 108, 105, 122, 101, 45, 111, 46, 34, 10, 34, 110, 111, 32, 115, 111, 117, 110,
+100, 34, 32, 61, 32, 34, 115, 101, 109, 32, 115, 111, 109, 34, 10,
 };
 } // namespace lynx::i18n::data

+ 9 - 1
src/ui/PatcherEditor.cpp

@@ -1,7 +1,9 @@
+#include "ui/VideoPlayerView.h"
 #include "ui/PatcherEditor.h"
 #include "ui/VisualEditors.h"
 #include "ui/FlExtraEditors.h"
 #include "core/ControlSurface.h"
+#include "core/VideoPlayer.h"
 #include "core/VoltageController.h"
 #include "ui/VoltageEditor.h"
 #include "core/XyController.h"
@@ -1292,6 +1294,7 @@ public:
         builtIn ("MIDI", InstrumentKind::midiOut, "MIDI Out", [] (ChannelDef& c) { midictl::writeMidiOut (c.pluginState, midictl::MidiOutSettings {}); });
         builtIn ("Misc", InstrumentKind::layer, tr ("Layer")); // round 165c: plays the generators on its Children pin
         builtIn ("Misc", InstrumentKind::soundfont, "LYNX Soundfont", [] (ChannelDef& c) { c = sf::makeChannel(); });
+        builtIn ("Visual", InstrumentKind::videoplayer, "Fruity Video Player", [] (ChannelDef& c) { c.pluginState = video::write (video::Settings {}); });
         builtIn ("Patcher", InstrumentKind::patcher, "Patcher");
         builtIn ("Synth classic", InstrumentKind::synth, tr ("Synth"));
         generators[tr ("Sampler")].push_back ({ tr ("Sampler (choose file)..."), true, [this, at] { chooseSampleNode (at); } });
@@ -1376,7 +1379,7 @@ public:
                 }
             }
         };
-        side (tr ("Generators"), true, generators, { "Controller", "Drum", "MIDI", "Misc", "Patcher", "Sampler", "Synth classic", "Synth special" },
+        side (tr ("Generators"), true, generators, { "Controller", "Drum", "MIDI", "Misc", "Patcher", "Sampler", "Synth classic", "Synth special", "Visual" },
               pluginInstruments);
         add.addColumnBreak();
         rows = 0.0f;
@@ -1901,6 +1904,11 @@ private:
             openToolWindow (makeVoltageControllerEditor (engine, locate), title + " - " + tr ("Patcher"), target.key() + "-node-" + juce::String (n));
             return;
         }
+        if (node.generator && node.channel.instrument == InstrumentKind::videoplayer) // round 165g
+        {
+            openToolWindow (makeVideoPlayerEditor (engine, locate, -1), title + " - " + tr ("Patcher"), target.key() + "-node-" + juce::String (n));
+            return;
+        }
         if (node.generator && node.channel.instrument == InstrumentKind::midiOut)
         {
             openToolWindow (makeMidiOutEditor (engine, locate), title + " - " + tr ("Patcher"), target.key() + "-node-" + juce::String (n));

+ 8 - 0
src/ui/QuickAddPalette.cpp

@@ -1,5 +1,6 @@
 #include "ui/QuickAddPalette.h"
 #include "core/ControlSurface.h"
+#include "core/VideoPlayer.h"
 #include "core/VoltageController.h"
 
 #include "core/Effects.h"
@@ -152,6 +153,13 @@ public:
                                         c.pluginState = voltage::write (voltage::Settings {});
                                         targets.addInstrument (c);
                                     } });
+        instruments.all.push_back ({ "Fruity Video Player", tr ("built-in"), [this] {
+                                        ChannelDef c;
+                                        c.name = "Fruity Video Player";
+                                        c.instrument = InstrumentKind::videoplayer;
+                                        c.pluginState = video::write (video::Settings {});
+                                        targets.addInstrument (c);
+                                    } });
 
         // FL's own instrument engines (round 142): those this PC can make (the user's FL installation)
         for (const auto& e : natives::instrumentEngines())

+ 8 - 0
src/ui/QuickPick.cpp

@@ -5,6 +5,7 @@
 #include "core/ControlSurface.h"
 #include "core/NativeEngines.h"
 #include "core/Preferences.h"
+#include "core/VideoPlayer.h"
 #include "core/VoltageController.h"
 #include "core/Vfx.h"
 #include "engine/PluginHost.h"
@@ -52,6 +53,13 @@ std::vector<GeneratorEntry> generatorEntries (AudioEngine& engine)
         c.pluginState = voltage::write (voltage::Settings {});
         return std::optional<ChannelDef> (c);
     });
+    add ("Fruity Video Player", "Fruity Video Player", tr ("built-in"), 0, [] {
+        ChannelDef c;
+        c.name = "Fruity Video Player";
+        c.instrument = InstrumentKind::videoplayer;
+        c.pluginState = video::write (video::Settings {});
+        return std::optional<ChannelDef> (c);
+    });
 
     const auto& fl = flStudioAccess();
     for (const auto& e : natives::instrumentEngines())

+ 1348 - 0
src/ui/VideoPlayerView.cpp

@@ -0,0 +1,1348 @@
+#include "ui/VideoPlayerView.h"
+
+#include <algorithm>
+#include <atomic>
+#include <cmath>
+#include <map>
+#include <mutex>
+#include <cstring>
+#include <thread>
+
+#include "core/VideoPlayer.h"
+#include "engine/AudioEngine.h"
+#include "platform/Paths.h"
+#include "ui/ControllerKnob.h"
+#include "ui/I18n.h"
+#include "ui/Theme.h"
+#include "ui/ValueControl.h"
+#include "ui/VisualEditors.h"
+
+namespace lynx
+{
+namespace
+{
+juce::File resolveVideo (const std::string& path)
+{
+    if (path.empty())
+        return {};
+    return platform::localFile (path);
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// ffmpeg's report (stderr of "ffmpeg -i"), per path
+struct Probe
+{
+    juce::String report;
+    video::Info info;
+};
+
+std::mutex probeLock;
+std::map<juce::String, Probe> probes;
+
+Probe probe (const juce::String& path)
+{
+    {
+        std::lock_guard<std::mutex> lock (probeLock);
+        if (const auto it = probes.find (path); it != probes.end())
+            return it->second;
+    }
+    Probe p;
+    const auto ffmpeg = findFfmpeg();
+    if (ffmpeg.existsAsFile() && juce::File (path).existsAsFile())
+    {
+        juce::ChildProcess process;
+        if (process.start (juce::StringArray { ffmpeg.getFullPathName(), "-hide_banner", "-nostdin", "-i", path }, juce::ChildProcess::wantStdErr))
+        {
+            p.report = process.readAllProcessOutput();
+            process.waitForProcessToFinish (2000);
+        }
+        p.info = video::parseFfmpegReport (p.report.toStdString());
+        std::lock_guard<std::mutex> lock (probeLock);
+        probes[path] = p; // (not cached without ffmpeg / the file: they may appear later)
+    }
+    return p;
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// The sound tracks (48 kHz stereo int16), decoded once per video in the background
+constexpr double trackRate = 48000.0;
+
+std::shared_ptr<const video::AudioTrack> decodeTrack (const juce::File& file)
+{
+    const auto ffmpeg = findFfmpeg();
+    if (! ffmpeg.existsAsFile() || ! file.existsAsFile())
+        return nullptr;
+    const auto info = probe (file.getFullPathName()).info;
+    if (! info.hasAudio)
+        return nullptr;
+    juce::ChildProcess process;
+    if (! process.start (juce::StringArray { ffmpeg.getFullPathName(), "-nostdin", "-v", "quiet", "-i", file.getFullPathName(), "-vn", "-sn",
+                                             "-ac", "2", "-ar", juce::String ((int) trackRate), "-f", "s16le", "-" },
+                         juce::ChildProcess::wantStdOut))
+        return nullptr;
+    auto track = std::make_shared<video::AudioTrack>();
+    track->rate = trackRate;
+    if (info.duration > 0.0)
+        track->samples.reserve ((std::size_t) (info.duration * trackRate * 2.0) + 4096);
+    std::vector<char> bytes;
+    char buffer[1 << 16];
+    std::size_t odd = 0; // a byte of a sample split between two reads
+    char carry = 0;
+    for (;;)
+    {
+        const auto got = process.readProcessOutput (buffer, (int) sizeof (buffer));
+        if (got <= 0)
+            break;
+        int i = 0;
+        if (odd != 0)
+        {
+            const auto lo = (unsigned char) carry, hi = (unsigned char) buffer[0];
+            track->samples.push_back ((std::int16_t) (lo | (hi << 8)));
+            odd = 0;
+            i = 1;
+        }
+        for (; i + 1 < got; i += 2)
+            track->samples.push_back ((std::int16_t) ((unsigned char) buffer[i] | ((unsigned char) buffer[i + 1] << 8)));
+        if (i < got)
+        {
+            carry = buffer[i];
+            odd = 1;
+        }
+    }
+    process.waitForProcessToFinish (2000);
+    if (track->samples.size() % 2 != 0)
+        track->samples.pop_back();
+    if (track->samples.empty())
+        return nullptr;
+    return track;
+}
+
+struct TrackEntry
+{
+    std::shared_ptr<const video::AudioTrack> track;
+    bool pending = false, done = false;
+};
+
+std::mutex trackLock;
+std::map<std::string, TrackEntry> tracks;
+AudioEngine* installedEngine = nullptr;
+juce::ThreadPool& trackPool()
+{
+    static juce::ThreadPool pool (1);
+    return pool;
+}
+
+std::shared_ptr<const video::AudioTrack> provideTrack (const std::string& path, bool wait)
+{
+    {
+        std::lock_guard<std::mutex> lock (trackLock);
+        auto& e = tracks[path];
+        if (e.done)
+            return e.track;
+        if (! wait)
+        {
+            if (! e.pending)
+            {
+                e.pending = true;
+                trackPool().addJob ([path] {
+                    auto track = decodeTrack (resolveVideo (path));
+                    {
+                        std::lock_guard<std::mutex> l (trackLock);
+                        auto& entry = tracks[path];
+                        entry.track = track;
+                        entry.done = true;
+                        entry.pending = false;
+                    }
+                    // the channel's instrument takes it at the next snapshot
+                    juce::MessageManager::callAsync ([] {
+                        if (installedEngine != nullptr)
+                            installedEngine->editSong ([] (Song&) {}, false);
+                    });
+                });
+            }
+            return nullptr;
+        }
+    }
+    // exporting: decode now (the export must have the sound)
+    auto track = decodeTrack (resolveVideo (path));
+    std::lock_guard<std::mutex> lock (trackLock);
+    auto& e = tracks[path];
+    if (! e.done)
+    {
+        e.track = track;
+        e.done = true;
+    }
+    return e.track;
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// The frames: ffmpeg decodes from the wanted time at the shown size (BGRA), one process per stretch of playback;
+// a still (stopped transport) is one frame.
+class FrameDecoder final : public juce::Thread
+{
+public:
+    FrameDecoder() : juce::Thread ("LYNX video frames") {}
+    ~FrameDecoder() override
+    {
+        signalThreadShouldExit();
+        notify();
+        {
+            std::lock_guard<std::mutex> lock (procLock);
+            if (process != nullptr)
+                process->kill(); // (our own child process)
+        }
+        stopThread (4000);
+    }
+
+    void setSource (const juce::String& p, const video::Info& i)
+    {
+        std::lock_guard<std::mutex> lock (want);
+        if (p == path)
+            return;
+        path = p;
+        info = i;
+        restart = true;
+        notify();
+    }
+
+    void setSize (int w, int h)
+    {
+        std::lock_guard<std::mutex> lock (want);
+        w = juce::jlimit (16, 1920, w & ~1);
+        h = juce::jlimit (16, 1080, h & ~1);
+        if (w == width && h == height)
+            return;
+        width = w;
+        height = h;
+        restart = true;
+        notify();
+    }
+
+    // the time to show (seconds) and whether it moves
+    void request (double t, bool moving)
+    {
+        std::lock_guard<std::mutex> lock (want);
+        if (std::abs (t - wantTime) < 1e-6 && moving == wantMoving)
+            return;
+        wantTime = t;
+        wantMoving = moving;
+        notify();
+    }
+
+    // the latest frame (UI thread)
+    juce::Image frame (double& time)
+    {
+        std::lock_guard<std::mutex> lock (out);
+        time = shownTime;
+        return shown;
+    }
+
+    int frameCount() const noexcept { return frames.load(); }
+
+    void run() override
+    {
+        double streamStart = -1.0, nextTime = 0.0, eofTime = -1.0, fps = 30.0;
+        int w = 0, h = 0;
+        bool streaming = false;
+        juce::String current;
+        std::vector<std::uint8_t> bytes;
+        while (! threadShouldExit())
+        {
+            double t;
+            bool moving, fresh;
+            juce::String p;
+            {
+                std::lock_guard<std::mutex> lock (want);
+                t = juce::jmax (0.0, wantTime);
+                moving = wantMoving;
+                fresh = restart;
+                restart = false;
+                p = path;
+                if (fresh)
+                {
+                    w = width;
+                    h = height;
+                    fps = info.fps > 1.0 && info.fps < 240.0 ? info.fps : 30.0;
+                }
+            }
+            if (p.isEmpty() || w <= 0 || h <= 0)
+            {
+                stopProcess();
+                streaming = false;
+                wait (100);
+                continue;
+            }
+            const auto frameTime = 1.0 / fps;
+            if (fresh || p != current)
+            {
+                eofTime = -1.0;
+                lastShown = -1e9;
+            }
+            bytes.resize ((std::size_t) w * (std::size_t) h * 4);
+            if (! moving)
+            {
+                // a still: one frame at t (once)
+                if (std::abs (t - lastShown) < frameTime * 0.5)
+                {
+                    if (streaming)
+                    {
+                        stopProcess();
+                        streaming = false;
+                    }
+                    wait (50);
+                    continue;
+                }
+                startProcess (p, t, w, h, fps, false);
+                current = p;
+                streaming = false;
+                if (readFrame (bytes))
+                    publish (bytes, w, h, t);
+                lastShown = t; // (past the end: the last frame stays)
+                stopProcess();
+                continue;
+            }
+            // playing: one ffmpeg per stretch; started again when the time jumps
+            if (! streaming && eofTime >= 0.0 && p == current && t >= eofTime - frameTime)
+            {
+                wait (50); // past the video's end
+                continue;
+            }
+            if (! streaming || p != current || t < streamStart - 1e-3 || t > nextTime + 1.0)
+            {
+                startProcess (p, t, w, h, fps, true);
+                current = p;
+                streamStart = nextTime = t;
+                eofTime = -1.0;
+                streaming = process != nullptr;
+                if (! streaming)
+                {
+                    wait (200);
+                    continue;
+                }
+            }
+            if (nextTime > t + 0.04)
+            {
+                wait (juce::jlimit (2, 30, (int) ((nextTime - t - 0.04) * 1000.0)));
+                continue;
+            }
+            if (! readFrame (bytes))
+            {
+                stopProcess();
+                streaming = false;
+                eofTime = nextTime;
+                continue;
+            }
+            const auto ft = nextTime;
+            nextTime += frameTime;
+            if (nextTime <= t)
+                continue; // late: on to the frame of now
+            publish (bytes, w, h, ft);
+            lastShown = ft;
+        }
+        stopProcess();
+    }
+
+private:
+    void startProcess (const juce::String& p, double t, int w, int h, double fps, bool moving)
+    {
+        stopProcess();
+        const auto ffmpeg = findFfmpeg();
+        if (! ffmpeg.existsAsFile())
+            return;
+        juce::StringArray args { ffmpeg.getFullPathName(), "-nostdin", "-v", "quiet", "-ss", juce::String (t, 3), "-i", p, "-an", "-sn" };
+        if (! moving)
+            args.addArray ({ "-frames:v", "1" });
+        args.addArray ({ "-vf", "fps=" + juce::String (fps, 6) + ",scale=" + juce::String (w) + ":" + juce::String (h) + ":flags=bilinear",
+                         "-pix_fmt", "bgra", "-f", "rawvideo", "-" });
+        auto proc = std::make_unique<juce::ChildProcess>();
+        if (! proc->start (args, juce::ChildProcess::wantStdOut))
+            return;
+        std::lock_guard<std::mutex> lock (procLock);
+        process = std::move (proc);
+    }
+
+    void stopProcess()
+    {
+        std::unique_ptr<juce::ChildProcess> old;
+        {
+            std::lock_guard<std::mutex> lock (procLock);
+            old = std::move (process);
+        }
+        if (old != nullptr && old->isRunning())
+            old->kill();
+    }
+
+    bool readFrame (std::vector<std::uint8_t>& bytes)
+    {
+        std::size_t got = 0;
+        while (got < bytes.size() && ! threadShouldExit())
+        {
+            juce::ChildProcess* p;
+            {
+                std::lock_guard<std::mutex> lock (procLock);
+                p = process.get();
+            }
+            if (p == nullptr)
+                return false;
+            const auto n = p->readProcessOutput (bytes.data() + got, (int) juce::jmin<std::size_t> (bytes.size() - got, 1 << 20));
+            if (n <= 0)
+                return false;
+            got += (std::size_t) n;
+        }
+        return got == bytes.size();
+    }
+
+    void publish (const std::vector<std::uint8_t>& bytes, int w, int h, double t)
+    {
+        if (back.isNull() || back.getWidth() != w || back.getHeight() != h)
+            back = juce::Image (juce::Image::ARGB, w, h, false);
+        {
+            juce::Image::BitmapData data (back, juce::Image::BitmapData::writeOnly);
+            for (int y = 0; y < h; ++y)
+                std::memcpy (data.getLinePointer (y), bytes.data() + (std::size_t) y * (std::size_t) w * 4, (std::size_t) w * 4);
+        }
+        {
+            std::lock_guard<std::mutex> lock (out);
+            std::swap (shown, back);
+            shownTime = t;
+        }
+        if (back.isValid() && (back.getWidth() != w || back.getHeight() != h))
+            back = {};
+        ++frames;
+    }
+
+    std::mutex want, out, procLock;
+    juce::String path;
+    video::Info info;
+    int width = 0, height = 0;
+    double wantTime = 0.0;
+    bool wantMoving = false, restart = false;
+    std::unique_ptr<juce::ChildProcess> process;
+    juce::Image shown, back;
+    double shownTime = -1.0, lastShown = -1e9;
+    std::atomic<int> frames { 0 };
+};
+
+// ---------------------------------------------------------------------------------------------------------------
+// Where the video is drawn (the editor's area or the detached window)
+class VideoSurface final : public juce::Component
+{
+public:
+    std::function<void (juce::Rectangle<int>)> onSize;
+    std::function<void()> onDoubleClick;
+    juce::String message; // drawn when there is no frame
+    bool keepAspect = true;
+    juce::Image image;
+
+    void paint (juce::Graphics& g) override
+    {
+        g.fillAll (juce::Colours::black);
+        if (image.isValid())
+        {
+            const auto area = getLocalBounds().toFloat();
+            if (keepAspect)
+                g.drawImageWithin (image, 0, 0, getWidth(), getHeight(), juce::RectanglePlacement::centred, false);
+            else
+                g.drawImage (image, area);
+            return;
+        }
+        g.setColour (theme::colour::textSecondary);
+        g.setFont (theme::font (theme::type::body));
+        g.drawFittedText (message, getLocalBounds().reduced (16), juce::Justification::centred, 4);
+    }
+
+    void resized() override
+    {
+        if (onSize)
+            onSize (getLocalBounds());
+    }
+
+    void mouseDoubleClick (const juce::MouseEvent&) override
+    {
+        if (onDoubleClick)
+            onDoubleClick();
+    }
+};
+
+// A small icon button (drawn paths, LYNX's style)
+class IconButton final : public juce::Button
+{
+public:
+    enum class Icon { load, options, play, pause, stop, loop, sound, mute, detach, start, end };
+
+    IconButton (Icon i) : juce::Button ({}), icon (i) {}
+    Icon icon;
+
+    void paintButton (juce::Graphics& g, bool over, bool down) override
+    {
+        auto r = getLocalBounds().toFloat().reduced (1.0f);
+        const auto on = getToggleState();
+        g.setColour (down ? theme::colour::bg6 : over ? theme::colour::bg5 : theme::colour::bg4);
+        g.fillRoundedRectangle (r, 4.0f);
+        if (on)
+        {
+            g.setColour (theme::colour::accent);
+            g.drawRoundedRectangle (r.reduced (0.5f), 4.0f, 1.2f);
+        }
+        g.setColour (on ? theme::colour::accent : theme::colour::textPrimary);
+        const auto c = r.getCentre();
+        const auto s = juce::jmin (r.getWidth(), r.getHeight()) * 0.30f;
+        juce::Path p;
+        switch (icon)
+        {
+            case Icon::play:
+                p.addTriangle (c.x - s * 0.8f, c.y - s, c.x - s * 0.8f, c.y + s, c.x + s, c.y);
+                g.fillPath (p);
+                break;
+            case Icon::pause:
+                g.fillRect (juce::Rectangle<float> (c.x - s * 0.8f, c.y - s, s * 0.55f, s * 2.0f));
+                g.fillRect (juce::Rectangle<float> (c.x + s * 0.25f, c.y - s, s * 0.55f, s * 2.0f));
+                break;
+            case Icon::stop:
+                g.fillRect (juce::Rectangle<float> (c.x - s * 0.8f, c.y - s * 0.8f, s * 1.6f, s * 1.6f));
+                break;
+            case Icon::loop:
+                p.addCentredArc (c.x, c.y, s, s * 0.8f, 0.0f, 0.6f, 5.6f, true);
+                g.strokePath (p, juce::PathStrokeType (1.6f));
+                {
+                    juce::Path a;
+                    const auto tip = juce::Point<float> (c.x + s * std::sin (0.6f), c.y - s * 0.8f * std::cos (0.6f));
+                    a.addTriangle (tip.x - s * 0.45f, tip.y - s * 0.35f, tip.x + s * 0.2f, tip.y + s * 0.45f, tip.x + s * 0.4f, tip.y - s * 0.4f);
+                    g.fillPath (a);
+                }
+                break;
+            case Icon::sound:
+            case Icon::mute:
+                p.startNewSubPath (c.x - s, c.y - s * 0.35f);
+                p.lineTo (c.x - s * 0.45f, c.y - s * 0.35f);
+                p.lineTo (c.x + s * 0.15f, c.y - s);
+                p.lineTo (c.x + s * 0.15f, c.y + s);
+                p.lineTo (c.x - s * 0.45f, c.y + s * 0.35f);
+                p.lineTo (c.x - s, c.y + s * 0.35f);
+                p.closeSubPath();
+                g.fillPath (p);
+                if (icon == Icon::mute)
+                {
+                    g.drawLine (c.x + s * 0.4f, c.y - s * 0.45f, c.x + s * 1.1f, c.y + s * 0.45f, 1.6f);
+                    g.drawLine (c.x + s * 0.4f, c.y + s * 0.45f, c.x + s * 1.1f, c.y - s * 0.45f, 1.6f);
+                }
+                else
+                {
+                    juce::Path w;
+                    w.addCentredArc (c.x + s * 0.2f, c.y, s * 0.75f, s * 0.75f, 0.0f, 0.6f, 2.55f, true);
+                    g.strokePath (w, juce::PathStrokeType (1.4f));
+                }
+                break;
+            case Icon::load:
+                p.startNewSubPath (c.x - s * 1.1f, c.y + s * 0.8f);
+                p.lineTo (c.x - s * 1.1f, c.y - s * 0.8f);
+                p.lineTo (c.x - s * 0.3f, c.y - s * 0.8f);
+                p.lineTo (c.x, c.y - s * 0.45f);
+                p.lineTo (c.x + s * 1.1f, c.y - s * 0.45f);
+                p.lineTo (c.x + s * 1.1f, c.y + s * 0.8f);
+                p.closeSubPath();
+                g.strokePath (p, juce::PathStrokeType (1.5f));
+                break;
+            case Icon::options:
+                p.addTriangle (c.x - s * 0.8f, c.y - s * 0.35f, c.x + s * 0.8f, c.y - s * 0.35f, c.x, c.y + s * 0.5f);
+                g.fillPath (p);
+                break;
+            case Icon::detach:
+                g.drawRect (juce::Rectangle<float> (c.x - s, c.y - s * 0.6f, s * 1.5f, s * 1.4f), 1.4f);
+                g.drawLine (c.x - s * 0.1f, c.y + s * 0.1f, c.x + s * 1.0f, c.y - s * 1.0f, 1.4f);
+                g.drawLine (c.x + s * 0.35f, c.y - s * 1.0f, c.x + s * 1.0f, c.y - s * 1.0f, 1.4f);
+                g.drawLine (c.x + s * 1.0f, c.y - s * 1.0f, c.x + s * 1.0f, c.y - s * 0.35f, 1.4f);
+                break;
+            case Icon::start:
+            case Icon::end:
+            {
+                const auto dir = icon == Icon::start ? 1.0f : -1.0f;
+                const auto x = c.x - dir * s * 0.8f;
+                g.drawLine (x, c.y - s, x, c.y + s, 1.6f);
+                p.addTriangle (x + dir * s * 0.3f, c.y, x + dir * s * 1.5f, c.y - s * 0.75f, x + dir * s * 1.5f, c.y + s * 0.75f);
+                g.fillPath (p);
+                break;
+            }
+        }
+    }
+};
+
+// The video position: the whole video, the start…end range, the time now; drag to move
+class TimeRail final : public juce::Component
+{
+public:
+    std::function<void (double)> onSeek; // seconds
+    double duration = 0.0, start = 0.0, end = 0.0, now = 0.0;
+
+    void paint (juce::Graphics& g) override
+    {
+        const auto r = getLocalBounds().toFloat().reduced (6.0f, 0.0f);
+        const auto rail = r.withSizeKeepingCentre (r.getWidth(), 4.0f);
+        g.setColour (theme::colour::bg4);
+        g.fillRoundedRectangle (rail, 2.0f);
+        if (duration <= 0.0)
+            return;
+        const auto x = [&] (double t) { return rail.getX() + (float) (juce::jlimit (0.0, 1.0, t / duration)) * rail.getWidth(); };
+        const auto e = end > 0.0 ? end : duration;
+        g.setColour (theme::colour::accentMuted);
+        g.fillRect (juce::Rectangle<float>::leftTopRightBottom (x (start), rail.getY(), x (e), rail.getBottom()));
+        g.setColour (theme::colour::accent);
+        g.fillRect (juce::Rectangle<float>::leftTopRightBottom (x (start), rail.getY(), x (juce::jlimit (start, e, now)), rail.getBottom()));
+        g.setColour (theme::colour::textSecondary);
+        g.fillRect (juce::Rectangle<float> (x (start) - 1.0f, r.getCentreY() - 7.0f, 2.0f, 14.0f));
+        g.fillRect (juce::Rectangle<float> (x (e) - 1.0f, r.getCentreY() - 7.0f, 2.0f, 14.0f));
+        g.setColour (theme::colour::textPrimary);
+        g.fillEllipse (juce::Rectangle<float> (12.0f, 12.0f).withCentre ({ x (juce::jmax (0.0, now)), r.getCentreY() }));
+    }
+
+    void mouseDown (const juce::MouseEvent& e) override { seekAt (e.x); }
+    void mouseDrag (const juce::MouseEvent& e) override { seekAt (e.x); }
+
+private:
+    void seekAt (int px)
+    {
+        if (duration <= 0.0 || ! onSeek)
+            return;
+        const auto r = getLocalBounds().toFloat().reduced (6.0f, 0.0f);
+        onSeek (juce::jlimit (0.0, duration, (double) (px - r.getX()) / juce::jmax (1.0f, r.getWidth()) * duration));
+    }
+};
+
+class ClickLabel final : public juce::Label
+{
+public:
+    std::function<void()> onLeft, onRight;
+    void mouseDown (const juce::MouseEvent& e) override
+    {
+        if (e.mods.isPopupMenu())
+        {
+            if (onRight)
+                onRight();
+        }
+        else if (onLeft)
+            onLeft();
+    }
+};
+
+std::optional<double> parseTime (const juce::String& typed)
+{
+    // H:M:S:ms, M:S, S (seconds, decimals allowed)
+    auto parts = juce::StringArray::fromTokens (typed.trim(), ":", "");
+    parts.removeEmptyStrings();
+    if (parts.isEmpty() || parts.size() > 4)
+        return std::nullopt;
+    for (const auto& p : parts)
+        if (! p.containsOnly ("0123456789.-"))
+            return std::nullopt;
+    double t = 0.0;
+    if (parts.size() == 4)
+        t = parts[0].getDoubleValue() * 3600.0 + parts[1].getDoubleValue() * 60.0 + parts[2].getDoubleValue() + parts[3].getDoubleValue() / 1000.0;
+    else if (parts.size() == 3)
+        t = parts[0].getDoubleValue() * 3600.0 + parts[1].getDoubleValue() * 60.0 + parts[2].getDoubleValue();
+    else if (parts.size() == 2)
+        t = parts[0].getDoubleValue() * 60.0 + parts[1].getDoubleValue();
+    else
+        t = parts[0].getDoubleValue();
+    return t;
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+class VideoPlayerEditor final : public juce::Component,
+                                public juce::FileDragAndDropTarget,
+                                private juce::Timer,
+                                private juce::ChangeListener
+{
+public:
+    VideoPlayerEditor (AudioEngine& e, std::function<ChannelDef* (Song&)> l, int c) : engine (e), locate (std::move (l)), channel (c)
+    {
+        setWantsKeyboardFocus (true);
+        addAndMakeVisible (surface);
+        surface.onSize = [this] (juce::Rectangle<int> r) {
+            if (window == nullptr)
+                sizeDecoder (r);
+        };
+        surface.onDoubleClick = [this] { detach(); };
+        surface.addMouseListener (this, false);
+
+        auto icon = [this] (IconButton& b, const juce::String& hint, std::function<void()> click) {
+            ui::setHint (b, hint);
+            b.onClick = std::move (click);
+            addAndMakeVisible (b);
+        };
+        icon (loadButton, tr ("Load video file..."), [this] { chooseFile(); });
+        icon (optionsButton, tr ("Plugin options"), [this] { showOptions(); });
+        icon (setStartButton, tr ("Set current position as start time"), [this] { setRange (true, nowTime); });
+        icon (setEndButton, tr ("Set current position as end time"), [this] { setRange (false, nowTime); });
+        icon (loopButton, tr ("Loop"), [this] { edit ([] (video::Settings& s) { s.loop = ! s.loop; }); });
+        icon (playButton, tr ("Play / pause"), [this] { playPause(); });
+        icon (stopButton, tr ("Stop"), [this] { stopPlayback(); });
+        icon (soundButton, tr ("Mute audio"), [this] { edit ([] (video::Settings& s) { s.mute = ! s.mute; }); });
+        icon (detachButton, tr ("Show the video in its own window (double-click the video)"), [this] { detach(); });
+
+        slaveButton.setButtonText (tr ("Host"));
+        slaveButton.setClickingTogglesState (false);
+        slaveButton.setColour (juce::TextButton::buttonOnColourId, theme::colour::accent);
+        slaveButton.onClick = [this] { edit ([] (video::Settings& s) { s.slave = ! s.slave; }); };
+        ui::setHint (slaveButton, tr ("Slave playback to host: the song position drives the video (off: the player's own Play / Stop)"));
+        addAndMakeVisible (slaveButton);
+
+        ui::ValueSpec vol;
+        vol.name = tr ("Volume");
+        vol.minimum = 0.0;
+        vol.maximum = 127.0;
+        vol.interval = 1.0;
+        vol.defaultValue = 100.0;
+        vol.toText = [] (double v) { return juce::String (juce::roundToInt (v / 100.0 * 100.0)) + "%"; };
+        volume = std::make_unique<ctlui::Knob> (&engine, vol, [this] { return (double) settings.volume; },
+                                                [this] (double v) { edit ([v] (video::Settings& s) { s.volume = juce::jlimit (0, 127, juce::roundToInt (v)); }); });
+        volume->shortName = tr ("Vol");
+        addAndMakeVisible (*volume);
+
+        for (auto* lab : { &startLabel, &endLabel, &nowLabel })
+        {
+            lab->setFont (theme::font (theme::type::body));
+            lab->setColour (juce::Label::textColourId, theme::colour::textPrimary);
+            lab->setJustificationType (juce::Justification::centred);
+            addAndMakeVisible (*lab);
+        }
+        nowLabel.setColour (juce::Label::textColourId, theme::colour::accent);
+        ui::setHint (startLabel, tr ("Start time (click to go to, right click to set)"));
+        ui::setHint (endLabel, tr ("End time (click to go to, right click to set)"));
+        ui::setHint (nowLabel, tr ("Current time (right click to set)"));
+        startLabel.onLeft = [this] { seekVideo (seconds (settings.start)); };
+        startLabel.onRight = [this] { typeTime (true); };
+        endLabel.onLeft = [this] { seekVideo (endTime()); };
+        endLabel.onRight = [this] { typeTime (false); };
+        nowLabel.onRight = [this] { typeNow(); };
+
+        rail.onSeek = [this] (double t) { seekVideo (t); };
+        ui::setHint (rail, tr ("Video position (use left/right keys for previous/next frame)"));
+        addAndMakeVisible (rail);
+
+        locateButton.setButtonText (tr ("Locate ffmpeg..."));
+        locateButton.onClick = [this] { chooseFfmpeg(); };
+        addChildComponent (locateButton);
+
+        decoder.startThread (juce::Thread::Priority::low);
+        engine.addChangeListener (this);
+        reload();
+        setSize (600, 420);
+        startTimerHz (30);
+    }
+
+    ~VideoPlayerEditor() override
+    {
+        engine.removeChangeListener (this);
+        window = nullptr;
+    }
+
+    void paint (juce::Graphics& g) override
+    {
+        g.fillAll (theme::colour::bg2);
+        g.setColour (theme::colour::bg3);
+        g.fillRect (panelArea);
+        g.setColour (theme::colour::border);
+        g.drawHorizontalLine (panelArea.getY(), 0.0f, (float) getWidth());
+        if (! info.hasVideo && settings.path.size() > 0)
+        {
+            g.setColour (theme::colour::textSecondary);
+            g.setFont (theme::font (theme::type::small));
+        }
+        g.setColour (theme::colour::textSecondary);
+        g.setFont (theme::font (theme::type::small));
+        g.drawText (statusLine, panelArea.withTrimmedTop (panelArea.getHeight() - 18).reduced (8, 0), juce::Justification::centredLeft);
+    }
+
+    void resized() override
+    {
+        auto r = getLocalBounds();
+        const auto panelHeight = 98;
+        panelArea = r.removeFromBottom (panelHeight);
+        surface.setBounds (r);
+        locateButton.setBounds (r.withSizeKeepingCentre (160, 28).translated (0, 40));
+        auto p = panelArea.reduced (8, 6);
+        auto row1 = p.removeFromTop (22);
+        startLabel.setBounds (row1.removeFromLeft (100));
+        endLabel.setBounds (row1.removeFromRight (100));
+        rail.setBounds (row1.reduced (4, 0));
+        p.removeFromTop (6);
+        auto row2 = p.removeFromTop (34);
+        const auto b = 30;
+        loadButton.setBounds (row2.removeFromLeft (b).withSizeKeepingCentre (b, 28));
+        row2.removeFromLeft (4);
+        optionsButton.setBounds (row2.removeFromLeft (b).withSizeKeepingCentre (b, 28));
+        row2.removeFromLeft (4);
+        detachButton.setBounds (row2.removeFromLeft (b).withSizeKeepingCentre (b, 28));
+        row2.removeFromLeft (10);
+        setStartButton.setBounds (row2.removeFromLeft (b).withSizeKeepingCentre (b, 28));
+        row2.removeFromLeft (4);
+        setEndButton.setBounds (row2.removeFromLeft (b).withSizeKeepingCentre (b, 28));
+        volume->setBounds (row2.removeFromRight (44));
+        row2.removeFromRight (4);
+        soundButton.setBounds (row2.removeFromRight (b).withSizeKeepingCentre (b, 28));
+        row2.removeFromRight (10);
+        slaveButton.setBounds (row2.removeFromRight (52).withSizeKeepingCentre (52, 26));
+        row2.removeFromRight (6);
+        stopButton.setBounds (row2.removeFromRight (b).withSizeKeepingCentre (b, 28));
+        row2.removeFromRight (4);
+        playButton.setBounds (row2.removeFromRight (b).withSizeKeepingCentre (b, 28));
+        row2.removeFromRight (4);
+        loopButton.setBounds (row2.removeFromRight (b).withSizeKeepingCentre (b, 28));
+        nowLabel.setBounds (row2.reduced (6, 2));
+    }
+
+    bool keyPressed (const juce::KeyPress& key) override
+    {
+        const auto frame = 1.0 / (info.fps > 1.0 ? info.fps : 30.0);
+        if (key.isKeyCode (juce::KeyPress::leftKey))
+        {
+            seekVideo (juce::jmax (0.0, nowTime - frame));
+            return true;
+        }
+        if (key.isKeyCode (juce::KeyPress::rightKey))
+        {
+            seekVideo (nowTime + frame);
+            return true;
+        }
+        return false;
+    }
+
+    bool isInterestedInFileDrag (const juce::StringArray& files) override
+    {
+        return files.size() == 1 && juce::File (files[0]).hasFileExtension (videoExtensions);
+    }
+    void filesDropped (const juce::StringArray& files, int, int) override { load (juce::File (files[0])); }
+
+private:
+    static constexpr const char* videoExtensions = "mp4;m4v;mov;avi;mkv;webm;wmv;flv;mpg;mpeg;ts;gif;ogv;3gp";
+
+    static double seconds (std::int64_t units) noexcept { return (double) units / (double) video::unitsPerSecond; }
+    static std::int64_t units (double s) noexcept { return (std::int64_t) std::llround (juce::jmax (0.0, s) * (double) video::unitsPerSecond); }
+    double endTime() const { return settings.end > 0 ? seconds (settings.end) : info.duration; }
+
+    const ChannelDef* def() const { return locate ? locate (const_cast<Song&> (engine.getSong())) : nullptr; }
+
+    void edit (std::function<void (video::Settings&)> change, bool undoable = true)
+    {
+        auto s = settings;
+        change (s);
+        if (s == settings)
+            return;
+        settings = s;
+        const auto state = video::write (s);
+        engine.editSong ([l = locate, state] (Song& song) {
+            if (auto* d = l ? l (song) : nullptr)
+                d->pluginState = state;
+        }, undoable);
+        refreshControls();
+    }
+
+    void reload()
+    {
+        const auto* d = def();
+        if (d == nullptr)
+            return;
+        settings = video::readOrDefault (d->pluginState);
+        const auto file = resolveVideo (settings.path);
+        const auto path = file.getFullPathName();
+        if (path != loadedPath)
+        {
+            loadedPath = path;
+            info = path.isNotEmpty() ? probe (path).info : video::Info {};
+            decoder.setSource (info.hasVideo ? path : juce::String(), info);
+        }
+        refreshControls();
+    }
+
+    void refreshControls()
+    {
+        loopButton.setToggleState (settings.loop, juce::dontSendNotification);
+        slaveButton.setToggleState (settings.slave, juce::dontSendNotification);
+        soundButton.icon = settings.mute ? IconButton::Icon::mute : IconButton::Icon::sound;
+        soundButton.setToggleState (settings.mute, juce::dontSendNotification);
+        surface.keepAspect = settings.keepAspect;
+        const auto noFfmpeg = ! findFfmpeg().existsAsFile();
+        locateButton.setVisible (noFfmpeg);
+        if (noFfmpeg)
+            surface.message = tr ("ffmpeg was not found. LYNX plays videos with ffmpeg: install it or locate it.");
+        else if (settings.path.empty())
+            surface.message = tr ("No video") + "\n" + tr ("Load a video file (or drop one here)");
+        else if (! resolveVideo (settings.path).existsAsFile())
+            surface.message = tr ("The video was not found:") + "\n" + juce::String::fromUTF8 (settings.path.c_str());
+        else if (! info.hasVideo)
+            surface.message = tr ("ffmpeg could not read a video in this file");
+        else
+            surface.message = {};
+        juce::String s;
+        if (info.hasVideo)
+            s << info.width << "x" << info.height << ", " << juce::String (info.fps, 3).trimCharactersAtEnd ("0").trimCharactersAtEnd (".") << " fps, "
+              << juce::String (video::formatTime (info.duration, video::hms, info.fps)) << (info.hasAudio ? "" : ", " + tr ("no sound"));
+        if (settings.delay > 0)
+            s << "  |  " << tr ("Delay playback by {0}", { juce::String (video::formatTime (seconds (settings.delay), settings.timeDisplay, info.fps)) });
+        statusLine = s;
+        rail.duration = info.duration;
+        rail.start = seconds (settings.start);
+        rail.end = settings.end > 0 ? seconds (settings.end) : 0.0;
+        startLabel.setText (video::formatTime (seconds (settings.start), settings.timeDisplay, info.fps), juce::dontSendNotification);
+        endLabel.setText (video::formatTime (endTime(), settings.timeDisplay, info.fps), juce::dontSendNotification);
+        for (auto* b : { &setStartButton, &setEndButton, &loopButton, &playButton, &stopButton })
+            b->setEnabled (info.hasVideo);
+        repaint();
+    }
+
+    video::Player* player() const
+    {
+        if (channel < 0)
+            return nullptr;
+        heldInstrument = engine.getChannelInstrument (channel);
+        return video::playerOf (heldInstrument.get());
+    }
+
+    double songSeconds() const
+    {
+        const auto ticks = engine.getTransport().positionTicks.load();
+        const auto& song = engine.getSong();
+        if (settings.ignoreTempo)
+            return song.secondsForTicks ((std::int64_t) ticks);
+        return ticks / (double) ppq * 60.0 / juce::jmax (1.0, song.bpm);
+    }
+
+    void timerCallback() override
+    {
+        const auto& t = engine.getTransport();
+        bool moving = false;
+        if (settings.slave)
+        {
+            nowTime = video::Clock::videoTime (songSeconds(), settings, info.duration);
+            moving = t.playing.load();
+        }
+        else if (auto* p = player())
+        {
+            nowTime = p->currentTime();
+            moving = p->running();
+        }
+        const auto shownTime = juce::jmax (0.0, nowTime < 0.0 ? seconds (settings.start) : nowTime);
+        if (info.hasVideo)
+            decoder.request (shownTime, moving && nowTime >= 0.0 && (settings.loop || nowTime < endTime() - 1e-3));
+        double ft = 0.0;
+        auto img = decoder.frame (ft);
+        auto* target = window != nullptr ? detachedSurface : &surface;
+        if (target != nullptr && (img.getPixelData() != target->image.getPixelData() || frames != decoder.frameCount()))
+        {
+            frames = decoder.frameCount();
+            target->image = img;
+            target->keepAspect = settings.keepAspect;
+            target->repaint();
+        }
+        if (window != nullptr && surface.image.isValid())
+        {
+            surface.image = {};
+            surface.message = tr ("The video is in its own window");
+            surface.repaint();
+        }
+        playButton.icon = moving ? IconButton::Icon::pause : IconButton::Icon::play;
+        playButton.repaint();
+        nowLabel.setText (video::formatTime (nowTime, settings.timeDisplay, info.fps), juce::dontSendNotification);
+        if (std::abs (rail.now - nowTime) > 1e-4)
+        {
+            rail.now = nowTime;
+            rail.repaint();
+        }
+    }
+
+    void changeListenerCallback (juce::ChangeBroadcaster*) override
+    {
+        const auto* d = def();
+        if (d == nullptr)
+            return;
+        if (d->pluginState != lastState)
+        {
+            lastState = d->pluginState;
+            reload();
+        }
+    }
+
+    void sizeDecoder (juce::Rectangle<int> r)
+    {
+        if (! info.hasVideo || r.isEmpty())
+            return;
+        const auto scale = juce::jmin (1.0, juce::jmin ((double) r.getWidth() / info.width, (double) r.getHeight() / info.height));
+        const auto dpi = juce::jmax (1.0f, juce::Desktop::getInstance().getDisplays().getPrimaryDisplay() != nullptr
+                                               ? (float) juce::Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale
+                                               : 1.0f);
+        const auto s = juce::jmin (1.0, scale * dpi);
+        decoder.setSize (juce::roundToInt (info.width * s), juce::roundToInt (info.height * s));
+    }
+
+    // the song position (slaved) or the player's clock that shows video time `t`
+    void seekVideo (double t)
+    {
+        t = juce::jlimit (0.0, juce::jmax (0.0, info.duration), t);
+        if (settings.slave)
+        {
+            const auto song = t - seconds (settings.start) + seconds (settings.delay);
+            const auto ticks = juce::jmax (0.0, song) * juce::jmax (1.0, engine.getSong().bpm) / 60.0 * (double) ppq;
+            engine.seek (ticks);
+        }
+        else if (auto* p = player())
+        {
+            const auto wasRunning = p->running();
+            p->ownPlay (t);
+            if (! wasRunning)
+                p->ownPause();
+        }
+        nowTime = t;
+    }
+
+    void playPause()
+    {
+        if (settings.slave)
+        {
+            if (engine.getTransport().playing.load())
+                engine.stop();
+            else
+                engine.play();
+            return;
+        }
+        if (auto* p = player())
+        {
+            if (p->running())
+                p->ownPause();
+            else
+                p->ownPlay (nowTime >= endTime() - 1e-3 ? seconds (settings.start) : juce::jmax (seconds (settings.start), nowTime));
+        }
+    }
+
+    void stopPlayback()
+    {
+        if (settings.slave)
+            engine.stop();
+        else if (auto* p = player())
+            p->ownStop();
+    }
+
+    void setRange (bool isStart, double t)
+    {
+        edit ([this, isStart, t] (video::Settings& s) {
+            if (isStart)
+            {
+                s.start = units (t);
+                if (s.end > 0 && s.end < s.start)
+                    s.end = s.start;
+            }
+            else
+            {
+                s.end = units (juce::jmin (t, info.duration));
+                if (s.end < s.start)
+                    s.start = s.end;
+            }
+        });
+    }
+
+    void typeTime (bool isStart)
+    {
+        auto* w = new juce::AlertWindow (isStart ? tr ("Start time (H:M:S:MS)") : tr ("End time (H:M:S:MS)"), {}, juce::MessageBoxIconType::NoIcon, this);
+        w->addTextEditor ("t", video::formatTime (isStart ? seconds (settings.start) : endTime(), video::hms, info.fps));
+        w->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
+        w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
+        juce::Component::SafePointer<VideoPlayerEditor> self (this);
+        w->enterModalState (true, juce::ModalCallbackFunction::create ([self, w, isStart] (int r) {
+            if (r == 1 && self != nullptr)
+                if (const auto t = parseTime (w->getTextEditorContents ("t")))
+                    self->setRange (isStart, *t);
+        }), true);
+    }
+
+    void typeNow()
+    {
+        auto* w = new juce::AlertWindow (tr ("Current time (H:M:S:MS)"), {}, juce::MessageBoxIconType::NoIcon, this);
+        w->addTextEditor ("t", video::formatTime (juce::jmax (0.0, nowTime), video::hms, info.fps));
+        w->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
+        w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
+        juce::Component::SafePointer<VideoPlayerEditor> self (this);
+        w->enterModalState (true, juce::ModalCallbackFunction::create ([self, w] (int r) {
+            if (r == 1 && self != nullptr)
+                if (const auto t = parseTime (w->getTextEditorContents ("t")))
+                    self->seekVideo (*t);
+        }), true);
+    }
+
+    void typeDelay()
+    {
+        auto* w = new juce::AlertWindow (tr ("Delay playback (H:M:S:MS)"), tr ("The video starts when the song reaches this time."),
+                                         juce::MessageBoxIconType::NoIcon, this);
+        w->addTextEditor ("t", video::formatTime (seconds (settings.delay), video::hms, info.fps));
+        w->addButton (tr ("OK"), 1, juce::KeyPress (juce::KeyPress::returnKey));
+        w->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
+        juce::Component::SafePointer<VideoPlayerEditor> self (this);
+        w->enterModalState (true, juce::ModalCallbackFunction::create ([self, w] (int r) {
+            if (r == 1 && self != nullptr)
+                if (const auto t = parseTime (w->getTextEditorContents ("t")))
+                    self->edit ([d = units (*t)] (video::Settings& s) { s.delay = d; });
+        }), true);
+    }
+
+    void showOptions()
+    {
+        juce::PopupMenu m;
+        m.addItem (tr ("Enable audio"), true, settings.enableAudio, [this] { edit ([] (video::Settings& s) { s.enableAudio = ! s.enableAudio; }); });
+        m.addItem (tr ("Dock control panel"), true, settings.dock, [this] { edit ([] (video::Settings& s) { s.dock = ! s.dock; }); });
+        m.addItem (tr ("Ignore tempo changes"), true, settings.ignoreTempo, [this] { edit ([] (video::Settings& s) { s.ignoreTempo = ! s.ignoreTempo; }); });
+        m.addItem (tr ("Keep aspect ratio"), true, settings.keepAspect, [this] { edit ([] (video::Settings& s) { s.keepAspect = ! s.keepAspect; }); });
+        juce::PopupMenu display;
+        // FL's menu order (the modes' numbers are FL's)
+        for (const auto mode : { video::hms, video::smpte23976, video::smpte24, video::smpte25, video::smpte2997drop, video::smpte2997, video::smpte30,
+                                 video::smpte48, video::smpte50, video::smpte5994drop, video::smpte5994, video::smpte60, video::smpte72, video::smpte120,
+                                 video::smpteAuto })
+            display.addItem (mode == video::hms ? tr ("Hours:Minutes:Seconds:Ms") : juce::String (video::timeDisplayName (mode)), true, settings.timeDisplay == mode,
+                             [this, mode] { edit ([mode] (video::Settings& s) { s.timeDisplay = mode; }); });
+        m.addSubMenu (tr ("Time display"), display);
+        m.addSeparator();
+        m.addItem (tr ("Send audio to playlist"), info.hasAudio, false, [this] { sendAudioToPlaylist(); });
+        juce::PopupMenu delay;
+        delay.addSectionHeader (tr ("Delay playback by {0}", { juce::String (video::formatTime (seconds (settings.delay), settings.timeDisplay, info.fps)) }));
+        delay.addItem (tr ("Set..."), [this] { typeDelay(); });
+        delay.addItem (tr ("Delay playback until the song position"), [this] {
+            const auto ticks = engine.getTransport().positionTicks.load();
+            edit ([d = units (ticks / (double) ppq * 60.0 / juce::jmax (1.0, engine.getSong().bpm))] (video::Settings& s) { s.delay = d; });
+        });
+        delay.addItem (tr ("No delay"), settings.delay != 0, false, [this] { edit ([] (video::Settings& s) { s.delay = 0; }); });
+        m.addSubMenu (tr ("Delay playback"), delay);
+        m.addSeparator();
+        m.addItem (tr ("Locate ffmpeg..."), [this] { chooseFfmpeg(); });
+        m.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&optionsButton));
+    }
+
+    void chooseFile()
+    {
+        chooser = std::make_unique<juce::FileChooser> (tr ("Load video file..."), resolveVideo (settings.path).getParentDirectory(),
+                                                       juce::String ("*.") + juce::String (videoExtensions).replace (";", ";*."));
+        juce::Component::SafePointer<VideoPlayerEditor> self (this);
+        chooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [self] (const juce::FileChooser& fc) {
+            if (self != nullptr && fc.getResult().existsAsFile())
+                self->load (fc.getResult());
+        });
+    }
+
+    void load (const juce::File& file)
+    {
+        const auto pr = probe (file.getFullPathName());
+        edit ([&] (video::Settings& s) {
+            s.path = file.getFullPathName().toStdString();
+            s.start = 0;
+            s.end = 0;
+            if (pr.info.hasVideo)
+            {
+                s.width = pr.info.width;
+                s.height = pr.info.height;
+            }
+        });
+        reload();
+    }
+
+    void chooseFfmpeg()
+    {
+        chooser = std::make_unique<juce::FileChooser> (tr ("Locate ffmpeg"), juce::File(),
+#if JUCE_WINDOWS
+                                                       "ffmpeg.exe");
+#else
+                                                       "*");
+#endif
+        juce::Component::SafePointer<VideoPlayerEditor> self (this);
+        chooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [self] (const juce::FileChooser& fc) {
+            if (self == nullptr || ! fc.getResult().existsAsFile())
+                return;
+            setFfmpegLocation (fc.getResult());
+            {
+                std::lock_guard<std::mutex> lock (probeLock);
+                probes.clear();
+            }
+            {
+                std::lock_guard<std::mutex> lock (trackLock);
+                tracks.clear();
+            }
+            self->loadedPath = {};
+            self->reload();
+            self->engine.editSong ([] (Song&) {}, false); // (the instrument asks for its sound track again)
+        });
+    }
+
+    // FL's "Send audio to playlist": the sound track as a WAV in an audio clip where the video starts
+    void sendAudioToPlaylist()
+    {
+        const auto file = resolveVideo (settings.path);
+        const auto ffmpeg = findFfmpeg();
+        if (! file.existsAsFile() || ! ffmpeg.existsAsFile())
+            return;
+        auto folder = platform::cacheFolder ("video-audio");
+        folder.createDirectory();
+        const auto key = juce::String::toHexString (file.getFullPathName().hashCode64()) + "-" + juce::String::toHexString (file.getLastModificationTime().toMilliseconds());
+        const auto wav = folder.getChildFile (file.getFileNameWithoutExtension() + " (" + tr ("audio") + ") " + key.substring (0, 8) + ".wav");
+        const auto delay = seconds (settings.delay);
+        juce::Component::SafePointer<VideoPlayerEditor> self (this);
+        statusLine = tr ("Extracting the sound...");
+        repaint();
+        std::thread ([self, file, ffmpeg, wav, delay] {
+            bool ok = wav.existsAsFile();
+            if (! ok)
+            {
+                juce::ChildProcess p;
+                if (p.start (juce::StringArray { ffmpeg.getFullPathName(), "-nostdin", "-v", "quiet", "-y", "-i", file.getFullPathName(), "-vn", "-sn",
+                                                 "-ac", "2", "-c:a", "pcm_s16le", wav.getFullPathName() },
+                             0))
+                    p.waitForProcessToFinish (10 * 60 * 1000);
+                ok = wav.existsAsFile() && wav.getSize() > 44;
+            }
+            juce::MessageManager::callAsync ([self, wav, ok, delay] {
+                if (self == nullptr)
+                    return;
+                if (ok)
+                    self->addClip (wav, delay);
+                self->refreshControls();
+            });
+        }).detach();
+    }
+
+    void addClip (const juce::File& wav, double delaySeconds)
+    {
+        const auto data = engine.getSampleLibrary().load (wav.getFullPathName());
+        if (data == nullptr)
+            return;
+        const auto bpm = juce::jmax (1.0, engine.getSong().bpm);
+        const auto length = juce::jmax<std::int64_t> (ppq / 4, (std::int64_t) ((double) data->frames() / data->sampleRate * bpm / 60.0 * ppq));
+        const auto start = (std::int64_t) std::llround (delaySeconds * bpm / 60.0 * ppq);
+        const auto path = wav.getFullPathName().toStdString();
+        const auto name = wav.getFileNameWithoutExtension().toStdString();
+        engine.editSong ([=] (Song& s) {
+            int track = 0;
+            for (;; ++track)
+                if (std::none_of (s.playlist.begin(), s.playlist.end(), [&] (const Clip& c) { return c.track == track && c.start < start + length && c.end() > start; }))
+                    break;
+            ChannelDef c;
+            c.name = name;
+            c.instrument = InstrumentKind::audioClip;
+            c.samplePath = path;
+            c.mixerTrack = s.claimFreeInsert();
+            s.channels.push_back (c);
+            Clip clip;
+            clip.kind = ClipKind::audio;
+            clip.channel = (int) s.channels.size() - 1;
+            clip.track = track;
+            clip.start = start;
+            clip.length = length;
+            s.playlist.push_back (clip);
+            s.mode = PlayMode::song;
+        });
+    }
+
+    // the video in its own resizable window (double-click: full screen)
+    class DetachedWindow final : public juce::DocumentWindow
+    {
+    public:
+        DetachedWindow (VideoPlayerEditor& o) : juce::DocumentWindow ("Video", theme::colour::bg1, juce::DocumentWindow::allButtons), owner (o)
+        {
+            setUsingNativeTitleBar (true);
+            setResizable (true, true);
+            auto* s = new VideoSurface();
+            s->onSize = [this] (juce::Rectangle<int> r) { owner.sizeDecoder (r); };
+            s->onDoubleClick = [this] { setFullScreen (! isFullScreen()); };
+            surface = s;
+            setContentOwned (s, false);
+            const auto w = owner.info.width > 0 ? owner.info.width : 640, h = owner.info.height > 0 ? owner.info.height : 360;
+            const auto scale = juce::jmin (1.0, 960.0 / w, 540.0 / h);
+            centreWithSize (juce::roundToInt (w * scale), juce::roundToInt (h * scale));
+            setVisible (true);
+        }
+        void closeButtonPressed() override
+        {
+            juce::MessageManager::callAsync ([o = juce::Component::SafePointer<VideoPlayerEditor> (&owner)] {
+                if (o != nullptr)
+                    o->attach();
+            });
+        }
+        VideoSurface* surface = nullptr;
+
+    private:
+        VideoPlayerEditor& owner;
+    };
+
+    void detach()
+    {
+        if (window != nullptr)
+        {
+            window->toFront (true);
+            return;
+        }
+        if (! info.hasVideo)
+            return;
+        window = std::make_unique<DetachedWindow> (*this);
+        window->setName (juce::File (juce::String::fromUTF8 (settings.path.c_str())).getFileName());
+        detachedSurface = window->surface;
+        detachButton.setToggleState (true, juce::dontSendNotification);
+        frames = -1;
+    }
+
+    void attach()
+    {
+        window = nullptr;
+        detachedSurface = nullptr;
+        detachButton.setToggleState (false, juce::dontSendNotification);
+        surface.message = {};
+        sizeDecoder (surface.getLocalBounds());
+        refreshControls();
+        frames = -1;
+    }
+
+    AudioEngine& engine;
+    std::function<ChannelDef* (Song&)> locate;
+    int channel = -1;
+    video::Settings settings;
+    video::Info info;
+    juce::String loadedPath, statusLine;
+    std::vector<std::uint8_t> lastState;
+    mutable std::shared_ptr<Instrument> heldInstrument;
+    double nowTime = 0.0;
+    int frames = -1;
+
+    FrameDecoder decoder;
+    VideoSurface surface;
+    VideoSurface* detachedSurface = nullptr;
+    std::unique_ptr<DetachedWindow> window;
+    juce::Rectangle<int> panelArea;
+    IconButton loadButton { IconButton::Icon::load }, optionsButton { IconButton::Icon::options }, setStartButton { IconButton::Icon::start },
+        setEndButton { IconButton::Icon::end }, loopButton { IconButton::Icon::loop }, playButton { IconButton::Icon::play },
+        stopButton { IconButton::Icon::stop }, soundButton { IconButton::Icon::sound }, detachButton { IconButton::Icon::detach };
+    juce::TextButton slaveButton, locateButton;
+    std::unique_ptr<ctlui::Knob> volume;
+    ClickLabel startLabel, endLabel, nowLabel;
+    TimeRail rail;
+    std::unique_ptr<juce::FileChooser> chooser;
+};
+} // namespace
+
+namespace videoview
+{
+void install (AudioEngine& engine)
+{
+    installedEngine = &engine;
+    video::setAudioProvider ([] (const std::string& path, bool wait) { return provideTrack (path, wait); });
+}
+
+juce::String report (const juce::String& path)
+{
+    return probe (path).report;
+}
+} // namespace videoview
+
+std::unique_ptr<juce::Component> makeVideoPlayerEditor (AudioEngine& engine, std::function<ChannelDef* (Song&)> locate, int channel)
+{
+    return std::make_unique<VideoPlayerEditor> (engine, std::move (locate), channel);
+}
+
+std::unique_ptr<juce::Component> makeVideoPlayerEditor (AudioEngine& engine, int channel)
+{
+    return makeVideoPlayerEditor (engine, [channel] (Song& s) -> ChannelDef* {
+        return channel >= 0 && channel < (int) s.channels.size() ? &s.channels[(std::size_t) channel] : nullptr;
+    }, channel);
+}
+} // namespace lynx

+ 31 - 0
src/ui/VideoPlayerView.h

@@ -0,0 +1,31 @@
+#pragma once
+
+// The Video Player's editor and the ffmpeg services behind it (round 165g, core/VideoPlayer.h): the video, decoded by
+// the user's own ffmpeg (found as for the video export, ui/VisualEditors findFfmpeg), drawn at the song's time; FL's
+// controls (time slider, start / end times, Loop, Play / Stop, Slave playback to host, Mute, Volume, the options menu);
+// a detachable video window; the sound track decoded once per video for the instrument.
+
+#include <functional>
+#include <memory>
+
+#include <juce_gui_basics/juce_gui_basics.h>
+
+namespace lynx
+{
+class AudioEngine;
+struct ChannelDef;
+struct Song;
+
+namespace videoview
+{
+// Installs the sound-track provider (core/VideoPlayer.h) for `engine`: decodes in the background and republishes the
+// song when a track is ready. Call once at start-up.
+void install (AudioEngine& engine);
+// ffmpeg's report of a video (cached per path; empty when ffmpeg or the file is missing)
+juce::String report (const juce::String& path);
+} // namespace videoview
+
+// `channel`: the Channel Rack channel (−1 in a Patcher: `locate` finds the node)
+std::unique_ptr<juce::Component> makeVideoPlayerEditor (AudioEngine& engine, std::function<ChannelDef* (Song&)> locate, int channel);
+std::unique_ptr<juce::Component> makeVideoPlayerEditor (AudioEngine& engine, int channel);
+} // namespace lynx

+ 169 - 0
tests/VideoPlayer165Tests.inc

@@ -0,0 +1,169 @@
+// --- Fruity Video Player (core/VideoPlayer.h) - round 165g
+
+#include "core/VideoPlayer.h"
+
+TEST (video165_fl_state)
+{
+    using namespace lynx::video;
+    // FL 2026's Default.fst (0xD5 payload, 37 bytes): version 3, flags 0x92, time display 0, 3 params (100, 0, 0),
+    // no path, the window size 375 x 0
+    const std::vector<std::uint8_t> fl = { 0x03, 0, 0, 0, 0x92, 0, 0, 0, 0, 0, 0, 0, 0x03, 0, 0, 0, 0x64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+                                           0x00, 0x77, 0x01, 0, 0, 0, 0, 0, 0 };
+    const auto s = read (fl);
+    CHECK (s.has_value());
+    if (! s)
+        return;
+    CHECK (s->keepAspect && s->enableAudio && s->slave && ! s->loop && ! s->ignoreTempo && ! s->dock && s->transport == 0);
+    CHECK (s->volume == 100 && ! s->mute && ! s->play && s->path.empty() && s->width == 375 && s->height == 0);
+    CHECK (s->timeDisplay == hms && s->delay == 0);
+    // written back: FL's bytes, then LYNX's tail
+    const auto back = write (*s);
+    CHECK (back.size() == fl.size() + 16 && std::equal (fl.begin(), fl.end(), back.begin()));
+    CHECK (read (back) == s);
+    // a defaulted Settings is FL's default
+    CHECK (Settings {} == *s);
+
+    // a path (UTF-16, with a non-ASCII letter), times, every flag
+    Settings v;
+    v.path = "C:\\Users\\kauan\\V\xc3\xad" "deos\\clip.mp4";
+    v.loop = true;
+    v.keepAspect = false;
+    v.transport = 2;
+    v.enableAudio = false;
+    v.ignoreTempo = true;
+    v.slave = false;
+    v.dock = true;
+    v.timeDisplay = smpte5994drop;
+    v.volume = 127;
+    v.mute = true;
+    v.play = true;
+    v.width = 640;
+    v.height = 360;
+    v.start = 12345678;
+    v.end = 98765432;
+    v.delay = unitsPerSecond * 3;
+    const auto bytes = write (v);
+    CHECK (read (bytes) == v);
+    // the path's length byte and characters as FL writes them (FUN_0071b530)
+    CHECK (bytes[28] == 30 && bytes[29] == 'C' && bytes[30] == 0 && bytes[29 + 2 * 16] == 0xed && bytes[30 + 2 * 16] == 0);
+    std::uint32_t flags = 0;
+    std::memcpy (&flags, bytes.data() + 4, 4);
+    CHECK (flags == (1u | 8u | 0x40u | 0x100u));
+    // older states: the audio switch in bits 4|5, slaved by default before version 3
+    auto old = fl;
+    old[0] = 2;
+    old[4] = 0x20;
+    CHECK (! read (old).has_value() || read (old)->enableAudio);
+    CHECK (! read ({ 9, 0, 0, 0 }).has_value() && ! read ({}).has_value());
+}
+
+TEST (video165_time_display)
+{
+    using namespace lynx::video;
+    CHECK (formatTime (0.0, hms, 0.0) == "0:00:00:000");
+    CHECK (formatTime (3723.456, hms, 0.0) == "1:02:03:456");
+    CHECK (formatTime (-1.25, hms, 0.0) == "-0:00:01:250");
+    CHECK (formatTime (1.52, smpte25, 0.0) == "0:00:01:13");
+    CHECK (formatTime (59.99, smpte30, 0.0) == "0:00:59:29");
+    // drop frame: 29.97 skips frames 0 and 1 at each minute but the tenth
+    CHECK (formatTime (1800.0 / 29.97, smpte2997drop, 0.0) == "0:01:00;02");
+    CHECK (formatTime (17982.0 / 29.97, smpte2997drop, 0.0) == "0:10:00;00");
+    CHECK (formatTime (1800.0 / 29.97, smpte2997, 0.0) == "0:01:00:00");
+    CHECK (formatTime (2.0, smpteAuto, 24.0) == "0:00:02:00" && formatTime (2.5, smpteAuto, 24.0) == "0:00:02:12");
+    CHECK (timeDisplayFps (smpte23976, 0.0) == 23.976 && timeDisplayDrops (smpte5994drop) && ! timeDisplayDrops (smpte5994));
+}
+
+TEST (video165_clock_and_report)
+{
+    using namespace lynx::video;
+    Settings s;
+    s.delay = unitsPerSecond;            // starts when the song reaches 1 s
+    s.start = 2 * unitsPerSecond;        // from the video's 2 s
+    s.end = 5 * unitsPerSecond;          // to 5 s
+    CHECK (Clock::videoTime (0.5, s, 10.0) < 0.0);
+    CHECK (std::abs (Clock::videoTime (1.0, s, 10.0) - 2.0) < 1e-9 && std::abs (Clock::videoTime (3.5, s, 10.0) - 4.5) < 1e-9);
+    CHECK (std::abs (Clock::videoTime (9.0, s, 10.0) - 5.0) < 1e-9); // holds the end
+    s.loop = true;
+    CHECK (std::abs (Clock::videoTime (5.0, s, 10.0) - 3.0) < 1e-9); // 4 s in = one 3-s pass + 1 s
+    s.end = 0;                           // to the video's end
+    s.loop = false;
+    CHECK (std::abs (Clock::videoTime (20.0, s, 10.0) - 10.0) < 1e-9);
+
+    const std::string report =
+        "Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'clip.mp4':\n"
+        "  Duration: 00:01:02.50, start: 0.000000, bitrate: 1205 kb/s\n"
+        "  Stream #0:0[0x1](und): Video: h264 (High) (avc1 / 0x31637661), yuv420p(progressive), 1280x720 [SAR 1:1 DAR 16:9], 1072 kb/s, 29.97 fps, 29.97 tbr, 30k tbn (default)\n"
+        "  Stream #0:1[0x2](und): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 128 kb/s (default)\n";
+    const auto info = parseFfmpegReport (report);
+    CHECK (info.hasVideo && info.hasAudio && info.width == 1280 && info.height == 720);
+    CHECK (std::abs (info.fps - 29.97) < 1e-9 && std::abs (info.duration - 62.5) < 1e-9);
+    const auto none = parseFfmpegReport ("Input #0, wav, from 'a.wav':\n  Duration: 00:00:03.00, bitrate: 1411 kb/s\n  Stream #0:0: Audio: pcm_s16le, 44100 Hz\n");
+    CHECK (! none.hasVideo && none.hasAudio);
+}
+
+TEST (video165_instrument_plays_the_track)
+{
+    using namespace lynx;
+    // a 2-s ramp-like sound track at 48 kHz (left = sample index, right = minus it)
+    auto track = std::make_shared<video::AudioTrack>();
+    track->rate = 48000.0;
+    for (int i = 0; i < 96000; ++i)
+    {
+        track->samples.push_back ((std::int16_t) (i % 30000));
+        track->samples.push_back ((std::int16_t) -(i % 30000));
+    }
+    video::setAudioProvider ([track] (const std::string& path, bool) -> std::shared_ptr<const video::AudioTrack> {
+        return path == "clip.mp4" ? track : nullptr;
+    });
+    auto inst = video::makeInstrument();
+    CHECK (video::playerOf (inst.get()) != nullptr);
+    ChannelDef def;
+    def.instrument = InstrumentKind::videoplayer;
+    video::Settings s;
+    s.path = "clip.mp4";
+    s.delay = video::unitsPerSecond / 2; // the video starts at 0.5 s of the song
+    def.pluginState = video::write (s);
+    const double bpm = 120.0, rate = 48000.0;
+    inst->prepare (rate);
+    inst->configure (def, bpm);
+    // stopped: silent
+    std::vector<float> l (480, 0.0f), r (480, 0.0f);
+    inst->setSongPosition (0.0);
+    inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
+    CHECK (std::all_of (l.begin(), l.end(), [] (float x) { return x == 0.0f; }));
+    // play from the song's 1.0 s: the video is at 0.5 s → frame 24000
+    const auto ticksPerSample = bpm * ppq / (60.0 * rate);
+    auto ticks = 1.0 * bpm / 60.0 * ppq;
+    double at = ticks;
+    inst->setSongPosition (at - 480 * ticksPerSample); // (the block before: it moves)
+    inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
+    std::fill (l.begin(), l.end(), 0.0f);
+    std::fill (r.begin(), r.end(), 0.0f);
+    inst->setSongPosition (at);
+    inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
+    CHECK (std::abs (l[0] * 32768.0f - 24000.0f) < 1.5f && std::abs (l[100] * 32768.0f - 24100.0f) < 1.5f);
+    CHECK (std::abs (r[100] + l[100]) < 1e-6f);
+    // muted / volume 50 %
+    s.volume = 50;
+    def.pluginState = video::write (s);
+    inst->configure (def, bpm);
+    std::fill (l.begin(), l.end(), 0.0f);
+    at += 480 * ticksPerSample;
+    inst->setSongPosition (at);
+    inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
+    CHECK (std::abs (l[0] * 32768.0f - 24480.0f * 0.5f) < 1.5f);
+    s.mute = true;
+    def.pluginState = video::write (s);
+    inst->configure (def, bpm);
+    CHECK (inst->idle());
+    // before the delay: silence
+    s.mute = false;
+    def.pluginState = video::write (s);
+    inst->configure (def, bpm);
+    std::fill (l.begin(), l.end(), 0.0f);
+    inst->setSongPosition (0.0);
+    inst->setSongPosition (480 * ticksPerSample);
+    inst->render (l.data(), r.data(), 480, 1.0f, 1.0f);
+    CHECK (std::all_of (l.begin(), l.end(), [] (float x) { return x == 0.0f; }));
+    video::setAudioProvider (nullptr);
+}

+ 1 - 0
tests/tests.cpp

@@ -16230,6 +16230,7 @@ TEST (fl_low_lifter_matches_fl_engine)
 #include "PerfMode165Tests.inc"
 #include "Patch165Tests.inc"
 #include "FlPlugins165Tests.inc"
+#include "VideoPlayer165Tests.inc"
 #include "Dash165Tests.inc"
 #include "LinuxMouse165Tests.inc"
 #include "Fl165Tests.inc"

Некоторые файлы не были показаны из-за большого количества измененных файлов