Przeglądaj źródła

round190un: a tempo change never renders a warped clip's stretch on the UI (#381)

Issue #381 (chlantutztetr): a 3:53 song auto-warped (119 markers), then a drag of the
tempo display, and LYNX stopped responding. Every tempo step built the clip's channel
again on the message thread, and that build rendered the whole stretch there (1.6 s
for 3:53 on this machine; a drag makes one step per pixel).

- core/StretchDefer: the live engine's deferred stretch renders. One wanted render per
  channel, debounced (150 ms: a drag renders once, where it stops), a newer request
  cancels the running one (core/TimeStretch's stretchdetail::CancelScope; a cancelled
  render is neither cached nor written to disk), results held until the next publish
  builds the channel from them.
- RackState::build: a keep-pitch channel whose stretch changed (tempo, warp markers,
  mode, or keep pitch turned on by Auto-warp) keeps its running instrument while
  Factories::deferStretch says its render is not ready; it is marked stale and plays
  its old stretch at the speed that fits the new length (the renderer's tempo hook;
  its new voices keep their pitch through their shifters). FL plays its precomputed
  stretch modes the same way until it restretches (REA_rodada3 5.1).
- AudioEngine: the worker thread (background, the message thread's float mode), and the
  timer publishes again when a render is ready. Only engines with an audio device defer;
  exports and offline renders still render in place, bit for bit as before.
- A channel built anew from its new stretch while its clips play starts them again
  where they are (RackState::restretched; Scheduler scheduleResumedAudio, launcher
  resumeAudio for Clip-launch clips). Before, a tempo change while playing silenced a
  long stretched clip until it started again.
- buildInstrument's sample preparation moved to playedSample (shared with the worker).

Checks: --round190untest / --selftest "round190un" (src/engine/TempoStretch190unTest.cpp,
the real engine on a stand-in device): Auto-warp on the 3:53 song, 20 tempo changes in
1 s stopped and playing, tempo automation, 44.1 kHz, Beats, Stretch without markers,
Resample, Clip-launch; longest message-thread call under 50 ms (~2 ms), one render per
drag, the final stretch bit for bit a fresh render, no silence. Unit tests
stretch190un_* (queue debounce / cancel / publish, cancel scope, build, key).

(cherry picked from commit 41b8c4e063442d67d8730023744e9a0dc6b34965)
Ka1-S 3 dni temu
rodzic
commit
5e9753cd06

+ 6 - 0
CHANGELOG.md

@@ -308,6 +308,12 @@ The feature release. This section grows as the work lands in the 0.1.33 rollup.
   FL Studio 360) and 32 x Surge XT **961 MB** (was 1,045; FL Studio 963).
   FL Studio 360) and 32 x Surge XT **961 MB** (was 1,045; FL Studio 963).
 
 
 **Fixed**
 **Fixed**
+- Changing the tempo with a long warped clip no longer freezes LYNX (#381). Each tempo step rendered the clip's whole
+  stretch again on the UI, so dragging the tempo display with an auto-warped song (3:53, 119 markers) on the Playlist
+  stopped LYNX responding. The new stretch now renders in the background, once the tempo stops moving; until it's
+  ready, the clip keeps playing at the new tempo from its previous stretch, as in FL Studio, and it keeps playing when
+  the new one takes over. The same applies to warp marker edits, the stretch modes (Beats, Tones, Texture...) and
+  Clip-launch clips. Exports still render the stretch in full first.
 - Text that doesn't fit is cut with "…" instead of being squeezed (#379). Buttons, drop-downs, labels, menus, tabs and
 - Text that doesn't fit is cut with "…" instead of being squeezed (#379). Buttons, drop-downs, labels, menus, tabs and
   names narrowed their letters before cutting them, so the Playlist's snap box read "Line (follows zoom)" squashed; now
   names narrowed their letters before cutting them, so the Playlist's snap box read "Line (follows zoom)" squashed; now
   the letters keep their shape and the text ends in "…" ("Line (follows zo…"); a cut button or label shows the whole
   the letters keep their shape and the text ends in "…" ("Line (follows zo…"); a cut button or label shows the whole

+ 2 - 0
CMakeLists.txt

@@ -123,6 +123,7 @@ add_library(lynx_core STATIC
     src/core/WorkerPool.cpp
     src/core/WorkerPool.cpp
     src/core/OverloadGuard.cpp
     src/core/OverloadGuard.cpp
     src/core/TimeStretch.cpp
     src/core/TimeStretch.cpp
+    src/core/StretchDefer.cpp
     src/core/WarpEngines.cpp
     src/core/WarpEngines.cpp
     src/core/Arpeggiator.cpp
     src/core/Arpeggiator.cpp
     src/core/SynthPresets.cpp
     src/core/SynthPresets.cpp
@@ -657,6 +658,7 @@ if(LYNX_BUILD_APP)
         src/engine/ExportParityTest.cpp
         src/engine/ExportParityTest.cpp
         src/engine/InsertRecord190ubTest.cpp
         src/engine/InsertRecord190ubTest.cpp
         src/engine/SamplerPitch190udTest.cpp
         src/engine/SamplerPitch190udTest.cpp
+        src/engine/TempoStretch190unTest.cpp
         src/engine/DeviceGuard.cpp
         src/engine/DeviceGuard.cpp
         src/engine/RecoveryTest.cpp
         src/engine/RecoveryTest.cpp
         src/engine/SampleZeroTest.cpp
         src/engine/SampleZeroTest.cpp

Plik diff jest za duży
+ 16 - 0
src/Main.cpp


+ 9 - 0
src/Round190unCheck.inc

@@ -0,0 +1,9 @@
+    // Round 190un (issue #381, chlantutztetr): changing the tempo with a long warped clip froze LYNX (each tempo step
+    // rendered the clip's whole stretch on the message thread). The stretch now renders off it (core/StretchDefer.h) and
+    // the clip plays its old stretch at the new tempo meanwhile: src/engine/TempoStretch190unTest.cpp.
+    // Included in the app class of Main.cpp; --round190untest <report> [seconds] and --selftest "round190un". No window.
+    juce::String round190unCheck (juce::String& log, double seconds = 233.0)
+    {
+        const auto result = lynx::AudioEngine::tempoStretch190unSelfTest ([&log] (const juce::String& line) { log << line << "\n"; }, seconds);
+        return result.startsWith ("OK") ? juce::String ("OK") : result;
+    }

+ 17 - 0
src/core/ClipLauncher.cpp

@@ -1186,4 +1186,21 @@ void playBlock (Runtime& runtime, const Song& song, const ClipGrid& grid, const
     runtime.clock = clock + numSamples * tps;
     runtime.clock = clock + numSamples * tps;
     runtime.running.store (true, std::memory_order_relaxed);
     runtime.running.store (true, std::memory_order_relaxed);
 }
 }
+
+void resumeAudio (const Runtime& runtime, const Song& song, const std::vector<std::uint8_t>& channels, double clock, double startTick, int numSamples,
+                  double tps, EventBuffer& out, const ScheduleIndex* index, bool wrap) noexcept
+{
+    const auto& player = runtime.player;
+    auto any = false;
+    for (int i = 0; i < player.virtualCount(); ++i)
+    {
+        const auto& v = player.virtualClip (i);
+        if (v.clip.kind == ClipKind::audio && v.clip.channel >= 0 && (std::size_t) v.clip.channel < channels.size()
+            && channels[(std::size_t) v.clip.channel] != 0)
+            any = resumeAudioClipAt (song, v.clip, slotKeyBase + (std::size_t) v.slot, clock, tps, out) || any;
+    }
+    if (any)
+        out.sortByOffset();
+    scheduleResumedAudio (song, channels, startTick, numSamples, tps, out, index, wrap, &player.taken());
+}
 } // namespace lynx::launcher
 } // namespace lynx::launcher

+ 5 - 0
src/core/ClipLauncher.h

@@ -303,4 +303,9 @@ public:
 void playBlock (Runtime& runtime, const Song& song, const ClipGrid& grid, const GridIndex& gridIndex, double startTick, int numSamples,
 void playBlock (Runtime& runtime, const Song& song, const ClipGrid& grid, const GridIndex& gridIndex, double startTick, int numSamples,
                 double tps, EventBuffer& out, bool resume, const ScheduleIndex* index, bool wrap, bool chase, ScheduledNotes& notes,
                 double tps, EventBuffer& out, bool resume, const ScheduleIndex* index, bool wrap, bool chase, ScheduledNotes& notes,
                 bool fill = false) noexcept;
                 bool fill = false) noexcept;
+// Round 190un (issue #381): after playBlock, the grid's audio clips of the channels marked in `channels` that are in progress
+// at `clock` (this block's start on the runtime's clock) start there, in the middle — their channel's instrument was just
+// built anew (its new stretch), the old one's voices are gone; and the Playlist's, on the tracks the grid did not take.
+void resumeAudio (const Runtime& runtime, const Song& song, const std::vector<std::uint8_t>& channels, double clock, double startTick, int numSamples,
+                  double tps, EventBuffer& out, const ScheduleIndex* index, bool wrap) noexcept;
 } // namespace lynx::launcher
 } // namespace lynx::launcher

+ 225 - 78
src/core/RackRenderer.cpp

@@ -10,6 +10,7 @@
 #include "core/NoteChance.h"
 #include "core/NoteChance.h"
 #include "core/LynxVerbs.h"
 #include "core/LynxVerbs.h"
 #include "core/PolyEdit.h"
 #include "core/PolyEdit.h"
+#include "core/StretchDefer.h" // round 190un
 #include "core/Dropouts.h"
 #include "core/Dropouts.h"
 #include "core/HostTimelineScope.h"
 #include "core/HostTimelineScope.h"
 #include "core/Rack.h"
 #include "core/Rack.h"
