Procházet zdrojové kódy

Note colours (FL import, MIDI channel, Piano Roll swatch, Alt+C / Shift+C), Piano Roll Select menu, chord readout, Detect tempo for audio clips, Playlist select overlapping/stacked clips; round 153 doc

Ka1-S před 1 měsícem
rodič
revize
08bc35230b

+ 2 - 1
CMakeLists.txt

@@ -174,7 +174,8 @@ target_sources(lynx_core PRIVATE
     src/core/Mp3Encoder.cpp
     src/core/PluginMonitor.cpp
     src/core/ProjectContents.cpp
-    src/core/PlaylistOps.cpp)
+    src/core/PlaylistOps.cpp
+    src/core/TempoDetect.cpp)
 
 # LAME's libmp3lame (LGPL; third_party/lame, encoder only, configured by third_party/lame/src/config.h)
 file(GLOB LAME_SOURCES third_party/lame/src/*.c)

+ 181 - 0
docs/analise/REA_rodada153.md

@@ -0,0 +1,181 @@
+# REA round 153 (fltech153): what's new in FL Studio (web research) → LYNX
+
+2026-10-24. Research of the features Image-Line added in FL Studio 21, 2024, 2025 and 2026, plus the long-standing
+workflow features people rely on; each checked against LYNX's code; the top missing items implemented clean-room.
+
+Evidence markers: [DOC] Image-Line's official manual / release notes (URLs below; read as data, behaviour only);
+[CODE] checked in LYNX's source (file named); [model] LYNX's own design choice. Nothing of FL was decompiled in this
+round (the manual described enough); no code, graphics, sounds or presets were copied.
+
+Sources ([DOC]):
+- N21 = https://www.image-line.com/fl-studio-learning/fl-studio-online-manual/html/basics_new_21.htm
+- N24 = https://www.image-line.com/fl-studio-learning/fl-studio-online-manual/html/basics_new_24.htm
+- N25 = https://www.image-line.com/fl-studio-learning/fl-studio-online-manual/html/basics_new_25.htm
+- N26 = https://www.image-line.com/fl-studio-learning/fl-studio-online-manual/html/basics_new.htm
+- WN  = https://www.image-line.com/fl-studio-learning/fl-studio-online-manual/html/WhatsNew.htm (changelog 25.1.3 … 26.1.7)
+- PRM = https://www.image-line.com/fl-studio-learning/fl-studio-online-manual/html/pianoroll_menu.htm
+- CPT = https://www.image-line.com/fl-studio-learning/fl-studio-online-manual/html/pianoroll_chordprogression.htm
+- PL  = https://www.image-line.com/fl-studio-learning/fl-studio-online-manual/html/playlist.htm
+- CR  = https://www.image-line.com/fl-studio-learning/fl-studio-online-manual/html/channelrack.htm
+- PAT = https://www.image-line.com/fl-studio-learning/fl-studio-online-manual/html/menu_patterns.htm
+- MusicRadar review of FL Studio 20 (Arrangements): https://www.musicradar.com/reviews/image-line-fl-studio-20
+
+Legend: LYNX ✅ has it / ⚠️ partial / ❌ missing / ⛔ out of scope (online service, AI model or licence). Priority =
+user value / effort: **H** high, **M** medium, **L** low. "153" = done in this round.
+
+## 1. Feature table
+
+### FL Studio 21 (2022-12 … 2023-10)
+
+| Feature | What it does | LYNX | Priority |
+|---|---|---|---|
+| Audio clip fades and gain (N21) | fade-in/out and gain handles on audio clips, optional auto-crossfades | ⚠️ fades + gain (`Clip::fadeIn/fadeOut/gain`); no automatic crossfades | M |
+| [+] add track button (N21) | adds an instrument or audio Playlist track | ✅ track mode menu, "Can't create new audio track" flow (`PlaylistComponent.cpp`) | — |
+| Sequential sample drop (N21) | Shift+drop of several samples places them one after another | ❌ | L |
+| Chop pattern/automation clips (N21) | clip Chop works on every clip type | ✅ "Chop to grid" (P8) | — |
+| Select overlapping (N21, 24.2) | selects every layer but the lowest; "stacked" = 100 % covered | ✅ **153** (Playlist ruler menu → Select; `clipops::overlappingClips / stackedClips`) | H |
+| Project folders (N21) | per-project Recorded / Rendered / Sliced folders | ⚠️ project safety folders (`core/ProjectSafety`) | L |
+| Auto-save every minute, undone recordings to the bin (N21) | | ✅ autosave + backups (`ProjectSafety`) | — |
+| Themes (N21) | colour themes | ❌ one LYNX theme (by design, `docs/WORKFLOW_FL.md` §4) | L |
+| Browser tags and favourites (N21) | tags, starred items, boolean search, "Locate file" | ⚠️ STARRED tab, search, locate; no tags | M |
+| Browser preview from the click (N21) | right/Shift+click previews from the clicked position | ✅ preview strip (`BrowserComponent::PreviewStrip`) | — |
+| Mixer multi-select, "render selected tracks" (N21) | | ⚠️ selection and freeze per insert; no batch render of the selection | M |
+| Automation clip → events (N21) | | ❌ | L |
+| Patcherize (N21, 25.2 FX) | wraps a channel / effect chain in a Patcher | ❌ (Patcher exists, `core/Patcher.cpp`) | M |
+| Snap to scale (21.1) | placed and moved notes snap to the scale | ✅ (R14, `setScaleSnap`) | — |
+| Piano roll Python scripts (21.1) | user scripts that edit notes | ❌ (LYNX ships the scripts' tools natively: Euclidean, humanize, note repeat) | L |
+| Coloured (spectral) waveforms (21.1) | waveform colour by frequency | ✅ (`core/WaveAnalysis`, `WaveformView`) | — |
+| External MIDI clock sync (21.1) | FL follows an external clock | ❌ | M |
+| Extract stems (21.2), "Remix a song" (26.1) | AI split into drums / bass / instruments / vocals | ⛔ needs a neural model (Demucs: MIT code and weights, but ~80 MB of weights and an inference runtime such as ONNX Runtime, MIT); not this round | — |
+| FL Cloud sounds, mastering, distribution (21.2) | online services | ⛔ (online) | — |
+| Double-click a pattern clip → Piano roll, Alt → rack (21.2) | | ✅ (P10) | — |
+| Scale highlighting saved with the project (21.2) | | ⚠️ the scale is published to the engine, not stored in `.lynx` | L |
+
+### FL Studio 2024 (24.1, 24.2)
+
+| Feature | What it does | LYNX | Priority |
+|---|---|---|---|
+| Chord progression tool (24.1, CPT) | generate / analyse / rework chord progressions | ✅ (`prtools::generateProgression`, Alt+P) — LYNX's own generator, no AI | — |
+| Note repeat (24.1) | repeat tool | ✅ (`NoteTool::noteRepeat`) | — |
+| Make unique on drag Shift+V (24.1) | | ✅ (`EditorPolish.h`) | — |
+| Browser tempo/key sync on drop (24.1) | samples with tempo metadata fit the project | ❌ (no metadata read); **Detect tempo 153** covers the manual case | M |
+| Per-channel swing truncation (24.1) | | ❌ | L |
+| Welcome window (24.1) | start-up quick actions | ✅ first-start wizard + new project dialog (`SetupWizard`, `NewProjectDialog`) | — |
+| CLAP (24.1) | | ✅ | — |
+| "Switch selected audio clips" stretch mode (24.1) | | ❌ | L |
+| Ghost notes from overlapping patterns (24.2) | outlined ghosts of the clips playing at the same time | ✅ (ghost button tooltip, `PianoRollComponent`) | — |
+| Snap MIDI input to scale (24.2) | | ✅ (`AudioEngine::setInputScale`) | — |
+| Pattern colour without the rename dialog (24.2) | | ✅ "Change color", "Random color" | — |
+| Mixer per-track low-latency monitoring (24.2) | PDC off while monitoring that track | ❌ | M |
+| Select routed sources (24.2) | | ✅ "Channels routed to this track" | — |
+| Tap tempo "Apply tempo" (24.2) | | ✅ (`TempoTapper`) | — |
+| Metronome "Pulse" sound, SMPTE time (24.2) | | ❌ | L |
+| Browser "current project" samples (24.2) | | ✅ PROJECT tab | — |
+| Per-plugin window scaling (24.2) | | ❌ | L |
+
+### FL Studio 2025 (25.1, 25.2)
+
+| Feature | What it does | LYNX | Priority |
+|---|---|---|---|
+| Loop Starter (25.1/25.2) | genre-based starter from FL Cloud loops and one-shots with generated steps | ⛔ content from FL Cloud; a local variant (own folders + generated steps) is possible later | L |
+| Gopher (25.1) | AI assistant | ⛔ (AI service) | — |
+| Dynamic mixer tracks, up to 500 (25.1) | | ⚠️ "Insert multiple…"; 127 inserts | L |
+| Unroute tracks routed to the selection (25.1) | | ✅ | — |
+| Undo track deletion (25.1) | | ✅ (snapshot undo) | — |
+| Audio clip properties dialog (25.1) | stretch, pitch, reverse | ✅ (`ui/ClipProperties`) | — |
+| Pitch selected clips ±1, reverse (25.1) | | ⚠️ reverse; no clip-level pitch keys | L |
+| AI Deverb / Declipper / Denoiser | | ⛔ (AI models) | — |
+| Colourful channel controls (25.1) | rack controls tinted with the channel colour | ⚠️ name buttons are tinted (C21) | L |
+| Sampler loop start/end knobs (25.2) | | ⚠️ the file's own loop is read (`SampleData::loopStart`) | L |
+| Number keys mute visible channels only (25.2) | | ✅ (C9 acts on the rows shown) | — |
+| Fruity Slicer 2, Emphasis, Emphasizer (25.x) | new plugins | ❌ (r154 owns FL plugins' DSP) | — |
+
+### FL Studio 2026 (26.1)
+
+| Feature | What it does | LYNX | Priority |
+|---|---|---|---|
+| Chord detection panel (26.1) | names the chord of MIDI / typing keyboard / selected notes | ✅ **153** (Piano Roll toolbar readout, `prtools::detectChord`) | H |
+| Chord stamp top-down / bottom-up (26.1) | the clicked key is the chord's top note | ❌ | M |
+| Custom key labels (26.1) | rename piano roll keys (drum maps) | ❌ | M |
+| Stretch snaps by default (26.1) | | ⚠️ | L |
+| Per-clip pan, normalise clip gain (26.1) | | ⚠️ normalise; no clip pan | M |
+| Collapse / expand all groups (26.1) | | ⚠️ per group | L |
+| Performance mode markers (26.1) and Performance mode (≤20) | clip launching by columns | ❌ (large) | M |
+| Sort channels by type (26.1) | | ✅ | — |
+| Audio Logger (26.1) | keeps recording the Master output | ❌ | M |
+| FL Cloud backups (26.1) | | ⛔ (online); local backups ✅ | — |
+| Browser inline waveforms (26.1) | | ❌ (preview strip only) | L |
+| MIDI recording follows the tempo map (26.1) | | ✅ (recording in ticks) | — |
+
+### Long-standing features (≤ FL 20, still current)
+
+| Feature | What it does | LYNX | Priority |
+|---|---|---|---|
+| Playlist arrangements + merge (PL) | | ✅ (P20, "Arrangements and merging…") | — |
+| Piano roll Tools: quantize, legato, articulate, chop, glue, arpeggiate, strum, flam, claw, riff machine, limit, flip, randomise, scale levels, LFO (PRM) | | ✅ all (`KeyMap` pianoRoll.*, `NoteToolDialogs`) | — |
+| Stamp chords (PRM) | | ✅ chord combo | — |
+| **Note colours** (PRM: Change colour Alt+C, Select by colour Shift+C; the colour is the MIDI channel) | 16 colour groups per note | ✅ **153** (was ❌: the `.flp` byte was read but dropped) | H |
+| **Select menu** (PRM): invert Shift+I, odd, random, muted, overlapping, stacked, by colour | | ✅ **153** (was ⚠️: velocity only) | H |
+| Note group / ungroup Shift+G / Alt+G (PRM) | notes move together | ❌ | M |
+| Piano roll time markers (PRM) | | ❌ (Playlist markers only) | L |
+| Snap: line / cell / markers (PRM) | | ⚠️ (R11) | L |
+| Playlist tools and edit menu (PL) | | ✅ (P1 … P17) | — |
+| Consolidate / render to audio (PL) | | ✅ "Consolidate track" | — |
+| Make unique (PL) | | ✅ | — |
+| **Detect tempo** (PL: audio clip Sample menu) | estimate the sample's BPM | ✅ **153** (was ❌) | H |
+| Fit to tempo / time-warp (PL) | | ✅ fit; ❌ time-warp | — |
+| Split by channel (PAT) | | ✅ | — |
+| Track groups (PL) | | ✅ | — |
+| Song markers, time signatures, marker actions (PL) | | ✅ (subset of actions) | — |
+| Channel Rack: clone, sort, groups, colour, zip (CR) | | ✅ except zip / colour gradient | L |
+| Burn MIDI to pattern (CR) | | ❌ | L |
+| Step sequencer graph editor (CR) | | ✅ (C4) | — |
+
+## 2. Implemented in this round
+
+### 2.1 Note colours [DOC PRM] [CODE]
+- `Note::colour` 0..15 (`core/Song.h`, `noteColourCount`). FL stores it in the low nibble of each note record's
+  "extra" byte (`flp::Note::extra`, bits 0–3; 0x10 porta, 0x20 muted): the importer now keeps it
+  (`FlpImport.cpp`). Saved in `.lynx` as the note array's 14th element (only when not 0; older files load with the first colour, shown as "Colour 1").
+- MIDI files: a note's MIDI channel becomes its colour on import and the colour is the channel on export (as FL).
+- Piano Roll: a colour swatch in the toolbar sets the colour of new notes (pencil, brush, drum brush, chord stamp);
+  its menu colours the selection and selects by colour. Keys (FL's): **Alt+C** colour the selection, **Shift+C**
+  select the notes of the selection's colour. Notes are drawn in their group's hue (LYNX's own 16-hue wheel;
+  colour 1 keeps LYNX's note red), the velocity still sets the brightness; the velocity lane uses the same colours.
+- The undo history compares colours (`core/History.cpp`).
+
+### 2.2 Select menu [DOC PRM] [CODE]
+Piano Roll "…" → Select: All, Invert (**Shift+I**), Deselect, Odd notes (every other note in time order, starting
+with the first [model]), Even notes, Random (half), Muted, Overlapping (every layer except the first of an
+overlapping run on the same key), Stacked (notes completely inside another note of the same key; of exact duplicates
+all but the first — deleting them changes nothing audible), Same colour. Maths in `core/NoteTools.cpp`
+(`invertSelection`, `selectOdd`, `selectRandom`, `selectMuted`, `selectOverlapping`, `selectStacked`,
+`selectByColour`, `setColour`). Playlist ruler menu → Select: Overlapping / Stacked / Muted clips per track
+(`core/ClipOps.h`).
+
+### 2.3 Chord readout [DOC N26] [model]
+A label at the right of the Piano Roll toolbar names the chord of the keys held on MIDI inputs and the typing piano
+(`AudioEngine::heldInputKeys`, a lock-free 128-bit mask updated where the notes arrive, cleared by panic), or, when
+fewer than two keys are held, of the selected notes. `prtools::detectChord`: up to 10 keys; exact interval
+templates (major, minor, dim, aug, sus2/4, 6, m6, 7, maj7, m7, m7b5, dim7, m(maj7), 7sus4, add9, madd9, 7#5, 7b5,
+maj7#5, 9, maj9, m9, 7b9, 7#9, 6/9, 9sus4, m11, 13, sevenths without the fifth, power chord); the lowest key is
+preferred as the root (C-E-G-A = C6, not Am7/C), otherwise a slash chord over the bass.
+
+### 2.4 Detect tempo [DOC PL] [model]
+Audio clip menu → Detect tempo → a range (70–140, 90–180, 60–200 BPM; the range decides the octave, as FL's range
+choice). `core/TempoDetect.cpp` (LYNX's own method): an onset curve from three band energies (one-pole splits at
+150 Hz and 2 kHz, log-energy rises per 5 ms hop, local mean removed, ±15 ms blur), its autocorrelation with a
+4-harmonic comb and a mild preference for the range's middle, then a fine search over 16 periods with fractional-lag
+correlation; a loop of whole beats (≥ 4, within 0.2 %) snaps to the tempo its length gives exactly. The dialog
+offers: fit the clip to the project tempo (stretch, keep pitch), use it as the project tempo, or rounded to a whole
+BPM (FL 2024's "ignore decimals"). Tests: drum loops at 87 / 100 / 128 / 140 BPM within 0.05 BPM; 8-beat loops at
+93 / 127 / 85.5 exact; silence → none.
+
+## 3. Next candidates (by priority)
+M: chord stamp top-down mode; custom key labels; note grouping; Audio Logger; per-clip pan; external MIDI clock;
+per-track low-latency monitoring; Patcherize; browser tags; batch render of selected mixer tracks; performance mode.
+⛔ stays out: FL Cloud (sounds, mastering, backups, Loop Starter content), Gopher and the AI tools; stem separation
+only with a bundled open model (Demucs, MIT) — a separate decision because of the download size.
+
+## Where I stopped
+(updated at the end of the round)

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

@@ -4216,3 +4216,34 @@ countries: br
 "Mic pre" = "Pré de microfone"
 "Mic" = "Mic"
 "Vocal detector" = "Detector vocal"
+
+# REA round 153: note colours, Select menu, chord readout
+"Colour the selected notes with the note colour" = "Colorir as notas selecionadas com a cor de nota"
+"Select the notes of the same colour" = "Selecionar as notas da mesma cor"
+"Invert the note selection" = "Inverter a seleção de notas"
+"Note colour: new notes get this colour. Click: choose it, colour the selection (Alt+C), select by colour (Shift+C)" = "Cor de nota: as notas novas recebem esta cor. Clique: escolher, colorir a seleção (Alt+C), selecionar por cor (Shift+C)"
+"Note colour" = "Cor de nota"
+"Chord: the chord of the keys held on the MIDI keyboard or the typing piano, else of the selected notes" = "Acorde: o acorde das teclas pressionadas no teclado MIDI ou no piano de digitação; senão, das notas selecionadas"
+"Colour for new notes" = "Cor das notas novas"
+"Colour {0}" = "Cor {0}"
+"Colour the selected notes with it" = "Colorir as notas selecionadas com ela"
+"Colour the selected notes" = "Colorir as notas selecionadas"
+"Select by colour" = "Selecionar por cor"
+"Invert selection" = "Inverter seleção"
+"Odd notes (every other one)" = "Notas ímpares (uma sim, uma não)"
+"Even notes" = "Notas pares"
+"Random (half of the notes)" = "Aleatório (metade das notas)"
+"Muted notes" = "Notas silenciadas"
+"Overlapping notes" = "Notas sobrepostas"
+"Stacked notes (hidden duplicates)" = "Notas empilhadas (duplicatas escondidas)"
+"Same colour as the selection" = "Mesma cor da seleção"
+"{0}-{1} BPM" = "{0}-{1} BPM"
+"Detect tempo" = "Detectar andamento"
+"No steady tempo was found in this sample." = "Nenhum andamento estável foi encontrado nesta amostra."
+"Detected tempo: {0} BPM ({1} beats in the sample). The project plays at {2} BPM." = "Andamento detectado: {0} BPM ({1} tempos na amostra). O projeto toca a {2} BPM."
+"Fit the clip to the project tempo" = "Ajustar o clipe ao andamento do projeto"
+"Use it as the project tempo" = "Usar como andamento do projeto"
+"Use it, rounded to a whole BPM" = "Usar, arredondado para BPM inteiro"
+"Overlapping clips ({0})" = "Clipes sobrepostos ({0})"
+"Stacked clips: hidden duplicates ({0})" = "Clipes empilhados: duplicatas escondidas ({0})"
+"Muted clips ({0})" = "Clipes silenciados ({0})"

+ 1 - 1
scripts/build-local.sh

@@ -49,7 +49,7 @@ CORE="$CORE src/core/DirectWave.cpp"
 # Ogg Vorbis decoding as FL does (REA round 77)
 CORE="$CORE src/core/OggVorbis.cpp"
 # export options, MP3 encoding, plugin performance monitor, clip properties / arrangements (round 84)
-CORE="$CORE src/core/ExportOptions.cpp src/core/Mp3Encoder.cpp src/core/PluginMonitor.cpp src/core/PlaylistOps.cpp src/core/ProjectContents.cpp"
+CORE="$CORE src/core/ExportOptions.cpp src/core/Mp3Encoder.cpp src/core/PluginMonitor.cpp src/core/PlaylistOps.cpp src/core/ProjectContents.cpp src/core/TempoDetect.cpp"
 # LYNX's Facet EQ and Apex Limiter (round 99)
 CORE="$CORE src/core/FacetEq.cpp src/core/ApexLimiter.cpp"
 # LYNX's dynamics suite and FabFilter state translation (round 108)

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

@@ -129,7 +129,7 @@ APP_SOURCES+=(src/core/DirectWave.cpp)
 # Ogg Vorbis decoding as FL does (REA round 77)
 APP_SOURCES+=(src/core/OggVorbis.cpp)
 # export options + MP3, plugin performance monitor, clip properties / arrangements, new project, touch keyboard (round 84)
-APP_SOURCES+=(src/core/ExportOptions.cpp src/core/Mp3Encoder.cpp src/core/PluginMonitor.cpp src/core/PlaylistOps.cpp src/core/ProjectContents.cpp)
+APP_SOURCES+=(src/core/ExportOptions.cpp src/core/Mp3Encoder.cpp src/core/PluginMonitor.cpp src/core/PlaylistOps.cpp src/core/ProjectContents.cpp src/core/TempoDetect.cpp)
 APP_SOURCES+=(src/ui/NewProjectDialog.cpp src/ui/ClipProperties.cpp src/ui/PluginMonitorWindow.cpp src/ui/TouchKeyboard.cpp)
 # native plugin editors in FL's arrangement (round 93)
 APP_SOURCES+=(src/core/PluginLayout.cpp src/core/StateParams.cpp src/ui/PluginEditors.cpp src/ui/PatcherEditor.cpp)

+ 63 - 0
src/core/ClipOps.h

@@ -63,6 +63,69 @@ inline std::vector<int> sameSource (const Song& song, int clip)
     return out;
 }
 
+// FL's Playlist Select > Overlapping / Stacked (REA round 153, behaviour from its manual): per track, in time order.
+// Overlapping: clips that start before an earlier clip of the track ends (every layer except the lowest).
+// Stacked: clips lying completely inside another clip of the track (exact duplicates: all but the first), so
+// deleting them leaves what is heard unchanged.
+inline std::vector<int> overlappingClips (const Song& song)
+{
+    std::vector<int> order ((std::size_t) song.playlist.size());
+    for (std::size_t i = 0; i < order.size(); ++i)
+        order[i] = (int) i;
+    std::stable_sort (order.begin(), order.end(), [&song] (int a, int b) {
+        const auto& ca = song.playlist[(std::size_t) a];
+        const auto& cb = song.playlist[(std::size_t) b];
+        return ca.track != cb.track ? ca.track < cb.track : ca.start < cb.start;
+    });
+    std::vector<int> out;
+    int track = -1;
+    std::int64_t reach = 0;
+    for (auto i : order)
+    {
+        const auto& c = song.playlist[(std::size_t) i];
+        if (c.track != track)
+        {
+            track = c.track;
+            reach = c.end();
+            continue;
+        }
+        if (c.start < reach)
+            out.push_back (i);
+        reach = std::max (reach, c.end());
+    }
+    std::sort (out.begin(), out.end());
+    return out;
+}
+
+inline std::vector<int> stackedClips (const Song& song)
+{
+    std::vector<int> out;
+    const auto& list = song.playlist;
+    for (int a = 0; a < (int) list.size(); ++a)
+        for (int b = 0; b < (int) list.size(); ++b)
+        {
+            const auto& c = list[(std::size_t) a];
+            const auto& o = list[(std::size_t) b];
+            if (a == b || o.track != c.track || o.start > c.start || o.end() < c.end())
+                continue;
+            if (! (o.start == c.start && o.end() == c.end()) || b < a)
+            {
+                out.push_back (a);
+                break;
+            }
+        }
+    return out;
+}
+
+inline std::vector<int> mutedClips (const Song& song)
+{
+    std::vector<int> out;
+    for (int i = 0; i < (int) song.playlist.size(); ++i)
+        if (song.playlist[(std::size_t) i].muted)
+            out.push_back (i);
+    return out;
+}
+
 // Audio "Make unique": the clips get their own copy of the audio channel (so reversing, stretching or renaming
 // them leaves the other clips of that sample alone). Returns the new channel, or -1.
 inline int makeAudioUnique (Song& song, const std::vector<int>& clips)

+ 1 - 0
src/core/FlpImport.cpp

@@ -2636,6 +2636,7 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
             note.muted = n.muted();
             note.slide = n.slide();
             note.porta = n.porta();
+            note.colour = n.extra & 0x0F;
             p.notes.push_back (note);
         }
 

+ 1 - 1
src/core/History.cpp

@@ -10,7 +10,7 @@ bool sameNote (const Note& a, const Note& b) noexcept
 {
     return a.start == b.start && a.length == b.length && a.channel == b.channel && a.key == b.key && a.velocity == b.velocity
            && a.pan == b.pan && a.finePitch == b.finePitch && a.muted == b.muted && a.slide == b.slide && a.porta == b.porta
-           && a.release == b.release && a.modX == b.modX && a.modY == b.modY;
+           && a.release == b.release && a.modX == b.modX && a.modY == b.modY && a.colour == b.colour;
 }
 
 bool sameNotes (const std::vector<Note>& a, const std::vector<Note>& b) noexcept

+ 4 - 0
src/core/KeyMap.cpp

@@ -124,6 +124,10 @@ std::vector<Action> makeActions()
         { "pianoRoll.articulate", TR_NOOP ("Articulate..."), Context::pianoRoll, { chord ('L', alt) } },
         { "pianoRoll.riffMachine", TR_NOOP ("Riff machine..."), Context::pianoRoll, { chord ('E', alt) } },
         { "pianoRoll.chordProgression", TR_NOOP ("Generate chord progression..."), Context::pianoRoll, { chord ('P', alt) } },
+        // note colours and the Select menu (REA round 153: FL's keys from its piano roll manual)
+        { "pianoRoll.colourSelected", TR_NOOP ("Colour the selected notes with the note colour"), Context::pianoRoll, { chord ('C', alt) } },
+        { "pianoRoll.selectByColour", TR_NOOP ("Select the notes of the same colour"), Context::pianoRoll, { chord ('C', shift) } },
+        { "pianoRoll.invertSelection", TR_NOOP ("Invert the note selection"), Context::pianoRoll, { chord ('I', shift) } },
         { "pianoRoll.zoomIn", TR_NOOP ("Zoom in"), Context::pianoRoll, { chord (pageUp) } },
         { "pianoRoll.zoomOut", TR_NOOP ("Zoom out"), Context::pianoRoll, { chord (pageDown) } },
         { "pianoRoll.zoom1", TR_NOOP ("Zoom: one bar"), Context::pianoRoll, { chord ('1', shift) }, true },

+ 123 - 0
src/core/NoteTools.cpp

@@ -2,6 +2,7 @@
 
 #include <algorithm>
 #include <cmath>
+#include <iterator>
 #include <map>
 #include <tuple>
 
@@ -536,4 +537,126 @@ std::vector<int> selectLoudest (const Pattern& pattern, const std::vector<int>&
     std::sort (list.begin(), list.end());
     return list;
 }
+
+// --- selection helpers ------------------------------------------------------------------------
+
+std::vector<int> invertSelection (const std::vector<int>& all, const std::vector<int>& selected)
+{
+    auto a = all, b = selected;
+    std::sort (a.begin(), a.end());
+    a.erase (std::unique (a.begin(), a.end()), a.end());
+    std::sort (b.begin(), b.end());
+    std::vector<int> out;
+    std::set_difference (a.begin(), a.end(), b.begin(), b.end(), std::back_inserter (out));
+    return out;
+}
+
+std::vector<int> selectByColour (const Pattern& pattern, const std::vector<int>& indices, int colour)
+{
+    std::vector<int> out;
+    for (auto i : validSorted (pattern, indices))
+        if (pattern.notes[(std::size_t) i].colour == colour)
+            out.push_back (i);
+    return out;
+}
+
+namespace
+{
+std::vector<int> inTimeOrder (const Pattern& pattern, const std::vector<int>& indices)
+{
+    auto list = validSorted (pattern, indices);
+    std::stable_sort (list.begin(), list.end(), [&pattern] (int a, int b) {
+        const auto& na = pattern.notes[(std::size_t) a];
+        const auto& nb = pattern.notes[(std::size_t) b];
+        return std::tie (na.start, na.key) < std::tie (nb.start, nb.key);
+    });
+    return list;
+}
+} // namespace
+
+std::vector<int> selectOdd (const Pattern& pattern, const std::vector<int>& indices)
+{
+    const auto list = inTimeOrder (pattern, indices);
+    std::vector<int> out;
+    for (std::size_t k = 0; k < list.size(); k += 2)
+        out.push_back (list[k]);
+    std::sort (out.begin(), out.end());
+    return out;
+}
+
+std::vector<int> selectRandom (const Pattern& pattern, const std::vector<int>& indices, float fraction, std::uint32_t seed)
+{
+    Random random (seed);
+    const auto f = std::clamp (fraction, 0.0f, 1.0f);
+    std::vector<int> out;
+    for (auto i : validSorted (pattern, indices))
+        if (random.next() < f)
+            out.push_back (i);
+    return out;
+}
+
+std::vector<int> selectMuted (const Pattern& pattern, const std::vector<int>& indices)
+{
+    std::vector<int> out;
+    for (auto i : validSorted (pattern, indices))
+        if (pattern.notes[(std::size_t) i].muted)
+            out.push_back (i);
+    return out;
+}
+
+std::vector<int> selectOverlapping (const Pattern& pattern, const std::vector<int>& indices)
+{
+    // per key, in time order: a note starting before the furthest end so far overlaps an earlier one
+    const auto list = inTimeOrder (pattern, indices);
+    std::map<int, std::int64_t> reach; // key -> furthest end of the notes seen
+    std::vector<int> out;
+    for (auto i : list)
+    {
+        const auto& n = pattern.notes[(std::size_t) i];
+        const auto it = reach.find (n.key);
+        if (it != reach.end() && n.start < it->second)
+        {
+            out.push_back (i);
+            it->second = std::max (it->second, (n.start + n.length));
+        }
+        else
+            reach[n.key] = (n.start + n.length);
+    }
+    std::sort (out.begin(), out.end());
+    return out;
+}
+
+std::vector<int> selectStacked (const Pattern& pattern, const std::vector<int>& indices)
+{
+    const auto list = inTimeOrder (pattern, indices);
+    std::vector<int> out;
+    for (std::size_t a = 0; a < list.size(); ++a)
+    {
+        const auto& n = pattern.notes[(std::size_t) list[a]];
+        for (std::size_t b = 0; b < list.size(); ++b)
+        {
+            if (a == b)
+                continue;
+            const auto& o = pattern.notes[(std::size_t) list[b]];
+            if (o.key != n.key || o.start > n.start || (o.start + o.length) < (n.start + n.length))
+                continue;
+            // inside `o`; exact duplicates: only the later ones (in time order) count as stacked
+            const auto same = o.start == n.start && (o.start + o.length) == (n.start + n.length);
+            if (! same || b < a)
+            {
+                out.push_back (list[a]);
+                break;
+            }
+        }
+    }
+    std::sort (out.begin(), out.end());
+    return out;
+}
+
+void setColour (Pattern& pattern, const std::vector<int>& indices, int colour)
+{
+    const auto c = std::clamp (colour, 0, noteColourCount - 1);
+    for (auto i : validSorted (pattern, indices))
+        pattern.notes[(std::size_t) i].colour = c;
+}
 } // namespace lynx::notetools

+ 18 - 0
src/core/NoteTools.h

@@ -159,4 +159,22 @@ std::vector<int> repeatNotes (Pattern& pattern, const std::vector<int>& indices,
 std::vector<int> selectByVelocity (const Pattern& pattern, const std::vector<int>& indices, float low, float high);
 // The loudest / quietest `fraction` (0..1) of `indices` (at least one note when there are any).
 std::vector<int> selectLoudest (const Pattern& pattern, const std::vector<int>& indices, float fraction, bool loudest);
+
+// --- selection helpers (FL's piano roll Select menu, behaviour from its manual; REA round 153) ------------------
+// `all` minus `selected` (both index lists; the result is sorted).
+std::vector<int> invertSelection (const std::vector<int>& all, const std::vector<int>& selected);
+// The notes of `indices` in colour group `colour` (0..15).
+std::vector<int> selectByColour (const Pattern& pattern, const std::vector<int>& indices, int colour);
+// Every other note in time order (start, then key): the 1st, 3rd, 5th ...
+std::vector<int> selectOdd (const Pattern& pattern, const std::vector<int>& indices);
+// About `fraction` (0..1) of `indices` chosen at random (each note independently; deterministic for a seed).
+std::vector<int> selectRandom (const Pattern& pattern, const std::vector<int>& indices, float fraction, std::uint32_t seed);
+std::vector<int> selectMuted (const Pattern& pattern, const std::vector<int>& indices);
+// Notes that overlap an earlier note of the same key (every layer except the first of each overlapping run).
+std::vector<int> selectOverlapping (const Pattern& pattern, const std::vector<int>& indices);
+// Notes that lie completely inside another note of the same key (exact duplicates: all but the first), so deleting
+// them leaves what is heard unchanged.
+std::vector<int> selectStacked (const Pattern& pattern, const std::vector<int>& indices);
+// Puts the notes into colour group `colour` (0..15).
+void setColour (Pattern& pattern, const std::vector<int>& indices, int colour);
 } // namespace lynx::notetools

+ 56 - 0
src/core/PianoRollTools.cpp

@@ -1,6 +1,7 @@
 #include "core/PianoRollTools.h"
 
 #include <algorithm>
+#include <bit>
 #include <cmath>
 #include <map>
 #include <random>
@@ -1028,6 +1029,61 @@ std::string chordName (const Chord& c)
     return s;
 }
 
+std::optional<DetectedChord> detectChord (std::vector<int> keys, bool preferFlats)
+{
+    keys.erase (std::remove_if (keys.begin(), keys.end(), [] (int k) { return k < 0 || k > 127; }), keys.end());
+    std::sort (keys.begin(), keys.end());
+    keys.erase (std::unique (keys.begin(), keys.end()), keys.end());
+    if (keys.size() > 10)
+        keys.resize (10);
+
+    unsigned set = 0;
+    for (auto k : keys)
+        set |= 1u << (k % 12);
+    if (std::popcount (set) < 2)
+        return std::nullopt;
+
+    struct Template { std::initializer_list<int> intervals; const char* suffix; };
+    // in order of preference when one set fits several roots equally
+    static const Template templates[] = {
+        { { 0, 4, 7 }, "" },            { { 0, 3, 7 }, "m" },          { { 0, 3, 6 }, "dim" },
+        { { 0, 4, 8 }, "aug" },         { { 0, 2, 7 }, "sus2" },       { { 0, 5, 7 }, "sus4" },
+        { { 0, 4, 7, 10 }, "7" },       { { 0, 4, 7, 11 }, "maj7" },   { { 0, 3, 7, 10 }, "m7" },
+        { { 0, 3, 6, 10 }, "m7b5" },    { { 0, 3, 6, 9 }, "dim7" },    { { 0, 3, 7, 11 }, "m(maj7)" },
+        { { 0, 4, 7, 9 }, "6" },        { { 0, 3, 7, 9 }, "m6" },      { { 0, 5, 7, 10 }, "7sus4" },
+        { { 0, 2, 4, 7 }, "add9" },     { { 0, 2, 3, 7 }, "madd9" },   { { 0, 4, 8, 10 }, "7#5" },
+        { { 0, 4, 6, 10 }, "7b5" },     { { 0, 4, 8, 11 }, "maj7#5" },
+        { { 0, 2, 4, 7, 10 }, "9" },    { { 0, 2, 4, 7, 11 }, "maj9" }, { { 0, 2, 3, 7, 10 }, "m9" },
+        { { 0, 1, 4, 7, 10 }, "7b9" },  { { 0, 3, 4, 7, 10 }, "7#9" }, { { 0, 2, 4, 7, 9 }, "6/9" },
+        { { 0, 2, 5, 7, 10 }, "9sus4" }, { { 0, 2, 3, 5, 7, 10 }, "m11" }, { { 0, 4, 7, 9, 10 }, "13" },
+        { { 0, 4, 10 }, "7" },          { { 0, 4, 11 }, "maj7" },      { { 0, 3, 10 }, "m7" }, // without the fifth
+        { { 0, 7 }, "5" },
+    };
+    static const char* sharps[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
+    static const char* flats[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
+    const auto names = preferFlats ? flats : sharps;
+    const auto bass = keys.front() % 12;
+
+    auto mask = [] (const Template& t, int root) {
+        unsigned m = 0;
+        for (auto i : t.intervals)
+            m |= 1u << ((root + i) % 12);
+        return m;
+    };
+
+    // the bass as the root first, then any template on another root (a slash chord)
+    for (const auto& t : templates)
+        if (mask (t, bass) == set)
+            return DetectedChord { bass, bass, std::string (names[bass]) + t.suffix };
+
+    for (const auto& t : templates)
+        for (int root = 0; root < 12; ++root)
+            if (root != bass && (set >> root & 1u) != 0 && mask (t, root) == set)
+                return DetectedChord { root, bass, std::string (names[root]) + t.suffix + "/" + names[bass] };
+
+    return std::nullopt;
+}
+
 std::string toNumerals (const std::vector<Chord>& chords, int tonic)
 {
     static const char* upperNames[] = { "I", "II", "III", "IV", "V", "VI", "VII" };

+ 12 - 0
src/core/PianoRollTools.h

@@ -159,6 +159,18 @@ std::string chordName (const Chord& chord); // "Am7", "C/E"...
 // Roman numerals of the chords in the key of `tonic` ("I-V-vi-IV"), readable by parseProgression.
 std::string toNumerals (const std::vector<Chord>& chords, int tonic);
 
+// Chord detection (FL 2026's chord readout, LYNX's own rules; REA round 153): names the chord of a set of MIDI keys
+// (up to 10 are read, the rest ignored). Exact interval templates only (triads, sixths, sevenths, sus, add9, ninths,
+// power chord); the lowest key is preferred as the root, otherwise the chord is written over its bass ("Am7/C").
+// Returns nothing for fewer than two pitch classes or a set no template fits.
+struct DetectedChord
+{
+    int root = 0;      // pitch class
+    int bass = 0;      // pitch class of the lowest key
+    std::string name;  // "C", "F#m7", "Bbmaj7"... ("Am7/C" when the bass is not the root)
+};
+std::optional<DetectedChord> detectChord (std::vector<int> keys, bool preferFlats = false);
+
 struct ProgressionPreset
 {
     std::string name;          // "I-V-vi-IV: Hopeful"

+ 3 - 0
src/core/Song.h

@@ -717,8 +717,11 @@ struct Note
     bool porta = false;       // inverts the channel's porta on this note (the note glides from the previous one; as in FL)
     float release = 0.5f;     // release velocity 0..1 (Note inspector; stored, not yet used by the instruments)
     float modX = 0.5f, modY = 0.5f; // two free per-note modulation values 0..1 (stored, not yet routed)
+    int colour = 0;           // note colour group 0..15 (FL's note colours; .flp note byte 'extra' bits 0-3)
 };
 
+constexpr int noteColourCount = 16;
+
 // Swing delay (FL's formula, docs/analise/REA_rodada3.md §3): only notes whose nearest step
 // is odd move, with triangular weight by distance to the grid; half a step at swing 1.
 std::int64_t swingDelay (std::int64_t start, float swing, float channelMix = 1.0f) noexcept;

+ 209 - 0
src/core/TempoDetect.cpp

@@ -0,0 +1,209 @@
+#include "core/TempoDetect.h"
+
+#include <algorithm>
+#include <cmath>
+#include <numeric>
+
+namespace lynx::tempodetect
+{
+std::vector<float> onsetCurve (const float* left, const float* right, std::size_t frames, double sampleRate, double hopSeconds)
+{
+    std::vector<float> curve;
+    if (left == nullptr || frames == 0 || sampleRate <= 0.0)
+        return curve;
+
+    const auto hop = std::max<std::size_t> (16, (std::size_t) std::llround (hopSeconds * sampleRate));
+    const auto hops = frames / hop;
+    if (hops < 2)
+        return curve;
+
+    // three bands from two one-pole low-passes (~150 Hz and ~2 kHz): kick, body, hats
+    const auto coefficient = [sampleRate] (double hz) { return (float) (1.0 - std::exp (-2.0 * 3.14159265358979 * hz / sampleRate)); };
+    const auto aLow = coefficient (150.0), aMid = coefficient (2000.0);
+    float low = 0.0f, mid = 0.0f;
+    std::vector<float> previous (3, 0.0f);
+    curve.reserve (hops);
+
+    for (std::size_t h = 0; h < hops; ++h)
+    {
+        double e[3] = { 0.0, 0.0, 0.0 };
+        for (std::size_t i = h * hop, end = i + hop; i < end; ++i)
+        {
+            const auto x = right != nullptr ? 0.5f * (left[i] + right[i]) : left[i];
+            low += aLow * (x - low);
+            mid += aMid * (x - mid);
+            const float bands[3] = { low, mid - low, x - mid };
+            for (int b = 0; b < 3; ++b)
+                e[b] += (double) bands[b] * bands[b];
+        }
+
+        auto flux = 0.0f;
+        for (int b = 0; b < 3; ++b)
+        {
+            const auto level = (float) std::log (1.0e-10 + e[b] / (double) hop);
+            if (h > 0)
+                flux += std::max (0.0f, level - previous[(std::size_t) b]);
+            previous[(std::size_t) b] = level;
+        }
+        curve.push_back (flux);
+    }
+
+    // remove the local mean (~0.4 s) so sustained parts do not count as pulses
+    const auto half = std::max<std::size_t> (1, (std::size_t) std::llround (0.2 / hopSeconds));
+    std::vector<double> prefix (curve.size() + 1, 0.0);
+    for (std::size_t i = 0; i < curve.size(); ++i)
+        prefix[i + 1] = prefix[i] + curve[i];
+    std::vector<float> out (curve.size());
+    for (std::size_t i = 0; i < curve.size(); ++i)
+    {
+        const auto a = i > half ? i - half : 0, b = std::min (curve.size(), i + half + 1);
+        const auto mean = (prefix[b] - prefix[a]) / (double) (b - a);
+        out[i] = std::max (0.0f, curve[i] - (float) mean);
+    }
+
+    // a short triangular blur (~±15 ms): pulses a fraction of a hop apart still correlate, so the period can be
+    // read between whole hops
+    const auto radius = std::max<int> (1, (int) std::lround (0.015 / hopSeconds));
+    std::vector<float> smooth (out.size(), 0.0f);
+    for (std::size_t i = 0; i < out.size(); ++i)
+    {
+        double sum = 0.0, weights = 0.0;
+        for (int k = -radius; k <= radius; ++k)
+        {
+            const auto j = (long long) i + k;
+            if (j < 0 || j >= (long long) out.size())
+                continue;
+            const auto w = (double) (radius + 1 - std::abs (k));
+            sum += w * out[(std::size_t) j];
+            weights += w;
+        }
+        smooth[i] = (float) (sum / weights);
+    }
+    return smooth;
+}
+
+Result detect (const float* left, const float* right, std::size_t frames, double sampleRate, const Options& options)
+{
+    Result result;
+    if (sampleRate <= 0.0 || frames < (std::size_t) (2.0 * sampleRate))
+        return result;
+    // the hop in whole frames (as onsetCurve rounds it): its exact length in seconds keeps the tempo unbiased
+    const auto hopFrames = std::max<long long> (16, std::llround (0.005 * sampleRate));
+    const auto hopSeconds = (double) hopFrames / sampleRate;
+
+    // at most two minutes are read (enough for a steady tempo; a long file stays quick)
+    const auto analysed = std::min (frames, (std::size_t) (120.0 * sampleRate));
+    const auto curve = onsetCurve (left, right, analysed, sampleRate, hopSeconds);
+    const auto n = curve.size();
+    const auto minBpm = std::clamp (options.minBpm, 20.0, 400.0);
+    const auto maxBpm = std::clamp (options.maxBpm, minBpm + 1.0, 800.0);
+    constexpr int harmonics = 4;
+    const auto maxLag = (std::size_t) std::ceil (harmonics * 60.0 / (minBpm * hopSeconds)) + 2;
+    if (n < maxLag + 8)
+        return result;
+
+    const auto energy = std::inner_product (curve.begin(), curve.end(), curve.begin(), 0.0);
+    if (energy <= 1.0e-9)
+        return result;
+
+    // autocorrelation per lag, normalised by the overlap
+    std::vector<double> r (maxLag + 1, 0.0);
+    for (std::size_t lag = 1; lag <= maxLag; ++lag)
+    {
+        double sum = 0.0;
+        for (std::size_t i = lag; i < n; ++i)
+            sum += (double) curve[i] * curve[i - lag];
+        r[lag] = sum / (double) (n - lag);
+    }
+    const auto at = [&r] (double lag) {
+        const auto i = (std::size_t) lag;
+        if (i + 1 >= r.size())
+            return 0.0;
+        const auto f = lag - (double) i;
+        return r[i] * (1.0 - f) + r[i + 1] * f;
+    };
+
+    // a comb over the period and its multiples, with a mild preference for the middle of the range (geometric)
+    const auto middle = std::sqrt (minBpm * maxBpm);
+    auto score = [&] (double bpm) {
+        const auto period = 60.0 / (bpm * hopSeconds);
+        double s = 0.0;
+        for (int k = 1; k <= harmonics; ++k)
+            s += at (period * k) / (double) k;
+        const auto octaves = std::log2 (bpm / middle);
+        return s * std::exp (-0.5 * octaves * octaves / (1.2 * 1.2));
+    };
+
+    auto best = minBpm, bestScore = -1.0, total = 0.0;
+    int count = 0;
+    for (auto bpm = minBpm; bpm <= maxBpm + 1.0e-9; bpm += 0.05)
+    {
+        const auto s = score (bpm);
+        total += s;
+        ++count;
+        if (s > bestScore)
+        {
+            bestScore = s;
+            best = bpm;
+        }
+    }
+    // refine the period on many beats (fractional-lag correlation of the curve itself, up to 16 periods):
+    // a long lag reads the tempo far more precisely than one period
+    const auto direct = [&curve, n] (double lag) {
+        const auto whole = (std::size_t) lag;
+        const auto f = (float) (lag - (double) whole);
+        if (whole + 2 >= n)
+            return 0.0;
+        double sum = 0.0;
+        for (std::size_t i = whole + 1; i < n; ++i)
+            sum += (double) curve[i] * (curve[i - whole] * (1.0f - f) + curve[i - whole - 1] * f);
+        return sum / (double) (n - whole);
+    };
+    {
+        const auto period = 60.0 / (best * hopSeconds);
+        const auto periods = std::clamp ((int) ((double) n * 0.5 / period), 1, 16);
+        auto fine = [&] (double bpm) {
+            const auto p = 60.0 / (bpm * hopSeconds);
+            double s = 0.0;
+            for (int k = 1; k <= periods; ++k)
+                s += direct (p * k);
+            return s;
+        };
+        auto bestFine = fine (best);
+        const auto centre = best;
+        for (int step = -40; step <= 40; ++step)
+        {
+            const auto bpm = centre * (1.0 + 0.0002 * step);
+            if (const auto s = fine (bpm); s > bestFine)
+            {
+                bestFine = s;
+                best = bpm;
+            }
+        }
+    }
+
+    const auto mean = total / std::max (1, count);
+    if (bestScore <= 0.0)
+        return result;
+    result.confidence = std::clamp ((bestScore - mean) / bestScore, 0.0, 1.0);
+    result.bpm = best;
+
+    const auto seconds = (double) frames / sampleRate;
+    if (options.snapToLength)
+    {
+        // a loop of whole beats: the length gives the exact tempo
+        const auto beats = seconds * best / 60.0;
+        const auto whole = std::round (beats);
+        if (whole >= 4.0)
+        {
+            const auto exact = whole * 60.0 / seconds;
+            if (std::abs (exact - best) / best < 0.002 && exact >= minBpm - 0.5 && exact <= maxBpm + 0.5)
+                result.bpm = exact;
+        }
+    }
+    if (options.wholeBpm)
+        result.bpm = std::round (result.bpm);
+    result.beats = seconds * result.bpm / 60.0;
+    return result;
+}
+} // namespace lynx::tempodetect

+ 32 - 0
src/core/TempoDetect.h

@@ -0,0 +1,32 @@
+#pragma once
+
+// Tempo detection of audio (FL's audio clip "Detect tempo", behaviour from its manual; the method is LYNX's own,
+// REA round 153): an onset-strength curve from band energies, its autocorrelation over the tempo range, and a final
+// snap to the sample's length when the sample is a loop of whole beats.
+
+#include <cstddef>
+#include <cstdint>
+#include <vector>
+
+namespace lynx::tempodetect
+{
+struct Options
+{
+    double minBpm = 70.0, maxBpm = 180.0; // the range the result is folded into
+    bool wholeBpm = false;                // FL 2024's "ignore decimals": round the result to a whole BPM
+    bool snapToLength = true;             // a loop of whole beats: the tempo that fits its length exactly
+};
+
+struct Result
+{
+    double bpm = 0.0;        // 0 = no tempo found (silence, too short, no pulse)
+    double confidence = 0.0; // 0..1: how much the winning period stands out
+    double beats = 0.0;      // the sample's length in beats at `bpm`
+};
+
+// `left` / `right` (right may be null = mono) with `frames` frames at `sampleRate`.
+Result detect (const float* left, const float* right, std::size_t frames, double sampleRate, const Options& options = {});
+
+// The onset-strength curve (one value per hop of `hopSeconds`), exposed for tests.
+std::vector<float> onsetCurve (const float* left, const float* right, std::size_t frames, double sampleRate, double hopSeconds);
+} // namespace lynx::tempodetect

+ 36 - 0
src/engine/AudioEngine.cpp

@@ -548,10 +548,41 @@ double AudioEngine::getPreviewPosition() const noexcept
     return preview != nullptr ? preview->getPlayPosition() : -1.0;
 }
 
+void AudioEngine::markHeldKey (int key, bool on) noexcept
+{
+    if (key < 0 || key > 127)
+        return;
+    auto& count = heldKeyCount[(std::size_t) key];
+    auto before = count.load();
+    std::uint8_t after = 0;
+    do
+        after = on ? (std::uint8_t) std::min (255, before + 1) : (std::uint8_t) (before > 0 ? before - 1 : 0);
+    while (! count.compare_exchange_weak (before, after));
+    const auto bit = std::uint64_t { 1 } << (key & 63);
+    if (after > 0)
+        heldKeyBits[key >> 6].fetch_or (bit);
+    else
+        heldKeyBits[key >> 6].fetch_and (~bit);
+}
+
+std::vector<int> AudioEngine::heldInputKeys() const
+{
+    std::vector<int> keys;
+    for (int word = 0; word < 2; ++word)
+    {
+        const auto bits = heldKeyBits[word].load();
+        for (int b = 0; b < 64; ++b)
+            if ((bits >> b & 1u) != 0)
+                keys.push_back (word * 64 + b);
+    }
+    return keys;
+}
+
 void AudioEngine::sendLiveNote (int channel, int key, float velocity, bool on, bool record)
 {
     if (record) // played notes (the PC keyboard) follow the scale snap; previews don't
     {
+        markHeldKey (key, on);
         // the note-off stops the key its note-on started, even if the snap changed in between
         const auto requested = key;
         if (on)
@@ -581,6 +612,10 @@ void AudioEngine::panic()
     e.type = NoteEvent::Type::choke;
     e.channel = -1; // every channel
     liveEvents.push (e);
+    for (auto& c : heldKeyCount)
+        c.store (0);
+    for (auto& w : heldKeyBits)
+        w.store (0);
 }
 
 double AudioEngine::estimatedPositionNow() const noexcept
@@ -969,6 +1004,7 @@ void AudioEngine::handleIncomingMidiMessage (juce::MidiInput* source, const juce
         return;
 
     const auto on = m.isNoteOn();
+    markHeldKey (m.getNoteNumber(), on);
 
     if (on)
         startOnInput();

+ 6 - 0
src/engine/AudioEngine.h

@@ -142,6 +142,9 @@ public:
     // Note played live (PC keyboard, preview). UI thread.
     // `record` = goes into the recording if recording is on (Piano Roll preview doesn't).
     void sendLiveNote (int channel, int key, float velocity, bool on, bool record = false);
+    // The keys held right now on MIDI inputs and the typing piano (as played, before the scale snap), ascending; for
+    // the Piano Roll's chord readout (any thread).
+    std::vector<int> heldInputKeys() const;
 
     // Scale snap for played notes (MIDI input and the PC keyboard): scale index into notetools::scales()
     // (0 = off) and its root (0..11). Any thread.
@@ -453,6 +456,9 @@ private:
     LiveEventQueue liveEvents;   // UI -> audio
     LiveEventQueue midiEvents;   // MIDI thread -> audio
     InputHeldNotes midiHeld;     // MIDI thread: what each held MIDI key started
+    std::atomic<std::uint64_t> heldKeyBits[2] {}; // keys held on MIDI inputs / the typing piano (chord readout)
+    std::atomic<std::uint8_t> heldKeyCount[128] {};
+    void markHeldKey (int key, bool on) noexcept;
     KeyLedger playedKeys;        // UI thread: the keys the typing piano started (after the scale snap)
     SpscQueue<RecordedEvent, 1024> midiRecordQueue; // MIDI thread -> UI (recording)
 

+ 4 - 2
src/engine/MidiFileIo.cpp

@@ -80,6 +80,7 @@ std::optional<Parsed> parse (const juce::File& file, juce::String& error)
                 n.length = std::max<std::int64_t> (1, end - n.start);
                 n.key = m.getNoteNumber();
                 n.velocity = m.getFloatVelocity();
+                n.colour = juce::jlimit (0, noteColourCount - 1, m.getChannel() - 1); // FL: MIDI channel = note colour
                 notes.push_back (n);
                 channels.push_back (juce::jlimit (0, 15, m.getChannel() - 1));
             }
@@ -235,8 +236,9 @@ bool savePattern (const Song& song, int patternIndex, const juce::File& file, ju
     {
         auto& seq = byChannel[n.channel];
         const auto velocity = (juce::uint8) juce::jlimit (1, 127, juce::roundToInt (n.velocity * 127.0f));
-        seq.addEvent (juce::MidiMessage::noteOn (1, n.key, velocity), (double) n.start);
-        seq.addEvent (juce::MidiMessage::noteOff (1, n.key), (double) (n.start + std::max<std::int64_t> (1, n.length)));
+        const auto midiChannel = juce::jlimit (1, 16, n.colour + 1); // FL: the note colour is the MIDI channel
+        seq.addEvent (juce::MidiMessage::noteOn (midiChannel, n.key, velocity), (double) n.start);
+        seq.addEvent (juce::MidiMessage::noteOff (midiChannel, n.key), (double) (n.start + std::max<std::int64_t> (1, n.length)));
     }
 
     juce::MidiFile midi;

+ 6 - 1
src/engine/ProjectFile.cpp

@@ -1339,7 +1339,8 @@ juce::String toJson (const Song& song)
                                           juce::roundToInt (n.velocity * 1000.0f) / 1000.0 };
 
             // [.., pan, fine pitch, muted] only when not default
-            const auto extra = n.release != 0.5f || n.modX != 0.5f || n.modY != 0.5f; // [.., release, mod X, mod Y]
+            // [.., release, mod X, mod Y (, colour)]
+            const auto extra = n.release != 0.5f || n.modX != 0.5f || n.modY != 0.5f || n.colour != 0;
             if (n.pan != 0.0f || n.finePitch != 0.0f || n.muted || n.slide || n.porta || extra)
             {
                 note.add (juce::roundToInt (n.pan * 1000.0f) / 1000.0);
@@ -1351,6 +1352,8 @@ juce::String toJson (const Song& song)
                 if (extra)
                     for (auto v : { n.release, n.modX, n.modY })
                         note.add (juce::roundToInt (v * 1000.0f) / 1000.0);
+                if (n.colour != 0)
+                    note.add (n.colour);
             }
 
             notes.add (note);
@@ -1617,6 +1620,8 @@ std::optional<Song> fromJson (const juce::String& json, juce::String& error)
                             note.modX = juce::jlimit (0.0f, 1.0f, (float) (double) n[11]);
                             note.modY = juce::jlimit (0.0f, 1.0f, (float) (double) n[12]);
                         }
+                        if (n.size() >= 14)
+                            note.colour = juce::jlimit (0, noteColourCount - 1, (int) n[13]);
                     }
 
                     if (note.channel >= 0 && note.channel < (int) song.channels.size())

+ 93 - 1
src/ui/I18nData.h

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

+ 141 - 2
src/ui/PianoRollComponent.cpp

@@ -179,6 +179,21 @@ PianoRollComponent::PianoRollComponent (AudioEngine& e)
     slideButton.setColour (juce::TextButton::buttonOnColourId, theme::colour::accent);
     addAndMakeVisible (slideButton);
 
+    colourButton.setTooltip (tr ("Note colour: new notes get this colour. Click: choose it, colour the selection (Alt+C), "
+                                 "select by colour (Shift+C)"));
+    ui::setQuickTip (colourButton, tr ("Note colour"));
+    colourButton.setWantsKeyboardFocus (false);
+    colourButton.setMouseClickGrabsKeyboardFocus (false);
+    colourButton.onClick = [this] { showColourMenu(); };
+    addAndMakeVisible (colourButton);
+
+    chordLabel.setJustificationType (juce::Justification::centred);
+    chordLabel.setFont (theme::font (theme::type::caption, true));
+    chordLabel.setColour (juce::Label::textColourId, theme::colour::textPrimary);
+    chordLabel.setTooltip (tr ("Chord: the chord of the keys held on the MIDI keyboard or the typing piano, else of the selected notes"));
+    chordLabel.setInterceptsMouseClicks (true, false);
+    addAndMakeVisible (chordLabel);
+
     for (auto* box : { &chordBox, &scaleBox })
     {
         box->setWantsKeyboardFocus (false);
@@ -354,6 +369,7 @@ void PianoRollComponent::resized()
     place (snapBox, 128);
     place (ghostButton, h);
     place (slideButton, 54, true);
+    place (colourButton, h, true);
     place (chordBox, 86, true);
     place (scaleBox, 150, true);
     if (scaleBox.isVisible())
@@ -361,6 +377,7 @@ void PianoRollComponent::resized()
     else
         scaleSnapButton.setVisible (false);
     place (moreButton, h);
+    place (chordLabel, 84, true);
     laneBox.setBounds (2, velocityArea().getY() + 4, keyboardWidth - 4, 20);
     overview.setBounds (keyboardWidth, toolbarHeight, getWidth() - keyboardWidth - scrollBarSize, overviewHeight);
     vBar.setBounds (getWidth() - scrollBarSize, headerHeight, scrollBarSize, getHeight() - headerHeight - velocityHeight);
@@ -546,6 +563,7 @@ void PianoRollComponent::drumPaintAt (juce::Point<int> p, bool snapOn)
     n.length = cell;
     n.key = key;
     n.channel = channel;
+    n.colour = noteColour;
     editNotes ([&n] (Pattern& pat) { noteedit::paste (pat, { n }, 0); });
 
     if (key != previewKey)
@@ -732,7 +750,7 @@ void PianoRollComponent::paint (juce::Graphics& g)
             const auto hovered = i == hover.note && drag == Drag::none;
             const auto r = juce::Rectangle<float> ((float) tickToX ((double) n.start), (float) keyToY (n.key) + 1,
                                                    juce::jmax (4.0f, (float) (n.length * pixelsPerTick) - 1.0f), (float) rowHeight - 2);
-            auto fill = selected ? accentHover.brighter (0.15f) : n.muted ? noteMuted : theme::noteColour (n.velocity);
+            auto fill = selected ? accentHover.brighter (0.15f) : n.muted ? noteMuted : theme::noteGroupColour (n.colour, n.velocity);
             if (hovered)
                 fill = fill.brighter (0.18f);
             g.setColour (fill);
@@ -882,7 +900,7 @@ void PianoRollComponent::paint (juce::Graphics& g)
 
             const auto x = (float) tickToX ((double) n.start);
             const auto top = (float) lane.getBottom() - 2.0f - usable * laneValue (n);
-            auto colour = isSelected (i) ? accentHover.brighter (0.15f) : theme::noteColour (n.velocity);
+            auto colour = isSelected (i) ? accentHover.brighter (0.15f) : theme::noteGroupColour (n.colour, n.velocity);
             if (n.muted)
                 colour = noteMuted;
             const auto hovered = i == hover.note && drag == Drag::none;
@@ -1174,6 +1192,7 @@ void PianoRollComponent::paintNoteAt (std::int64_t start, int key, bool monophon
     n.key = key;
     n.channel = engine.getSelectedChannel();
     n.slide = slideButton.getToggleState();
+    n.colour = noteColour;
 
     std::vector<Note> stamp;
     for (auto interval : chordIntervals())
@@ -1526,6 +1545,7 @@ void PianoRollComponent::mouseDown (const juce::MouseEvent& e)
     n.key = snapKey (yToKey (e.y));
     n.channel = engine.getSelectedChannel();
     n.slide = slideButton.getToggleState();
+    n.colour = noteColour;
 
     std::vector<Note> stamp;
     for (auto interval : chordIntervals())
@@ -2453,6 +2473,7 @@ void PianoRollComponent::showMoreMenu()
     menu.addItem (tr ("Rotate right within the bar") + "\tCtrl+Shift+Right", [this, grid, bar] { runOperation ([grid, bar] (Pattern& p, const std::vector<int>& t) { noteedit::rotate (p, t, grid, bar, 1); return t; }); });
     menu.addSeparator();
     menu.addSubMenu (tr ("Tools"), toolsMenu());
+    menu.addSubMenu (tr ("Select"), selectMenu());
     {
         juce::PopupMenu zoom;
         zoom.addItem (tr ("Zoom in") + "\tPageUp", [this] { runAction ("pianoRoll.zoomIn"); });
@@ -2634,6 +2655,115 @@ void PianoRollComponent::centreOnPlayhead()
     repaint();
 }
 
+void PianoRollComponent::ColourSwatch::paintButton (juce::Graphics& g, bool over, bool down)
+{
+    auto r = getLocalBounds().toFloat().reduced (3.0f);
+    g.setColour (theme::noteGroupColour (colourIndex, 0.85f));
+    g.fillRoundedRectangle (r, 3.0f);
+    g.setColour (over || down ? theme::colour::textPrimary : theme::colour::bg0.withAlpha (0.7f));
+    g.drawRoundedRectangle (r, 3.0f, 1.0f);
+    g.setColour (theme::colour::bg0.withAlpha (0.85f));
+    g.setFont (theme::font (theme::type::caption, true));
+    g.drawText (juce::String (colourIndex + 1), r, juce::Justification::centred, false);
+}
+
+void PianoRollComponent::colourSelection (int colour)
+{
+    const auto target = selection;
+    if (target.empty())
+        return;
+    editNotes ([&] (Pattern& p) { notetools::setColour (p, target, colour); });
+    repaint();
+}
+
+void PianoRollComponent::selectByColour (int colour)
+{
+    setSelection (notetools::selectByColour (currentPattern (engine.getSong()), channelNotes(), colour));
+}
+
+void PianoRollComponent::showColourMenu()
+{
+    juce::PopupMenu menu;
+    menu.addSectionHeader (tr ("Colour for new notes"));
+    for (int c = 0; c < noteColourCount; ++c)
+        menu.addColouredItem (c + 1, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f), true, c == noteColour);
+    menu.addSeparator();
+    menu.addItem (1000, tr ("Colour the selected notes with it") + "\tAlt+C", ! selection.empty());
+    {
+        juce::PopupMenu colourAs;
+        for (int c = 0; c < noteColourCount; ++c)
+            colourAs.addColouredItem (2001 + c, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f), true, false);
+        menu.addSubMenu (tr ("Colour the selected notes"), colourAs, ! selection.empty());
+    }
+    {
+        juce::PopupMenu select;
+        const auto& pattern = currentPattern (engine.getSong());
+        for (int c = 0; c < noteColourCount; ++c)
+            select.addColouredItem (3001 + c, tr ("Colour {0}", { juce::String (c + 1) }), theme::noteGroupColour (c, 0.9f),
+                                    ! notetools::selectByColour (pattern, channelNotes(), c).empty(), false);
+        menu.addSubMenu (tr ("Select by colour") + "\tShift+C", select);
+    }
+    menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (&colourButton), [safe = juce::Component::SafePointer (this)] (int id) {
+        if (safe == nullptr || id <= 0)
+            return;
+        if (id <= noteColourCount)
+        {
+            safe->noteColour = id - 1;
+            safe->colourButton.colourIndex = id - 1;
+            safe->colourButton.repaint();
+        }
+        else if (id == 1000)
+            safe->colourSelection (safe->noteColour);
+        else if (id > 2000 && id <= 2000 + noteColourCount)
+            safe->colourSelection (id - 2001);
+        else if (id > 3000 && id <= 3000 + noteColourCount)
+            safe->selectByColour (id - 3001);
+    });
+}
+
+juce::PopupMenu PianoRollComponent::selectMenu()
+{
+    // FL's piano roll Select submenu (its manual): all, invert, odd, random, muted, overlapping, stacked, by colour
+    juce::PopupMenu menu;
+    auto choose = [this] (std::function<std::vector<int> (const Pattern&, const std::vector<int>&)> pick) {
+        setSelection (pick (currentPattern (engine.getSong()), channelNotes()));
+    };
+    menu.addItem (tr ("All") + "\tCtrl+A", [this] { selectAll(); });
+    menu.addItem (tr ("Invert selection") + "\tShift+I", [this] { runAction ("pianoRoll.invertSelection"); });
+    menu.addItem (tr ("Deselect") + "\tEsc", ! selection.empty(), false, [this] { setSelection ({}); });
+    menu.addSeparator();
+    menu.addItem (tr ("Odd notes (every other one)"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectOdd (p, t); }); });
+    menu.addItem (tr ("Even notes"), [choose] {
+        choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::invertSelection (t, notetools::selectOdd (p, t)); });
+    });
+    menu.addItem (tr ("Random (half of the notes)"), [choose] {
+        const auto seed = (std::uint32_t) juce::Random::getSystemRandom().nextInt();
+        choose ([seed] (const Pattern& p, const std::vector<int>& t) { return notetools::selectRandom (p, t, 0.5f, seed); });
+    });
+    menu.addItem (tr ("Muted notes"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectMuted (p, t); }); });
+    menu.addItem (tr ("Overlapping notes"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectOverlapping (p, t); }); });
+    menu.addItem (tr ("Stacked notes (hidden duplicates)"), [choose] { choose ([] (const Pattern& p, const std::vector<int>& t) { return notetools::selectStacked (p, t); }); });
+    menu.addItem (tr ("Same colour as the selection") + "\tShift+C", [this] { runAction ("pianoRoll.selectByColour"); });
+    return menu;
+}
+
+void PianoRollComponent::updateChordReadout()
+{
+    auto keys = engine.heldInputKeys();
+    if (keys.size() < 2)
+    {
+        keys.clear();
+        const auto& notes = currentPattern (engine.getSong()).notes;
+        for (auto i : selection)
+            if (i >= 0 && i < (int) notes.size())
+                keys.push_back (notes[(std::size_t) i].key);
+    }
+    const auto chord = prtools::detectChord (keys);
+    const auto text = chord ? juce::String (chord->name) : juce::String();
+    if (chordLabel.getText() != text)
+        chordLabel.setText (text, juce::dontSendNotification);
+}
+
 bool PianoRollComponent::runAction (const std::string& id)
 {
     auto is = [&id] (const char* name) { return id == name; };
@@ -2660,6 +2790,14 @@ bool PianoRollComponent::runAction (const std::string& id)
     else if (is ("pianoRoll.zoomAll")) zoomAll();
     else if (is ("pianoRoll.zoomSelection")) zoomToSelection();
     else if (is ("pianoRoll.centrePlayhead")) centreOnPlayhead();
+    else if (is ("pianoRoll.colourSelected")) colourSelection (noteColour);
+    else if (is ("pianoRoll.selectByColour"))
+    {
+        // the colour of the selected note (FL: the selection's colour), else the current note colour
+        const auto& notes = currentPattern (engine.getSong()).notes;
+        selectByColour (! selection.empty() && selection.front() < (int) notes.size() ? notes[(std::size_t) selection.front()].colour : noteColour);
+    }
+    else if (is ("pianoRoll.invertSelection")) setSelection (notetools::invertSelection (channelNotes(), selection));
     else
         return false;
 
@@ -3213,6 +3351,7 @@ void PianoRollComponent::timerCallback()
 {
     if (channelBox.getSelectedId() != engine.getSelectedChannel() + 1)
         refreshChannelBox();
+    updateChordReadout();
 
     auto& transport = engine.getTransport();
     auto tick = -1.0;

+ 19 - 0
src/ui/PianoRollComponent.h

@@ -183,6 +183,25 @@ private:
     juce::ComboBox chordBox; // chord created on each click (like FL's "stamp")
     juce::TextButton slideButton { "Slide" }; // new notes slide (like FL's slide tool)
     juce::ComboBox scaleBox; // scale highlighted on the keyboard rows
+    // note colour groups (FL's 16 note colours; REA round 153): new notes get `noteColour`; the swatch opens a menu
+    // that picks it, colours the selection and selects by colour
+    class ColourSwatch final : public juce::Button
+    {
+    public:
+        ColourSwatch() : juce::Button ("noteColour") {}
+        int colourIndex = 0;
+        void paintButton (juce::Graphics& g, bool over, bool down) override;
+    };
+    ColourSwatch colourButton;
+    int noteColour = 0;
+    void showColourMenu();
+    void colourSelection (int colour);   // one undo step
+    void selectByColour (int colour);    // the channel's notes of that colour
+    juce::PopupMenu selectMenu();        // FL's Select submenu (invert, odd, random, muted, overlapping, stacked, colour)
+    // chord readout (FL 2026's chord detection): the chord of the held MIDI / typing-piano keys, else of the
+    // selected notes
+    juce::Label chordLabel;
+    void updateChordReadout();
     std::vector<int> chordIntervals() const;
     bool inScale (int key) const;
     int scaleRoot() const;  // 0..11

+ 55 - 0
src/ui/PlaylistComponent.cpp

@@ -9,6 +9,7 @@
 
 #include "core/NoteEdit.h"
 #include "core/PlaylistOps.h"
+#include "core/TempoDetect.h"
 #include "ui/ExportDialog.h"
 #include "engine/Text.h"
 #include "ui/BrowserComponent.h"
@@ -2648,6 +2649,17 @@ void PlaylistComponent::showRulerMenu (int x)
     }
 
     menu.addSeparator();
+    {
+        // FL's Select submenu (REA round 153)
+        juce::PopupMenu select;
+        const auto overlapping = clipops::overlappingClips (song), stacked = clipops::stackedClips (song), muted = clipops::mutedClips (song);
+        select.addItem (tr ("Overlapping clips ({0})", { juce::String ((int) overlapping.size()) }), ! overlapping.empty(), false,
+                        [this, overlapping] { setSelection (overlapping); });
+        select.addItem (tr ("Stacked clips: hidden duplicates ({0})", { juce::String ((int) stacked.size()) }), ! stacked.empty(), false,
+                        [this, stacked] { setSelection (stacked); });
+        select.addItem (tr ("Muted clips ({0})", { juce::String ((int) muted.size()) }), ! muted.empty(), false, [this, muted] { setSelection (muted); });
+        menu.addSubMenu (tr ("Select"), select);
+    }
     menu.addItem (tr ("Ripple editing (resizing and deleting move the later clips)") + "\tShift+S", true, ripple, [this] { setRipple (! ripple); });
     {
         juce::PopupMenu zoom;
@@ -2958,6 +2970,49 @@ juce::PopupMenu PlaylistComponent::buildClipMenu (int index, int mouseX)
         fit.addItem (tr ("Original speed (no stretch)"), true, channel.sampler.stretchBeats <= 0.0f, [fitTo] { fitTo (0.0f, false); });
         menu.addSubMenu (tr ("Fit to tempo"), fit, sample != nullptr);
 
+        // FL's "Detect tempo" (REA round 153; LYNX's own detector, core/TempoDetect): a range to fold the result
+        // into, then fit the clip to the project tempo or take its tempo for the project
+        {
+            juce::PopupMenu detect;
+            struct Range { double low, high; };
+            for (const auto r : { Range { 70.0, 140.0 }, Range { 90.0, 180.0 }, Range { 60.0, 200.0 } })
+                detect.addItem (tr ("{0}-{1} BPM", { juce::String (r.low, 0), juce::String (r.high, 0) }), [this, sample, fitTo, r] {
+                    if (sample == nullptr)
+                        return;
+                    tempodetect::Options options;
+                    options.minBpm = r.low;
+                    options.maxBpm = r.high;
+                    const auto found = tempodetect::detect (sample->leftData(), sample->isStereo() ? sample->rightData() : nullptr,
+                                                            sample->frames(), sample->sampleRate, options);
+                    if (found.bpm <= 0.0)
+                    {
+                        juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Detect tempo"),
+                                                                tr ("No steady tempo was found in this sample."));
+                        return;
+                    }
+                    const auto songBpm = engine.getSong().bpm;
+                    auto* window = new juce::AlertWindow (tr ("Detect tempo"),
+                                                          tr ("Detected tempo: {0} BPM ({1} beats in the sample). The project plays at {2} BPM.",
+                                                              { juce::String (found.bpm, 2), juce::String (found.beats, 2), juce::String (songBpm, 2) }),
+                                                          juce::MessageBoxIconType::NoIcon);
+                    window->addButton (tr ("Fit the clip to the project tempo"), 1);
+                    window->addButton (tr ("Use it as the project tempo"), 2);
+                    window->addButton (tr ("Use it, rounded to a whole BPM"), 3);
+                    window->addButton (tr ("Cancel"), 0, juce::KeyPress (juce::KeyPress::escapeKey));
+                    window->enterModalState (true, juce::ModalCallbackFunction::create ([this, found, fitTo] (int result) {
+                                                 if (result == 1)
+                                                     fitTo ((float) (std::round (found.beats * 4.0) / 4.0), true);
+                                                 else if (result == 2 || result == 3)
+                                                 {
+                                                     const auto bpm = juce::jlimit (minTempo, maxTempo, result == 3 ? std::round (found.bpm) : found.bpm);
+                                                     engine.editSong ([bpm] (Song& s) { s.bpm = bpm; });
+                                                 }
+                                             }),
+                                             true);
+                });
+            menu.addSubMenu (tr ("Detect tempo"), detect, sample != nullptr);
+        }
+
         if (clip.fadeIn > 0 || clip.fadeOut > 0)
             menu.addItem (tr ("Remove fades"), [this, targets] {
                 engine.editSong ([targets] (Song& s) {

+ 17 - 0
src/ui/Theme.h

@@ -119,6 +119,23 @@ inline juce::Colour noteColour (float velocity)
     return colour::noteSoft.interpolatedWith (colour::noteHard, juce::jlimit (0.0f, 1.0f, velocity));
 }
 
+// Note colour groups (REA round 153): group 0 is LYNX's note colour, groups 1..15 LYNX's own hue wheel; the velocity
+// sets the brightness, as for group 0.
+inline juce::Colour noteGroupHue (int group)
+{
+    if (group <= 0)
+        return colour::noteHard;
+    return juce::Colour::fromHSV (std::fmod (0.02f + (float) group / 16.0f, 1.0f), 0.62f, 0.95f, 1.0f);
+}
+
+inline juce::Colour noteGroupColour (int group, float velocity)
+{
+    if (group <= 0)
+        return noteColour (velocity);
+    const auto hue = noteGroupHue (group);
+    return hue.withMultipliedBrightness (0.68f + 0.32f * juce::jlimit (0.0f, 1.0f, velocity));
+}
+
 // A user/channel colour toned down to sit on the dark surfaces without shouting.
 inline juce::Colour tame (juce::Colour c)
 {

+ 191 - 0
tests/Rea153Tests.inc

@@ -0,0 +1,191 @@
+// --- REA round 153 (fltech153): FL's note colours, the piano roll Select menu and the chord readout -------------
+
+#include "core/NoteTools.h"
+#include "core/PianoRollTools.h"
+#include "core/TempoDetect.h"
+#include "core/ClipOps.h"
+
+namespace
+{
+lynx::Note n153 (std::int64_t start, std::int64_t length, int key, int colour = 0, bool muted = false)
+{
+    lynx::Note n;
+    n.start = start;
+    n.length = length;
+    n.key = key;
+    n.colour = colour;
+    n.muted = muted;
+    return n;
+}
+} // namespace
+
+TEST (rea153_flp_note_colour_is_imported)
+{
+    // FL keeps the note colour (0..15) in the low nibble of the note's 'extra' byte (bits 4/5 = porta / muted)
+    flp::Project p;
+    p.channels.push_back ({ 0, flp::ChannelType::sampler, "Lead", "", "", 1 });
+    flp::Pattern pat;
+    pat.index = 1;
+    for (int c : { 0, 5, 15 })
+    {
+        flp::Note n;
+        n.position = (std::uint32_t) (c * 96);
+        n.length = 96;
+        n.extra = (std::uint8_t) (c | 0x20); // muted as well: the colour must not take the flag bits
+        pat.notes.push_back (n);
+    }
+    p.patterns.push_back (pat);
+    const auto song = lynx::importFlp (p);
+    CHECK (song.patterns.size() == 1);
+    if (song.patterns.size() == 1 && song.patterns[0].notes.size() == 3)
+    {
+        CHECK (song.patterns[0].notes[0].colour == 0);
+        CHECK (song.patterns[0].notes[1].colour == 5);
+        CHECK (song.patterns[0].notes[2].colour == 15);
+        CHECK (song.patterns[0].notes[2].muted);
+    }
+}
+
+TEST (rea153_select_helpers_follow_fls_select_menu)
+{
+    using namespace lynx::notetools;
+    lynx::Pattern p;
+    p.notes = { n153 (0, 96, 60, 1), n153 (0, 96, 64, 2), n153 (96, 96, 60, 1, true), n153 (192, 96, 60),
+                n153 (192, 96, 60),          // exact duplicate of note 3: stacked
+                n153 (200, 40, 60),          // inside note 3: stacked and overlapping
+                n153 (250, 100, 60) };       // starts inside note 3: overlapping, not stacked
+    const std::vector<int> all { 0, 1, 2, 3, 4, 5, 6 };
+    CHECK ((invertSelection (all, { 1, 3 }) == std::vector<int> { 0, 2, 4, 5, 6 }));
+    CHECK ((invertSelection ({ 2, 0, 2 }, {}) == std::vector<int> { 0, 2 }));
+    CHECK ((selectByColour (p, all, 1) == std::vector<int> { 0, 2 }));
+    CHECK ((selectMuted (p, all) == std::vector<int> { 2 }));
+    // time order: 0 (t0 k60), 1 (t0 k64), 2, 3, 4, 5, 6 -> every other one from the first
+    CHECK ((selectOdd (p, all) == std::vector<int> { 0, 2, 4, 6 }));
+    CHECK ((selectStacked (p, all) == std::vector<int> { 4, 5 }));
+    CHECK ((selectOverlapping (p, all) == std::vector<int> { 4, 5, 6 }));
+    // deleting the stacked notes leaves what is heard: the remaining notes still cover the same key/time
+    const auto half = selectRandom (p, all, 0.5f, 7u);
+    CHECK (half == selectRandom (p, all, 0.5f, 7u)); // deterministic for a seed
+    CHECK (selectRandom (p, all, 0.0f, 3u).empty());
+    CHECK (selectRandom (p, all, 1.0f, 3u) == all);
+    setColour (p, { 3, 4 }, 9);
+    CHECK (p.notes[3].colour == 9 && p.notes[4].colour == 9 && p.notes[5].colour == 0);
+    setColour (p, { 0 }, 40);
+    CHECK (p.notes[0].colour == lynx::noteColourCount - 1);
+}
+
+TEST (rea153_chord_detection_names_chords)
+{
+    using lynx::prtools::detectChord;
+    auto name = [] (std::vector<int> keys, bool flats = false) {
+        const auto c = detectChord (std::move (keys), flats);
+        return c ? c->name : std::string ("-");
+    };
+    CHECK (name ({ 60, 64, 67 }) == "C");
+    CHECK (name ({ 57, 60, 64 }) == "Am");
+    CHECK (name ({ 64, 67, 72 }) == "C/E");          // first inversion
+    CHECK (name ({ 55, 59, 62, 65 }) == "G7");
+    CHECK (name ({ 60, 64, 67, 69 }) == "C6");       // the bass as the root wins over Am7/C
+    CHECK (name ({ 57, 60, 64, 67 }) == "Am7");
+    CHECK (name ({ 62, 65, 69, 72 }) == "Dm7");
+    CHECK (name ({ 59, 62, 65, 69 }) == "Bm7b5");
+    CHECK (name ({ 60, 63, 66, 69 }) == "Cdim7");
+    CHECK (name ({ 60, 64, 68 }) == "Caug");
+    CHECK (name ({ 60, 62, 67 }) == "Csus2");
+    CHECK (name ({ 60, 65, 67 }) == "Csus4");
+    CHECK (name ({ 60, 64, 67, 71 }) == "Cmaj7");
+    CHECK (name ({ 60, 64, 67, 74 }) == "Cadd9");
+    CHECK (name ({ 60, 64, 67, 70, 74 }) == "C9");
+    CHECK (name ({ 40, 47 }) == "E5");               // power chord
+    CHECK (name ({ 58, 62, 65 }, true) == "Bb");
+    CHECK (name ({ 58, 62, 65 }) == "A#");
+    CHECK (name ({ 48, 60, 64, 67, 72 }) == "C");    // doubled notes and octaves
+    CHECK (name ({ 60 }) == "-");
+    CHECK (name ({ 60, 72 }) == "-");               // one pitch class
+    CHECK (name ({ 60, 61, 62 }) == "-");           // a cluster: no chord
+    const auto c = detectChord ({ 64, 67, 72 });
+    CHECK (c && c->root == 0 && c->bass == 4);
+}
+
+namespace
+{
+// a drum loop: a pitched kick on the beats, noise hats off the beat, a noise snare on 2 and 4, a little noise floor
+std::vector<float> drums153 (double bpm, double seconds, double rate, unsigned seed)
+{
+    std::vector<float> x ((std::size_t) (seconds * rate));
+    std::uint32_t state = seed * 2654435761u + 1u;
+    auto noise = [&state] {
+        state ^= state << 13;
+        state ^= state >> 17;
+        state ^= state << 5;
+        return (float) ((double) state / 4294967296.0 * 2.0 - 1.0);
+    };
+    const auto beat = 60.0 / bpm;
+    for (std::size_t i = 0; i < x.size(); ++i)
+    {
+        const auto t = (double) i / rate;
+        const auto kick = std::fmod (t, beat), hat = std::fmod (t + beat / 2.0, beat), snare = std::fmod (t + beat, 2.0 * beat);
+        x[i] = 0.02f * noise() + (float) (0.8 * std::exp (-kick * 25.0) * std::sin (2.0 * 3.14159265358979 * (50.0 + 80.0 * std::exp (-kick * 40.0)) * kick))
+               + (float) (0.15 * std::exp (-hat * 60.0)) * noise() + (float) (0.4 * std::exp (-snare * 20.0)) * noise();
+    }
+    return x;
+}
+} // namespace
+
+TEST (rea153_detect_tempo_of_drum_loops)
+{
+    using namespace lynx::tempodetect;
+    constexpr double rate = 44100.0;
+    // free lengths (not whole beats): the tempo itself within 0.05 BPM
+    for (const auto bpm : { 87.0, 100.0, 128.0, 140.0 })
+    {
+        const auto x = drums153 (bpm, 12.3, rate, (unsigned) bpm);
+        const auto r = detect (x.data(), nullptr, x.size(), rate);
+        CHECK (std::abs (r.bpm - bpm) < 0.05);
+        CHECK (r.confidence > 0.5);
+    }
+    // a loop of exactly 8 beats: its length gives the tempo exactly, and the clip spans 8 beats
+    for (const auto bpm : { 93.0, 127.0, 85.5 })
+    {
+        const auto x = drums153 (bpm, 8.0 * 60.0 / bpm, rate, 3u);
+        const auto r = detect (x.data(), x.data(), x.size(), rate);
+        CHECK (std::abs (r.bpm - bpm) < 0.002);
+        CHECK (std::abs (r.beats - 8.0) < 0.001);
+    }
+    // the range decides the octave: 75 BPM with off-beat hats reads as 150 in 90-180
+    {
+        const auto x = drums153 (75.0, 12.3, rate, 9u);
+        Options o;
+        o.minBpm = 90.0;
+        o.maxBpm = 180.0;
+        CHECK (std::abs (detect (x.data(), nullptr, x.size(), rate, o).bpm - 150.0) < 0.1);
+        o.minBpm = 60.0;
+        o.maxBpm = 120.0;
+        o.wholeBpm = true;
+        CHECK (detect (x.data(), nullptr, x.size(), rate, o).bpm == 75.0);
+    }
+    // silence and too-short audio: no tempo
+    const std::vector<float> silence ((std::size_t) (4.0 * rate), 0.0f);
+    CHECK (detect (silence.data(), nullptr, silence.size(), rate).bpm == 0.0);
+    CHECK (detect (silence.data(), nullptr, 1000, rate).bpm == 0.0);
+}
+
+TEST (rea153_playlist_select_overlapping_and_stacked_clips)
+{
+    lynx::Song song;
+    auto clip = [] (int track, std::int64_t start, std::int64_t length, bool muted = false) {
+        lynx::Clip c;
+        c.track = track;
+        c.start = start;
+        c.length = length;
+        c.muted = muted;
+        return c;
+    };
+    song.playlist = { clip (0, 0, 100), clip (0, 0, 100),  // exact duplicate: stacked
+                      clip (0, 20, 30),                     // inside clip 0: stacked
+                      clip (0, 80, 100, true),              // overlaps the end of clip 0
+                      clip (1, 50, 10), clip (0, 300, 10) };
+    CHECK ((lynx::clipops::overlappingClips (song) == std::vector<int> { 1, 2, 3 }));
+    CHECK ((lynx::clipops::stackedClips (song) == std::vector<int> { 1, 2 }));
+    CHECK ((lynx::clipops::mutedClips (song) == std::vector<int> { 3 }));
+}

+ 1 - 0
tests/tests.cpp

@@ -15820,3 +15820,4 @@ TEST (plugin_layout_options_match_the_engine_values)
 #include "Vox145Tests.inc"
 #include "Vox148Tests.inc"
 #include "Natives142Tests.inc"
+#include "Rea153Tests.inc"