@@ -233,6 +234,100 @@ std::unique_ptr<const RackState> RackState::build (Song song,
 
 
 namespace
 namespace
 {
 {
+// The sample a sampler-like channel plays (buildInstrument; round 190un: also the live engine's deferred stretch renders,
+// off the message thread): the file, its polyphonic edits, its precomputed effects, its stretch to `bpm`
+std::shared_ptr<const SampleData> playedSampleOf (const ChannelDef& channel, double bpm, const RackState::Factories& factories,
+                                                 std::vector<std::shared_ptr<const SampleData>>* keep = nullptr)
+{
+    const auto& samples = factories.samples;
+    const auto kind = channel.instrument;
+    std::shared_ptr<const SampleData> sample;
+
+    if ((kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip || kind == InstrumentKind::granulizer
+         || kind == InstrumentKind::wavetraveller || kind == InstrumentKind::fruityslicer) && samples
+        && ! channel.samplePath.empty())
+        sample = samples (channel.samplePath);
+
+    // round 190lk (core/PolyEdit.h): an audio clip whose notes were edited in the polyphonic editor plays the edited
+    // render of its sample (made once per edit state, cached; a channel without edits takes none of this)
+    const auto polyKey = kind == InstrumentKind::audioClip && sample != nullptr ? polyedit::stateKey (channel.polyEdit) : std::string();
+    if (! polyKey.empty())
+        sample = polyedit::renderedFor (channel.samplePath, sample, channel.polyEdit);
+
+    // FL's Sampler › Precomputed effects (REA_rodada167h §2): the played region, processed once
+    // Audio clips too (round 167k, FL render r167k/fl/clip/p_*: an audio clip channel's Normalize, Reverse polarity,
+    // Fade in / out play in FL); a clip plays the whole file, so the region stays whole there
+    const auto clip = kind == InstrumentKind::audioClip;
+    auto spanSettings = channel.sampler;
+    if (clip)
+        spanSettings.regionStart = 0.0f, spanSettings.regionEnd = 1.0f;
+    const auto precomputes = sample != nullptr
+                             && ((kind == InstrumentKind::sampler && precompute::needed (channel.sampler))
+                                 || (clip && channel.sampler.precompute.any()));
+    auto precomputed = false;
+
+    // pitch-preserving stretch: the sample comes already stretched to the current tempo
+    if (sample != nullptr && kind != InstrumentKind::granulizer && kind != InstrumentKind::wavetraveller
+        && kind != InstrumentKind::fruityslicer && channel.sampler.keepPitch && channel.sampler.stretchBeats > 0.0f
+        && (factories.stretchedSamples || factories.stretchedSpans)
+        && sample->frames() > 0)
+    {
+        const auto target = channel.sampler.stretchBeats * 60.0 / std::max (1.0, bpm);
+        if (precomputes && channel.sampler.warp.empty())
+        {
+            // FL stretches what plays: the region after its precomputed effects and Trim, not the whole file (round 180d:
+            // Thief's Importer Ride, 1.30 s of file faded out to 0.38 s, plays 2x slower in FL at TIME 367). The span is cut
+            // first and only it is stretched, so the stretcher's smear of the silence around it is not kept by the trim.
+            if (std::shared_ptr<const SampleData> span = precompute::apply (*sample, spanSettings); span != nullptr && span->frames() > 0)
+            {
+                const auto ratio = target / ((double) span->frames() / span->sampleRate);
+                auto stretched = factories.stretchedSpans
+                                     ? factories.stretchedSpans (channel.samplePath, precompute::variantKey (spanSettings, clip) + polyKey, span, ratio,
+                                                                 channel.sampler.stretchMethod, channel.sampler.stretchPitch, stretchOptionsOf (channel.sampler))
+                                     : std::shared_ptr<const SampleData> (timeStretchSpan (*span, ratio, channel.sampler.stretchMethod,
+                                                                                           channel.sampler.stretchPitch, stretchOptionsOf (channel.sampler)));
+                if (keep != nullptr && stretched != nullptr)
+                    keep->push_back (stretched);
+                sample = stretched != nullptr ? std::move (stretched) : std::move (span);
+                precomputed = true;
+            }
+        }
+        else if (factories.stretchedSamples)
+        {
+            // the whole file (no precomputed effects; or a warp map, whose markers are in the file's frames)
+            const auto ratio = target / ((double) precompute::stretchedFrames (sample, channel.sampler, clip) / sample->sampleRate);
+            const auto map = warpStretchMap (channel.sampler.warp, (double) sample->frames(), sample->sampleRate,
+                                             (double) std::llround ((double) sample->frames() * ratio));
+            // round 190lk: the polyphonic editor's render (not the file) is what stretches (a warp map's clip plays the
+            // file's stretch without the note edits: the span cache takes no warp map)
+            if (! polyKey.empty() && channel.sampler.warp.empty() && factories.stretchedSpans)
+            {
+                if (auto stretched = factories.stretchedSpans (channel.samplePath, polyKey, sample, ratio, channel.sampler.stretchMethod,
+                                                               channel.sampler.stretchPitch, stretchOptionsOf (channel.sampler)))
+                {
+                    if (keep != nullptr)
+                        keep->push_back (stretched);
+                    sample = std::move (stretched);
+                }
+            }
+            else if (auto stretched = factories.stretchedSamples (channel.samplePath, ratio, channel.sampler.stretchMethod, channel.sampler.stretchPitch, map,
+                                                         stretchOptionsOf (channel.sampler)))
+            {
+                if (keep != nullptr)
+                    keep->push_back (stretched);
+                sample = std::move (stretched);
+            }
+        }
+    }
+
+    if (precomputes && ! precomputed)
+        if (auto processed = precompute::apply (*sample, spanSettings))
+            sample = std::move (processed);
+    if (keep != nullptr && sample != nullptr)
+        keep->push_back (sample);
+    return sample;
+}
+
 // A channel's instrument, built new (UI thread)
 // A channel's instrument, built new (UI thread)
 // deferKeyShift (round 165i): the pitch shifters of a keep-pitch sampler are made later by the caller, all channels at
 // deferKeyShift (round 165i): the pitch shifters of a keep-pitch sampler are made later by the caller, all channels at
 // once in parallel (Thief: 29 such channels × 8 shifters took most of the 860 ms of rack_instruments, one by one)
 // once in parallel (Thief: 29 such channels × 8 shifters took most of the 860 ms of rack_instruments, one by one)
@@ -353,78 +448,7 @@ std::shared_ptr<Instrument> buildInstrument (const ChannelDef& channel, double s
         return instrument;
         return instrument;
     }
     }
 
 
-    std::shared_ptr<const SampleData> sample;
-
-    if ((kind == InstrumentKind::sampler || kind == InstrumentKind::audioClip || kind == InstrumentKind::granulizer
-         || kind == InstrumentKind::wavetraveller || kind == InstrumentKind::fruityslicer) && samples
-        && ! channel.samplePath.empty())
-        sample = samples (channel.samplePath);
-
-    // round 190lk (core/PolyEdit.h): an audio clip whose notes were edited in the polyphonic editor plays the edited
-    // render of its sample (made once per edit state, cached; a channel without edits takes none of this)
-    const auto polyKey = kind == InstrumentKind::audioClip && sample != nullptr ? polyedit::stateKey (channel.polyEdit) : std::string();
-    if (! polyKey.empty())
-        sample = polyedit::renderedFor (channel.samplePath, sample, channel.polyEdit);
-
-    // FL's Sampler › Precomputed effects (REA_rodada167h §2): the played region, processed once
-    // Audio clips too (round 167k, FL render r167k/fl/clip/p_*: an audio clip channel's Normalize, Reverse polarity,
-    // Fade in / out play in FL); a clip plays the whole file, so the region stays whole there
-    const auto clip = kind == InstrumentKind::audioClip;
-    auto spanSettings = channel.sampler;
-    if (clip)
-        spanSettings.regionStart = 0.0f, spanSettings.regionEnd = 1.0f;
-    const auto precomputes = sample != nullptr
-                             && ((kind == InstrumentKind::sampler && precompute::needed (channel.sampler))
-                                 || (clip && channel.sampler.precompute.any()));
-    auto precomputed = false;
-
-    // pitch-preserving stretch: the sample comes already stretched to the current tempo
-    if (sample != nullptr && kind != InstrumentKind::granulizer && kind != InstrumentKind::wavetraveller
-        && kind != InstrumentKind::fruityslicer && channel.sampler.keepPitch && channel.sampler.stretchBeats > 0.0f
-        && (factories.stretchedSamples || factories.stretchedSpans)
-        && sample->frames() > 0)
-    {
-        const auto target = channel.sampler.stretchBeats * 60.0 / std::max (1.0, bpm);
-        if (precomputes && channel.sampler.warp.empty())
-        {
-            // FL stretches what plays: the region after its precomputed effects and Trim, not the whole file (round 180d:
-            // Thief's Importer Ride, 1.30 s of file faded out to 0.38 s, plays 2x slower in FL at TIME 367). The span is cut
-            // first and only it is stretched, so the stretcher's smear of the silence around it is not kept by the trim.
-            if (std::shared_ptr<const SampleData> span = precompute::apply (*sample, spanSettings); span != nullptr && span->frames() > 0)
-            {
-                const auto ratio = target / ((double) span->frames() / span->sampleRate);
-                auto stretched = factories.stretchedSpans
-                                     ? factories.stretchedSpans (channel.samplePath, precompute::variantKey (spanSettings, clip) + polyKey, span, ratio,
-                                                                 channel.sampler.stretchMethod, channel.sampler.stretchPitch, stretchOptionsOf (channel.sampler))
-                                     : std::shared_ptr<const SampleData> (timeStretchSpan (*span, ratio, channel.sampler.stretchMethod,
-                                                                                           channel.sampler.stretchPitch, stretchOptionsOf (channel.sampler)));
-                sample = stretched != nullptr ? std::move (stretched) : std::move (span);
-                precomputed = true;
-            }
-        }
-        else if (factories.stretchedSamples)
-        {
-            // the whole file (no precomputed effects; or a warp map, whose markers are in the file's frames)
-            const auto ratio = target / ((double) precompute::stretchedFrames (sample, channel.sampler, clip) / sample->sampleRate);
-            const auto map = warpStretchMap (channel.sampler.warp, (double) sample->frames(), sample->sampleRate,
-                                             (double) std::llround ((double) sample->frames() * ratio));
-            // round 190lk: the polyphonic editor's render (not the file) is what stretches (a warp map's clip plays the
-            // file's stretch without the note edits: the span cache takes no warp map)
-            if (! polyKey.empty() && channel.sampler.warp.empty() && factories.stretchedSpans)
-            {
-                if (auto stretched = factories.stretchedSpans (channel.samplePath, polyKey, sample, ratio, channel.sampler.stretchMethod,
-                                                               channel.sampler.stretchPitch, stretchOptionsOf (channel.sampler)))
-                    sample = std::move (stretched);
-            }
-            else if (auto stretched = factories.stretchedSamples (channel.samplePath, ratio, channel.sampler.stretchMethod, channel.sampler.stretchPitch, map,
-                                                         stretchOptionsOf (channel.sampler)))
-                sample = std::move (stretched);
-        }
-    }
-
-    if (precomputes && ! precomputed)
-        if (auto processed = precompute::apply (*sample, spanSettings))
-            sample = std::move (processed);
+    std::shared_ptr<const SampleData> sample = playedSampleOf (channel, bpm, factories);
 
 
     // Fruity Slicer (round 180c): FL's edits to the sample (reverse, declick, fades), then the sampler on the slices
     // Fruity Slicer (round 180c): FL's edits to the sample (reverse, declick, fades), then the sampler on the slices
     if (kind == InstrumentKind::fruityslicer)
     if (kind == InstrumentKind::fruityslicer)
@@ -1008,6 +1032,7 @@ std::unique_ptr<const RackState> RackState::build (Song songIn,
         const auto& channel = song.channels[i];
         const auto& channel = song.channels[i];
         const auto kind = channel.instrument;
         const auto kind = channel.instrument;
         const auto p = channelOrigin[i] >= 0 ? (std::size_t) channelOrigin[i] : std::numeric_limits<std::size_t>::max();
         const auto p = channelOrigin[i] >= 0 ? (std::size_t) channelOrigin[i] : std::numeric_limits<std::size_t>::max();
+        auto deferred = false; // (round 190un)
 
 
         // round 190kx: an audio clip channel edited in an ARA plugin plays through that plugin (the ARA host keeps one
         // round 190kx: an audio clip channel edited in an ARA plugin plays through that plugin (the ARA host keeps one
         // instance per channel: asking again returns the same instance)
         // instance per channel: asking again returns the same instance)
@@ -1048,7 +1073,10 @@ std::unique_ptr<const RackState> RackState::build (Song songIn,
                 || (previous->song.channels[p].samplePath == channel.samplePath && previous->song.channels[p].zones == channel.zones
                 || (previous->song.channels[p].samplePath == channel.samplePath && previous->song.channels[p].zones == channel.zones
                     && previous->song.channels[p].polyEdit == channel.polyEdit // (round 190lk: other note edits, another render)
                     && previous->song.channels[p].polyEdit == channel.polyEdit // (round 190lk: other note edits, another render)
                     && previous->song.channels[p].modelParams == channel.modelParams
                     && previous->song.channels[p].modelParams == channel.modelParams
-                    && previous->song.channels[p].sampler.keepPitch == channel.sampler.keepPitch
+                    && (previous->song.channels[p].sampler.keepPitch == channel.sampler.keepPitch
+                        // (round 190un: keep pitch turned on — Auto-warp, a stretch mode chosen — may keep it while its
+                        // first stretch renders, below)
+                        || (channel.sampler.keepPitch && factories.deferStretch && stretchDeferrable (previous->song.channels[p], channel)))
                     && clipShiftWanted (previous->song, p) == clipShiftWanted (song, i)
                     && clipShiftWanted (previous->song, p) == clipShiftWanted (song, i)
                     // FL's precomputed effects (round 167h): the sample is processed when the channel is built
                     // FL's precomputed effects (round 167h): the sample is processed when the channel is built
                     && previous->song.channels[p].sampler.precompute == channel.sampler.precompute
                     && previous->song.channels[p].sampler.precompute == channel.sampler.precompute
@@ -1059,12 +1087,19 @@ std::unique_ptr<const RackState> RackState::build (Song songIn,
                             && previous->song.channels[p].sampler.reverse == channel.sampler.reverse
                             && previous->song.channels[p].sampler.reverse == channel.sampler.reverse
                             && precompute::needed (previous->song.channels[p].sampler)))
                             && precompute::needed (previous->song.channels[p].sampler)))
                     && (! channel.sampler.keepPitch
                     && (! channel.sampler.keepPitch
-                        || (previous->song.channels[p].sampler.stretchBeats == channel.sampler.stretchBeats
+                        || (! previous->stale (p) // (round 190un: a kept instrument plays an older stretch than its channel says)
+                            && previous->song.channels[p].sampler.keepPitch
+                            && previous->song.channels[p].sampler.stretchBeats == channel.sampler.stretchBeats
                             && previous->song.channels[p].sampler.stretchMethod == channel.sampler.stretchMethod
                             && previous->song.channels[p].sampler.stretchMethod == channel.sampler.stretchMethod
                             && previous->song.channels[p].sampler.stretchPitch == channel.sampler.stretchPitch
                             && previous->song.channels[p].sampler.stretchPitch == channel.sampler.stretchPitch
                             && previous->song.channels[p].sampler.warp == channel.sampler.warp
                             && previous->song.channels[p].sampler.warp == channel.sampler.warp
                             && previous->song.channels[p].sampler.warpModes == channel.sampler.warpModes
                             && previous->song.channels[p].sampler.warpModes == channel.sampler.warpModes
-                            && previous->song.bpm == song.bpm))))
+                            && previous->song.bpm == song.bpm)
+                        // round 190un (issue #381): only its stretch differs (a new tempo, other markers or mode) and its
+                        // render is not ready: the instrument stays and plays its old stretch at the new length while the
+                        // live engine renders the new one off the message thread (it then builds the channel again)
+                        || (factories.deferStretch && stretchDeferrable (previous->song.channels[p], channel)
+                            && (deferred = factories.deferStretch (channel, song.bpm))))))
             && (kind != InstrumentKind::plugin
             && (kind != InstrumentKind::plugin
                 || (previous->song.channels[p].plugin.id == channel.plugin.id && previous->sampleRate == sampleRate
                 || (previous->song.channels[p].plugin.id == channel.plugin.id && previous->sampleRate == sampleRate
                     && samePluginProcessing (previous->song.channels[p].plugin, channel.plugin) && ! rebuilds (factories, channel.plugin)
                     && samePluginProcessing (previous->song.channels[p].plugin, channel.plugin) && ! rebuilds (factories, channel.plugin)
@@ -1072,6 +1107,30 @@ std::unique_ptr<const RackState> RackState::build (Song songIn,
         {
         {
             state->instruments.push_back (previous->instruments[p]);
             state->instruments.push_back (previous->instruments[p]);
             state->instruments.back()->configure (channel, song.bpm); // (a Slicer takes its slices from its state: issue #160)
             state->instruments.back()->configure (channel, song.bpm); // (a Slicer takes its slices from its state: issue #160)
+            if (deferred)
+            {
+                // the length the kept instrument's stretch was rendered for (a channel kept twice: the first one's), and
+                // the speed that makes it last what the channel lasts now
+                const auto& before = previous->song.channels[p];
+                auto played = previous->stale (p) && p < previous->playedStretchSeconds.size()
+                                  ? previous->playedStretchSeconds[p]
+                                  : (double) before.sampler.stretchBeats * 60.0 / std::max (1.0, previous->song.bpm);
+                // (one that did not keep its pitch plays its file at its own speed now: what it stretches lasts its seconds)
+                if (! previous->stale (p) && ! before.sampler.keepPitch)
+                {
+                    const auto file = factories.samples ? factories.samples (channel.samplePath) : nullptr;
+                    played = file != nullptr && file->sampleRate > 0.0
+                                 ? (double) precompute::stretchedFrames (file, before.sampler, kind == InstrumentKind::audioClip) / file->sampleRate
+                                 : 0.0;
+                }
+                const auto wanted = (double) channel.sampler.stretchBeats * 60.0 / std::max (1.0, song.bpm);
+                state->staleStretch.resize (song.channels.size(), 0);
+                state->staleSpeed.resize (song.channels.size(), 1.0);
+                state->playedStretchSeconds.resize (song.channels.size(), 0.0);
+                state->staleStretch[i] = 1;
+                state->playedStretchSeconds[i] = played;
+                state->staleSpeed[i] = played > 0.0 && wanted > 0.0 ? std::clamp (played / wanted, 0.05, 20.0) : 1.0;
+            }
             continue;
             continue;
         }
         }
 
 
@@ -1107,6 +1166,14 @@ std::unique_ptr<const RackState> RackState::build (Song songIn,
         }
         }
 
 
         state->instruments.push_back (buildInstrument (channel, sampleRate, song.bpm, factories, &keyShiftLater));
         state->instruments.push_back (buildInstrument (channel, sampleRate, song.bpm, factories, &keyShiftLater));
+        // round 190un (issue #381): built anew where the previous build played another stretch of the same file (a new
+        // tempo, other markers): its clips in progress start again in it (RackRenderer: the old one's voices go with it)
+        if (previous != nullptr && p < previous->song.channels.size() && p < previous->instruments.size()
+            && stretchDeferrable (previous->song.channels[p], channel) && stretchdefer::resumeEnabled())
+        {
+            state->restretched.resize (song.channels.size(), 0);
+            state->restretched[i] = 1;
+        }
         // FL 2026's clip pitch (round 167k): a channel with a pitched clip gets its pitch shifters even when it resamples
         // FL 2026's clip pitch (round 167k): a channel with a pitched clip gets its pitch shifters even when it resamples
         if (clipShiftWanted (song, i) && state->instruments.back() != nullptr)
         if (clipShiftWanted (song, i) && state->instruments.back() != nullptr)
         {
         {
@@ -5698,6 +5765,7 @@ void RackRenderer::process (const RackState* state,
             if (auto* block = propsOf ((std::size_t) ch))
             if (auto* block = propsOf ((std::size_t) ch))
                 block->slide.count = 0;
                 block->slide.count = 0;
     }
     }
+    const auto newSnapshot = state != lastState; // (round 190un)
     lastState = state; // so prepare() knows which instruments to reconfigure
     lastState = state; // so prepare() knows which instruments to reconfigure
     lastSerial = state->serial;
     lastSerial = state->serial;
 
 
@@ -5740,6 +5808,10 @@ void RackRenderer::process (const RackState* state,
 
 
     // started playing or jumped: audio clips in progress must start mid-way
     // started playing or jumped: audio clips in progress must start mid-way
     resumeAudio = playing && (! wasPlaying || jumped);
     resumeAudio = playing && (! wasPlaying || jumped);
+    // round 190un (issue #381): a channel built anew from its new stretch while its clips play: they start again here (a
+    // start or a jump resumes every clip already)
+    if (newSnapshot && ! state->restretched.empty())
+        resumeRestretched = playing && wasPlaying && ! jumped;
     // FL's "Play truncated notes on transport": at the start of playback, and after the user moves the position while
     // FL's "Play truncated notes on transport": at the start of playback, and after the user moves the position while
     // playing (FL's set-position FUN_011e7a10 → FUN_011e78a0 → FUN_011e7470 with its catch-up flag set, round 167k),
     // playing (FL's set-position FUN_011e7a10 → FUN_011e78a0 → FUN_011e7470 with its catch-up flag set, round 167k),
     // the notes already sounding there play. The loop's wrap is not a set-position and chases nothing.
     // the notes already sounding there play. The loop's wrap is not a set-position and chases nothing.
@@ -5783,9 +5855,16 @@ void RackRenderer::process (const RackState* state,
         const auto ratio = bpm / std::max (1.0, state->song.bpm);
         const auto ratio = bpm / std::max (1.0, state->song.bpm);
         // (round 190rf, ThreadSanitizer: this renderer's own channels only. With render-ahead two renderers run, and each set
         // (round 190rf, ThreadSanitizer: this renderer's own channels only. With render-ahead two renderers run, and each set
         // every instrument's ratio at its own place in the song: a live and an ahead tempo in turns on the same voices)
         // every instrument's ratio at its own place in the song: a live and an ahead tempo in turns on the same voices)
+        // (round 190un, issue #381: an instrument kept while its new stretch renders reads its old one at the speed that
+        // fits the channel's length now; as a moving tempo, its new voices keep their pitch through their shifters)
         for (std::size_t c = 0; c < state->instruments.size(); ++c)
         for (std::size_t c = 0; c < state->instruments.size(); ++c)
             if (state->instruments[c] != nullptr && ! foreignChannel ((int) c))
             if (state->instruments[c] != nullptr && ! foreignChannel ((int) c))
-                state->instruments[c]->setTempoRatio (ratio, moves);
+            {
+                if (state->stale (c) && c < state->staleSpeed.size())
+                    state->instruments[c]->setTempoRatio (ratio * state->staleSpeed[c], true);
+                else
+                    state->instruments[c]->setTempoRatio (ratio, moves);
+            }
     }
     }
 
 
     const auto tps = ticksPerSample (bpm, sampleRate);
     const auto tps = ticksPerSample (bpm, sampleRate);
@@ -6107,6 +6186,7 @@ void RackRenderer::process (const RackState* state,
         if (ownNotes)
         if (ownNotes)
             ownNotesAfterChunk (*state, n);
             ownNotesAfterChunk (*state, n);
         resumeAudio = false;
         resumeAudio = false;
+        resumeRestretched = false;
         chaseNotes = false;
         chaseNotes = false;
         done += n;
         done += n;
         if (grid && atEvent)
         if (grid && atEvent)
@@ -6747,6 +6827,9 @@ void RackRenderer::chunkPrelude (const RackState& state, bool playing, double st
             runningLauncher = state.clipLauncher;
             runningLauncher = state.clipLauncher;
             launcher::playBlock (*state.clipLauncher, song, *song.clipGrid, state.gridIndex, startTick, numSamples, tps, events, resumeAudio,
             launcher::playBlock (*state.clipLauncher, song, *song.clipGrid, state.gridIndex, startTick, numSamples, tps, events, resumeAudio,
                                  &state.schedule, wrap, chaseNotes, *scheduledNotes, fill);
                                  &state.schedule, wrap, chaseNotes, *scheduledNotes, fill);
+            if (resumeRestretched && ! resumeAudio) // (round 190un: a channel built anew from its new stretch while its clips play)
+                launcher::resumeAudio (*state.clipLauncher, song, state.restretched, state.clipLauncher->clock - numSamples * tps, startTick, numSamples,
+                                       tps, events, &state.schedule, wrap);
         }
         }
         else
         else
         {
         {
@@ -6756,6 +6839,8 @@ void RackRenderer::chunkPrelude (const RackState& state, bool playing, double st
                 runningLauncher = nullptr;
                 runningLauncher = nullptr;
             }
             }
             scheduleSong (song, startTick, numSamples, tps, events, resumeAudio, &state.schedule, wrap, chaseNotes, fill);
             scheduleSong (song, startTick, numSamples, tps, events, resumeAudio, &state.schedule, wrap, chaseNotes, fill);
+            if (resumeRestretched && ! resumeAudio) // (round 190un)
+                scheduleResumedAudio (song, state.restretched, startTick, numSamples, tps, events, &state.schedule, wrap);
         }
         }
         // Performance mode (round 165m): the launched clips, on the Player's steady clock (the transport's ticks from
         // Performance mode (round 165m): the launched clips, on the Player's steady clock (the transport's ticks from
         // where playback started, never wrapping with the song loop)
         // where playback started, never wrapping with the song loop)
@@ -6777,8 +6862,12 @@ void RackRenderer::chunkPrelude (const RackState& state, bool playing, double st
     else
     else
     {
     {
         if (songPlaying)
         if (songPlaying)
-            scheduleSong (song, startTick, numSamples, ticksPerSample (bpm, sampleRate), events, resumeAudio, &state.schedule,
-                          liveInput == nullptr || ! liveInput->linearSong.load (std::memory_order_relaxed), chaseNotes, fill);
+        {
+            const auto wrap = liveInput == nullptr || ! liveInput->linearSong.load (std::memory_order_relaxed);
+            scheduleSong (song, startTick, numSamples, ticksPerSample (bpm, sampleRate), events, resumeAudio, &state.schedule, wrap, chaseNotes, fill);
+            if (resumeRestretched && ! resumeAudio) // (round 190un: a channel built anew from its new stretch while its clips play)
+                scheduleResumedAudio (song, state.restretched, startTick, numSamples, ticksPerSample (bpm, sampleRate), events, &state.schedule, wrap);
+        }
         if (launchersRunning || (perfLive != nullptr && perfLive->anyPlaying.load (std::memory_order_relaxed)))
         if (launchersRunning || (perfLive != nullptr && perfLive->anyPlaying.load (std::memory_order_relaxed)))
         {
         {
             perfPlayer.process (song, state.performanceZone, perfLive, perfClock, startTick, 0.0, false);
             perfPlayer.process (song, state.performanceZone, perfLive, perfClock, startTick, 0.0, false);
@@ -8161,6 +8250,7 @@ void RackRenderer::processBatched (const RackState& state, bool playing, int num
         piece.live = liveInput != nullptr && liveInput->numChannels > 0;
         piece.live = liveInput != nullptr && liveInput->numChannels > 0;
         piece.recording = piece.live && liveInput->recording.load (std::memory_order_relaxed);
         piece.recording = piece.live && liveInput->recording.load (std::memory_order_relaxed);
         resumeAudio = false;
         resumeAudio = false;
+        resumeRestretched = false;
         chaseNotes = false;
         chaseNotes = false;
     }
     }
 
 
@@ -8928,6 +9018,7 @@ void RackRenderer::adoptGlobals (const RackRenderer& from) noexcept
     wasPlaying = from.wasPlaying;
     wasPlaying = from.wasPlaying;
     expectedTick = from.expectedTick;
     expectedTick = from.expectedTick;
     resumeAudio = from.resumeAudio;
     resumeAudio = from.resumeAudio;
+    resumeRestretched = from.resumeRestretched;
     chaseNotes = from.chaseNotes;
     chaseNotes = from.chaseNotes;
     playTruncatedOnTransport = from.playTruncatedOnTransport;
     playTruncatedOnTransport = from.playTruncatedOnTransport;
     resetPluginsOnTransport = from.resetPluginsOnTransport;
     resetPluginsOnTransport = from.resetPluginsOnTransport;
@@ -9056,4 +9147,60 @@ void RackRenderer::silenceChannels (const RackState& state, const char* channels
             state.echoes[c]->reset();
             state.echoes[c]->reset();
     }
     }
 }
 }
+
+// --- round 190un (issue #381): the live engine's deferred stretch renders (core/StretchDefer.h) ------------------------------
+
+std::shared_ptr<const SampleData> playedSample (const ChannelDef& channel, double bpm, const RackState::Factories& factories,
+                                               std::vector<std::shared_ptr<const SampleData>>* keep)
+{
+    return playedSampleOf (channel, bpm, factories, keep);
+}
+
+std::string stretchRequestKey (const ChannelDef& channel, double bpm)
+{
+    const auto& s = channel.sampler;
+    std::string key = channel.samplePath;
+    char text[48];
+    const auto add = [&] (double v) {
+        std::snprintf (text, sizeof text, "|%.17g", v);
+        key += text;
+    };
+    add ((double) channel.instrument);
+    add (bpm);
+    add ((double) s.stretchBeats);
+    add ((double) s.stretchMethod);
+    add ((double) s.stretchPitch);
+    add ((double) s.warp.size());
+    for (const auto& w : s.warp)
+    {
+        add (w.seconds);
+        add (w.beats);
+    }
+    key += stretchOptionsKey (stretchOptionsOf (s), s.stretchMethod);
+    // (the warp modes' every setting, not only those stretchOptionsKey keeps: a key a little too fine only costs a render)
+    const auto& m = s.warpModes;
+    for (const auto v : { (double) m.warpLaw, (double) m.beatsLaw, (double) m.beatsPreserve, (double) m.beatsLoop, (double) m.beatsEnvelope,
+                          (double) m.tonesGrain, (double) m.textureGrain, (double) m.textureFlux, (double) m.complexPro, (double) m.proFormants,
+                          (double) m.proEnvelope })
+        add (v);
+    auto span = s;
+    if (channel.instrument == InstrumentKind::audioClip)
+        span.regionStart = 0.0f, span.regionEnd = 1.0f;
+    key += "|" + precompute::variantKey (span, channel.instrument == InstrumentKind::audioClip);
+    if (channel.instrument == InstrumentKind::audioClip)
+        key += "|" + polyedit::stateKey (channel.polyEdit);
+    return key;
+}
+
+bool stretchDeferrable (const ChannelDef& before, const ChannelDef& now) noexcept
+{
+    const auto sampleLike = [] (const ChannelDef& c) {
+        return (c.instrument == InstrumentKind::sampler || c.instrument == InstrumentKind::audioClip) && c.zones.empty() && ! c.samplePath.empty()
+               && ! flmslicer::isChannel (c) && ! flmdw::isChannel (c);
+    };
+    // (before: its own stretch, or none — keep pitch turned on by Auto-warp or a stretch mode; now: a stretch to render)
+    return sampleLike (before) && sampleLike (now) && now.sampler.keepPitch && now.sampler.stretchBeats > 0.0f
+           && (! before.sampler.keepPitch || before.sampler.stretchBeats > 0.0f) && before.instrument == now.instrument
+           && before.samplePath == now.samplePath;
+}
 } // namespace lynx
 } // namespace lynx

+ 32 - 0
src/core/RackRenderer.h

@@ -85,6 +85,19 @@ struct RackState
     std::uint64_t serial = 0, builtFrom = 0;
     std::uint64_t serial = 0, builtFrom = 0;
     std::vector<int> channelFrom;
     std::vector<int> channelFrom;
     bool channelsMoved = false;
     bool channelsMoved = false;
+    // Round 190un (issue #381, core/StretchDefer.h): [channel] 1 = its instrument is the previous build's, kept while the
+    // stretch for its new settings (a new tempo, other warp markers) renders off the message thread; it plays the old
+    // stretch at the new length meanwhile. The next build makes it again once the render is ready. Empty = none.
+    std::vector<std::uint8_t> staleStretch;
+    bool stale (std::size_t channel) const noexcept { return channel < staleStretch.size() && staleStretch[channel] != 0; }
+    // [channel] for a kept one: the speed its voices read the old stretch at so it lasts what the channel lasts now (the
+    // length it was rendered for over the one wanted; the renderer's tempo hook, Instrument::setTempoRatio), and that
+    // rendered length in seconds (a channel kept twice still plays the first one). Sized with staleStretch.
+    std::vector<double> staleSpeed, playedStretchSeconds;
+    // [channel] 1 = built anew in this build where the previous one played another stretch of its file (its new stretch is
+    // ready): its audio clips that are in progress start again there, mid-way, when this snapshot first plays (the old
+    // instrument's voices go with it). Empty = none.
+    std::vector<std::uint8_t> restretched;
 
 
     // Automation, preprocessed so the audio thread only does table lookups.
     // Automation, preprocessed so the audio thread only does table lookups.
     // Indices into song.automations, or -1 = no automation.
     // Indices into song.automations, or -1 = no automation.
@@ -462,6 +475,11 @@ struct RackState
         // Round 190kx (core/AraLink.h): an audio clip channel edited in an ARA plugin takes the instrument this returns (the
         // Round 190kx (core/AraLink.h): an audio clip channel edited in an ARA plugin takes the instrument this returns (the
         // plugin's playback renderer, engine/AraHost); nullptr or unset: its clips play through its sampler as usual
         // plugin's playback renderer, engine/AraHost); nullptr or unset: its clips play through its sampler as usual
         std::function<std::shared_ptr<Instrument> (const ChannelDef&, double sampleRate)> araInstrument;
         std::function<std::shared_ptr<Instrument> (const ChannelDef&, double sampleRate)> araInstrument;
+        // Round 190un (issue #381, core/StretchDefer.h): a live engine's channel that keeps its pitch and was built with other
+        // stretch settings or at another tempo keeps its running instrument while its new stretch renders off the message
+        // thread. Asked with the channel and the song's tempo: true = deferred (keep the instrument); false = the render is
+        // ready (build it now: it reads the stretch from the cache). Unset (exports, offline renders, tests): built now.
+        std::function<bool (const ChannelDef&, double bpm)> deferStretch;
     };
     };
 
 
     // Round 190gp: what the renderer's effect loop needs of each slot, worked out once per snapshot ([track][slot], one
     // Round 190gp: what the renderer's effect loop needs of each slot, worked out once per snapshot ([track][slot], one
@@ -514,6 +532,19 @@ struct ClipAudio
 };
 };
 ClipAudio renderClipAudio (const Song& song, std::size_t clipIndex, double sampleRate, const RackState::Factories& factories);
 ClipAudio renderClipAudio (const Song& song, std::size_t clipIndex, double sampleRate, const RackState::Factories& factories);
 
 
+// Round 190un (issue #381): the sample a sampler or audio clip channel plays as RackState::build makes it — its file, its
+// polyphonic edits, its precomputed effects and, when it keeps its pitch, its stretch to `bpm` (through the factories'
+// cache). Any thread but the audio thread. `keep` (optional) gets every intermediate copy the factories cached, so
+// they stay cached for the next build.
+std::shared_ptr<const SampleData> playedSample (const ChannelDef& channel, double bpm, const RackState::Factories& factories,
+                                               std::vector<std::shared_ptr<const SampleData>>* keep = nullptr);
+// What that stretch depends on, as text (the deferred renders' key): the file, the tempo, Time, the stretch mode and
+// pitch, the warp markers and modes, the precomputed span, the polyphonic edits.
+std::string stretchRequestKey (const ChannelDef& channel, double bpm);
+// Whether a channel's instrument may be kept while its stretch renders: a sampler or audio clip on the same file that keeps
+// its pitch with Time set now, and before kept it with Time set too or did not keep it (Auto-warp, a stretch mode chosen)
+bool stretchDeferrable (const ChannelDef& before, const ChannelDef& now) noexcept;
+
 // A channel's instrument heard alone before it is in the song (round 190bu: the Simple workflow's sound picker): the
 // A channel's instrument heard alone before it is in the song (round 190bu: the Simple workflow's sound picker): the
 // notes `keys` (MIDI keys, 60 = C5) one after the other, `noteSeconds` each, then `tailSeconds` of release, at unity
 // notes `keys` (MIDI keys, 60 = C5) one after the other, `noteSeconds` each, then `tailSeconds` of release, at unity
 // through no mixer; then the whole is brought to `peak` (0 = left as rendered) so every sound previews at one level.
 // through no mixer; then the whole is brought to `peak` (0 = left as rendered) so every sound previews at one level.
@@ -1206,6 +1237,7 @@ private:
     bool wasPlaying = false;
     bool wasPlaying = false;
     double expectedTick = -1.0; // where the next block should start, to detect jumps
     double expectedTick = -1.0; // where the next block should start, to detect jumps
     bool resumeAudio = false;
     bool resumeAudio = false;
+    bool resumeRestretched = false; // (round 190un: a new snapshot's restretched channels' clips start again mid-way)
     bool chaseNotes = false; // this block starts playback: notes crossing the position play (setTransportOptions)
     bool chaseNotes = false; // this block starts playback: notes crossing the position play (setTransportOptions)
     bool playTruncatedOnTransport = true, resetPluginsOnTransport = false;
     bool playTruncatedOnTransport = true, resetPluginsOnTransport = false;
     unsigned userJumpSerial = 0, seenUserJumpSerial = 0;
     unsigned userJumpSerial = 0, seenUserJumpSerial = 0;

+ 44 - 0
src/core/Scheduler.cpp

@@ -1083,6 +1083,50 @@ void scheduleSong (const Song& song, double startTick, int numSamples, double tp
 
 
     out.sortByOffset();
     out.sortByOffset();
 }
 }
+bool resumeAudioClipAt (const Song& song, const Clip& clip, std::size_t key, double at, double tps, EventBuffer& out) noexcept
+{
+    if (clip.kind != ClipKind::audio || clip.channel < 0 || clip.channel >= (int) song.channels.size() || clip.length <= 0 || tps <= 0.0
+        || ! (at > (double) clip.start && at < (double) clip.end()))
+        return false;
+    // (as scheduleClip's resume)
+    const auto secondsPerTick = 60.0 / (std::max (song.bpm, 1.0) * ppq);
+    auto e = audioClipNote (song, clip, key, tps);
+    e.type = NoteEvent::Type::on;
+    e.sampleOffset = 0;
+    e.startSeconds = ((double) clip.offset + (double) clip.offsetFraction + at - (double) clip.start) * secondsPerTick;
+    e.clipElapsed = (float) ((at - (double) clip.start) / tps);
+    e.clipRemaining = (float) (((double) clip.end() - at) / tps);
+    e.clipEnvTick = clipenv::clipTick (clip, at);
+    out.add (e);
+    return true;
+}
+
+void scheduleResumedAudio (const Song& song, const std::vector<std::uint8_t>& channels, double startTick, int numSamples, double tps,
+                           EventBuffer& out, const ScheduleIndex* index, bool wrap, const TrackMask* skipTracks) noexcept
+{
+    if (numSamples <= 0 || tps <= 0.0 || song.playlist.empty() || channels.empty())
+        return;
+    const auto endTick = startTick + numSamples * tps;
+    auto loop = index != nullptr ? index->songLength : scheduleIndexLength (song);
+    if (! wrap)
+        loop = std::max<std::int64_t> (loop, (std::int64_t) std::ceil (endTick) + 1) * 2;
+    const auto loopStart = std::fmod (startTick, (double) loop);
+    const auto loopEnd = loopStart + (endTick - startTick);
+    const auto zoneEnd = song.performanceZoneEnd();
+    auto any = false;
+    forClipsInBlock (song, index, loop, loopStart, loopEnd, [&] (std::size_t clipIndex) {
+        const auto& clip = song.playlist[clipIndex];
+        if (clip.kind != ClipKind::audio || clip.channel < 0 || (std::size_t) clip.channel >= channels.size() || channels[(std::size_t) clip.channel] == 0
+            || ! clipPlaysInSong (song, clip, zoneEnd))
+            return;
+        if (skipTracks != nullptr && clip.track >= 0 && clip.track < scheduleMaskTracks && (*skipTracks)[(std::size_t) clip.track])
+            return;
+        any = resumeAudioClipAt (song, clip, clipIndex, loopStart, tps, out) || any;
+    });
+    if (any)
+        out.sortByOffset();
+}
+
 void scheduleSongAround (const Song& song, const TrackMask& taken, const TrackMask& givenBack, double startTick, int numSamples,
 void scheduleSongAround (const Song& song, const TrackMask& taken, const TrackMask& givenBack, double startTick, int numSamples,
                          double tps, EventBuffer& out, bool resume, const ScheduleIndex* index, bool wrap, bool chase, bool fill) noexcept
                          double tps, EventBuffer& out, bool resume, const ScheduleIndex* index, bool wrap, bool chase, bool fill) noexcept
 {
 {

+ 11 - 0
src/core/Scheduler.h

@@ -302,6 +302,17 @@ void scheduleSong (const Song& song,
 // progress at startTick starts there, in the middle.
 // progress at startTick starts there, in the middle.
 constexpr int scheduleMaskTracks = 500;
 constexpr int scheduleMaskTracks = 500;
 using TrackMask = std::bitset<scheduleMaskTracks>;
 using TrackMask = std::bitset<scheduleMaskTracks>;
+// Round 190un (issue #381): the audio clips of the channels marked in `channels` that are in progress at startTick start
+// there, in the middle, as at a start of playback — their channel's instrument was just built anew (its new stretch) while
+// they played, and the old one's voices are gone. Only those starts (the block's other events are scheduleSong's);
+// `skipTracks`: tracks whose Playlist clips are silent (taken by the clip grid).
+void scheduleResumedAudio (const Song& song, const std::vector<std::uint8_t>& channels, double startTick, int numSamples,
+                           double ticksPerSampleValue, EventBuffer& out, const ScheduleIndex* index = nullptr, bool wrap = true,
+                           const TrackMask* skipTracks = nullptr) noexcept;
+// One audio clip in progress at `at` (a tick of the clip's own timeline) started there, in the middle, on the block's first
+// sample (as a start of playback resumes it); `key` its voice key (its Playlist index, a grid slot's). False when it is
+// not in progress there.
+bool resumeAudioClipAt (const Song& song, const Clip& clip, std::size_t key, double at, double ticksPerSampleValue, EventBuffer& out) noexcept;
 void scheduleSongAround (const Song& song, const TrackMask& taken, const TrackMask& givenBack, double startTick, int numSamples,
 void scheduleSongAround (const Song& song, const TrackMask& taken, const TrackMask& givenBack, double startTick, int numSamples,
                          double ticksPerSampleValue, EventBuffer& out, bool resume, const ScheduleIndex* index, bool wrap,
                          double ticksPerSampleValue, EventBuffer& out, bool resume, const ScheduleIndex* index, bool wrap,
                          bool chase, bool fill = false) noexcept;
                          bool chase, bool fill = false) noexcept;

+ 99 - 0
src/core/StretchDefer.cpp

@@ -0,0 +1,99 @@
+#include "core/StretchDefer.h"
+
+namespace lynx::stretchdefer
+{
+namespace
+{
+std::atomic<bool> on { true }, resume { true };
+}
+
+bool enabled() noexcept { return on.load (std::memory_order_relaxed); }
+void setEnabled (bool yes) noexcept { on.store (yes, std::memory_order_relaxed); }
+bool resumeEnabled() noexcept { return resume.load (std::memory_order_relaxed); }
+void setResumeEnabled (bool yes) noexcept { resume.store (yes, std::memory_order_relaxed); }
+
+Queue::Answer Queue::request (std::uint64_t channel, const std::string& key, Render render, double nowMs)
+{
+    ++stats.requested;
+    if (done.count (key) > 0)
+    {
+        ++stats.readyHits;
+        return Answer::ready;
+    }
+    // the channel's other results are out of date now (a newer tempo, other markers)
+    for (auto it = done.begin(); it != done.end();)
+        it = it->second.channel == channel ? done.erase (it) : std::next (it);
+    if (running && running->channel == channel)
+    {
+        if (running->key == key)
+        {
+            waiting.erase (channel); // (it renders what is wanted: nothing else waits)
+            return Answer::deferred;
+        }
+        running->cancelled->store (true, std::memory_order_relaxed); // superseded
+    }
+    auto& w = waiting[channel];
+    if (w.key != key || ! w.render) // (the same request again — another edit's build — keeps its place in the debounce)
+    {
+        w.key = key;
+        w.since = nowMs;
+    }
+    w.render = std::move (render);
+    return Answer::deferred;
+}
+
+std::optional<Queue::Job> Queue::next (double nowMs, double* dueInMs)
+{
+    if (dueInMs != nullptr)
+        *dueInMs = -1.0;
+    if (running)
+        return std::nullopt;
+    auto best = waiting.end();
+    for (auto it = waiting.begin(); it != waiting.end(); ++it)
+        if (best == waiting.end() || it->second.since < best->second.since)
+            best = it;
+    if (best == waiting.end())
+        return std::nullopt;
+    const auto due = best->second.since + debounce;
+    if (nowMs < due)
+    {
+        if (dueInMs != nullptr)
+            *dueInMs = due - nowMs;
+        return std::nullopt;
+    }
+    Job job { best->first, std::move (best->second.key), std::move (best->second.render), std::make_shared<std::atomic<bool>> (false) };
+    waiting.erase (best);
+    running = Running { job.channel, job.key, job.cancelled };
+    ++stats.started;
+    return job;
+}
+
+bool Queue::finished (const Job& job, Result result)
+{
+    if (running && running->cancelled == job.cancelled)
+        running.reset();
+    if (job.cancelled->load (std::memory_order_relaxed) || result == nullptr)
+    {
+        ++stats.cancelled;
+        return false;
+    }
+    // (a newer request for the channel that waits makes this one stale too: it is kept anyway, the build decides)
+    done[job.key] = Done { job.channel, std::move (result), publishSerial };
+    ++stats.kept;
+    return true;
+}
+
+void Queue::endPublish (std::uint64_t publishStarted)
+{
+    for (auto it = done.begin(); it != done.end();)
+        it = it->second.serial < publishStarted ? done.erase (it) : std::next (it);
+}
+
+void Queue::clear()
+{
+    waiting.clear();
+    if (running)
+        running->cancelled->store (true, std::memory_order_relaxed);
+    done.clear();
+}
+} // namespace lynx::stretchdefer

+ 118 - 0
src/core/StretchDefer.h

@@ -0,0 +1,118 @@
+#pragma once
+
+// Round 190un (issue #381, chlantutztetr: "software freezes when adjusting the bpm of a project when a sample is warped").
+// A channel stretched to the tempo keeping its pitch (Time set with a Stretch mode, warp markers) plays a copy of its
+// sample rendered offline for the project's tempo (core/TimeStretch). Every tempo change built the channel again on the
+// message thread, which rendered the whole stretch there: a 3:53 song with 119 auto-warp markers took seconds per step,
+// and a drag of the tempo display asked for one per pixel, so LYNX stopped responding.
+//
+// Now the live engine (engine/AudioEngine) keeps the channel's running instrument while the stretch for the new settings
+// renders on a worker thread, and builds the channel again once it is ready. Until then the kept copy plays at the new
+// tempo: its sampler reads the old stretch at the new length (SamplerInstrument::baseRate from its Time and the tempo), as
+// FL plays a precomputed stretch (REA_rodada3 §5.1: r = len / (T·mul) over the buffer already stretched) until its
+// restretch. Exports and other offline renders keep rendering the stretch in place (bit for bit as before).
+//
+// This file is the queue's logic, without threads or clocks of its own, so the tests can drive it step by step:
+//  - one wanted render per channel: a newer request for the channel replaces the waiting one, and cancels the one
+//    rendering if it is for other settings (its result is thrown away);
+//  - debounce: a request runs only once its channel has asked for nothing else for `debounceMs` (a drag of the tempo
+//    display asks for a new render at every step; only where it stops is rendered);
+//  - a finished render is kept, by its key, until the next publish has built the channel from it.
+
+#include <atomic>
+#include <cstdint>
+#include <functional>
+#include <map>
+#include <memory>
+#include <optional>
+#include <string>
+
+
+namespace lynx::stretchdefer
+{
+// Whether the live engine defers stretch renders (default on). Off: every build renders in place, as before round 190un
+// (the tests' A/B).
+bool enabled() noexcept;
+void setEnabled (bool on) noexcept;
+// Whether a channel built anew from its new stretch while its clips play starts them again where they are (default on;
+// RackState::restretched). Off: they go silent until they start again, as before round 190un (the tests' A/B).
+bool resumeEnabled() noexcept;
+void setResumeEnabled (bool on) noexcept;
+
+// What a render returns: what it made, held until the channel is built from it (the stretched copies stay in their caches
+// while they are held); nullptr = nothing (cancelled, failed: the channel is built in place then, as before).
+using Result = std::shared_ptr<const void>;
+// A render; `cancelled` turns true when a newer request made it useless (it may stop early and return anything).
+using Render = std::function<Result (const std::atomic<bool>& cancelled)>;
+
+class Queue
+{
+public:
+    explicit Queue (double debounceMs = 150.0) : debounce (debounceMs) {}
+
+    enum class Answer
+    {
+        ready,   // the render for `key` is done: build the channel now (it reads the stretch from the cache)
+        deferred // keep the channel's running instrument; the render is waiting or running
+    };
+    // A build wants channel `channel`'s stretch `key` (message thread), at time `nowMs`.
+    Answer request (std::uint64_t channel, const std::string& key, Render render, double nowMs);
+
+    struct Job
+    {
+        std::uint64_t channel = 0;
+        std::string key;
+        Render render;
+        std::shared_ptr<std::atomic<bool>> cancelled;
+    };
+    // The next render due at `nowMs` (its channel asked for nothing else for the debounce time), marked running; empty
+    // when none is due (dueInMs: how long until the next one is, or −1 when nothing waits). One render runs at a time.
+    std::optional<Job> next (double nowMs, double* dueInMs = nullptr);
+    // A render ended. True when its result was kept (the engine then builds the rack again).
+    bool finished (const Job& job, Result result);
+
+    // After a publish: the results it built from are let go; the ones it did not ask for (a channel removed, other
+    // settings since) too. Results that finished after `publishStarted` (a serial from beginPublish) stay for the next.
+    std::uint64_t beginPublish() noexcept { return ++publishSerial; }
+    void endPublish (std::uint64_t publishStarted);
+
+    void clear(); // everything waiting dropped, the running render cancelled, results let go (a new project, shutdown)
+
+    bool idle() const noexcept { return waiting.empty() && ! running.has_value(); }
+    bool hasResults() const noexcept { return ! done.empty(); }
+    std::size_t waitingCount() const noexcept { return waiting.size(); }
+    bool isRunning() const noexcept { return running.has_value(); }
+
+    struct Counts
+    {
+        int requested = 0, started = 0, cancelled = 0, kept = 0, readyHits = 0;
+    };
+    const Counts& counts() const noexcept { return stats; }
+
+private:
+    struct Waiting
+    {
+        std::string key;
+        Render render;
+        double since = 0.0;
+    };
+    struct Running
+    {
+        std::uint64_t channel = 0;
+        std::string key;
+        std::shared_ptr<std::atomic<bool>> cancelled;
+    };
+    struct Done
+    {
+        std::uint64_t channel = 0;
+        Result result;
+        std::uint64_t serial = 0; // publishSerial when it finished
+    };
+    double debounce;
+    std::map<std::uint64_t, Waiting> waiting; // by channel
+    std::optional<Running> running;
+    std::map<std::string, Done> done; // by key
+    std::uint64_t publishSerial = 0;
+    Counts stats;
+};
+} // namespace lynx::stretchdefer

+ 17 - 0
src/core/TimeStretch.cpp

@@ -1161,6 +1161,8 @@ bool stretchBakesPitch (StretchMethod method, const WarpModeSettings& modes) noe
 std::shared_ptr<SampleData> timeStretch (const SampleData& in, double ratio, StretchMethod method, double semitones,
 std::shared_ptr<SampleData> timeStretch (const SampleData& in, double ratio, StretchMethod method, double semitones,
                                          const StretchOptions& options)
                                          const StretchOptions& options)
 {
 {
+    if (stretchdetail::cancelled()) // (round 190un: a newer render was asked for)
+        return nullptr;
     const auto frames = (long) in.frames();
     const auto frames = (long) in.frames();
     if (! stretchBakesPitch (method, options.modes))
     if (! stretchBakesPitch (method, options.modes))
         semitones = 0.0;
         semitones = 0.0;
@@ -1311,6 +1313,8 @@ Planar spectralStretchMapped (const Planar& in, const StretchMap& map, double sa
     constexpr long chunk = 256;
     constexpr long chunk = 256;
     for (long o = 0; o < outFrames; o += chunk)
     for (long o = 0; o < outFrames; o += chunk)
     {
     {
+        if ((o & (chunk * 64 - 1)) == 0 && stretchdetail::cancelled()) // (round 190un: a newer render was asked for)
+            break;
         const auto length = std::min (chunk, outFrames - o);
         const auto length = std::min (chunk, outFrames - o);
         const auto inEnd = std::clamp (inputFor ((double) (o + length) + outLatency), inPos, need);
         const auto inEnd = std::clamp (inputFor ((double) (o + length) + outLatency), inPos, need);
         for (int c = 0; c < channels; ++c)
         for (int c = 0; c < channels; ++c)
@@ -1322,9 +1326,22 @@ Planar spectralStretchMapped (const Planar& in, const StretchMap& map, double sa
 }
 }
 } // namespace
 } // namespace
 
 
+namespace stretchdetail
+{
+namespace
+{
+thread_local const std::atomic<bool>* cancelFlag = nullptr;
+}
+CancelScope::CancelScope (const std::atomic<bool>* flag) noexcept : previous (cancelFlag) { cancelFlag = flag; }
+CancelScope::~CancelScope() { cancelFlag = previous; }
+bool cancelled() noexcept { return cancelFlag != nullptr && cancelFlag->load (std::memory_order_relaxed); }
+} // namespace stretchdetail
+
 std::shared_ptr<SampleData> timeStretchMapped (const SampleData& in, const StretchMap& map, StretchMethod method, double semitones,
 std::shared_ptr<SampleData> timeStretchMapped (const SampleData& in, const StretchMap& map, StretchMethod method, double semitones,
                                                const StretchOptions& options)
                                                const StretchOptions& options)
 {
 {
+    if (stretchdetail::cancelled())
+        return nullptr;
     const auto frames = (long) in.frames();
     const auto frames = (long) in.frames();
     const auto plain = [&] {
     const auto plain = [&] {
         const auto ratio = frames > 0 && ! map.empty() ? map.back().second / (double) frames : 1.0;
         const auto ratio = frames > 0 && ! map.empty() ? map.back().second / (double) frames : 1.0;

+ 17 - 0
src/core/TimeStretch.h

@@ -227,5 +227,22 @@ float beatsEnvelopeGainClassic (float envelope, long i, long span) noexcept;
 inline constexpr double beatsTurnSeconds = 0.020;
 inline constexpr double beatsTurnSeconds = 0.020;
 // The spectral stretch with a given preset (no near-unity shortcut).
 // The spectral stretch with a given preset (no near-unity shortcut).
 std::shared_ptr<SampleData> stretchWith (const SampleData& input, double ratio, const Preset& preset);
 std::shared_ptr<SampleData> stretchWith (const SampleData& input, double ratio, const Preset& preset);
+
+// Round 190un (issue #381): a stretch its caller may give up (the live engine's deferred renders, core/StretchDefer.h).
+// While a CancelScope lives on a thread, the long loops of the stretches made there stop early once `flag` turns true;
+// what they return then is incomplete and the caller throws it away (cancelled() tells it so). Without a scope nothing
+// changes: every render is the same, bit for bit.
+class CancelScope
+{
+public:
+    explicit CancelScope (const std::atomic<bool>* flag) noexcept;
+    ~CancelScope();
+    CancelScope (const CancelScope&) = delete;
+    CancelScope& operator= (const CancelScope&) = delete;
+
+private:
+    const std::atomic<bool>* previous;
+};
+bool cancelled() noexcept;
 } // namespace stretchdetail
 } // namespace stretchdetail
 } // namespace lynx
 } // namespace lynx

+ 134 - 0
src/engine/AudioEngine.cpp

@@ -54,6 +54,7 @@
 #include "platform/Paths.h"
 #include "platform/Paths.h"
 #include "engine/FlStudio.h"
 #include "engine/FlStudio.h"
 
 
+#include <condition_variable>
 #include <limits>
 #include <limits>
 #include <map>
 #include <map>
 #include <mutex>
 #include <mutex>
@@ -83,6 +84,7 @@
 #include "core/ProjectSafety.h"
 #include "core/ProjectSafety.h"
 #include "core/SoftClip.h"
 #include "core/SoftClip.h"
 #include "core/Scheduler.h"
 #include "core/Scheduler.h"
+#include "core/StretchDefer.h"
 #include "core/TrackStates.h"
 #include "core/TrackStates.h"
 #include "engine/ChannelRackProcessor.h"
 #include "engine/ChannelRackProcessor.h"
 #include "engine/DllAsioDevice.h"
 #include "engine/DllAsioDevice.h"
@@ -749,6 +751,7 @@ AudioEngine::AudioEngine (bool openAudioDevice, int workerThreads, bool userPlug
     // VFX Script (round 165d): the audio thread waits a bounded time for the Python thread (exports wait for it)
     // VFX Script (round 165d): the audio thread waits a bounded time for the Python thread (exports wait for it)
     vfx::script::setRealtime (openAudioDevice);
     vfx::script::setRealtime (openAudioDevice);
     liveDevice = openAudioDevice; // (round 190qh)
     liveDevice = openAudioDevice; // (round 190qh)
+    deferStretches = openAudioDevice; // (round 190un: an export renders its stretches in place)
     const auto mark = [] (const char* step) { if (startupMark != nullptr) startupMark (step); };
     const auto mark = [] (const char* step) { if (startupMark != nullptr) startupMark (step); };
     mark ("  engine: workers + default song");
     mark ("  engine: workers + default song");
     if (juce::JUCEApplicationBase::getInstance() != nullptr) // issue #36: retired racks are freed from their own message
     if (juce::JUCEApplicationBase::getInstance() != nullptr) // issue #36: retired racks are freed from their own message
@@ -912,6 +915,7 @@ AudioEngine::~AudioEngine()
     }
     }
     previewAlive->store (false); // (round 190aq: a preview still being prepared ends without touching the engine)
     previewAlive->store (false); // (round 190aq: a preview still being prepared ends without touching the engine)
     previewJobs.stop();
     previewJobs.stop();
+    stretchWorker = nullptr; // (round 190un: its render reads the sample library; it is cancelled and joined first)
     stopTimer();
     stopTimer();
     rackExchange.dispose = nullptr; // (from here the racks are freed at once)
     rackExchange.dispose = nullptr; // (from here the racks are freed at once)
     rackDisposer.flush();
     rackDisposer.flush();
@@ -5789,6 +5793,94 @@ const AutomationDisplay& AudioEngine::getAutomationDisplay()
     return automationDisplay;
     return automationDisplay;
 }
 }
 
 
+// Round 190un (issue #381, core/StretchDefer.h): the thread that renders the deferred stretches, one at a time, at background
+// priority. The queue's own rules (debounce, a newer request cancels the older) are in stretchdefer::Queue; this only waits
+// for the next job that is due, runs it, and tells the engine's timer when a render is ready.
+struct AudioEngine::StretchWorker
+{
+    std::mutex lock;
+    std::condition_variable wake;
+    stretchdefer::Queue queue { 150.0 }; // (a drag of the tempo display moves it every few ms: only where it stops renders)
+    std::thread thread;
+    bool stopping = false;
+    std::atomic<bool> ready { false };
+
+    static double nowMs() { return juce::Time::getMillisecondCounterHiRes(); }
+
+    ~StretchWorker()
+    {
+        {
+            const std::scoped_lock l (lock);
+            stopping = true;
+            queue.clear();
+        }
+        wake.notify_all();
+        if (thread.joinable())
+            thread.join();
+    }
+
+    void run()
+    {
+        juce::Thread::setCurrentThreadName ("LYNX stretch");
+        std::unique_lock l (lock);
+        while (! stopping)
+        {
+            auto due = -1.0;
+            auto job = queue.next (nowMs(), &due);
+            if (! job)
+            {
+                if (due < 0.0)
+                    wake.wait (l);
+                else
+                    wake.wait_for (l, std::chrono::microseconds ((std::int64_t) (due * 1000.0) + 100));
+                continue;
+            }
+            l.unlock();
+            stretchdefer::Result result;
+            try
+            {
+                result = job->render (*job->cancelled);
+            }
+            catch (...)
+            {
+                result = nullptr;
+            }
+            l.lock();
+            if (queue.finished (*job, std::move (result)))
+                ready.store (true);
+        }
+    }
+};
+
+AudioEngine::StretchWorker& AudioEngine::stretchWorkerNow()
+{
+    if (stretchWorker == nullptr)
+    {
+        stretchWorker = std::make_unique<StretchWorker>();
+        stretchWorker->thread = std::thread ([w = stretchWorker.get()] { w->run(); });
+    }
+    return *stretchWorker;
+}
+
+bool AudioEngine::stretchesSettled() const
+{
+    if (! lastPublishedShape.staleStretch.empty()
+        && std::any_of (lastPublishedShape.staleStretch.begin(), lastPublishedShape.staleStretch.end(), [] (std::uint8_t s) { return s != 0; }))
+        return false;
+    if (stretchWorker == nullptr)
+        return true;
+    const std::scoped_lock l (stretchWorker->lock);
+    return stretchWorker->queue.idle() && ! stretchWorker->ready.load();
+}
+
+stretchdefer::Queue::Counts AudioEngine::stretchRenderCounts() const
+{
+    if (stretchWorker == nullptr)
+        return {};
+    const std::scoped_lock l (stretchWorker->lock);
+    return stretchWorker->queue.counts();
+}
+
 RackState::Factories AudioEngine::rackFactories()
 RackState::Factories AudioEngine::rackFactories()
 {
 {
     RackState::Factories factories;
     RackState::Factories factories;
@@ -6073,6 +6165,37 @@ void AudioEngine::publishSong()
         araHost->sync (played, transport.sampleRate.load());
         araHost->sync (played, transport.sampleRate.load());
         factories.araInstrument = [this] (const ChannelDef& c, double rate) { return araHost->instrumentFor (c, rate); };
         factories.araInstrument = [this] (const ChannelDef& c, double rate) { return araHost->instrumentFor (c, rate); };
     }
     }
+    // round 190un (issue #381): a keep-pitch channel whose stretch changed keeps playing while the new one renders off the
+    // message thread (core/StretchDefer.h); the timer builds the rack again when it is ready
+    std::uint64_t stretchPublish = 0;
+    if (deferStretches && stretchdefer::enabled())
+    {
+        auto& worker = stretchWorkerNow();
+        {
+            const std::scoped_lock l (worker.lock);
+            stretchPublish = worker.queue.beginPublish();
+        }
+        factories.deferStretch = [this, &worker, base = rackFactories(), mode = FloatMode::current()] (const ChannelDef& channel, double bpm) {
+            auto render = [channel, bpm, base, mode] (const std::atomic<bool>& cancelled) -> stretchdefer::Result {
+                const KeepFloatMode keep;
+                mode.applyHere(); // (the message thread's rounding and flushing: the same render, bit for bit)
+                const stretchdetail::CancelScope scope (&cancelled);
+                auto held = std::make_shared<std::vector<std::shared_ptr<const SampleData>>>();
+                playedSample (channel, bpm, base, held.get());
+                if (cancelled.load() || held->empty())
+                    return nullptr;
+                return held;
+            };
+            const auto id = channel.instance.id != 0 ? channel.instance.id : (std::uint64_t) std::hash<std::string> {} (channel.samplePath);
+            stretchdefer::Queue::Answer answer;
+            {
+                const std::scoped_lock l (worker.lock);
+                answer = worker.queue.request (id, stretchRequestKey (channel, bpm), std::move (render), StretchWorker::nowMs());
+            }
+            worker.wake.notify_one();
+            return answer == stretchdefer::Queue::Answer::deferred;
+        };
+    }
     factories.currentSource = currentSource; // (round 190my: FL's Current track's latency in the PDC plan)
     factories.currentSource = currentSource; // (round 190my: FL's Current track's latency in the PDC plan)
     factories.movePdcLines = liveDevice; // (round 190qh: a live edit moves the PDC lines without a cut; never in a render)
     factories.movePdcLines = liveDevice; // (round 190qh: a live edit moves the PDC lines without a cut; never in a render)
     // (round 190sz: the rack's song shares the song's copy-on-write lists and states, as the undo history's copies do,
     // (round 190sz: the rack's song shares the song's copy-on-write lists and states, as the undo history's copies do,
@@ -6100,6 +6223,14 @@ void AudioEngine::publishSong()
     lastPublishedShape.song.bpm = song.bpm;
     lastPublishedShape.song.bpm = song.bpm;
     lastPublishedShape.instruments = state->instruments;
     lastPublishedShape.instruments = state->instruments;
     lastPublishedShape.serial = state->serial; // (round 168s: the renderer moves held notes only along this chain)
     lastPublishedShape.serial = state->serial; // (round 168s: the renderer moves held notes only along this chain)
+    lastPublishedShape.staleStretch = state->staleStretch; // (round 190un: the kept instruments still wait for their stretch)
+    lastPublishedShape.staleSpeed = state->staleSpeed;
+    lastPublishedShape.playedStretchSeconds = state->playedStretchSeconds;
+    if (stretchWorker != nullptr && stretchPublish != 0)
+    {
+        const std::scoped_lock l (stretchWorker->lock);
+        stretchWorker->queue.endPublish (stretchPublish); // (the renders this build took are let go: the rack holds them)
+    }
     lastPublishedShape.effects = state->effects;
     lastPublishedShape.effects = state->effects;
     lastPublishedShape.sampleRate = state->sampleRate;
     lastPublishedShape.sampleRate = state->sampleRate;
     lastPublishedShape.latencies = state->latencies;
     lastPublishedShape.latencies = state->latencies;
@@ -6995,6 +7126,9 @@ void AudioEngine::timerCallback()
     }
     }
 
 
     updateRealtimeStats();
     updateRealtimeStats();
+    // round 190un (issue #381): a deferred stretch is ready: the channel is built again from it (a cache hit, no render here)
+    if (stretchWorker != nullptr && stretchWorker->ready.exchange (false))
+        publishSong();
     // round 190gn (A1): the racks' pitch-shifter stocks back to their reserve (a voice took one: a live keyboard on a
     // round 190gn (A1): the racks' pitch-shifter stocks back to their reserve (a voice took one: a live keyboard on a
     // keep-pitch channel); nothing to do, and no allocation, when none was taken
     // keep-pitch channel); nothing to do, and no allocation, when none was taken
     shifterstock::topUpAll();
     shifterstock::topUpAll();

+ 17 - 0
src/engine/AudioEngine.h

@@ -13,6 +13,7 @@
 #include <juce_audio_utils/juce_audio_utils.h>
 #include <juce_audio_utils/juce_audio_utils.h>
 
 
 #include "core/UndoNames.h"
 #include "core/UndoNames.h"
+#include "core/StretchDefer.h" // round 190un
 #include "core/LinkFormula.h"
 #include "core/LinkFormula.h"
 #include "core/Multilink.h"
 #include "core/Multilink.h"
 #include "core/RemoteMap.h"
 #include "core/RemoteMap.h"
@@ -1435,6 +1436,15 @@ public:
     // notes on their shifter — offline (an automation step) and live (the knobs, on a stand-in device)
     // notes on their shifter — offline (an automation step) and live (the knobs, on a stand-in device)
     // (src/engine/SamplerPitch190udTest.cpp; --round190udtest, --selftest "round190ud")
     // (src/engine/SamplerPitch190udTest.cpp; --round190udtest, --selftest "round190ud")
     static juce::String samplerPitch190udSelfTest (const std::function<void (const juce::String&)>& log = {});
     static juce::String samplerPitch190udSelfTest (const std::function<void (const juce::String&)>& log = {});
+    // Round 190un (issue #381): a tempo change never blocks the message thread on a long warped clip's stretch — 20 tempo
+    // changes in a second, stopped and playing, at 44.1 / 48 kHz, other stretch modes, a Clip-launch clip; the final render
+    // matches a fresh one (src/engine/TempoStretch190unTest.cpp; --round190untest, --selftest "round190un"). `seconds`:
+    // the long file's length (233 = the reporter's 3:53 song).
+    static juce::String tempoStretch190unSelfTest (const std::function<void (const juce::String&)>& log = {}, double seconds = 233.0);
+    // Whether every deferred stretch render is done and built into the rack (round 190un; tests)
+    bool stretchesSettled() const;
+    // How many deferred stretch renders were asked for, started, cancelled, kept (round 190un; tests)
+    stretchdefer::Queue::Counts stretchRenderCounts() const;
     // Round 190jb: exports with the live engine's plugin instances (engine/Exporter.h LiveExportHold), on a stand-in device:
     // Round 190jb: exports with the live engine's plugin instances (engine/Exporter.h LiveExportHold), on a stand-in device:
     // LYNX's own units render the same with and without the hold; a hosted plugin whose sound depends on its instance
     // LYNX's own units render the same with and without the hold; a hosted plugin whose sound depends on its instance
     // (`plugins`: VST3 / CLAP files, e.g. the LYNX Test Synth with LYNX_TEST_SYNTH_SEED=1, Surge XT) exports what
     // (`plugins`: VST3 / CLAP files, e.g. the LYNX Test Synth with LYNX_TEST_SYNTH_SEED=1, Surge XT) exports what
@@ -2086,6 +2096,13 @@ private:
     static juce::String remoteDeviceStateHashOf (const Song&);
     static juce::String remoteDeviceStateHashOf (const Song&);
     RackState lastPublishedShape; // channels + instruments of the last snapshot, to reuse voices
     RackState lastPublishedShape; // channels + instruments of the last snapshot, to reuse voices
     bool liveDevice = false; // (round 190qh) an engine made to play on an audio device (the app's); exports have none
     bool liveDevice = false; // (round 190qh) an engine made to play on an audio device (the app's); exports have none
+    // Round 190un (issue #381, core/StretchDefer.h): the stretches of keep-pitch channels are rendered off the message
+    // thread (a new tempo, other warp markers) while the channel's running instrument plays on; the engine's timer builds
+    // the rack again when one is ready. On for an engine with an audio device (deferStretches = liveDevice); the tests set it.
+    struct StretchWorker;
+    std::unique_ptr<StretchWorker> stretchWorker;
+    bool deferStretches = false;
+    StretchWorker& stretchWorkerNow();
     std::vector<int> standInChannels, standInInserts; // (playsStandIn)
     std::vector<int> standInChannels, standInInserts; // (playsStandIn)
     std::vector<int> frozenMissing;                    // (frozenAudioMissing)
     std::vector<int> frozenMissing;                    // (frozenAudioMissing)
     struct FreezeCheck
     struct FreezeCheck

+ 5 - 0
src/engine/SampleLibrary.cpp

@@ -834,6 +834,9 @@ std::shared_ptr<const SampleData> SampleLibrary::loadStretched (const juce::Stri
             made = map.empty() ? timeStretch (*original, ratio, method, semitones, options)
             made = map.empty() ? timeStretch (*original, ratio, method, semitones, options)
                                : timeStretchMapped (*original, map, method, semitones, options);
                                : timeStretchMapped (*original, map, method, semitones, options);
         }
         }
+        // (round 190un: a deferred render given up half-way, core/StretchDefer.h, is neither kept nor written)
+        if (made == nullptr || stretchdetail::cancelled())
+            return nullptr;
         stretched = std::move (made);
         stretched = std::move (made);
         if (stretched != nullptr && onDisk != juce::File())
         if (stretched != nullptr && onDisk != juce::File())
             writeStretchedLater (onDisk, stretched, path);
             writeStretchedLater (onDisk, stretched, path);
@@ -885,6 +888,8 @@ std::shared_ptr<const SampleData> SampleLibrary::loadStretchedSpan (const juce::
     {
     {
         const loadtrace::Scope timing ("stretch_compute");
         const loadtrace::Scope timing ("stretch_compute");
         stretched = timeStretchSpan (*span, ratio, method, semitones, options);
         stretched = timeStretchSpan (*span, ratio, method, semitones, options);
+        if (stretchdetail::cancelled()) // (round 190un: a deferred render given up half-way is neither kept nor written)
+            return nullptr;
         if (stretched != nullptr && onDisk != juce::File())
         if (stretched != nullptr && onDisk != juce::File())
             writeStretchedLater (onDisk, stretched);
             writeStretchedLater (onDisk, stretched);
     }
     }

+ 742 - 0
src/engine/TempoStretch190unTest.cpp

@@ -0,0 +1,742 @@
+// Round 190un (issue #381, chlantutztetr: "software freezes when adjusting the bpm of a project when a sample is warped"):
+// a 3:53 song at 48 kHz on the Playlist, Audio editor › Auto-warp (119 markers at 122.46 BPM), then a drag of the tempo
+// display: LYNX stopped responding. Each tempo step built the clip's channel again on the message thread, and that build
+// rendered the whole stretch there (core/TimeStretch's mapped stretch of the whole file: seconds per step, one step per
+// pixel of the drag). Now the live engine keeps the channel's instrument while the stretch renders on a worker thread
+// (core/StretchDefer.h): debounced, the older render cancelled by a newer one, and the channel built again when it is
+// ready; meanwhile the kept instrument reads its old stretch at the speed of the new tempo (FL plays its precomputed
+// stretch the same way until it restretches, REA_rodada3 §5.1).
+//
+// The check, through the real paths (AudioEngine::editSong + clipops::followTempo, what the tempo display's drag, wheel,
+// typed value and the tap tempo all call; the engine's timer; a stand-in audio device on its own thread):
+//  A0. Auto-warp on the long song (keep pitch turned on): the edit returns at once, the first stretch renders off it;
+//  A. before (stretchdefer off, the build of 0.1.32): one tempo step blocks the message thread for the whole render;
+//  B. 20 tempo changes in 1 s while stopped: no call on the message thread takes 50 ms or more; at most two renders
+//     start (the debounce), the final stretch is ready, the channel is built from it, and it is bit for bit a fresh render
+//     at the final tempo;
+//  C. the same while playing: no call takes 50 ms, the clip never goes silent (before, during and after the new stretch
+//     is swapped in), and the final render is right; C2: without the resume (0.1.32) the clip went silent at the swap;
+//  D. tempo automation while playing: nothing is built again (the tempo follows in real time, issue #187's hook);
+//  E. the other cases on the same path: the file at 44.1 kHz, the Beats mode, Stretch without markers (Time set), a
+//     Resample clip (nothing renders) and a Clip-launch clip, each with a tempo burst.
+
+#include "engine/AudioEngine.h"
+
+#include "core/AutoWarp.h"
+#include "core/ClipLauncher.h"
+#include "core/ClipOps.h"
+#include "core/StretchDefer.h"
+#include "core/TimeStretch.h"
+#include "core/WarpEdit.h"
+
+namespace lynx
+{
+namespace
+{
+constexpr int block190un = 512;
+constexpr double deviceRate190un = 48000.0;
+
+// the stand-in device: plays the engine from its own thread, in real time, and keeps what the engine wrote (left channel)
+struct TempoDevice final : juce::AudioIODevice, private juce::Thread
+{
+    TempoDevice() : juce::AudioIODevice ("Tempo test device", "Tempo stretch test"), juce::Thread ("tempo test device") {}
+    ~TempoDevice() override { close(); }
+
+    static inline std::vector<float>* capture = nullptr; // (sized by the test before Play; the device thread fills it)
+    static inline std::atomic<int> captured { 0 };
+    static inline std::atomic<bool> recording { false };
+
+    juce::StringArray getOutputChannelNames() override { return { "Out 1", "Out 2" }; }
+    juce::StringArray getInputChannelNames() override { return {}; }
+    juce::Array<double> getAvailableSampleRates() override { return { deviceRate190un }; }
+    juce::Array<int> getAvailableBufferSizes() override { return { block190un }; }
+    int getDefaultBufferSize() override { return block190un; }
+    juce::String open (const juce::BigInteger&, const juce::BigInteger& outs, double, int) override
+    {
+        close();
+        outsNow = outs;
+        outsNow.setRange (2, juce::jmax (0, outsNow.getHighestBit() - 1), false);
+        data.setSize (2, block190un);
+        opened = true;
+        startThread();
+        return {};
+    }
+    void close() override
+    {
+        stop();
+        stopThread (10000);
+        opened = false;
+    }
+    bool isOpen() override { return opened; }
+    void start (juce::AudioIODeviceCallback* cb) override
+    {
+        if (! opened || cb == nullptr)
+            return;
+        cb->audioDeviceAboutToStart (this);
+        const juce::ScopedLock sl (callbackLock);
+        callback = cb;
+    }
+    void stop() override
+    {
+        juce::AudioIODeviceCallback* old = nullptr;
+        {
+            const juce::ScopedLock sl (callbackLock);
+            old = std::exchange (callback, nullptr);
+        }
+        if (old != nullptr)
+            old->audioDeviceStopped();
+    }
+    bool isPlaying() override { return callback != nullptr; }
+    juce::String getLastError() override { return {}; }
+    int getCurrentBufferSizeSamples() override { return block190un; }
+    double getCurrentSampleRate() override { return deviceRate190un; }
+    int getCurrentBitDepth() override { return 32; }
+    juce::BigInteger getActiveOutputChannels() const override { return outsNow; }
+    juce::BigInteger getActiveInputChannels() const override { return {}; }
+    int getOutputLatencyInSamples() override { return block190un; }
+    int getInputLatencyInSamples() override { return 0; }
+
+private:
+    void run() override
+    {
+        const auto blockMs = 1000.0 * block190un / deviceRate190un;
+        auto next = juce::Time::getMillisecondCounterHiRes();
+        while (! threadShouldExit())
+        {
+            {
+                const juce::ScopedLock sl (callbackLock);
+                if (callback != nullptr)
+                {
+                    callback->audioDeviceIOCallbackWithContext (nullptr, 0, data.getArrayOfWritePointers(), data.getNumChannels(), block190un, {});
+                    if (recording.load() && capture != nullptr)
+                    {
+                        const auto at = captured.load();
+                        const auto n = juce::jmin (block190un, (int) capture->size() - at);
+                        if (n > 0)
+                        {
+                            std::copy (data.getReadPointer (0), data.getReadPointer (0) + n, capture->begin() + at);
+                            captured.store (at + n);
+                        }
+                    }
+                }
+            }
+            // (real time: one block per block's duration, as a sound card asks)
+            next += blockMs;
+            const auto wait = next - juce::Time::getMillisecondCounterHiRes();
+            if (wait > 0.5)
+                juce::Thread::sleep ((int) wait);
+            else if (wait < -100.0)
+                next = juce::Time::getMillisecondCounterHiRes();
+        }
+    }
+
+    juce::BigInteger outsNow;
+    juce::AudioBuffer<float> data;
+    juce::CriticalSection callbackLock;
+    juce::AudioIODeviceCallback* callback = nullptr;
+    bool opened = false;
+};
+
+struct TempoType final : juce::AudioIODeviceType
+{
+    TempoType() : juce::AudioIODeviceType ("Tempo stretch test") {}
+    void scanForDevices() override {}
+    juce::StringArray getDeviceNames (bool input) const override { return input ? juce::StringArray() : juce::StringArray ("Tempo test device"); }
+    int getDefaultDeviceIndex (bool input) const override { return input ? -1 : 0; }
+    int getIndexOfDevice (juce::AudioIODevice* d, bool input) const override { return d != nullptr && ! input ? 0 : -1; }
+    bool hasSeparateInputsAndOutputs() const override { return false; }
+    juce::AudioIODevice* createDevice (const juce::String& out, const juce::String&) override
+    {
+        return out == "Tempo test device" ? new TempoDevice() : nullptr;
+    }
+};
+
+// A song-like file: a kick on every beat at 122.46 BPM, a hat between them and a held two-note pad under them (never
+// silent), stereo 24-bit WAV; the same every time (a fixed noise sequence).
+bool writeSong (const juce::File& file, double seconds, double rate)
+{
+    const auto frames = (int) std::llround (seconds * rate);
+    juce::AudioBuffer<float> b (2, frames);
+    const auto beat = 60.0 / 122.46;
+    std::uint32_t noise = 190381u;
+    for (int i = 0; i < frames; ++i)
+    {
+        const auto t = (double) i / rate;
+        const auto inBeat = std::fmod (t, beat);
+        const auto inHalf = std::fmod (t + beat * 0.5, beat);
+        auto x = 0.12 * std::sin (2.0 * juce::MathConstants<double>::pi * 220.0 * t) + 0.08 * std::sin (2.0 * juce::MathConstants<double>::pi * 329.63 * t);
+        x += 0.6 * std::exp (-inBeat * 30.0) * std::sin (2.0 * juce::MathConstants<double>::pi * (55.0 + 90.0 * std::exp (-inBeat * 40.0)) * inBeat);
+        noise = noise * 1664525u + 1013904223u;
+        x += 0.25 * std::exp (-inHalf * 120.0) * ((double) (noise >> 8) / 8388608.0 - 1.0);
+        b.setSample (0, i, (float) x);
+        b.setSample (1, i, (float) (x * 0.9));
+    }
+    file.deleteFile();
+    juce::WavAudioFormat wav;
+    std::unique_ptr<juce::AudioFormatWriter> w (wav.createWriterFor (file.createOutputStream().release(), rate, 2, 24, {}, 0));
+    return w != nullptr && w->writeFromAudioSampleBuffer (b, 0, frames);
+}
+
+bool sameSamples (const SampleData* a, const SampleData* b)
+{
+    if (a == nullptr || b == nullptr || a->frames() != b->frames() || a->left.size() != b->left.size() || a->right.size() != b->right.size())
+        return false;
+    return std::memcmp (a->left.data(), b->left.data(), a->left.size() * sizeof (float)) == 0
+           && (a->right.empty() || std::memcmp (a->right.data(), b->right.data(), a->right.size() * sizeof (float)) == 0);
+}
+
+// the longest run of 10 ms windows whose level stays under −50 dBFS, in ms (`where`: the frame it starts at)
+double longestSilenceMs (const std::vector<float>& x, int from, int to, int* where = nullptr)
+{
+    const int window = (int) (deviceRate190un * 0.010);
+    double longest = 0.0, run = 0.0;
+    int runStart = 0;
+    for (int i = juce::jmax (0, from); i + window <= juce::jmin ((int) x.size(), to); i += window)
+    {
+        double sum = 0.0;
+        for (int k = 0; k < window; ++k)
+            sum += (double) x[(std::size_t) (i + k)] * x[(std::size_t) (i + k)];
+        const auto rms = std::sqrt (sum / window);
+        if (rms < 0.00316)
+        {
+            if (run == 0.0)
+                runStart = i;
+            run += 10.0;
+        }
+        else
+            run = 0.0;
+        if (run > longest)
+        {
+            longest = run;
+            if (where != nullptr)
+                *where = runStart;
+        }
+    }
+    return longest;
+}
+} // namespace
+
+juce::String AudioEngine::tempoStretch190unSelfTest (const std::function<void (const juce::String&)>& log, double seconds)
+{
+    auto say = [&log] (const juce::String& line) {
+        if (log)
+            log (line);
+    };
+    const auto folder = juce::File::getSpecialLocation (juce::File::tempDirectory)
+                            .getChildFile ("lynx-tempo190un-" + juce::String::toHexString (juce::Random::getSystemRandom().nextInt64()));
+    folder.createDirectory();
+    struct Cleanup
+    {
+        juce::File f;
+        ~Cleanup()
+        {
+            f.deleteRecursively();
+            TempoDevice::capture = nullptr;
+            TempoDevice::recording = false;
+            stretchdefer::setEnabled (true);
+            stretchdefer::setResumeEnabled (true);
+        }
+    } cleanup { folder };
+
+    juce::StringArray errors;
+    int checks = 0;
+    auto check = [&] (const juce::String& what, bool ok, const juce::String& detail = {}) {
+        ++checks;
+        say ((ok ? "ok   " : "FAIL ") + what + (detail.isNotEmpty() ? " (" + detail + ")" : juce::String()));
+        if (! ok)
+            errors.add (what + (detail.isNotEmpty() ? " (" + detail + ")" : juce::String()));
+    };
+    auto ms = [] (double v) { return juce::String (v, 1) + " ms"; };
+    auto now = [] { return juce::Time::getMillisecondCounterHiRes(); };
+
+    const auto long48 = folder.getChildFile ("song48k.wav"), long44 = folder.getChildFile ("song44k.wav");
+    const auto shortSeconds = juce::jmin (seconds, 75.0); // (over a minute: Auto-warp follows its bars, as on a song)
+    const auto short48 = folder.getChildFile ("loop48k.wav");
+    if (! writeSong (long48, seconds, 48000.0) || ! writeSong (long44, shortSeconds, 44100.0) || ! writeSong (short48, shortSeconds, 48000.0))
+        return "ERROR can't write the test songs in " + folder.getFullPathName();
+
+    // Auto-warp as the Audio editor runs it (AudioEditor::autoWarp: autowarp::analyse on the decoded file, then editWarp:
+    // ensureMarkers, the markers, keep pitch, syncLength)
+    SampleLibrary library;
+    auto warped = [&] (const juce::File& file, double fileSeconds, StretchMethod method, int markersMode, double& autoMs, int& markerCount) {
+        // markersMode: 0 auto-warp, 1 Time set without markers (FL's Stretch), 2 Resample with Time set (no keep pitch)
+        ChannelDef c;
+        c.instrument = InstrumentKind::audioClip;
+        c.samplePath = file.getFullPathName().toStdString();
+        c.name = file.getFileNameWithoutExtension().toStdString();
+        c.mixerTrack = 0;
+        c.sampler.stretchMethod = method;
+        autoMs = 0.0;
+        markerCount = 0;
+        if (markersMode == 0)
+        {
+            const auto data = library.load (file.getFullPathName());
+            if (data == nullptr)
+                return c;
+            autowarp::Options o;
+            o.songBpm = 122.0;
+            o.beatsPerBar = 4.0;
+            const auto t0 = juce::Time::getMillisecondCounterHiRes();
+            const auto result = autowarp::analyse (*data, o);
+            autoMs = juce::Time::getMillisecondCounterHiRes() - t0;
+            markerCount = (int) result.markers.size();
+            warpedit::ensureMarkers (c.sampler, fileSeconds, 122.0);
+            if (result.markers.size() >= 2)
+                c.sampler.warp = result.markers;
+            c.sampler.keepPitch = true;
+            warpedit::syncLength (c.sampler, fileSeconds);
+        }
+        else
+        {
+            c.sampler.stretchBeats = (float) (fileSeconds * 122.0 / 60.0);
+            c.sampler.keepPitch = markersMode == 1;
+        }
+        return c;
+    };
+    auto songOf = [] (const ChannelDef& channel, bool grid) {
+        Song s;
+        s.bpm = 122.0;
+        s.mixer = Song::defaultMixer (2);
+        s.mixer[0].effects.clear();
+        s.channels.push_back (channel);
+        Clip ac;
+        ac.kind = ClipKind::audio;
+        ac.channel = 0;
+        ac.track = 0;
+        ac.length = (std::int64_t) std::ceil ((double) channel.sampler.stretchBeats * ppq);
+        if (grid)
+        {
+            launcher::setClip (s, 0, 0, ac);
+            s.clipGrid->globalQuant = LaunchQuant::none;
+            // (a long, empty Playlist under it: with none the song loops every bar, and that jump ends every voice)
+            auto& p = s.patterns.emplace_back();
+            p.lengthTicks = s.barTicks();
+            Clip pc;
+            pc.kind = ClipKind::pattern;
+            pc.pattern = 0;
+            pc.track = 5;
+            pc.length = 400 * s.barTicks();
+            s.playlist.push_back (pc);
+        }
+        else
+            s.playlist.push_back (ac);
+        s.mode = PlayMode::song;
+        return s;
+    };
+
+    // an engine on the stand-in device, the song published and its first stretch made (setSong builds the rack)
+    struct Live
+    {
+        std::unique_ptr<AudioEngine> engine;
+        double firstBuildMs = 0.0;
+    };
+    auto start = [&] (const Song& song, bool defer) {
+        Live live;
+        live.engine = std::make_unique<AudioEngine> (false);
+        auto& engine = *live.engine;
+        engine.deferStretches = defer;
+        engine.player.setProcessor (&engine.graph);
+        engine.deviceManager.addAudioDeviceType (std::make_unique<TempoType>());
+        if (const auto e = engine.deviceManager.initialise (0, 2, nullptr, true); e.isNotEmpty())
+        {
+            errors.add ("open the stand-in device: " + e);
+            live.engine = nullptr;
+            return live;
+        }
+        engine.deviceManager.addAudioCallback (&engine);
+        const auto t0 = juce::Time::getMillisecondCounterHiRes();
+        engine.setSong (song);
+        live.firstBuildMs = juce::Time::getMillisecondCounterHiRes() - t0;
+        for (int i = 0; i < 5; ++i)
+        {
+            engine.timerCallback();
+            juce::Thread::sleep (5);
+        }
+        return live;
+    };
+    auto finish = [] (Live& live) {
+        if (live.engine == nullptr)
+            return;
+        auto& engine = *live.engine;
+        engine.stop();
+        engine.timerCallback();
+        engine.deviceManager.removeAudioCallback (&engine);
+        engine.deviceManager.closeAudioDevice();
+        live.engine = nullptr;
+    };
+
+    // 20 tempo changes in 1 s, as a drag of the tempo display makes them (TempoDisplay::setBpm: editSong + followTempo),
+    // the engine's timer running between them; then the message thread goes on (timer only) until the stretches settle.
+    // Returns the longest call on the message thread; `settleMs`: from the last change until the rack plays the new stretch.
+    struct Burst
+    {
+        double longestMs = 0.0, longestEditMs = 0.0, settleMs = -1.0, finalBpm = 0.0;
+        int publishes = 0;
+    };
+    auto burst = [&] (AudioEngine& engine, double from, double step, bool waitSettle, double settleLimitMs = 120000.0) {
+        Burst b;
+        const auto publishesBefore = engine.getPublishCount();
+        const auto t0 = now();
+        for (int k = 1; k <= 20; ++k)
+        {
+            const auto bpm = from + step * k;
+            const auto a = now();
+            engine.editSong ([bpm] (Song& s) { clipops::followTempo (s, bpm); });
+            const auto took = now() - a;
+            b.longestEditMs = juce::jmax (b.longestEditMs, took);
+            b.longestMs = juce::jmax (b.longestMs, took);
+            b.finalBpm = bpm;
+            // the rest of this step's 50 ms: the timer, as the message loop runs it (30 Hz)
+            while (now() - t0 < 50.0 * k)
+            {
+                const auto c = now();
+                engine.timerCallback();
+                b.longestMs = juce::jmax (b.longestMs, now() - c);
+                juce::Thread::sleep (2);
+            }
+        }
+        const auto last = now();
+        if (waitSettle)
+            while (now() - last < settleLimitMs)
+            {
+                const auto c = now();
+                engine.timerCallback();
+                b.longestMs = juce::jmax (b.longestMs, now() - c);
+                if (engine.stretchesSettled())
+                {
+                    b.settleMs = now() - last;
+                    break;
+                }
+                juce::Thread::sleep (10);
+            }
+        b.publishes = (int) (engine.getPublishCount() - publishesBefore);
+        return b;
+    };
+    // the channel's stretch at the engine's tempo now: what the rack built (through the engine's cache: its time shows
+    // it was already made) against a fresh render with no cache
+    auto finalRender = [&] (AudioEngine& engine, const juce::String& what) {
+        const auto& channel = engine.getSong().channels[0];
+        const auto bpm = engine.getSong().bpm;
+        const auto t0 = now();
+        const auto cached = playedSample (channel, bpm, engine.rackFactories());
+        const auto cachedMs = now() - t0;
+        RackState::Factories fresh;
+        fresh.samples = [&library] (const std::string& path) { return library.load (juce::String::fromUTF8 (path.c_str())); };
+        fresh.stretchedSamples = [] (const std::string& path, double ratio, StretchMethod method, double semitones, const StretchMap& map,
+                                     const StretchOptions& options) -> std::shared_ptr<const SampleData> {
+            SampleLibrary own;
+            const auto original = own.load (juce::String::fromUTF8 (path.c_str()));
+            if (original == nullptr)
+                return nullptr;
+            if (! stretchBakesPitch (method, options.modes))
+                semitones = 0.0;
+            return map.empty() ? timeStretch (*original, ratio, method, semitones, options) : timeStretchMapped (*original, map, method, semitones, options);
+        };
+        fresh.stretchedSpans = [] (const std::string&, const std::string&, const std::shared_ptr<const SampleData>& span, double ratio, StretchMethod method,
+                                   double semitones, const StretchOptions& options) -> std::shared_ptr<const SampleData> {
+            return span != nullptr ? timeStretchSpan (*span, ratio, method, semitones, options) : nullptr;
+        };
+        const auto reference = playedSample (channel, bpm, fresh);
+        check (what + ": the rack's stretch was already made (no render on the message thread)", cachedMs < 50.0, ms (cachedMs));
+        check (what + ": it is bit for bit a fresh render at the final tempo (" + juce::String (bpm, 2) + " BPM)", sameSamples (cached.get(), reference.get()),
+               cached != nullptr && reference != nullptr ? juce::String (cached->frames()) + " / " + juce::String (reference->frames()) + " frames" : "missing");
+        check (what + ": the rack plays it (no channel waits for its stretch)",
+               engine.lastPublishedShape.staleStretch.empty()
+                   || std::none_of (engine.lastPublishedShape.staleStretch.begin(), engine.lastPublishedShape.staleStretch.end(), [] (std::uint8_t s) { return s != 0; }));
+    };
+    auto counts = [] (AudioEngine& engine) { return engine.stretchRenderCounts(); };
+
+    // --- the reporter's song: 3:53 at 48 kHz, auto-warped -----------------------------------------------------------------
+    double autoMs = 0.0;
+    int markerCount = 0;
+    const auto main = warped (long48, seconds, StretchMethod::general, 0, autoMs, markerCount);
+    say ("info: " + juce::String (seconds, 0) + " s at 48 kHz, auto-warp " + juce::String (markerCount) + " markers in " + ms (autoMs) + ", Time "
+         + juce::String (main.sampler.stretchBeats, 2) + " beats");
+    check ("auto-warp locks the long song bar by bar", markerCount >= 20, juce::String (markerCount) + " markers");
+
+    // A0. Auto-warp itself (the reporter's step 2; first, so nothing of this file is cached yet): the clip did not keep its
+    // pitch; the edit that sets its markers (the Audio editor's editWarp) returns at once, the first stretch renders off
+    // the message thread
+    {
+        auto plain = main;
+        plain.sampler.keepPitch = false;
+        plain.sampler.stretchBeats = 0.0f;
+        plain.sampler.warp.clear();
+        auto song = songOf (plain, false);
+        song.playlist[0].length = (std::int64_t) std::ceil (seconds * 122.0 / 60.0 * ppq);
+        auto live = start (song, true);
+        if (live.engine != nullptr)
+        {
+            auto& engine = *live.engine;
+            const auto t0 = now();
+            engine.editSong ([&main] (Song& s) { s.channels[0].sampler = main.sampler; });
+            const auto took = now() - t0;
+            auto longest = took;
+            const auto last = now();
+            auto settled = -1.0;
+            while (now() - last < 120000.0)
+            {
+                const auto c = now();
+                engine.timerCallback();
+                longest = juce::jmax (longest, now() - c);
+                if (engine.stretchesSettled())
+                {
+                    settled = now() - last;
+                    break;
+                }
+                juce::Thread::sleep (10);
+            }
+            check ("Auto-warp on the long song: the edit returns at once, no call on the message thread takes 50 ms", longest < 50.0,
+                   "the edit " + ms (took) + ", longest " + ms (longest) + "; its stretch played " + ms (settled) + " later");
+            if (settled >= 0.0)
+                finalRender (engine, "Auto-warp");
+        }
+        finish (live);
+    }
+
+    // A. before: one tempo step with the render in place (stretchdefer off = 0.1.32's build)
+    {
+        stretchdefer::setEnabled (false);
+        auto live = start (songOf (main, false), true);
+        if (live.engine != nullptr)
+        {
+            say ("info: the first build (the stretch at 122 BPM, made in place) took " + ms (live.firstBuildMs));
+            const auto t0 = now();
+            live.engine->editSong ([] (Song& s) { clipops::followTempo (s, 123.0); });
+            const auto took = now() - t0;
+            say ("info: before the fix one tempo step blocked the message thread " + ms (took) + " (a drag makes one per pixel)");
+            check ("before the fix (renders in place): a tempo step blocks the message thread (the freeze this round removes)", took >= 50.0, ms (took));
+        }
+        finish (live);
+        stretchdefer::setEnabled (true);
+    }
+
+    // B. stopped: 20 tempo changes in 1 s
+    {
+        auto live = start (songOf (main, false), true);
+        if (live.engine != nullptr)
+        {
+            auto& engine = *live.engine;
+            const auto b = burst (engine, 122.0, 0.4, true);
+            const auto n = counts (engine);
+            say ("info: stopped: " + juce::String (b.publishes) + " publishes, renders started " + juce::String (n.started) + ", cancelled "
+                 + juce::String (n.cancelled) + ", kept " + juce::String (n.kept) + "; the new stretch played " + ms (b.settleMs) + " after the last change");
+            check ("stopped, 20 tempo changes in 1 s: no call on the message thread takes 50 ms", b.longestMs < 50.0,
+                   "longest " + ms (b.longestMs) + ", longest tempo edit " + ms (b.longestEditMs));
+            check ("stopped: the debounce renders once for the whole drag (at most 2 started)", n.started >= 1 && n.started <= 2,
+                   juce::String (n.started) + " started");
+            check ("stopped: the stretch for the final tempo is built into the rack", b.settleMs >= 0.0, ms (b.settleMs));
+            finalRender (engine, "stopped");
+        }
+        finish (live);
+    }
+
+    // C. playing: the same, the clip sounding all along
+    {
+        auto live = start (songOf (main, false), true);
+        if (live.engine != nullptr)
+        {
+            auto& engine = *live.engine;
+            std::vector<float> out ((std::size_t) (deviceRate190un * 90.0), 0.0f);
+            TempoDevice::capture = &out;
+            TempoDevice::captured = 0;
+            engine.stop();
+            engine.rewind();
+            engine.timerCallback();
+            TempoDevice::recording = true;
+            engine.startPlayback();
+            auto pump = [&] (double forMs, double* longest) {
+                const auto t0 = now();
+                while (now() - t0 < forMs)
+                {
+                    const auto c = now();
+                    engine.timerCallback();
+                    if (longest != nullptr)
+                        *longest = juce::jmax (*longest, now() - c);
+                    juce::Thread::sleep (5);
+                }
+            };
+            double longest = 0.0;
+            pump (1000.0, &longest);
+            const auto burstAt = TempoDevice::captured.load();
+            const auto b = burst (engine, 122.0, -0.35, true);
+            const auto settledAt = TempoDevice::captured.load();
+            pump (1500.0, &longest);
+            TempoDevice::recording = false;
+            const auto end = TempoDevice::captured.load();
+            const auto n = counts (engine);
+            const auto beforeGap = longestSilenceMs (out, 4800, burstAt);
+            const auto duringGap = longestSilenceMs (out, burstAt, settledAt);
+            const auto afterGap = longestSilenceMs (out, settledAt, end);
+            say ("info: playing: renders started " + juce::String (n.started) + ", cancelled " + juce::String (n.cancelled) + "; settled "
+                 + ms (b.settleMs) + " after the last change; captured " + juce::String ((double) end / deviceRate190un, 2) + " s");
+            check ("playing, 20 tempo changes in 1 s: no call on the message thread takes 50 ms", juce::jmax (b.longestMs, longest) < 50.0,
+                   "longest " + ms (juce::jmax (b.longestMs, longest)) + ", longest tempo edit " + ms (b.longestEditMs));
+            check ("playing: the new stretch is swapped in", b.settleMs >= 0.0, ms (b.settleMs));
+            check ("playing: the clip sounds before the changes", end > burstAt && beforeGap < 30.0, "longest silence " + ms (beforeGap));
+            check ("playing: the clip keeps sounding during the changes (the kept stretch at the new tempo)", duringGap < 30.0, "longest silence " + ms (duringGap));
+            check ("playing: the clip keeps sounding after the new stretch is swapped in", afterGap < 30.0 && end - settledAt > (int) deviceRate190un,
+                   "longest silence " + ms (afterGap));
+            engine.stop();
+            engine.timerCallback();
+            finalRender (engine, "playing");
+        }
+        TempoDevice::capture = nullptr;
+        finish (live);
+    }
+
+    // C2. before the fix's resume (stretchdefer::setResumeEnabled (false)): the clip went silent once its channel was built
+    // from the new stretch while it played (the old instrument's voice went with it) — measured on a shorter file
+    {
+        double oAuto = 0.0;
+        int oMarkers = 0;
+        stretchdefer::setResumeEnabled (false);
+        auto live = start (songOf (warped (short48, shortSeconds, StretchMethod::general, 0, oAuto, oMarkers), false), true);
+        if (live.engine != nullptr)
+        {
+            auto& engine = *live.engine;
+            std::vector<float> out ((std::size_t) (deviceRate190un * 40.0), 0.0f);
+            TempoDevice::capture = &out;
+            TempoDevice::captured = 0;
+            engine.rewind();
+            TempoDevice::recording = true;
+            engine.startPlayback();
+            for (int i = 0; i < 100; ++i)
+            {
+                engine.timerCallback();
+                juce::Thread::sleep (5);
+            }
+            const auto b = burst (engine, 122.0, 0.3, true);
+            const auto settledAt = TempoDevice::captured.load();
+            const auto t0 = now();
+            while (now() - t0 < 1000.0)
+            {
+                engine.timerCallback();
+                juce::Thread::sleep (5);
+            }
+            TempoDevice::recording = false;
+            const auto gap = longestSilenceMs (out, settledAt, TempoDevice::captured.load());
+            say ("info: without the resume the clip was silent " + ms (gap) + " after its new stretch came in (" + ms (b.settleMs) + " after the changes)");
+            check ("before the fix's resume: the playing clip went silent when its channel was built from the new stretch", gap >= 500.0, ms (gap));
+            engine.stop();
+        }
+        TempoDevice::capture = nullptr;
+        finish (live);
+        stretchdefer::setResumeEnabled (true);
+    }
+
+    // D. tempo automation while playing: no rebuild at all (the tempo hook follows it in real time)
+    {
+        auto song = songOf (main, false);
+        Automation a;
+        a.name = "Tempo";
+        a.target = { AutomationTargetKind::tempo, 0 };
+        const auto bar = song.barTicks();
+        a.points = { { 0, valueFromTempo (122.0), 0.0f }, { 2 * bar, valueFromTempo (140.0), 0.0f }, { 4 * bar, valueFromTempo (110.0), 0.0f } };
+        song.automations.push_back (a);
+        Clip ac;
+        ac.kind = ClipKind::automation;
+        ac.automation = 0;
+        ac.track = 2;
+        ac.length = 4 * bar;
+        song.playlist.push_back (ac);
+        auto live = start (song, true);
+        if (live.engine != nullptr)
+        {
+            auto& engine = *live.engine;
+            engine.rewind();
+            engine.startPlayback();
+            const auto publishes = engine.getPublishCount();
+            double longest = 0.0;
+            const auto t0 = now();
+            while (now() - t0 < 2000.0)
+            {
+                const auto c = now();
+                engine.timerCallback();
+                longest = juce::jmax (longest, now() - c);
+                juce::Thread::sleep (5);
+            }
+            check ("tempo automation while playing: nothing is built again, the message thread never waits",
+                   engine.getPublishCount() == publishes && longest < 50.0, juce::String ((int) (engine.getPublishCount() - publishes)) + " publishes, longest " + ms (longest));
+            engine.stop();
+        }
+        finish (live);
+    }
+
+    // E. the other stretched clips on the same path (a shorter file: the path is the same, the render shorter)
+    struct Other
+    {
+        const char* name;
+        juce::File file;
+        StretchMethod method;
+        int markersMode;
+        bool grid;
+        bool renders;
+    };
+    for (const auto& o : { Other { "44.1 kHz file, auto-warped", long44, StretchMethod::general, 0, false, true },
+                           Other { "Beats mode, auto-warped", short48, StretchMethod::beats, 0, false, true },
+                           Other { "Stretch with Time set, no markers", short48, StretchMethod::general, 1, false, true },
+                           Other { "Resample with Time set (nothing renders)", short48, StretchMethod::general, 2, false, false },
+                           Other { "Clip-launch clip, auto-warped", short48, StretchMethod::general, 0, true, true } })
+    {
+        double oAuto = 0.0;
+        int oMarkers = 0;
+        const auto channel = warped (o.file, shortSeconds, o.method, o.markersMode, oAuto, oMarkers);
+        auto live = start (songOf (channel, o.grid), true);
+        if (live.engine == nullptr)
+            continue;
+        auto& engine = *live.engine;
+        std::vector<float> out;
+        int launchedAt = 0;
+        if (o.grid) // (launched and sounding through the whole burst, and after its new stretch is swapped in)
+        {
+            out.assign ((std::size_t) (deviceRate190un * 60.0), 0.0f);
+            TempoDevice::capture = &out;
+            TempoDevice::captured = 0;
+            engine.rewind();
+            TempoDevice::recording = true;
+            engine.startPlayback();
+            launcher::Command launch;
+            launch.type = launcher::Command::Type::launch;
+            engine.launcherCommand (launch);
+            for (int i = 0; i < 50; ++i)
+            {
+                engine.timerCallback();
+                juce::Thread::sleep (10);
+            }
+            launchedAt = TempoDevice::captured.load();
+        }
+        const auto b = burst (engine, 122.0, 0.5, true);
+        check (juce::String (o.name) + ": 20 tempo changes in 1 s, no call on the message thread takes 50 ms", b.longestMs < 50.0,
+               "longest " + ms (b.longestMs) + ", settled " + ms (b.settleMs));
+        if (o.grid)
+        {
+            const auto settledAt = TempoDevice::captured.load();
+            const auto t0 = now();
+            while (now() - t0 < 1500.0)
+            {
+                engine.timerCallback();
+                juce::Thread::sleep (5);
+            }
+            TempoDevice::recording = false;
+            const auto end = TempoDevice::captured.load();
+            int at = -1;
+            const auto during = longestSilenceMs (out, launchedAt, settledAt, &at), after = longestSilenceMs (out, settledAt, end);
+            check (juce::String (o.name) + ": the launched clip keeps sounding during the changes and after its new stretch is swapped in",
+                   launchedAt > 0 && during < 30.0 && after < 30.0 && end - settledAt > (int) deviceRate190un,
+                   "longest silence " + ms (during) + " / " + ms (after) + "; launched by frame " + juce::String (launchedAt) + ", silence from "
+                       + juce::String (at) + ", burst to " + juce::String (settledAt));
+            TempoDevice::capture = nullptr;
+        }
+        if (o.renders)
+            finalRender (engine, o.name);
+        else
+            check (juce::String (o.name) + ": no stretch render was asked for", counts (engine).requested == 0, juce::String (counts (engine).requested) + " requests");
+        engine.stop();
+        finish (live);
+    }
+
+    say ("checks: " + juce::String (checks) + ", failed: " + juce::String (errors.size()));
+    return errors.isEmpty() ? "OK " + juce::String (checks) + " checks" : "FAIL: " + errors.joinIntoString ("; ");
+}
+} // namespace lynx

+ 283 - 0
tests/StretchDefer190unTests.inc

@@ -0,0 +1,283 @@
+// Round 190un (issue #381): the live engine's deferred stretch renders (core/StretchDefer.h) — the queue's debounce and
+// cancel rules, the stretch's cancel hook (core/TimeStretch.h stretchdetail::CancelScope) and RackState::build keeping a
+// channel's instrument while its new stretch renders.
+
+namespace stretch190un
+{
+using namespace lynx;
+
+inline stretchdefer::Render renderOf (int value, int* calls = nullptr)
+{
+    return [value, calls] (const std::atomic<bool>&) -> stretchdefer::Result {
+        if (calls != nullptr)
+            ++*calls;
+        return std::make_shared<int> (value);
+    };
+}
+
+inline std::shared_ptr<SampleData> tone (int frames, double rate = 48000.0)
+{
+    auto d = std::make_shared<SampleData>();
+    d->sampleRate = rate;
+    d->left.resize ((std::size_t) frames);
+    d->right.resize ((std::size_t) frames);
+    for (int i = 0; i < frames; ++i)
+        d->left[(std::size_t) i] = d->right[(std::size_t) i]
+            = (float) (0.3 * std::sin (2.0 * 3.141592653589793 * 220.0 * i / rate) + (i % 12000 < 400 ? 0.5 * std::exp (-(i % 12000) / 60.0) : 0.0));
+    return d;
+}
+} // namespace stretch190un
+
+// a drag asks for a render at every step: only where it stops, once nothing new came for the debounce time, is rendered
+TEST (stretch190un_queue_debounces_a_drag)
+{
+    using namespace lynx;
+    using Q = stretchdefer::Queue;
+    Q q (150.0);
+    for (int k = 0; k < 20; ++k) // 20 steps, 50 ms apart
+        CHECK (q.request (7, "bpm" + std::to_string (122 + k), stretch190un::renderOf (k), 50.0 * k) == Q::Answer::deferred);
+    CHECK (q.waitingCount() == 1);
+    double due = 0.0;
+    CHECK (! q.next (950.0 + 149.0, &due).has_value()); // (the last step at 950 ms: due at 1100)
+    CHECK (due > 0.0 && due <= 1.0 + 1.0e-9);
+    const auto job = q.next (1100.0);
+    CHECK (job.has_value() && job->key == "bpm141" && job->channel == 7);
+    CHECK (q.counts().started == 1 && q.isRunning());
+    CHECK (! q.next (5000.0).has_value()); // (one render at a time)
+    // the same request again (another edit's build while it renders): nothing new waits, it stays deferred
+    CHECK (q.request (7, "bpm141", stretch190un::renderOf (0), 1200.0) == Q::Answer::deferred);
+    CHECK (q.waitingCount() == 0);
+    CHECK (q.finished (*job, job->render (*job->cancelled)));
+    CHECK (q.idle() && q.hasResults());
+    // the build that follows finds it ready; the publish lets it go
+    const auto serial = q.beginPublish();
+    CHECK (q.request (7, "bpm141", stretch190un::renderOf (0), 1300.0) == Q::Answer::ready);
+    q.endPublish (serial);
+    CHECK (! q.hasResults());
+    CHECK (q.counts().readyHits == 1 && q.counts().kept == 1 && q.counts().cancelled == 0);
+}
+
+// a newer request for the channel cancels the render that runs for other settings; its result is thrown away
+TEST (stretch190un_queue_cancels_a_superseded_render)
+{
+    using namespace lynx;
+    using Q = stretchdefer::Queue;
+    Q q (100.0);
+    q.request (1, "a", stretch190un::renderOf (1), 0.0);
+    const auto first = q.next (100.0);
+    CHECK (first.has_value() && first->key == "a" && ! first->cancelled->load());
+    CHECK (q.request (1, "b", stretch190un::renderOf (2), 150.0) == Q::Answer::deferred);
+    CHECK (first->cancelled->load()); // (superseded: the stretch loops stop early)
+    CHECK (! q.finished (*first, std::make_shared<int> (1))); // (not kept)
+    CHECK (! q.hasResults() && q.counts().cancelled == 1);
+    CHECK (! q.next (200.0).has_value()); // (b waits for its own debounce: 150 + 100)
+    const auto second = q.next (250.0);
+    CHECK (second.has_value() && second->key == "b");
+    CHECK (q.finished (*second, std::make_shared<int> (2)));
+    // a stale result of the channel goes when the channel asks for something else
+    CHECK (q.request (1, "c", stretch190un::renderOf (3), 400.0) == Q::Answer::deferred);
+    CHECK (! q.hasResults());
+    // asking back for a key that is ready, after another channel's requests: still ready
+    const auto third = q.next (500.0);
+    CHECK (third.has_value() && q.finished (*third, std::make_shared<int> (3)));
+    CHECK (q.request (2, "x", stretch190un::renderOf (4), 510.0) == Q::Answer::deferred);
+    CHECK (q.request (1, "c", stretch190un::renderOf (3), 520.0) == Q::Answer::ready);
+    // a cancelled or failed render (nullptr) is never kept
+    const auto fourth = q.next (700.0);
+    CHECK (fourth.has_value() && fourth->channel == 2);
+    CHECK (! q.finished (*fourth, nullptr));
+    // clear: the running render cancelled, everything waiting and every result dropped
+    q.request (3, "y", stretch190un::renderOf (5), 800.0);
+    const auto fifth = q.next (900.0);
+    CHECK (fifth.has_value());
+    q.request (4, "z", stretch190un::renderOf (6), 950.0);
+    q.clear();
+    CHECK (fifth->cancelled->load() && q.waitingCount() == 0 && ! q.hasResults());
+}
+
+// results that finish while a build runs stay for the next one; those before it go after it
+TEST (stretch190un_queue_keeps_results_across_publishes)
+{
+    using namespace lynx;
+    using Q = stretchdefer::Queue;
+    Q q (0.0);
+    q.request (1, "a", stretch190un::renderOf (1), 0.0);
+    q.request (2, "b", stretch190un::renderOf (2), 0.0);
+    auto a = q.next (1.0);
+    CHECK (a.has_value() && q.finished (*a, std::make_shared<int> (1)));
+    const auto publish = q.beginPublish();
+    auto b = q.next (2.0); // (finishes during the publish)
+    CHECK (b.has_value() && q.finished (*b, std::make_shared<int> (2)));
+    q.endPublish (publish);
+    CHECK (q.request (1, "a", stretch190un::renderOf (1), 3.0) == Q::Answer::deferred); // (a went: asked again, rendered again)
+    CHECK (q.request (2, "b", stretch190un::renderOf (2), 3.0) == Q::Answer::ready);   // (b stays for the next build)
+}
+
+// the stretch's cancel hook: a flag raised before the render gives nothing; a flag that stays down changes nothing
+TEST (stretch190un_cancel_scope)
+{
+    using namespace lynx;
+    const auto in = stretch190un::tone (48000 * 2);
+    const StretchMap map { { 0.0, 0.0 }, { 48000.0, 52000.0 }, { 96000.0, 110000.0 } };
+    const auto plain = timeStretchMapped (*in, map);
+    CHECK (plain != nullptr && plain->frames() == 110000);
+    {
+        std::atomic<bool> flag { false };
+        const stretchdetail::CancelScope scope (&flag);
+        const auto same = timeStretchMapped (*in, map);
+        CHECK (same != nullptr && same->left == plain->left && same->right == plain->right);
+        CHECK (! stretchdetail::cancelled());
+        flag = true;
+        CHECK (stretchdetail::cancelled());
+        CHECK (timeStretchMapped (*in, map) == nullptr);
+        CHECK (timeStretch (*in, 1.3) == nullptr);
+    }
+    CHECK (! stretchdetail::cancelled()); // (the scope ended)
+}
+
+// RackState::build: a keep-pitch channel whose tempo changed keeps its instrument while deferStretch says its render
+// is not ready (marked stale, the speed that fits the new length), and is built anew once it is; exports (no hook) and
+// changes beyond the stretch build at once, as before
+TEST (stretch190un_build_keeps_the_instrument_while_the_stretch_renders)
+{
+    using namespace lynx;
+    const auto data = stretch190un::tone (48000 * 3);
+    Song song;
+    song.bpm = 120.0;
+    song.mixer = Song::defaultMixer (1);
+    ChannelDef ch;
+    ch.instrument = InstrumentKind::audioClip;
+    ch.samplePath = "/stretch190un/tone.wav";
+    ch.mixerTrack = 1;
+    ch.sampler.keepPitch = true;
+    ch.sampler.stretchBeats = 6.0f; // (3 s at 120 BPM)
+    ch.sampler.warp = { { 0.0, 0.0 }, { 1.0, 2.2 }, { 3.0, 6.0 } };
+    song.channels.push_back (ch);
+    int renders = 0, asked = 0;
+    bool ready = false;
+    RackState::Factories f;
+    f.samples = [data] (const std::string&) { return std::shared_ptr<const SampleData> (data); };
+    f.stretchedSamples = [&renders, data] (const std::string&, double ratio, StretchMethod method, double semitones, const StretchMap& map,
+                                           const StretchOptions& options) -> std::shared_ptr<const SampleData> {
+        ++renders;
+        return map.empty() ? timeStretch (*data, ratio, method, semitones, options) : timeStretchMapped (*data, map, method, semitones, options);
+    };
+    f.deferStretch = [&asked, &ready] (const ChannelDef&, double) {
+        ++asked;
+        return ! ready;
+    };
+    const auto first = RackState::build (song, nullptr, 48000.0, f);
+    CHECK (renders == 1 && asked == 0 && ! first->stale (0));
+    // the tempo moves: kept, stale, no render here
+    auto faster = song;
+    clipops::followTempo (faster, 130.0);
+    const auto second = RackState::build (faster, first.get(), 48000.0, f);
+    CHECK (renders == 1 && asked == 1);
+    CHECK (second->instruments[0] == first->instruments[0] && second->stale (0));
+    CHECK (second->staleSpeed.size() == 1 && std::abs (second->staleSpeed[0] - 130.0 / 120.0) < 1.0e-9);
+    // again (the drag goes on): still kept, the speed from the length it was rendered for (120 BPM's)
+    auto fasterStill = faster;
+    clipops::followTempo (fasterStill, 140.0);
+    const auto third = RackState::build (fasterStill, second.get(), 48000.0, f);
+    CHECK (renders == 1 && third->instruments[0] == first->instruments[0] && third->stale (0));
+    CHECK (std::abs (third->staleSpeed[0] - 140.0 / 120.0) < 1.0e-9 && std::abs (third->playedStretchSeconds[0] - 3.0) < 1.0e-9);
+    // an unrelated edit while it renders: still kept (the same tempo, but its stretch is the old one)
+    auto renamed = fasterStill;
+    renamed.channels[0].name = "renamed";
+    const auto fourth = RackState::build (renamed, third.get(), 48000.0, f);
+    CHECK (renders == 1 && fourth->instruments[0] == first->instruments[0] && fourth->stale (0));
+    // the render is ready: built anew from it, not stale
+    ready = true;
+    const auto fifth = RackState::build (renamed, fourth.get(), 48000.0, f);
+    CHECK (renders == 2 && fifth->instruments[0] != first->instruments[0] && ! fifth->stale (0));
+    // and the next edit keeps that one without asking
+    const auto askedBefore = asked;
+    const auto sixth = RackState::build (renamed, fifth.get(), 48000.0, f);
+    CHECK (sixth->instruments[0] == fifth->instruments[0] && asked == askedBefore && renders == 2);
+    // without the hook (an export): built anew at once
+    ready = false;
+    auto slower = renamed;
+    clipops::followTempo (slower, 100.0);
+    auto noHook = f;
+    noHook.deferStretch = nullptr;
+    const auto exported = RackState::build (slower, sixth.get(), 48000.0, noHook);
+    CHECK (renders == 3 && exported->instruments[0] != sixth->instruments[0] && ! exported->stale (0));
+    // a change beyond the stretch (another file) never waits
+    auto other = renamed;
+    other.channels[0].samplePath = "/stretch190un/other.wav";
+    const auto otherFile = RackState::build (other, sixth.get(), 48000.0, f);
+    CHECK (otherFile->instruments[0] != sixth->instruments[0] && ! otherFile->stale (0) && renders == 4);
+    // Auto-warp on a clip that did not keep its pitch (its file at its own speed, 3 s): kept while its first stretch renders,
+    // at the speed that fits the file's 3 s into the length it has now
+    {
+        auto plain = song;
+        plain.channels[0].sampler.keepPitch = false;
+        plain.channels[0].sampler.stretchBeats = 0.0f;
+        plain.channels[0].sampler.warp.clear();
+        ready = false;
+        const auto p1 = RackState::build (plain, nullptr, 48000.0, f);
+        auto warpedSong = plain;
+        warpedSong.channels[0].sampler = song.channels[0].sampler; // (keep pitch, 6 beats = 3 s at 120 BPM)
+        warpedSong.channels[0].sampler.stretchBeats = 8.0f;        // (4 s at 120 BPM)
+        const auto rendersBefore = renders;
+        const auto p2 = RackState::build (warpedSong, p1.get(), 48000.0, f);
+        CHECK (p2->instruments[0] == p1->instruments[0] && p2->stale (0) && renders == rendersBefore);
+        CHECK (p2->staleSpeed.size() == 1 && std::abs (p2->staleSpeed[0] - 3.0 / 4.0) < 1.0e-6);
+        ready = true;
+        const auto p3 = RackState::build (warpedSong, p2.get(), 48000.0, f);
+        CHECK (p3->instruments[0] != p1->instruments[0] && ! p3->stale (0) && renders == rendersBefore + 1);
+        CHECK (p3->restretched.size() == 1 && p3->restretched[0] == 1); // (its clips in progress start again in the new one)
+    }
+    // a channel that resamples (no keep pitch) never asks: the tempo only changes its speed
+    auto resample = song;
+    resample.channels[0].sampler.keepPitch = false;
+    resample.channels[0].sampler.warp.clear();
+    const auto r1 = RackState::build (resample, nullptr, 48000.0, f);
+    auto resampleFaster = resample;
+    clipops::followTempo (resampleFaster, 150.0);
+    const auto askedNow = asked;
+    const auto r2 = RackState::build (resampleFaster, r1.get(), 48000.0, f);
+    CHECK (r2->instruments[0] == r1->instruments[0] && asked == askedNow && ! r2->stale (0));
+}
+
+// the key of a render follows everything the stretch depends on, and nothing else
+TEST (stretch190un_request_key)
+{
+    using namespace lynx;
+    ChannelDef c;
+    c.instrument = InstrumentKind::audioClip;
+    c.samplePath = "/a.wav";
+    c.sampler.keepPitch = true;
+    c.sampler.stretchBeats = 8.0f;
+    c.sampler.warp = { { 0.0, 0.0 }, { 4.0, 8.0 } };
+    const auto base = stretchRequestKey (c, 120.0);
+    CHECK (stretchRequestKey (c, 120.0) == base);
+    CHECK (stretchRequestKey (c, 120.5) != base);
+    auto d = c;
+    d.name = "other name";
+    d.volume = 0.3f;
+    CHECK (stretchRequestKey (d, 120.0) == base);
+    d = c;
+    d.sampler.warp[1].beats = 8.5;
+    CHECK (stretchRequestKey (d, 120.0) != base);
+    d = c;
+    d.sampler.stretchMethod = StretchMethod::beats;
+    CHECK (stretchRequestKey (d, 120.0) != base);
+    d = c;
+    d.sampler.warpModes.tonesGrain = 50.0f;
+    CHECK (stretchRequestKey (d, 120.0) != base);
+    d = c;
+    d.sampler.precompute.normalize = true;
+    CHECK (stretchRequestKey (d, 120.0) != base);
+    CHECK (stretchDeferrable (c, c));
+    d = c;
+    d.sampler.keepPitch = false;
+    CHECK (! stretchDeferrable (c, d)); // (keep pitch turned off: nothing to render, built at once)
+    CHECK (stretchDeferrable (d, c));   // (turned on — Auto-warp: its first stretch may render while the clip plays on)
+    d.sampler.keepPitch = true;
+    d.sampler.stretchBeats = 0.0f;
+    CHECK (! stretchDeferrable (d, c)); // (kept its pitch with no Time: not this path)
+    d = c;
+    d.samplePath = "/b.wav";
+    CHECK (! stretchDeferrable (c, d));
+}

+ 2 - 0
tests/tests.cpp

@@ -24,6 +24,7 @@
 
 
 #include "core/FlTrackMenus.h" // round 190dx
 #include "core/FlTrackMenus.h" // round 190dx
 #include "core/OneClickRec.h"
 #include "core/OneClickRec.h"
+#include "core/StretchDefer.h" // round 190un
 #include "core/TakeRecording.h"
 #include "core/TakeRecording.h"
 
 
 #if defined(__SSE__) || defined(_M_X64) || defined(__x86_64__) || defined(__aarch64__) || defined(_M_ARM64) // x86 SSE, or ARM64 through core/Simd.h (sse2neon)
 #if defined(__SSE__) || defined(_M_X64) || defined(__x86_64__) || defined(__aarch64__) || defined(_M_ARM64) // x86 SSE, or ARM64 through core/Simd.h (sse2neon)
@@ -18262,6 +18263,7 @@ TEST (fl_low_lifter_matches_fl_engine)
 #include "MixFx190toTests.inc" // round 190to (0.1.33, QUEUE item 96): FL's per-insert effects switch; the Master's arm tap
 #include "MixFx190toTests.inc" // round 190to (0.1.33, QUEUE item 96): FL's per-insert effects switch; the Master's arm tap
 #include "InsRec190ubTests.inc" // round 190ub (0.1.33, issue #371): armed inserts record their routed audio without an input device
 #include "InsRec190ubTests.inc" // round 190ub (0.1.33, issue #371): armed inserts record their routed audio without an input device
 #include "Pitch190udTests.inc" // round 190ud (0.1.33, issue #375): the channel's PITCH reaches sounding audio clips and shifted voices
 #include "Pitch190udTests.inc" // round 190ud (0.1.33, issue #375): the channel's PITCH reaches sounding audio clips and shifted voices
+#include "StretchDefer190unTests.inc" // round 190un (0.1.33, issue #381): tempo changes never render a warped clip's stretch on the message thread
 #include "Tempo190tvTests.inc" // round 190tv (0.1.33, QUEUE item 99 / issue #364): FL's tempo digits, the number wheel, History rows
 #include "Tempo190tvTests.inc" // round 190tv (0.1.33, QUEUE item 99 / issue #364): FL's tempo digits, the number wheel, History rows
 #include "UxTracks190tpTests.inc" // round 190tp (issues #365 / #366): the header drag that moves a track, Ctrl+V of copied files
 #include "UxTracks190tpTests.inc" // round 190tp (issues #365 / #366): the header drag that moves a track, Ctrl+V of copied files
 #include "OsKeys190ukTests.inc" // round 190uk (issue #378): the keys each system keeps, the key map per platform
 #include "OsKeys190ukTests.inc" // round 190uk (issue #378): the keys each system keeps, the key map per platform

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików