Q-W3: main.cpp → pointers+entry+dispatch via 4 capture hoists; one pure wav_codec RIFF owner; ICaptureBackend deleted; capture_realtime rename + finalize split; shared stampCaptureSample; makeUniqueTag gains monotonic counter (fixes same-second batch collisions). 60/60 green.

This commit is contained in:
2026-07-29 10:56:11 -04:00
parent d7d7f7e084
commit 09f7173db2
29 changed files with 2972 additions and 2426 deletions
+90 -59
View File
@@ -1,5 +1,5 @@
#include "core/namespaces.h"
// capture.cpp — REAPER-facing offline-render backend (OfflineRenderBackend).
// capture.cpp — REAPER-facing offline-render backend (OfflineRenderBackend) plus
// the shared backend helpers (makeUniqueTag / stampCaptureSample — Q-W3 riders).
//
// Compiled into the reaper_reasampler MODULE. Includes
// reaper_plugin_functions.h WITHOUT REAPERAPI_IMPLEMENT — main.cpp is the one TU
@@ -36,6 +36,7 @@
#include "shell/capture/capture.h"
#include <atomic>
#include <cstdint>
#include <ctime>
#include <filesystem>
@@ -44,6 +45,7 @@
#include <vector>
#include "core/capture/capture_paths.h"
#include "core/capture/wav_codec.h" // hashWavContent — the one WAV/RIFF owner
#include "core/util/file_bytes.h"
#include "core/capture/render_settings.h"
@@ -58,7 +60,7 @@
#define REAPERAPI_WANT_TimeMap_GetTimeSigAtTime
#include "reaper_plugin_functions.h"
namespace reasampler {
namespace reasampler::capture {
namespace {
@@ -219,21 +221,84 @@ struct ScopedRenderSettings {
ScopedRenderSettings& operator=(const ScopedRenderSettings&) = delete;
};
// A monotonic, filesystem-safe timestamp tag so repeated captures in one session
// do not collide on the file name. NOTE: the tag varies the file NAME, not the
// audio bytes — bit-identical-repeat is about identical *content* for identical
// requests; two deliberate captures naturally live in two files.
std::string makeUniqueTag() {
std::time_t now = std::time(nullptr);
return std::to_string(static_cast<long long>(now));
}
// Whole-file reads go through the shared core/util readFileBytes (Q-W1, T2-03):
// empty on any I/O failure (the caller then leaves contentHash empty — the safe,
// confirm-eliciting direction for an unreadable file).
} // namespace
// --- Shared backend helpers (Q-W3 riders — see capture.h) --------------------
std::string makeUniqueTag(const std::string& prefix) {
// Timestamp + PER-SESSION MONOTONIC counter (T1-11 fix). The timestamp alone
// had one-second resolution: two captures of the same baseName within the same
// wall-clock second derived the same file stem, so the second render silently
// overwrote the first file and minted two Samples with colliding ids —
// reachable in practice via batch capture. The counter (shared across both
// backends — this is the one definition both call) makes every tag of a
// session distinct regardless of timing. NOTE: the tag varies the file NAME,
// not the audio bytes — bit-identical-repeat is about identical *content* for
// identical requests; two deliberate captures naturally live in two files.
static std::atomic<unsigned long long> counter{0};
const std::time_t now = std::time(nullptr);
return prefix + std::to_string(static_cast<long long>(now)) + "-" +
std::to_string(++counter);
}
void stampCaptureSample(Sample& s, const CaptureRequest& req,
ReaProject* rateProj, ReaProject* timeSigProj,
const std::string& absolutePath) {
// Track GUIDs + channel count: echoed from the request (the caller resolved
// the selection; the backends stay source-agnostic).
s.trackGuids = req.trackGuids;
s.channelCount = req.channelCount;
// Resolved sample rate: the request's pinned rate, else PROJECT_SRATE read
// from the caller's project handle. PROJECT_SRATE can read 0 on a project that
// never explicitly pinned a rate — the value stays 0 (the Sample zero-value)
// rather than a bogus literal (the honest "unknown" both backends shared).
s.sampleRate = (req.sampleRate > 0)
? req.sampleRate
: static_cast<int>(GetSetProjectInfo(rateProj, "PROJECT_SRATE", 0.0, false));
s.captureTempo = Master_GetTempo(); // BPM at capture time (verified ~4651)
// Time signature at the capture's START time (L7 F1 stamp). TimeMap_GetTimeSigAtTime
// (verified reaper_plugin_functions.h:7130 — void(ReaProject*, double time,
// int* numOut, int* denomOut, double* tempoOut)) reads the meter effective at
// that project time, so a sample captured under 3/4 keeps a 3/4 read-out even
// if the project later switches to 4/4. `timeSigProj` is the CALLER's project
// pin — offline passes nullptr (the active project); realtime pins the record's
// own project (the T2-09 divergence, kept caller-visible as this argument).
// tempoOut is ignored — captureTempo already carries the master tempo. Leaves
// 0/0 (unstamped) if the API is somehow unavailable; the formatter renders a
// blank musical read-out.
{
int tsNum = 0, tsDenom = 0;
double tsTempo = 0.0;
TimeMap_GetTimeSigAtTime(timeSigProj, req.startSeconds, &tsNum, &tsDenom, &tsTempo);
s.captureTimeSigNum = tsNum;
s.captureTimeSigDenom = tsDenom;
}
// Content hash: WAV-aware FNV-1a over the finished file's fmt+data chunks so
// hashReferencedElsewhere can identify copies in other banks and suppress the
// last-reference confirm when another bank still holds the same file. Using
// hashWavContent (not the raw hashBytes) skips render-varying metadata chunks
// (bext origination timestamp, iXML, LIST/INFO, etc.) so two renders/records of
// identical audio collapse to the same hash. Best-effort: an unreadable file
// leaves contentHash empty — the safe, confirm-eliciting direction (bank_model
// treats "" as non-participating in dedup).
{
const std::vector<std::uint8_t> fileBytes = util::readFileBytes(absolutePath);
if (!fileBytes.empty()) {
s.contentHash = hashWavContent(fileBytes);
}
}
s.createdTimestamp = static_cast<std::int64_t>(std::time(nullptr));
}
CaptureResult OfflineRenderBackend::capture(const CaptureRequest& request) {
CaptureResult result;
@@ -340,9 +405,9 @@ CaptureResult OfflineRenderBackend::capture(const CaptureRequest& request) {
}();
// Compute the unique tag ONCE so the file stem and Sample.id carry the same
// timestamp. Calling makeUniqueTag() twice could yield different values if a
// second boundary crosses between the two calls (bug: id and filename diverge).
const std::string uniqueTag = makeUniqueTag();
// tag. Calling makeUniqueTag() twice would yield different values (the counter
// advances per callbug: id and filename diverge).
const std::string uniqueTag = makeUniqueTag("");
const BankPaths paths =
deriveBankPaths(projectDir, request.baseName, uniqueTag);
@@ -477,50 +542,16 @@ CaptureResult OfflineRenderBackend::capture(const CaptureRequest& request) {
// Seconds are the authoritative source for the render. Do NOT add DAW-
// unverifiable PPQ resolution here — it requires a live REAPER to validate.
s.wetDry = request.wetDry;
// Track GUIDs for track-scoped captures (empty for master/items/razor). The
// caller resolved the selection to canonical GUID strings; we record them so a
// "re-capture from source" (M10) knows which tracks the sample came from.
s.trackGuids = request.trackGuids;
s.channelCount = request.channelCount;
// Store the resolved sample rate only when it is known (> 0). If the project
// never pinned a rate (PROJECT_SRATE read 0), we did not force RENDER_SRATE
// either, so the render ran at REAPER's project default — an unknown value from
// this code's perspective. Leave sampleRate at 0 (the Sample zero-value) rather
// than store a bogus literal; M6/M7 can fill it in by probing the rendered file.
s.sampleRate = effectiveSampleRate; // 0 when project rate was unknown
s.lengthSeconds = request.endSeconds - request.startSeconds;
s.captureTempo = Master_GetTempo(); // BPM at capture time (verified ~4651)
// Time signature at the capture's START time (L7 F1 stamp). TimeMap_GetTimeSigAtTime
// (verified reaper_plugin_functions.h:7130 — void(ReaProject*, double time,
// int* numOut, int* denomOut, double* tempoOut)) reads the meter effective at that
// project time, so a sample captured under 3/4 keeps a 3/4 read-out even if the
// project later switches to 4/4. proj=nullptr => the active project (matches the
// Master_GetTempo() call above, which is also active-project). The tempoOut is
// ignored — captureTempo already carries the master tempo. Leaves 0/0 (unstamped)
// if the API is somehow unavailable; the formatter renders a blank musical read-out.
{
int tsNum = 0, tsDenom = 0;
double tsTempo = 0.0;
TimeMap_GetTimeSigAtTime(nullptr, request.startSeconds, &tsNum, &tsDenom, &tsTempo);
s.captureTimeSigNum = tsNum;
s.captureTimeSigDenom = tsDenom;
}
s.tier = Tier::Scratch; // captures land in scratch by default
// Content hash: WAV-aware FNV-1a over the rendered file's fmt+data chunks so
// hashReferencedElsewhere can identify copies in other banks and suppress the
// last-reference confirm when another bank still holds the same file. Using
// hashWavContent (not the raw hashBytes) skips render-varying metadata chunks
// (bext origination timestamp, iXML, LIST/INFO, etc.) so two renders of identical
// audio collapse to the same hash. Best-effort: an unreadable file leaves
// contentHash empty — the safe, confirm-eliciting direction (bank_model treats
// "" as non-participating in dedup, which is the existing fallback semantics).
{
const std::vector<std::uint8_t> fileBytes = readFileBytes(expectedPath);
if (!fileBytes.empty()) {
s.contentHash = hashWavContent(fileBytes);
}
}
s.createdTimestamp = static_cast<std::int64_t>(std::time(nullptr));
s.tier = model::Tier::Scratch; // captures land in scratch by default
// The SHARED finished-capture stamp (T2-09 dedupe): trackGuids + channelCount
// (request echo), resolved sampleRate (request rate else PROJECT_SRATE(proj) —
// 0 stays 0 when the project never pinned a rate; we did not force RENDER_SRATE
// either, so the render ran at REAPER's default), captureTempo, the capture-
// start time signature (timeSigProj = nullptr => the active project matching
// the Master_GetTempo read, which is also active-project), the WAV-aware
// contentHash of the rendered file, and createdTimestamp.
stampCaptureSample(s, request, proj, /*timeSigProj=*/nullptr, expectedPath);
// Phase S seam fields (rootNote / loop) left empty (D-B). An offline render of a
// master mix / track / time-selection is not a single played note, so no root
// note is derivable here — we do NOT guess one. Loop points are set later by an
@@ -537,4 +568,4 @@ CaptureResult OfflineRenderBackend::capture(const CaptureRequest& request) {
// guard's dtor restores every RENDER_* setting here.
}
} // namespace reasampler
} // namespace reasampler::capture
+70 -41
View File
@@ -1,19 +1,23 @@
#pragma once
#include "core/namespaces.h"
// capture — the REAPER-facing capture shell (CLAUDE.md §load-bearing split).
//
// This header declares the capture *seam* the later milestones fill:
// * CaptureRequest — everything a capture needs, source-mode-agnostic.
// * ICaptureBackend — the SYNCHRONOUS interface OfflineRenderBackend implements
// (headless, immediate, returns a finished Sample).
// * OfflineRenderBackend — the deterministic default; drives the offline scopes.
// * OfflineRenderBackend — the deterministic default; a plain CONCRETE class
// (the former ICaptureBackend interface was deleted in
// Q-W3, T4-26 — it had one deriver and zero polymorphic
// call sites; every construction site instantiates the
// concrete type).
// * RealtimeRecordBackend — the ASYNC realtime seam (begin/tick/abort), driven
// across timer ticks; deliberately NOT an ICaptureBackend
// across timer ticks; a genuinely different lifecycle
// (see the SEAM CHOICE note at its declaration).
// * makeUniqueTag / stampCaptureSample — the shared file-tag mint and the shared
// finished-capture metadata stamp both backends call
// (Q-W3 riders T1-11 / T2-09).
//
// It includes bank_model (pure) to hand back a populated Sample, but NO REAPER
// headers — the .cpp is the REAPER-facing translation unit. Keeping this header
// REAPER-free lets callers (main.cpp, future actions.cpp) depend on the seam
// REAPER-free lets callers (the capture orchestration TUs) depend on the seam
// without dragging the SDK into every include site.
#include <memory>
@@ -23,13 +27,17 @@
#include "core/model/bank_model.h"
#include "core/capture/render_settings.h" // TailMode (pure) — the three-state tail contract
// MediaTrack is forward-declared (like track_guid.h) so this header stays
// REAPER-free while RealtimeRecordBackend::begin can take the resolved source
// MediaTrack* to tap. The pointers are opaque here — never dereferenced in a
// pure/header context; only the REAPER-facing capture_realtime.cpp touches them.
// MediaTrack / ReaProject are forward-declared (like track_guid.h) so this header
// stays REAPER-free while RealtimeRecordBackend::begin can take the resolved source
// MediaTrack* to tap and stampCaptureSample can take the project handles its reads
// pin. The pointers are opaque here — never dereferenced in a pure/header context;
// only the REAPER-facing capture TUs touch them.
class MediaTrack;
class ReaProject;
namespace reasampler {
namespace reasampler::capture {
using model::Sample;
// Audio bit-depth for the rendered wav. 32-bit float is the M3 default —
// rationale lives in capture.cpp next to the sink-config bytes.
@@ -106,27 +114,48 @@ struct CaptureResult {
std::string message; // human-readable detail for the console log
};
// The capture seam. One method: run a request, return a populated Sample (or a
// failure code). Backends are non-destructive — they must restore any global
// state they touch before returning (OfflineRenderBackend snapshots/restores the
// RENDER_* project settings).
class ICaptureBackend {
public:
virtual ~ICaptureBackend() = default;
virtual CaptureResult capture(const CaptureRequest& request) = 0;
};
// Deterministic offline-render backend. Drives the full offline source family —
// master mix / time selection, selected tracks, selected items, razor area — all
// wet-only (render_settings.h) with optional tail. The source selection + range
// are resolved by the caller (the action layer) and handed in via the
// CaptureRequest; the backend drives RENDER_* and never reads the DAW selection
// itself. SourceMode::Realtime returns UnsupportedMode (that is the M8 backend).
class OfflineRenderBackend : public ICaptureBackend {
// Non-destructive: restores every RENDER_* setting it touches on every path.
// A plain concrete class — the former ICaptureBackend interface was deleted
// (Q-W3, T4-26): it had one deriver, zero polymorphic call sites, and the async
// realtime backend deliberately never implemented it (see SEAM CHOICE below).
class OfflineRenderBackend {
public:
CaptureResult capture(const CaptureRequest& request) override;
CaptureResult capture(const CaptureRequest& request);
};
// --- Shared backend helpers (Q-W3 riders) ------------------------------------
// Mints the filesystem-safe disambiguating tag for one capture's file stem +
// Sample id: "<prefix><unix-epoch-seconds>-<n>" where <n> is a PER-SESSION
// MONOTONIC counter (T1-11 fix). The wall-clock second alone had a collision
// window: two captures of the same baseName within one second derived the same
// stem, so the second render silently overwrote the first file (reachable via
// batch capture driving short renders back-to-back). The counter makes every tag
// of a session distinct regardless of timing. `prefix` is the backend's family
// marker ("" offline, "rt-" realtime).
std::string makeUniqueTag(const std::string& prefix);
// Stamps the SHARED finished-capture metadata onto `s` (T2-09 dedupe — this stamp
// was copy-pasted per backend and had silently diverged): trackGuids +
// channelCount (echoed from the request), the resolved sampleRate (request rate,
// else PROJECT_SRATE read from `rateProj`; 0 stays 0 when unknown), captureTempo
// (Master_GetTempo), the capture-start time signature (TimeMap_GetTimeSigAtTime
// against `timeSigProj` — the offline path passes nullptr = active project, the
// realtime path pins the record's own project; the divergence stays caller-visible
// as this argument), the WAV-aware contentHash of the finished file at
// `absolutePath` (left empty when unreadable — the safe, confirm-eliciting
// direction), and createdTimestamp (now). The per-backend bits (id, paths, bounds,
// tier, realtime's recorded-length override) stay with each caller.
void stampCaptureSample(Sample& s, const CaptureRequest& req,
ReaProject* rateProj, ReaProject* timeSigProj,
const std::string& absolutePath);
// --- Realtime-record backend: the ASYNC seam ---------------------------------
//
// A realtime record is inherently asynchronous: CSurf_OnRecord starts the transport
@@ -137,16 +166,17 @@ public:
// from the same OnTimer that runs session.poll()) advances the in-flight record and
// reports when it is done.
//
// SEAM CHOICE (surfaced): RealtimeRecordBackend deliberately does NOT implement the
// synchronous ICaptureBackend — that interface returns a finished Sample from one
// call, which no longer fits a record that spans ticks. The two backends have
// genuinely different lifecycles (offline is headless + immediate; realtime is
// transport-driven + async), so forcing a shared async interface would make offline
// fake a lifecycle it does not have (its tick() would always be Done on the first
// call — dead code / an LSP smell). Offline stays synchronous and unchanged; the
// realtime backend owns this small bespoke async seam, driven by exactly one caller
// (main.cpp's OnTimer). This is the split-sync/async fork, chosen over a unified
// async interface for that reason.
// SEAM CHOICE (surfaced): the two backends deliberately share NO interface. The
// lifecycles are genuinely different (offline is headless + immediate — one
// synchronous capture() call returns a finished Sample; realtime is
// transport-driven + async — begin/tick/abort across timer ticks), so a shared
// interface would make offline fake a lifecycle it does not have (its tick()
// would always be Done on the first call — dead code / an LSP smell). Offline
// stays synchronous; the realtime backend owns this small bespoke async seam,
// driven by exactly one caller (the timer-driven realtime_lifecycle). This is the
// split-sync/async fork, chosen over a unified async interface for that reason.
// (The old synchronous ICaptureBackend interface over OfflineRenderBackend was
// deleted in Q-W3 — T4-26: one deriver, zero polymorphic call sites.)
// One tick's verdict from the in-flight record.
enum class RealtimeTickStatus {
@@ -163,9 +193,8 @@ struct RealtimeTickResult {
// The opaque in-flight capture state. Owns the snapshot of everything to restore
// (temp track + its receive sends from the source tracks, other tracks' I_RECARM,
// transport, edit cursor, time selection) and the record's own project handle.
// Defined in
// capture_realtime.cpp; the header stays REAPER-free (no MediaTrack*/ReaProject*
// leaks here) by holding it behind a forward-declared type + unique_ptr.
// Defined in capture_realtime_shell.cpp; the header stays REAPER-free (nothing is
// dereferenced here) by holding it behind a forward-declared type + unique_ptr.
//
// restore()/teardown is idempotent and lives ON THIS OBJECT (not a function-scope
// RAII guard) because the record spans ticks — no single stack frame outlives it.
@@ -173,10 +202,10 @@ struct RealtimeTickResult {
// funnels through the same single restore, safe to call once from whichever fires.
class RealtimeCaptureState;
// Out-of-line deleter so callers (main.cpp) can own a unique_ptr to the opaque
// RealtimeCaptureState WITHOUT its full (REAPER-typed) definition — the delete is
// compiled in capture_realtime.cpp where the type is complete, keeping this header
// REAPER-free (load-bearing split).
// Out-of-line deleter so callers (realtime_lifecycle) can own a unique_ptr to the
// opaque RealtimeCaptureState WITHOUT its full (REAPER-typed) definition — the
// delete is compiled in capture_realtime_shell.cpp where the type is complete,
// keeping this header REAPER-free (load-bearing split).
struct RealtimeCaptureStateDeleter {
void operator()(RealtimeCaptureState* p) const noexcept;
};
@@ -232,4 +261,4 @@ public:
RealtimeTickResult abort(RealtimeCaptureState& state);
};
} // namespace reasampler
} // namespace reasampler::capture
+523
View File
@@ -0,0 +1,523 @@
// capture_batch.cpp — the M11 batch-capture family + the M10 re-capture-from-source
// action (Q-W3 hoist out of main.cpp; the code moved verbatim, the session threaded
// as a parameter). See the header.
//
// Compiled into the reaper_reasampler MODULE. Includes reaper_plugin_functions.h
// WITHOUT REAPERAPI_IMPLEMENT — main.cpp is the one TU that defines the API
// pointers; here they are extern (CLAUDE.md §contract).
#include "shell/capture/capture_batch.h"
#include <cstddef>
#include <optional>
#include <string>
#include <utility>
#include <vector>
#include "bank_panel.h" // bankPanelSelectedSampleIds / Refresh
#include "core/capture/batch_capture.h" // planCaptureUnits / BatchOutcome
#include "core/model/bank_book.h" // BankBook / Bank
#include "core/model/provenance.h" // recipe parse/build, fingerprint
#include "persist.h" // ReaSamplerSession
#include "shell/capture/capture_orchestrator.h" // captureAndIndexOne / renderOffline
#include "shell/capture/provenance_shell.h" // fxChainIdentity* / trackByGuid
#include "shell/capture/scope_resolve.h" // ResolvedSource
#include "shell/capture/track_guid.h" // guidString
#include "reaper_plugin.h" // UNDO_STATE_MISCCFG
#define REAPERAPI_MINIMAL
#define REAPERAPI_WANT_CountSelectedMediaItems
#define REAPERAPI_WANT_GetSelectedMediaItem
#define REAPERAPI_WANT_GetMediaItem_Track
#define REAPERAPI_WANT_GetMediaItemInfo_Value
#define REAPERAPI_WANT_CountMediaItems
#define REAPERAPI_WANT_GetMediaItem
#define REAPERAPI_WANT_SetMediaItemSelected
#define REAPERAPI_WANT_UpdateArrange
#define REAPERAPI_WANT_CountTracks
#define REAPERAPI_WANT_GetTrack
#define REAPERAPI_WANT_GetSetMediaTrackInfo_String
#define REAPERAPI_WANT_CountSelectedTracks
#define REAPERAPI_WANT_GetSelectedTrack
#define REAPERAPI_WANT_SetTrackSelected
#define REAPERAPI_WANT_SetOnlyTrackSelected
#define REAPERAPI_WANT_ShowConsoleMsg
#define REAPERAPI_WANT_Undo_BeginBlock2
#define REAPERAPI_WANT_Undo_EndBlock2
#include "reaper_plugin_functions.h"
namespace reasampler::capture {
// --- M11: batch capture (per selected item / per razor area) ----------------
//
// One action fires N captures — one bank sample per selected item (item scope) or per
// razor area (track scope, each area's own range). Each individual capture honors every
// precision invariant via captureAndIndexOne (exact bounds, non-destructive FX/fader/pan
// neutralize, relative paths, channel preservation) and M10 provenance stamping applies
// per capture where its detection rule matches. The load-bearing principle holds: each
// unit writes a file + a bank index entry ONLY; nothing lands in the arrange.
//
// Per-unit FILE NAMING: each unit's baseName carries its ordinal ("item-1",
// "item-2", ...) so two units are never asked to write the same stem within one
// batch, and the shared makeUniqueTag now appends a per-session monotonic counter
// (T1-11 fix) so even same-second units across batches cannot collide.
namespace {
// RAII snapshot/restore of the project's media-item selection. Batch item capture must
// transiently select exactly one item per render (RENDER_SETTINGS &32 renders whatever is
// selected); the user's ORIGINAL selection must be restored on EVERY exit path — including
// a mid-batch failure or early return — because selection restoration is part of the
// non-destructive invariant. Snapshot on construct (the currently-selected item set),
// restore on destruct (deselect everything, then re-select exactly the snapshot).
class ItemSelectionGuard
{
public:
ItemSelectionGuard()
{
const int n = CountSelectedMediaItems(nullptr);
for (int i = 0; i < n; ++i)
if (MediaItem* it = GetSelectedMediaItem(nullptr, i))
selected_.push_back(it);
}
~ItemSelectionGuard()
{
// Deselect every item in the project, then re-select the snapshot — restoring the
// exact original set regardless of what the batch selected in between. Iterate ALL
// items (not just the currently-selected) so any transient selection is cleared.
const int total = CountMediaItems(nullptr);
for (int i = 0; i < total; ++i)
if (MediaItem* it = GetMediaItem(nullptr, i))
SetMediaItemSelected(it, false);
for (MediaItem* it : selected_)
SetMediaItemSelected(it, true);
UpdateArrange(); // reflect the restored selection in the arrange view
}
ItemSelectionGuard(const ItemSelectionGuard&) = delete;
ItemSelectionGuard& operator=(const ItemSelectionGuard&) = delete;
private:
std::vector<MediaItem*> selected_;
};
// Selects exactly `item` (deselect-all then select-one) so the offline render's
// selected-items bit (&32) captures a single item. Used inside the batch loop under the
// ItemSelectionGuard, which restores the user's original selection afterward.
void selectOnlyItem(MediaItem* item)
{
const int total = CountMediaItems(nullptr);
for (int i = 0; i < total; ++i)
if (MediaItem* it = GetMediaItem(nullptr, i))
SetMediaItemSelected(it, it == item);
}
// Collects every track's razor AUDIO areas as (owning track, range) pairs, preserving
// track order then area order — the batch analog of resolveRazorRange, which unions them.
// Read-only (never clears the razor selection). Reuses the pure parseRazorEdits parser.
std::vector<std::pair<MediaTrack*, RazorRange>> collectRazorAreas()
{
std::vector<std::pair<MediaTrack*, RazorRange>> areas;
const int n = CountTracks(nullptr);
for (int i = 0; i < n; ++i)
{
MediaTrack* tr = GetTrack(nullptr, i);
if (!tr) continue;
std::vector<char> buf(8192, '\0');
if (!GetSetMediaTrackInfo_String(tr, "P_RAZOREDITS", buf.data(), false))
continue;
for (const RazorRange& r : parseRazorEdits(std::string(buf.data())))
areas.push_back({tr, r});
}
return areas;
}
// RAII snapshot/restore of the project's TRACK selection. Batch razor capture must
// transiently select exactly the area's owning track per render (track scope's &128 bit
// renders whatever TRACKS are selected); the user's original track selection is restored
// on EVERY exit path (part of the non-destructive invariant). Mirror of ItemSelectionGuard.
class TrackSelectionGuard
{
public:
TrackSelectionGuard()
{
const int n = CountSelectedTracks(nullptr);
for (int i = 0; i < n; ++i)
if (MediaTrack* tr = GetSelectedTrack(nullptr, i))
selected_.push_back(tr);
}
~TrackSelectionGuard()
{
// Deselect every track, then re-select the snapshot — the exact original set.
const int total = CountTracks(nullptr);
for (int i = 0; i < total; ++i)
if (MediaTrack* tr = GetTrack(nullptr, i))
SetTrackSelected(tr, false);
for (MediaTrack* tr : selected_)
SetTrackSelected(tr, true);
}
TrackSelectionGuard(const TrackSelectionGuard&) = delete;
TrackSelectionGuard& operator=(const TrackSelectionGuard&) = delete;
private:
std::vector<MediaTrack*> selected_;
};
} // namespace
// Batch item capture: one bank sample per SELECTED item, item scope. Snapshots the
// selection (RAII restore on every path), then for each selected item transiently selects
// only it, renders its exact [pos, pos+len] range under item-scope FX neutralize, adds the
// Sample, and records a per-unit verdict. Persists ONCE at the end (one ext-state write for
// the whole batch). Reports a mixed-result summary (explicit-action response — allowed).
void RunBatchCaptureItems(ReaSamplerSession& session)
{
// Read the selected items up front (pointers stay valid — batch mutates only selection
// flags, never adds/removes items). Also capture each item's exact bounds and owning
// track NOW, while the full selection is live, before any transient re-selection.
struct ItemUnit { MediaItem* item; MediaTrack* track; double start; double end; };
std::vector<ItemUnit> itemUnits;
{
const int n = CountSelectedMediaItems(nullptr);
for (int i = 0; i < n; ++i)
{
MediaItem* it = GetSelectedMediaItem(nullptr, i);
if (!it) continue;
MediaTrack* tr = GetMediaItem_Track(it);
if (!tr) continue;
const double pos = GetMediaItemInfo_Value(it, "D_POSITION");
const double len = GetMediaItemInfo_Value(it, "D_LENGTH");
itemUnits.push_back({it, tr, pos, pos + len});
}
}
if (itemUnits.empty())
{
ShowConsoleMsg("ReaSampler batch capture: select at least one media item.\n");
return;
}
// Plan the exact source ranges -> validated, ordinal-assigned units (pure). Empty/
// inverted item ranges (a zero-length item) are dropped here so no stray render runs.
std::vector<BatchRange> ranges;
ranges.reserve(itemUnits.size());
for (const ItemUnit& u : itemUnits)
ranges.push_back({u.start, u.end});
const std::vector<CaptureUnit> plan = planCaptureUnits(ranges);
BatchOutcome outcome;
bool anyAdded = false;
{
// Restore the user's ORIGINAL item selection on every exit path (incl. early
// return / mid-batch failure) — non-destructive invariant.
ItemSelectionGuard selGuard;
// The plan and itemUnits are parallel over the KEPT units. Walk itemUnits, but only
// for those whose range survived planning (same drop rule), matching by ordinal.
std::size_t planIdx = 0;
for (const ItemUnit& u : itemUnits)
{
if (!(u.end > u.start)) continue; // dropped by planCaptureUnits — skip in lockstep
const CaptureUnit& unit = plan[planIdx++];
// Transiently select ONLY this item so the item-scope render captures exactly it.
selectOnlyItem(u.item);
ResolvedSource src;
src.startSeconds = unit.startSeconds;
src.endSeconds = unit.endSeconds;
src.sourceTracks.push_back(u.track);
if (std::string g = guidString(u.track); !g.empty())
src.trackGuids.push_back(std::move(g));
const std::string baseName = "item-" + std::to_string(unit.ordinal);
CaptureResult res = captureAndIndexOne(
session, CaptureScope::Item, src, baseName,
unit.startSeconds, unit.endSeconds);
const bool ok = (res.status == CaptureStatus::Ok);
outcome.record(unit.ordinal, ok, ok ? std::string{} : res.message);
if (ok) anyAdded = true;
}
} // selGuard restores the original selection here, on every path
// Persist ONCE for the whole batch (one ext-state write) — only if something landed.
// S9: one bump for the whole batch (coalesced) — the counter is monotonic, not per-sample,
// so a single increment past the last-seen value is enough to trigger one instance reload.
if (anyAdded) {
session.bumpBankGeneration();
session.saveToActiveProject();
}
ShowConsoleMsg((outcome.summaryLine("item") + "\n").c_str());
}
// Batch razor capture: one bank sample per razor AREA, track scope over that area's own
// range (the area's owning track is the source track). Track scope renders the selected
// TRACKS via master (&128), so each unit transiently selects ONLY its owning track
// (SetOnlyTrackSelected) under the TrackSelectionGuard, which restores the user's original
// track selection on every path. The razor selection itself is read-only and left intact.
// Persists ONCE at the end. Reports a mixed-result summary.
void RunBatchCaptureRazor(ReaSamplerSession& session)
{
const std::vector<std::pair<MediaTrack*, RazorRange>> areas = collectRazorAreas();
if (areas.empty())
{
ShowConsoleMsg("ReaSampler batch capture: make at least one razor area first.\n");
return;
}
std::vector<BatchRange> ranges;
ranges.reserve(areas.size());
for (const auto& a : areas)
ranges.push_back({a.second.startSeconds, a.second.endSeconds});
const std::vector<CaptureUnit> plan = planCaptureUnits(ranges);
BatchOutcome outcome;
bool anyAdded = false;
{
// Restore the user's ORIGINAL track selection on every exit path.
TrackSelectionGuard selGuard;
std::size_t planIdx = 0;
for (const auto& a : areas)
{
if (!(a.second.endSeconds > a.second.startSeconds)) continue; // dropped — lockstep
const CaptureUnit& unit = plan[planIdx++];
MediaTrack* tr = a.first;
// Transiently select ONLY this track so the track-scope render (&128) captures
// exactly it via master (over the custom time bounds we set per unit).
SetOnlyTrackSelected(tr);
ResolvedSource src;
src.startSeconds = unit.startSeconds;
src.endSeconds = unit.endSeconds;
src.sourceTracks.push_back(tr);
if (std::string g = guidString(tr); !g.empty())
src.trackGuids.push_back(std::move(g));
const std::string baseName = "razor-" + std::to_string(unit.ordinal);
CaptureResult res = captureAndIndexOne(
session, CaptureScope::Track, src, baseName,
unit.startSeconds, unit.endSeconds);
const bool ok = (res.status == CaptureStatus::Ok);
outcome.record(unit.ordinal, ok, ok ? std::string{} : res.message);
if (ok) anyAdded = true;
}
} // selGuard restores the original track selection here, on every path
// S9: one coalesced bump for the whole razor batch (see the item-batch note above).
if (anyAdded) {
session.bumpBankGeneration();
session.saveToActiveProject();
}
ShowConsoleMsg((outcome.summaryLine("razor area") + "\n").c_str());
}
// --- M10: re-capture from source --------------------------------------------
//
// Regenerates a PROVENANCED bank sample's file from its recorded source's CURRENT
// state, then updates the bank Sample IN PLACE. BANK-ONLY — it renders a file and
// refreshes the index entry; it NEVER calls InsertMedia / touches the timeline (the
// load-bearing capture-never-places line, structurally visible: this function has no
// insert path at all). Non-destructive to the source (FxBypassGuard snapshot/restore
// via renderOffline). Fork P2=a: refresh the bank entry only; the user re-places
// manually if they want the new version on the timeline.
//
// Failure modes are handled explicitly and reported to the user (a direct response
// to an explicit action is allowed by the console policy):
// * the selected sample has no provenance (not a resample) -> reported, no-op.
// * the recorded fingerprint is unparseable (legacy/corrupt) -> reported, no-op.
// * the recorded source track(s) no longer exist -> reported, no-op.
// * the render itself fails to satisfy the recorded request -> reported, no-op.
// On success, if the source FX chain drifted since capture (recorded vs current
// identity differ) the user is told — the re-capture still reflects the source AS IT
// IS NOW (P1=a: the fingerprint detects drift, it does not freeze the source).
void RunRecaptureFromSource(ReaSamplerSession& session)
{
const std::vector<std::string> selected = bankPanelSelectedSampleIds();
if (selected.empty())
{
ShowConsoleMsg("ReaSampler re-capture: select a sample in the bank panel first.\n");
return;
}
if (selected.size() > 1)
{
ShowConsoleMsg("ReaSampler re-capture: select a single sample to re-capture.\n");
return;
}
const std::string sampleId = selected.front();
// Resolve the sample from the bank it lives in (the focused region's displayed bank).
const std::string srcBankId = bankPanelSelectedSourceBankId();
const Bank* bank = session.book().bank(srcBankId);
const model::Sample* orig = bank ? bank->index.query(sampleId) : nullptr;
if (!orig)
{
ShowConsoleMsg("ReaSampler re-capture: the selected sample is no longer in the bank.\n");
return;
}
if (!orig->provenance)
{
ShowConsoleMsg("ReaSampler re-capture: this sample has no provenance "
"(it was not resampled from a bank sample).\n");
return;
}
// Parse the recorded capture recipe from the fingerprint. A legacy / corrupt
// string fails gracefully — never a partial re-capture.
const std::string recordedParentId = orig->provenance->parentSampleId;
const std::string recordedFingerprint = orig->provenance->fxChainSnapshot;
const std::optional<model::CaptureRecipe> recipe =
model::parseFingerprint(recordedFingerprint);
if (!recipe)
{
ShowConsoleMsg("ReaSampler re-capture: this sample's provenance is unreadable "
"(recorded by an older/incompatible build); cannot re-capture.\n");
return;
}
// Resolve the recorded source track GUID(s) to live tracks. Any missing track is a
// hard failure — we will not silently re-capture a different source.
std::vector<MediaTrack*> sourceTracks;
for (const std::string& g : recipe->trackGuids)
{
MediaTrack* tr = trackByGuid(g);
if (!tr)
{
ShowConsoleMsg("ReaSampler re-capture: a recorded source track no longer "
"exists in this project; cannot re-capture from source.\n");
return;
}
sourceTracks.push_back(tr);
}
if (sourceTracks.empty())
{
// The recipe recorded no source tracks (e.g. an item-scope capture whose source
// tracks were not track-scoped). Without a resolvable source we cannot re-run.
ShowConsoleMsg("ReaSampler re-capture: no resolvable recorded source for this "
"sample; cannot re-capture from source.\n");
return;
}
const CaptureScope scope =
recipe->scope == model::ProvenanceScope::Item ? CaptureScope::Item
: CaptureScope::Track;
// Rebuild the capture request verbatim from the recorded recipe — the SAME request,
// re-run against the source's CURRENT state (P1=a). Exact bounds, tail, rate,
// channels, bit depth all match the original so an unchanged source produces a
// byte-identical file (bit-identical-repeats invariant, consumed as a feature).
CaptureRequest req;
req.sourceMode = static_cast<SourceMode>(recipe->sourceMode);
req.startSeconds = recipe->startSeconds;
req.endSeconds = recipe->endSeconds;
req.wetDry = 1.0;
req.tailMode = static_cast<TailMode>(recipe->tailMode);
req.tailMs = recipe->tailMs;
req.sampleRate = recipe->sampleRate;
req.channelCount = recipe->channelCount;
req.bitDepth = WavBitDepth::Float32;
req.baseName = orig->displayName.empty() ? "recapture" : orig->displayName;
req.trackGuids = recipe->trackGuids;
// Read the CURRENT source FX-chain identity BEFORE the render bypasses it, to
// compare against the recorded identity for drift reporting. Mirror the same
// scope split as buildCaptureProvenance: item scope reads take FX via TakeFX_*;
// track scope reads the track FX chain via TrackFX_*.
std::string currentIdentity;
if (scope == CaptureScope::Item) {
const int n = CountSelectedMediaItems(nullptr);
std::vector<MediaItem*> items;
items.reserve(static_cast<std::size_t>(n < 0 ? 0 : n));
for (int i = 0; i < n; ++i) {
MediaItem* it = GetSelectedMediaItem(nullptr, i);
if (it) items.push_back(it);
}
currentIdentity = fxChainIdentityForItems(items);
} else {
std::vector<std::string> perTrackNow;
perTrackNow.reserve(sourceTracks.size());
for (MediaTrack* tr : sourceTracks)
perTrackNow.push_back(fxChainIdentityForTrack(tr));
currentIdentity = model::combineChainIdentities(perTrackNow);
}
const bool drifted = (currentIdentity != recipe->fxChainIdentity);
// Render (bank-only; renderOffline never touches the timeline).
CaptureResult res = renderOffline(scope, sourceTracks, req);
if (res.status != CaptureStatus::Ok)
{
ShowConsoleMsg(("ReaSampler re-capture failed: " + res.message + "\n").c_str());
return;
}
// Update the Sample IN PLACE: keep its identity (id) and its provenance thread
// (same parent + a REFRESHED fingerprint reflecting the source as re-captured), but
// adopt the regenerated file's path / hash / length / rate / timestamp. The
// fingerprint is rebuilt from the recipe with the CURRENT FX identity so a
// subsequent re-capture measures drift from this point, not the original.
model::CaptureRecipe refreshed = *recipe;
refreshed.fxChainIdentity = currentIdentity;
model::Sample updated = *orig; // copy: preserves id, displayName, tier, key
updated.relativePath = res.sample.relativePath;
updated.contentHash = res.sample.contentHash;
updated.sourceMode = res.sample.sourceMode;
updated.sourceRange = res.sample.sourceRange;
updated.channelCount = res.sample.channelCount;
updated.sampleRate = res.sample.sampleRate;
updated.lengthSeconds = res.sample.lengthSeconds;
updated.captureTempo = res.sample.captureTempo;
updated.captureTimeSigNum = res.sample.captureTimeSigNum; // L7 F1: refresh meter stamp
updated.captureTimeSigDenom = res.sample.captureTimeSigDenom; // to the re-capture's meter
updated.trackGuids = res.sample.trackGuids;
updated.createdTimestamp = res.sample.createdTimestamp;
// NOTE: levels, clipped, and lengthBeats are carried from the original (via the
// *orig copy above) because the offline backend does not populate them today
// (res.sample leaves them at defaults). If a later milestone populates these
// fields at capture time, refresh them here from res.sample instead.
model::Provenance prov;
prov.parentSampleId = recordedParentId;
prov.fxChainSnapshot = model::buildFingerprint(refreshed);
updated.provenance = prov;
// Single batched undo point around the in-place bank mutation (mirrors the bank
// action family's R-B pattern). The mutation is index-only ext-state; the render
// wrote a new file but placed nothing on the timeline.
Undo_BeginBlock2(nullptr);
const bool changed = session.book().updateSampleInPlace(sampleId, updated);
if (changed)
{
// Record the regenerated file in the owned manifest (a new file the tool wrote);
// the superseded old file becomes an orphan reclaimed by Phase R prune.
session.owned().add(updated.relativePath);
// S9: re-capture-in-place regenerates the SAME id's audio — the exact case the
// hands-free refresh exists for (an instance referencing this id keeps playing the
// OLD audio until it reloads). Bump inside the undo block so undo rolls back the
// generation with the rest of the blob.
session.bumpBankGeneration();
const bool persisted = session.saveToActiveProject(); // book + manifest + generation + MarkProjectDirty
Undo_EndBlock2(nullptr, persisted ? "ReaSampler: re-capture from source" : "",
persisted ? UNDO_STATE_MISCCFG : 0);
}
else
{
Undo_EndBlock2(nullptr, "", 0); // nothing mutated -> discard the empty point
}
bankPanelRefresh(); // reflect the regenerated file in the docked grid
if (drifted)
ShowConsoleMsg("ReaSampler re-capture: the source FX chain changed since the "
"original capture -- the sample was regenerated from the source's "
"current state.\n");
}
} // namespace reasampler::capture
+32
View File
@@ -0,0 +1,32 @@
#pragma once
// capture_batch — the batch-capture family + re-capture-from-source (Q-W3 hoist
// out of main.cpp; the fourth hoist, T4-02 — recapture is planner-driven like
// batch and shares the RAII selection-guard machinery, so it belongs here, not
// with the single-shot path). Owns:
// * RunBatchCaptureItems — one bank sample per SELECTED item (item scope), the
// user's item selection snapshot/restored on every path (ItemSelectionGuard);
// * RunBatchCaptureRazor — one bank sample per razor AREA (track scope over the
// area's own range), the user's track selection snapshot/restored on every
// path (TrackSelectionGuard);
// * RunRecaptureFromSource — regenerate a PROVENANCED bank sample from its
// recorded source's CURRENT state, updating the Sample in place. BANK-ONLY.
//
// Every unit honors every precision invariant via capture_orchestrator's
// captureAndIndexOne / renderOffline (exact bounds, non-destructive neutralize,
// relative paths); nothing here ever touches the arrange/timeline (load-bearing
// principle). Persist is batched: ONE ext-state write per action.
//
// REAPER-facing: the .cpp includes reaper_plugin_functions.h WITHOUT
// REAPERAPI_IMPLEMENT (main.cpp owns the API pointers — CLAUDE.md §contract).
namespace reasampler {
class ReaSamplerSession;
}
namespace reasampler::capture {
void RunBatchCaptureItems(ReaSamplerSession& session);
void RunBatchCaptureRazor(ReaSamplerSession& session);
void RunRecaptureFromSource(ReaSamplerSession& session);
} // namespace reasampler::capture
+487
View File
@@ -0,0 +1,487 @@
// capture_orchestrator.cpp — the single-capture orchestration + realtime/insert
// action bodies (Q-W3 hoist out of main.cpp; the code moved verbatim, the session
// threaded as a parameter). See the header. FxBypassGuard lives here as a STACK
// RAII object (precision-invariant-critical — it must restore on every exit path
// of exactly one render call).
//
// Compiled into the reaper_reasampler MODULE. Includes reaper_plugin_functions.h
// WITHOUT REAPERAPI_IMPLEMENT — main.cpp is the one TU that defines the API
// pointers; here they are extern (CLAUDE.md §contract).
#include "shell/capture/capture_orchestrator.h"
#include <optional>
#include <vector>
#include "bank_panel.h" // bankPanelTailSetting / bankPanelRefresh
#include "core/capture/tail_control.h" // TailSetting
#include "core/model/provenance.h" // model::Provenance
#include "ingest.h" // ingestAssignActiveInstance
#include "persist.h" // ReaSamplerSession
#include "shell/capture/insert.h" // runInsert / InsertRequest
#include "shell/capture/realtime_lifecycle.h" // the in-flight realtime state
#include "reaper_plugin.h" // UNDO_STATE_MISCCFG
#define REAPERAPI_MINIMAL
#define REAPERAPI_WANT_EnumProjects
#define REAPERAPI_WANT_GetParentTrack
#define REAPERAPI_WANT_GetMasterTrack
#define REAPERAPI_WANT_GetMediaTrackInfo_Value
#define REAPERAPI_WANT_SetMediaTrackInfo_Value
#define REAPERAPI_WANT_ShowConsoleMsg
#define REAPERAPI_WANT_Undo_BeginBlock2
#define REAPERAPI_WANT_Undo_EndBlock2
#include "reaper_plugin_functions.h"
namespace reasampler::capture {
namespace {
// --- FX-bypass + full parent-chain neutralize around render (RAII, non-destr.) --
// For every track a scope must NOT hear the FX of, this ALSO neutralizes that
// track's fader gain AND its full pan chain (pan/width/law/mode) for the render —
// because a Track/Item capture renders via master and would otherwise sum through
// the parent/folder/master FADERS and PAN/WIDTH/LAW, printing their gain and pan
// coloring into the file (Daniel: the capture is likely re-routed through that
// same chain later, so parent/master level and pan must not be baked in). The
// neutralize set is IDENTICAL to the FX-bypass set:
// Item -> own track + all ancestors + master (take vol/pan kept: item content).
// Track -> all ancestors + master (selected track's OWN vol/pan kept).
// (Master is a bypass TARGET for both scopes — never a scope of its own.)
//
// Per track in that set we snapshot & set the full parent-chain-independence set,
// so a Track/Item capture is uncolored by the parent/folder/master it renders
// through — no FX, no fader, and no pan/width/law/mode coloring:
// I_FXEN -> 0 (FX bypassed; SDK ~2194)
// D_VOL -> 1.0 (unity trim volume; SDK ~2226 "1=+0dB")
// D_PAN -> 0.0 (center; SDK ~2227 "trim pan of track, -1..1")
// D_WIDTH -> 1.0 (full/neutral stereo width; SDK ~2228 "width, -1..1",
// 1.0 = full width = no narrowing/collapse)
// D_PANLAW -> 1.0 (no coloring; SDK ~2232 "1=+0dB" — pan-law applies no gain)
// I_PANMODE -> 5 (stereo pan; SDK ~2231 "0=classic,3=balance,5=stereo,6=dual")
// All are restored to their ORIGINAL values on EVERY exit path (RAII).
//
// Why also force I_PANMODE (pan mode). D_PAN's effect is mode-dependent. In modes
// 0/3/5, D_PAN=0 + D_WIDTH=1 is a provable pass-through. But in mode 6 (dual pan)
// D_PAN/D_WIDTH are ignored — routing is governed instead by D_DUALPANL/D_DUALPANR
// (SDK ~2229-2230, live only when I_PANMODE==6), whose neutral pass-through the
// header does not state as such. Rather than snapshot two more mode-conditional
// params and infer their neutral values, we force I_PANMODE=5 (stereo pan) for the
// render, where D_PAN=0 + D_WIDTH=1 is unambiguously uncolored, then restore the
// original mode. This fully neutralizes pan for every original mode with no
// residual — the "handle it fully" the brief requires. (See Snap dual-pan note.)
//
// Structurally non-destructive: no takes, no items, no project restructuring —
// only transient FX-enable + trim-volume toggles, always restored.
class FxBypassGuard
{
public:
// scope drives fxBypassPlanFor; sourceTracks are the captured tracks whose
// ancestor chains (walked via GetParentTrack) + the master are bypassed per the
// plan. proj is the active project (for GetMasterTrack).
FxBypassGuard(CaptureScope scope,
const std::vector<MediaTrack*>& sourceTracks,
ReaProject* proj)
{
const FxBypassPlan plan = fxBypassPlanFor(scope);
for (MediaTrack* tr : sourceTracks)
{
if (!tr) continue;
if (plan.bypassSelfFx) bypass(tr);
if (plan.bypassAncestorFx)
{
// Walk parents to the top: GetParentTrack returns the immediate
// parent (folder) track, nullptr at the outermost level (SDK
// header ~2407). The master is NOT returned here — handled below.
for (MediaTrack* p = GetParentTrack(tr); p; p = GetParentTrack(p))
bypass(p);
}
}
if (plan.bypassMaster)
{
// GetMasterTrack(proj) -> the master track (SDK header ~1925). bypass()
// neutralizes its FX (I_FXEN), gain (D_VOL) AND pan/width/law/mode on it
// just like any other in-scope track; only the master's summing/routing
// topology (the mix bus itself) remains — that is not a per-track param.
if (MediaTrack* master = GetMasterTrack(proj)) bypass(master);
}
}
~FxBypassGuard()
{
// Restore in reverse for symmetry (order is not load-bearing — each track
// appears once, snapshots are independent). EVERY snapshotted param is
// restored to its ORIGINAL value on this (every) exit path. Restore
// I_PANMODE before the pan values so any mode-conditional params (e.g. dual
// pan) settle under the original mode.
for (auto it = snapshots_.rbegin(); it != snapshots_.rend(); ++it)
{
SetMediaTrackInfo_Value(it->track, "I_FXEN", it->fxen);
SetMediaTrackInfo_Value(it->track, "D_VOL", it->vol);
SetMediaTrackInfo_Value(it->track, "I_PANMODE", it->panmode);
SetMediaTrackInfo_Value(it->track, "D_PAN", it->pan);
SetMediaTrackInfo_Value(it->track, "D_WIDTH", it->width);
SetMediaTrackInfo_Value(it->track, "D_PANLAW", it->panlaw);
}
}
FxBypassGuard(const FxBypassGuard&) = delete;
FxBypassGuard& operator=(const FxBypassGuard&) = delete;
private:
// One snapshot per bypassed track: all params we neutralize, at their originals.
// panmode captures I_PANMODE so we can force stereo-pan for the render and put
// the original mode back — which also makes D_DUALPANL/D_DUALPANR (live only when
// I_PANMODE==6, SDK ~2229-2230) irrelevant during the render without us having to
// touch or guess neutral values for them.
struct Snap
{
MediaTrack* track;
double fxen;
double vol;
double pan;
double width;
double panlaw;
double panmode;
};
std::vector<Snap> snapshots_;
// Snapshot every neutralized param once per track (dedup: an ancestor shared by
// two selected tracks must be restored to its ORIGINAL values, not to a
// re-snapshot of the already-neutralized state), then read ALL originals, push
// one Snap, and set all to neutral — bypass FX, unity gain, uncolored pan chain.
void bypass(MediaTrack* tr)
{
for (const Snap& s : snapshots_) if (s.track == tr) return; // already done
// Read ALL originals first (atomic snapshot), then push, then neutralize.
const double fxen = GetMediaTrackInfo_Value(tr, "I_FXEN");
const double vol = GetMediaTrackInfo_Value(tr, "D_VOL");
const double pan = GetMediaTrackInfo_Value(tr, "D_PAN");
const double width = GetMediaTrackInfo_Value(tr, "D_WIDTH");
const double panlaw = GetMediaTrackInfo_Value(tr, "D_PANLAW");
const double panmode = GetMediaTrackInfo_Value(tr, "I_PANMODE");
snapshots_.push_back({tr, fxen, vol, pan, width, panlaw, panmode});
SetMediaTrackInfo_Value(tr, "I_FXEN", 0.0); // 0 = bypassed (SDK ~2194)
SetMediaTrackInfo_Value(tr, "D_VOL", 1.0); // 1.0 = unity gain (SDK ~2226)
SetMediaTrackInfo_Value(tr, "I_PANMODE", 5.0); // 5 = stereo pan (SDK ~2231)
SetMediaTrackInfo_Value(tr, "D_PAN", 0.0); // 0.0 = center (SDK ~2227)
SetMediaTrackInfo_Value(tr, "D_WIDTH", 1.0); // 1.0 = full width (SDK ~2228)
SetMediaTrackInfo_Value(tr, "D_PANLAW", 1.0); // 1.0 = +0dB, no law (SDK ~2232)
}
};
} // namespace
// Renders one CaptureRequest through the offline backend under the scope's
// FX-bypass guard, returning the backend's CaptureResult. Shared by RunCapture and
// RunRecaptureFromSource so the FX-scope neutralize + render recipe lives in ONE
// place: the out-of-scope FX / fader / pan chain is snapshotted, neutralized for the
// render, and fully restored on every path (RAII). Non-destructive; touches no
// timeline item (load-bearing principle) — it writes a file only.
CaptureResult renderOffline(CaptureScope scope,
const std::vector<MediaTrack*>& sourceTracks,
const CaptureRequest& req)
{
ReaProject* proj = EnumProjects(-1, nullptr, 0);
FxBypassGuard fxGuard(scope, sourceTracks, proj);
OfflineRenderBackend backend;
return backend.capture(req);
}
// Renders ONE capture request under the scope's FX-bypass guard, stamps provenance,
// and adds the resulting Sample to the ACTIVE bank + records the created file in the
// owned-file manifest — WITHOUT persisting. The caller persists once (single-capture:
// right after; batch: once at the end) so a batch does not write ext state N times.
//
// Provenance is read from the LIVE selection here, so a batch that transiently
// selects exactly one item per unit gets per-unit-correct provenance. `src` supplies
// the source tracks (FX bypass + Sample GUIDs); `scope` drives the bypass plan and
// provenance scope. Returns the backend's CaptureResult (status + message) so the
// caller can report success/failure. Load-bearing principle holds: writes a file +
// a bank index entry ONLY; never touches the arrange/timeline. Non-destructive: the
// out-of-scope FX/fader/pan chain is fully restored on every path (FxBypassGuard),
// and the backend restores every RENDER_* setting.
//
// On success, res.sample.id carries the LANDED bank-index id (S8): the newly-added id
// on a fresh add, or the EXISTING entry's id on a hash-dedup collapse — so the S8
// capture+assign path can target the sample actually in the bank. Batch callers ignore
// it; the plain capture actions are unaffected.
CaptureResult captureAndIndexOne(ReaSamplerSession& session,
CaptureScope scope,
const ResolvedSource& src,
const std::string& baseName,
double startSeconds,
double endSeconds)
{
// The tail mode is a PANEL SETTING (docked bank panel's toggle), not a per-action
// variant: the capture actions apply whatever the panel is set to. Default is None
// (exact bounds / byte-identical to today) until the user opts in via the toggle.
const TailSetting tail = bankPanelTailSetting();
CaptureRequest req;
req.sourceMode = sourceModeForScope(scope);
req.startSeconds = startSeconds; // exact bounds — no rounding
req.endSeconds = endSeconds;
req.wetDry = 1.0; // wet post the FX left enabled by the scope
req.tailMode = tail.mode; // None / Auto / Manual, from the panel toggle
req.tailMs = tail.manualMs; // Manual-only (clamped); ignored for None/Auto
req.sampleRate = 0; // follow project rate
req.channelCount = 2;
req.bitDepth = WavBitDepth::Float32; // deterministic, no dither
req.baseName = baseName;
req.trackGuids = src.trackGuids; // recorded on the Sample (provenance)
// M10: compute provenance BEFORE the FxBypassGuard neutralizes the in-scope chain —
// the source FX-chain identity must be read from the LIVE (un-bypassed) chain, and
// the source selection is still live here. Returns nullopt unless this capture
// genuinely resamples from a bank sample (detectParent). Read-only.
const std::optional<model::Provenance> prov =
buildCaptureProvenance(session.book(), req, scope, src);
// Render under the scope's FX-bypass guard (out-of-scope FX / fader / pan chain
// neutralized for the render, fully restored on every path). Writes a file only.
CaptureResult res = renderOffline(scope, src.sourceTracks, req);
if (res.status != CaptureStatus::Ok)
return res;
// Stamp provenance onto the captured Sample (only set when this was a genuine
// resample-from-sample; otherwise the optional stays empty, per M1's contract).
res.sample.provenance = prov;
// Add to the ACTIVE bank: session.bank() resolves to book.activeIndex() (B2). The
// AddResult tells a fresh add from a hash-dedup collapse, so the assign path (S8) can
// target the sample actually in the bank (the existing entry on a collapse).
const model::AddResult addResult = session.bank().add(res.sample);
// B-cap: record the created file in the owned-file manifest, at the same point the
// Sample is added. Recorded regardless of the index AddResult — even a hash-collapse
// still WROTE a file the tool owns, and the manifest dedups a repeat path itself
// (Phase R prune reconciles manifest vs index later).
session.owned().add(res.sample.relativePath);
// Resolve the LANDED bank-index id into res.sample.id for the S8 assign path: the new
// id on a fresh Added (already in res.sample.id); the EXISTING entry's id on a
// Collapsed (the file we just rendered deduped onto an already-present sample — assign
// THAT one). Batch/plain-capture callers ignore this field; behaviour unchanged.
if (addResult == model::AddResult::Collapsed && !res.sample.contentHash.empty())
{
if (const model::Sample* existing =
session.bank().findByHash(res.sample.contentHash))
res.sample.id = existing->id;
}
return res;
}
// Runs one capture-action-table row: resolve its scope source + range, render + add +
// record via captureAndIndexOne, then persist + mark dirty. The load-bearing principle
// holds structurally — this path writes a file + a bank index entry ONLY; it never
// calls InsertMedia or touches the arrange/timeline.
// Returns the bank-index id of the sample the capture landed on: the newly-added id on a
// fresh capture, or the EXISTING id on a hash-dedup collapse (so an ingest-with-assign
// targets the sample actually in the bank). Empty on any failure / no-op. The S8 arrange
// capture+assign path reads this to write an assignment request; the plain capture actions
// ignore it (their behaviour is unchanged — capture still writes a file + index entry only).
std::string RunCapture(ReaSamplerSession& session, const CaptureActionDef& def)
{
ResolvedSource src;
std::string why;
if (!ResolveScopeSource(def.scope, src, why))
{
ShowConsoleMsg(("ReaSampler capture: " + why + ".\n").c_str());
return {};
}
CaptureResult res = captureAndIndexOne(session, def.scope, src, def.baseName,
src.startSeconds, src.endSeconds);
if (res.status != CaptureStatus::Ok)
{
ShowConsoleMsg(("ReaSampler capture failed: " + res.message + "\n").c_str());
return {};
}
// captureAndIndexOne has already stamped provenance, added the Sample to the ACTIVE
// bank, and recorded the created file in the owned-file manifest (WITHOUT persisting).
// Persist the updated book AND manifest into the active project's ext state (the
// `banks` + `owned_files` keys) so the capture survives Save / close+reopen (M4) and
// travels with the .rpp. saveToActiveProject also clears the retired legacy key and
// calls MarkProjectDirty. Non-destructive: writes only our own ext-state keys.
// S9: a capture add is a bank-content change -> bump before the persist so an assigned
// live instance refreshes hands-free (the S8 capture+assign path builds on this).
session.bumpBankGeneration();
session.saveToActiveProject();
// Hand the LANDED bank-index id back to the assign path (S8): captureAndIndexOne
// resolved res.sample.id to the fresh id on a new add or the existing entry's id on a
// hash-dedup collapse. Empty on any reject (unreachable here — status was Ok above).
return res.sample.id;
}
// S8 arrange ingest: capture the selected item / time-selection into the active bank
// (reusing the Item-scope capture path verbatim) and, on success, write an assignment
// request so the active sampler instance plays the new sample on its next reload. The
// capture itself is unchanged — RunCapture writes a file + an index entry and NEVER
// inserts a timeline item (load-bearing principle); the only addition here is the
// bank-index-id -> assignment-request write after the sample lands. If the capture
// failed / no-op'd (empty id), no assignment is written (nothing to assign).
//
// UNDO GROUPING: both the bank mutation (RunCapture -> saveToActiveProject) AND the
// assignment-request write (ingestAssignActiveInstance -> writeAssignmentRequest) are
// wrapped in a single undo block so Ctrl-Z rolls back both ext-state keys atomically.
// An undo that removes the captured sample also clears the assign_request that named it,
// preventing a stale request from pointing at a removed sample. The block uses the house
// pattern (UNDO_STATE_MISCCFG, discarded on an unsaved project with empty label + zero
// flag) matching the bank-op family in actions.cpp.
void RunCaptureItemAssign(ReaSamplerSession& session)
{
// Reuse the Item-scope def from the capture table (index 0) — same range logic, same
// FX-scope neutralize, same bank/persist landing as the plain "capture item" action.
Undo_BeginBlock2(nullptr);
const std::string sampleId = RunCapture(session, captureActionTable()[0]);
if (sampleId.empty())
{
// Capture failed or no-op'd — RunCapture already reported. Discard the empty point.
Undo_EndBlock2(nullptr, "", 0);
return;
}
// Assign inside the same block so undo clears both keys together.
ingestAssignActiveInstance(session.book().activeBankId(), sampleId);
Undo_EndBlock2(nullptr, "ReaSampler: capture + assign to active instance",
UNDO_STATE_MISCCFG);
bankPanelRefresh();
ShowConsoleMsg("ReaSampler ingest: captured into the bank and assigned to the active "
"instance.\n");
}
// STARTS the REALTIME track capture and returns immediately — the record runs across
// timer ticks (DriveRealtimeCapture in realtime_lifecycle), so REAPER's UI stays
// responsive. Resolves the selected tracks + the range (razor-else-time, the same
// orthogonal range logic as the offline scopes) and starts recording each selected
// track's OWN output into a hidden temp track via RealtimeRecordBackend::begin (a
// send FROM each source track INTO the temp — see capture_realtime_shell.cpp §TAP);
// OnTimer drives it to completion, then adds the Sample and persists. TRACK scope
// only this increment (item realtime is deferred). Dialog-free. Non-bit-identical
// by nature (it is realtime) — offline stays the deterministic default.
// FxBypassGuard is NOT used here — the track-output tap is PRE-parent by
// construction (§TAP), so there is no live chain to neutralize. The load-bearing
// principle holds structurally — this writes a file + a bank entry ONLY; the temp
// track is a transient sink removed by the backend, nothing lands in arrange.
//
// A SECOND realtime capture requested while one is in progress is REJECTED — the
// first keeps running (we own the transport for its window; starting a second would
// collide on the transport and the temp-track/arm snapshot).
void RunCaptureRealtimeTrack(ReaSamplerSession& session)
{
(void)session; // start path persists nothing — commit happens on the terminal tick
if (g_rtCapture)
{
ShowConsoleMsg("ReaSampler realtime capture: a capture is already in "
"progress -- let it finish (or stop the transport) first.\n");
return;
}
// Resolve the selected tracks + range exactly as the offline Track scope does.
// No track selected -> refuse (same no-op as offline track scope).
ResolvedSource src;
std::string why;
if (!ResolveScopeSource(CaptureScope::Track, src, why))
{
ShowConsoleMsg(("ReaSampler realtime capture: " + why + ".\n").c_str());
return;
}
// The tail mode is the SAME panel setting the offline capture actions read (the
// docked bank panel's toggle). Realtime honors it via a parallel path: the backend
// records a generous window past the range end, then trims by PCM decay-scan (T2 /
// capture-tail.md §The realtime path) — it does NOT drive RENDER_*. Default None
// keeps realtime exact-bounds / byte-identical to today.
const TailSetting tail = bankPanelTailSetting();
CaptureRequest req;
req.sourceMode = SourceMode::SelectedTracks; // realtime track scope
req.startSeconds = src.startSeconds; // exact bounds — no rounding
req.endSeconds = src.endSeconds;
req.wetDry = 1.0; // fully wet (post-fader tap)
req.tailMode = tail.mode; // None / Auto / Manual, from the panel toggle
req.tailMs = tail.manualMs; // Manual-only (pre-clamped); ignored for None/Auto
req.sampleRate = 0; // follow project rate
req.channelCount = 2;
req.bitDepth = WavBitDepth::Float32;
req.baseName = "realtime";
req.trackGuids = src.trackGuids; // provenance on the Sample
CaptureResult failure;
RealtimeCaptureHandle st = g_rtBackend.begin(req, src.sourceTracks, failure);
if (!st)
{
// begin() validated/failed and already restored anything it touched.
ShowConsoleMsg(("ReaSampler realtime capture failed: " + failure.message + "\n").c_str());
return;
}
// Started. Store the in-flight state + its project; OnTimer drives it to
// completion across ticks (UI stays responsive).
g_rtCaptureProject = EnumProjects(-1, nullptr, 0);
g_rtCapture = std::move(st);
}
// Cancels the in-flight realtime capture on demand (bindable action). Force-terminates
// via abort() — stop the transport + restore ALL snapshotted state (non-destructive),
// committing whatever audio was already captured (best effort) so a cancel near the end
// still keeps the take. Runs only against the record's OWN project (abort() self-guards
// the closed-project case, review §1). No-op with a note when nothing is in flight.
void RunCancelRealtime(ReaSamplerSession& session)
{
if (!g_rtCapture)
{
ShowConsoleMsg("ReaSampler: no realtime capture in progress to cancel.\n");
return;
}
RealtimeTickResult r = g_rtBackend.abort(*g_rtCapture);
if (r.status == RealtimeTickStatus::Done)
CommitRealtimeResult(session, r.result); // Ok: keep what was captured up to the cancel
else
ShowConsoleMsg(("ReaSampler realtime capture cancelled -- " +
r.result.message + "\n").c_str());
g_rtCapture.reset();
g_rtCaptureProject = nullptr;
}
// Runs the M6 insert: place the bank panel's selected sample(s) at the edit cursor
// via InsertMedia, undo-wrapped. `conform` selects the explicit opt-in tempo-match
// variant (never silent — it fires only from the distinct "conform" action). This
// is the INTENDED placement path: it adds items to the arrange on purpose
// (CONTEXT.md §load-bearing principle) and runs only from a user-invoked action.
void RunInsertSelected(ReaSamplerSession& session, bool conform)
{
InsertRequest req;
// target defaults to CurrentTrack (InsertOptions::target) — inserts onto the
// user's currently-selected track(s) at the edit cursor.
req.options.conform = conform ? TempoConform::Ratio1x : TempoConform::None;
// preservePitch stays true: a tempo conform matches tempo without varispeeding
// pitch. (A pitch-shifting variant is a later opt-in if wanted — YAGNI now.)
InsertResult res = runInsert(&session, req);
switch (res.status)
{
case InsertStatus::Ok:
break; // success — no console chatter
case InsertStatus::NoSelection:
// "select a track first" is printed by runInsert when no track is
// selected; this branch covers the no-panel-selection case.
ShowConsoleMsg("ReaSampler insert: nothing selected in the bank panel.\n");
break;
case InsertStatus::NoProject:
ShowConsoleMsg("ReaSampler insert: no saved project, so the bank has no location.\n");
break;
case InsertStatus::NothingResolved:
ShowConsoleMsg("ReaSampler insert: selected sample(s) could not be resolved to a file.\n");
break;
}
}
} // namespace reasampler::capture
+73
View File
@@ -0,0 +1,73 @@
#pragma once
// capture_orchestrator — the single-capture orchestration + the realtime/insert
// action bodies (Q-W3 hoist out of main.cpp, T4-02). Owns:
// * renderOffline — ONE offline render under the scope's FxBypassGuard (the
// stack-RAII out-of-scope FX/fader/pan neutralize, defined in the .cpp —
// precision-invariant-critical, shared by single-shot / batch / recapture);
// * captureAndIndexOne — render + provenance stamp + bank add + owned-manifest
// record, WITHOUT persisting (single-shot persists right after; batch persists
// once at the end);
// * RunCapture / RunCaptureItemAssign — the bindable single-capture actions;
// * RunCaptureRealtimeTrack / RunCancelRealtime — the realtime action bodies
// (the in-flight state itself lives in realtime_lifecycle);
// * RunInsertSelected — the M6 placement action body (the INTENDED, explicit
// placement path — the one deliberate exception to capture-never-places).
//
// The session is threaded explicitly (no hidden module state): main.cpp's dispatch
// passes its ReaSamplerSession. The load-bearing principle holds structurally —
// no capture path here calls InsertMedia or touches the arrange/timeline; only
// RunInsertSelected places, on purpose, via the insert shell.
//
// REAPER-facing: the .cpp includes reaper_plugin_functions.h WITHOUT
// REAPERAPI_IMPLEMENT (main.cpp owns the API pointers — CLAUDE.md §contract).
#include <string>
#include "shell/capture/capture.h" // CaptureResult / CaptureRequest
#include "shell/capture/scope_resolve.h" // ResolvedSource
#include "core/capture/render_settings.h" // CaptureScope, CaptureActionDef
namespace reasampler {
class ReaSamplerSession;
}
namespace reasampler::capture {
// Renders one CaptureRequest through the offline backend under the scope's
// FX-bypass guard, returning the backend's CaptureResult. Shared by RunCapture and
// RunRecaptureFromSource so the FX-scope neutralize + render recipe lives in ONE
// place. Non-destructive; touches no timeline item — it writes a file only.
CaptureResult renderOffline(CaptureScope scope,
const std::vector<MediaTrack*>& sourceTracks,
const CaptureRequest& req);
// Renders ONE capture request under the scope's FX-bypass guard, stamps provenance,
// and adds the resulting Sample to the ACTIVE bank + records the created file in
// the owned-file manifest — WITHOUT persisting. On success, res.sample.id carries
// the LANDED bank-index id (fresh add or hash-dedup collapse target — S8).
CaptureResult captureAndIndexOne(ReaSamplerSession& session,
CaptureScope scope,
const ResolvedSource& src,
const std::string& baseName,
double startSeconds,
double endSeconds);
// Runs one capture-action-table row: resolve, render + add + record, persist +
// mark dirty. Returns the landed bank-index id ("" on failure/no-op) — the S8
// capture+assign path consumes it; the plain capture actions ignore it.
std::string RunCapture(ReaSamplerSession& session, const CaptureActionDef& def);
// S8 arrange ingest: Item-scope capture into the active bank + assignment-request
// write, in one undo block.
void RunCaptureItemAssign(ReaSamplerSession& session);
// STARTS the realtime track capture (async, timer-driven — the in-flight state is
// realtime_lifecycle's; OnTimer drives it) / cancels the in-flight one.
void RunCaptureRealtimeTrack(ReaSamplerSession& session);
void RunCancelRealtime(ReaSamplerSession& session);
// Runs the M6 insert: place the bank panel's selected sample(s) at the edit cursor
// via the insert shell. `conform` selects the explicit opt-in tempo-match variant.
void RunInsertSelected(ReaSamplerSession& session, bool conform);
} // namespace reasampler::capture
@@ -0,0 +1,252 @@
// capture_realtime_finalize.cpp — the FILE-SIDE half of the realtime-record shell
// (Q-W3, T4-08 split): recorded-file discovery, move-into-bank, the Auto-tail PCM
// decay-scan trim, and the finished-Sample population. See the header. The async
// record lifecycle lives in capture_realtime_shell.cpp.
//
// Compiled into the reaper_reasampler MODULE. Includes reaper_plugin_functions.h
// WITHOUT REAPERAPI_IMPLEMENT — main.cpp is the one TU that defines the API
// pointers; here they are extern (CLAUDE.md §contract).
#include "shell/capture/capture_realtime_finalize.h"
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <string>
#include <vector>
#include "core/audio/peaks.h" // lastFrameAboveThreshold
#include "core/capture/capture_realtime.h" // RecordedCapture, sampleFromRecordedCapture
#include "core/capture/render_settings.h" // autoTrimEndRatio
#include "core/capture/wav_codec.h" // parseWavLayout, extractFloatFrames, planWavTruncate, patchU32LE
#include "core/util/file_bytes.h" // shared whole-file loader (Q-W1, T2-03)
#define REAPERAPI_MINIMAL
#define REAPERAPI_WANT_GetTrackNumMediaItems
#define REAPERAPI_WANT_GetTrackMediaItem
#define REAPERAPI_WANT_GetMediaItemTake
#define REAPERAPI_WANT_GetMediaItemTake_Source
#define REAPERAPI_WANT_GetMediaSourceFileName
#include "reaper_plugin_functions.h"
namespace reasampler::capture {
namespace {
std::string normSlashes(std::string s) {
for (char& c : s) if (c == '\\') c = '/';
if (s.size() > 1 && s.back() == '/') s.pop_back();
return s;
}
// ============================================================================
// §TAIL — Auto-mode PCM decay-scan trim (docs/product/capture-tail.md §realtime)
// ============================================================================
// After the recorded file is stable and moved into the bank (the file we OWN — never
// the project), Auto mode trims the trailing decay: read the WAV, scan the tail
// region (frames AFTER the original range end) backward for the last frame above
// -72 dB, and truncate the file there. Rules (spec):
// * no frame in the tail window above -72 dB -> trim back to the original range end
// * signal never falls below -72 dB in window -> keep the full window (cap did its job)
// * otherwise -> trim one frame past the last audible
//
// Returns the trimmed length in SECONDS (for the Sample), or a negative value to
// signal "no trim applied" (caller keeps the pre-trim length). Best-effort and
// non-fatal: any unreadable/unknown/short file skips the trim (keeps the full window)
// rather than risk corrupting the capture — realtime tail is a convenience path.
//
// FORMAT / FLUSH ASSUMPTIONS (DAW-verify): the recorded file is a canonical 32-bit
// float WAV (REAPER project record format — the manual procedure sets it) and is fully
// flushed/closed before this runs (the tick() Finalizing size-stable wait guarantees
// that for the normal path; abort()'s best-effort finalize races it, documented).
double trimAutoTailInPlace(const std::string& path,
double rangeStartSeconds,
double rangeEndSeconds) {
constexpr double kNoTrim = -1.0;
std::vector<std::uint8_t> bytes = util::readFileBytes(path);
if (bytes.empty()) return kNoTrim;
const WavLayout layout = parseWavLayout(bytes);
if (!layout.valid || layout.sampleRate == 0) return kNoTrim; // not a WAV we trim
const std::size_t totalFrames = layout.frameCount();
if (totalFrames == 0) return kNoTrim;
// The original range end as a frame index within the file (frame 0 == start). Use
// the FILE's own sample rate (authoritative) — the request rate may be 0 (=follow
// project). Clamp to the file so a rounding overshoot cannot exceed it.
const double rangeSeconds = rangeEndSeconds - rangeStartSeconds;
if (rangeSeconds <= 0.0) return kNoTrim;
std::size_t rangeEndFrame = static_cast<std::size_t>(
rangeSeconds * static_cast<double>(layout.sampleRate) + 0.5);
if (rangeEndFrame > totalFrames) rangeEndFrame = totalFrames;
// Nothing recorded past the range end (the tail window was empty) -> nothing to
// trim; keep as-is. (Shouldn't happen for Auto, but total by construction.)
if (rangeEndFrame >= totalFrames) return kNoTrim;
// Scan ONLY the tail region (frames after the original range end). The trim never
// eats into the range body — the scan starts at rangeEndFrame.
const std::size_t tailFrames = totalFrames - rangeEndFrame;
const std::vector<AudioSample> tailPcm =
extractFloatFrames(bytes, layout, rangeEndFrame, tailFrames);
if (tailPcm.empty()) return kNoTrim;
const float threshold = static_cast<float>(autoTrimEndRatio());
const std::size_t lastAbove = audio::lastFrameAboveThreshold(
tailPcm, layout.channelCount, tailFrames, threshold);
// keptFrames: the total frame count the trimmed file retains.
// no audible tail frame -> trim back to the range end (rangeEndFrame frames)
// an audible frame at idx -> keep range body + up to and including that frame
// The "signal never falls below threshold" case falls out naturally: lastAbove is
// the final tail frame, so keptFrames == totalFrames (the full window is kept).
std::size_t keptFrames;
if (lastAbove == audio::kNoFrameAboveThreshold) {
keptFrames = rangeEndFrame;
} else {
keptFrames = rangeEndFrame + (lastAbove + 1);
}
if (keptFrames >= totalFrames) return kNoTrim; // full window kept -> no truncate
const WavTruncatePlan plan = planWavTruncate(layout, keptFrames);
if (!plan.valid) return kNoTrim;
// Patch the RIFF + data size fields in the in-memory buffer so they describe the
// kept frame count (wav_codec's patch primitive — the one RIFF owner), then
// rewrite the file as exactly the first newFileByteLength bytes (header +
// patched sizes + retained PCM). A single truncating write is the simplest
// correct truncate — no separate resize step, no partial-write window where the
// on-disk sizes and length disagree. The result is a valid, playable WAV of the
// kept frames (verified by the wav_codec re-parse test).
patchU32LE(bytes, plan.dataSizeFieldOffset, plan.newDataSize);
patchU32LE(bytes, plan.riffSizeFieldOffset, plan.newRiffSize);
// NOTE (DAW-verify, best-effort): a truncating write that fails MID-write (a full
// disk, a yanked drive) would leave a short file while we return kNoTrim, so the
// Sample length would overstate the file. Vanishingly unlikely for a just-recorded
// local bank file, and realtime tail is a convenience path, so a temp-file+atomic-
// rename is not warranted here; flagged rather than built.
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out) return kNoTrim; // could not reopen to rewrite — leave the full file
out.write(reinterpret_cast<const char*>(bytes.data()),
static_cast<std::streamsize>(plan.newFileByteLength));
if (!out) return kNoTrim;
out.close();
// The trimmed length in seconds for the Sample metadata.
return static_cast<double>(keptFrames) / static_cast<double>(layout.sampleRate);
}
} // namespace
std::string recordedFilePath(MediaTrack* temp) {
if (!temp) return {};
if (GetTrackNumMediaItems(temp) <= 0) return {};
MediaItem* item = GetTrackMediaItem(temp, 0);
if (!item) return {};
MediaItem_Take* take = GetMediaItemTake(item, 0);
if (!take) return {};
PCM_source* src = GetMediaItemTake_Source(take);
if (!src) return {};
std::vector<char> buf(4096, '\0');
GetMediaSourceFileName(src, buf.data(), static_cast<int>(buf.size()));
return normSlashes(std::string(buf.data()));
}
CaptureResult finalizeRecording(ReaProject* proj, MediaTrack* temp,
const CaptureRequest& request,
const BankPaths& paths,
const std::string& uniqueTag,
double recordWindowEnd) {
CaptureResult result;
const std::string recorded = recordedFilePath(temp);
if (recorded.empty() || !std::filesystem::exists(recorded)) {
result.status = CaptureStatus::RenderFailed;
result.message = "Realtime record produced no file (check transport/record "
"settings in the DAW).";
return result;
}
std::error_code ec;
std::filesystem::create_directories(paths.absoluteDir, ec);
const std::string destPath = paths.absoluteDir + "/" + paths.fileName;
std::filesystem::rename(recorded, destPath, ec);
if (ec) {
// Cross-volume rename can fail; fall back to copy+remove.
ec.clear();
std::filesystem::copy_file(
recorded, destPath,
std::filesystem::copy_options::overwrite_existing, ec);
if (ec) {
result.status = CaptureStatus::RenderFailed;
result.message = "Recorded file could not be moved into the bank: " +
ec.message();
return result;
}
std::error_code rmEc;
std::filesystem::remove(recorded, rmEc); // best-effort
}
// TAIL (Auto): trim the trailing decay of the recorded window in place — on the
// BANK file we now own (destPath), never the project. Best-effort: an unreadable /
// unknown-format / short file skips the trim (keeps the full window) rather than
// corrupt the capture. Only Auto trims; None recorded exact bounds and Manual is a
// fixed window (spec §The realtime path). Returns the trimmed length in seconds,
// or < 0 for "no trim applied".
double trimmedLenSeconds = -1.0;
if (request.tailMode == TailMode::Auto) {
trimmedLenSeconds = trimAutoTailInPlace(destPath,
request.startSeconds,
request.endSeconds);
}
// The pure recorded-capture -> Sample mapping (identity, bounds echo, tier).
RecordedCapture cap;
cap.relativePath = paths.relativePath;
cap.uniqueTag = uniqueTag;
cap.sourceMode = SourceMode::Realtime;
cap.startSeconds = request.startSeconds;
cap.endSeconds = request.endSeconds;
cap.wetDry = request.wetDry;
cap.displayName = request.baseName;
cap.trackGuids = request.trackGuids;
cap.channelCount = request.channelCount;
result.status = CaptureStatus::Ok;
result.sample = sampleFromRecordedCapture(cap);
// The SHARED finished-capture stamp (T2-09 dedupe): trackGuids + channelCount
// (request echo), resolved sampleRate (request rate else PROJECT_SRATE — read
// against the record's OWN project), captureTempo, the capture-start time
// signature (timeSigProj = proj: the realtime path PINS the record's own
// project — the divergence from offline's active-project read, kept
// caller-visible here), the WAV-aware contentHash of the (possibly trimmed)
// bank file, and createdTimestamp.
stampCaptureSample(result.sample, request, /*rateProj=*/proj,
/*timeSigProj=*/proj, destPath);
// The recorded file's true length differs from the request range when a tail was
// recorded, so the Sample length must reflect the FILE, not the range:
// Auto with a trim applied -> the trimmed length trimAutoTailInPlace returned.
// Auto with no trim, or Manual -> the full recorded window (end - start).
// None -> the exact range (unchanged; recordWindowEnd == endSeconds).
// sampleFromRecordedCapture already set lengthSeconds = end - start; override it
// to the recorded/trimmed length so downstream (thumbnail, placement) matches disk.
if (trimmedLenSeconds >= 0.0) {
result.sample.lengthSeconds = trimmedLenSeconds;
} else {
result.sample.lengthSeconds = recordWindowEnd - request.startSeconds;
}
result.message = "Realtime-captured [" +
std::to_string(request.startSeconds) + "s, " +
std::to_string(request.endSeconds) + "s] (recorded " +
std::to_string(result.sample.lengthSeconds) + "s) -> " +
paths.relativePath;
return result;
}
} // namespace reasampler::capture
@@ -0,0 +1,42 @@
#pragma once
// capture_realtime_finalize — the FILE-SIDE half of the realtime-record shell
// (Q-W3, T4-08 split riding the Q-9 rename): discovering the file REAPER actually
// recorded, moving it into the bank, the Auto-tail PCM decay-scan trim, and the
// finished-Sample population. The async record LIFECYCLE (state snapshot/restore,
// begin/tick/abort) lives in capture_realtime_shell.cpp; this half talks to
// wav_codec and the filesystem, not to the transport.
//
// REAPER-facing: the .cpp includes reaper_plugin_functions.h WITHOUT
// REAPERAPI_IMPLEMENT (main.cpp owns the API pointers — CLAUDE.md §contract).
// MediaTrack / ReaProject are forward-declared (via capture.h) so this header
// stays SDK-lite.
#include <string>
#include "shell/capture/capture.h" // CaptureRequest / CaptureResult
#include "core/capture/capture_paths.h" // BankPaths
namespace reasampler::capture {
// Discovers the file REAPER actually recorded onto the temp track: the first media
// item's active take's source file, forward-slashed. Empty string if nothing was
// recorded (no item / take / source). Also used by the lifecycle's flush wait
// (size-stable check) before finalize runs.
std::string recordedFilePath(MediaTrack* temp);
// Builds a CaptureResult for a finalized recording: discover the recorded file,
// move it into the bank at `paths`, Auto-trim the tail decay in place when the
// request asks for it, and populate the Sample (pure sampleFromRecordedCapture +
// the shared stampCaptureSample — both project reads pinned to `proj`, the
// record's OWN project). Returns Ok + Sample on success, or a RenderFailed result.
// Does NOT restore any snapshotted state — the caller restores unconditionally
// afterward (finalize + restore are separate steps so a finalize failure still
// restores). `recordWindowEnd` is the recorded window end in project seconds
// (>= request.endSeconds when a tail was recorded) — the untrimmed-length source.
CaptureResult finalizeRecording(ReaProject* proj, MediaTrack* temp,
const CaptureRequest& request,
const BankPaths& paths,
const std::string& uniqueTag,
double recordWindowEnd);
} // namespace reasampler::capture
@@ -1,5 +1,10 @@
#include "core/namespaces.h"
// capture_realtime.cpp — REAPER-facing realtime-record backend (RealtimeRecordBackend).
// capture_realtime_shell.cpp — REAPER-facing realtime-record backend
// (RealtimeRecordBackend): the ASYNC record LIFECYCLE — state snapshot/restore +
// begin/tick/abort. (Renamed from capture_realtime.cpp in Q-W3 — the Q-9 naming
// rider: the PURE module owns the capture_realtime stem, this shell takes the
// suffix, matching drag_out ↔ drag_out_win.) The FILE-SIDE half — recorded-file
// discovery, move-into-bank, Auto-tail trim, Sample population — lives in
// capture_realtime_finalize.cpp (T4-08 split).
//
// Compiled into the reaper_reasampler MODULE. Includes reaper_plugin_functions.h
// WITHOUT REAPERAPI_IMPLEMENT — main.cpp is the one TU that defines the API
@@ -30,8 +35,9 @@
// completion, user stop, error, second-capture reject, project switch, unload —
// funnels through the SAME single restore, safe to call once from whichever fires.
// The pure record-mode bookkeeping, the recorded-file->Sample mapping, and the
// completion state machine (advanceRecordPhase) all live in realtime_record.{h,cpp}
// (unit-tested outside the DAW). This TU owns only the REAPER-bound recipe.
// completion state machine (advanceRecordPhase) all live in the pure
// core/capture/capture_realtime.{h,cpp} (unit-tested outside the DAW). This TU
// owns only the REAPER-bound lifecycle recipe.
//
// ============================================================================
// §TAP — track-output tap (selected track's own output, PRE-parent)
@@ -72,26 +78,18 @@
#include <chrono>
#include <cstdint>
#include <cstring>
#include <ctime>
#include <filesystem>
#include <fstream>
#include <string>
#include <vector>
#include "core/capture/capture_paths.h" // hashBytes, deriveBankPaths
#include "core/util/file_bytes.h" // shared whole-file loader (Q-W1, T2-03)
#include "core/audio/peaks.h" // lastFrameAboveThreshold, AudioSample
#include "core/capture/realtime_record.h"
#include "core/capture/render_settings.h" // autoTrimEndRatio, realtimeRecordWindowEnd
#include "core/capture/wav_trim.h" // parseWavLayout, extractFloatFrames, planWavTruncate
#include "core/capture/capture_paths.h" // deriveBankPaths
#include "core/capture/capture_realtime.h" // RecordPhase machine, record-mode plan (pure)
#include "core/capture/render_settings.h" // realtimeRecordWindowEnd
#include "shell/capture/capture_realtime_finalize.h" // recordedFilePath, finalizeRecording
#define REAPERAPI_MINIMAL
#define REAPERAPI_WANT_EnumProjects
#define REAPERAPI_WANT_Main_SaveProject
#define REAPERAPI_WANT_Master_GetTempo
#define REAPERAPI_WANT_TimeMap_GetTimeSigAtTime
#define REAPERAPI_WANT_GetSetProjectInfo
#define REAPERAPI_WANT_InsertTrackAtIndex
#define REAPERAPI_WANT_DeleteTrack
#define REAPERAPI_WANT_CountTracks
@@ -99,11 +97,6 @@
#define REAPERAPI_WANT_CreateTrackSend
#define REAPERAPI_WANT_GetMediaTrackInfo_Value
#define REAPERAPI_WANT_SetMediaTrackInfo_Value
#define REAPERAPI_WANT_GetTrackNumMediaItems
#define REAPERAPI_WANT_GetTrackMediaItem
#define REAPERAPI_WANT_GetMediaItemTake
#define REAPERAPI_WANT_GetMediaItemTake_Source
#define REAPERAPI_WANT_GetMediaSourceFileName
#define REAPERAPI_WANT_CSurf_OnRecord
#define REAPERAPI_WANT_OnStopButtonEx
#define REAPERAPI_WANT_GetPlayStateEx
@@ -114,16 +107,10 @@
#define REAPERAPI_WANT_ValidatePtr2
#include "reaper_plugin_functions.h"
namespace reasampler {
namespace reasampler::capture {
namespace {
// A monotonic, filesystem-safe timestamp tag so repeated captures do not collide.
std::string makeUniqueTag() {
std::time_t now = std::time(nullptr);
return "rt-" + std::to_string(static_cast<long long>(now));
}
std::string normSlashes(std::string s) {
for (char& c : s) if (c == '\\') c = '/';
if (s.size() > 1 && s.back() == '/') s.pop_back();
@@ -138,22 +125,6 @@ std::string readRppPath() {
return std::string(buf.data());
}
// Discovers the file REAPER actually recorded onto the temp track: the first media
// item's active take's source file. Empty string if nothing was recorded.
std::string recordedFilePath(MediaTrack* temp) {
if (!temp) return {};
if (GetTrackNumMediaItems(temp) <= 0) return {};
MediaItem* item = GetTrackMediaItem(temp, 0);
if (!item) return {};
MediaItem_Take* take = GetMediaItemTake(item, 0);
if (!take) return {};
PCM_source* src = GetMediaItemTake_Source(take);
if (!src) return {};
std::vector<char> buf(4096, '\0');
GetMediaSourceFileName(src, buf.data(), static_cast<int>(buf.size()));
return std::string(buf.data());
}
// The recorded file's current size in bytes, or -1 if it cannot be resolved yet (no
// item/take/source, or the file does not exist on disk this tick). Used by the flush
// wait to detect stability (size unchanged across a tick) BEFORE moving the file — a
@@ -323,236 +294,9 @@ private:
bool finalized_ = false;
};
namespace {
// Whole-file reads go through the shared core/util readFileBytes (Q-W1, T2-03):
// empty on any I/O failure — the caller treats an unreadable file as "skip the
// trim" (keep the untrimmed window), never as a corruption of the recorded audio.
// Patches a little-endian uint32 into a byte buffer at `off` (the header size fields).
void writeU32LE(std::vector<std::uint8_t>& bytes, std::size_t off, std::uint32_t v) {
bytes[off + 0] = static_cast<std::uint8_t>(v & 0xFF);
bytes[off + 1] = static_cast<std::uint8_t>((v >> 8) & 0xFF);
bytes[off + 2] = static_cast<std::uint8_t>((v >> 16) & 0xFF);
bytes[off + 3] = static_cast<std::uint8_t>((v >> 24) & 0xFF);
}
// ============================================================================
// §TAIL — Auto-mode PCM decay-scan trim (docs/product/capture-tail.md §realtime)
// ============================================================================
// After the recorded file is stable and moved into the bank (the file we OWN — never
// the project), Auto mode trims the trailing decay: read the WAV, scan the tail
// region (frames AFTER the original range end) backward for the last frame above
// -72 dB, and truncate the file there. Rules (spec):
// * no frame in the tail window above -72 dB -> trim back to the original range end
// * signal never falls below -72 dB in window -> keep the full window (cap did its job)
// * otherwise -> trim one frame past the last audible
//
// Returns the trimmed length in SECONDS (for the Sample), or a negative value to
// signal "no trim applied" (caller keeps the pre-trim length). Best-effort and
// non-fatal: any unreadable/unknown/short file skips the trim (keeps the full window)
// rather than risk corrupting the capture — realtime tail is a convenience path.
//
// FORMAT / FLUSH ASSUMPTIONS (DAW-verify): the recorded file is a canonical 32-bit
// float WAV (REAPER project record format — the manual procedure sets it) and is fully
// flushed/closed before this runs (the tick() Finalizing size-stable wait guarantees
// that for the normal path; abort()'s best-effort finalize races it, documented).
double trimAutoTailInPlace(const std::string& path,
double rangeStartSeconds,
double rangeEndSeconds) {
constexpr double kNoTrim = -1.0;
std::vector<std::uint8_t> bytes = readFileBytes(path);
if (bytes.empty()) return kNoTrim;
const reasampler::WavLayout layout = parseWavLayout(bytes);
if (!layout.valid || layout.sampleRate == 0) return kNoTrim; // not a WAV we trim
const std::size_t totalFrames = layout.frameCount();
if (totalFrames == 0) return kNoTrim;
// The original range end as a frame index within the file (frame 0 == start). Use
// the FILE's own sample rate (authoritative) — the request rate may be 0 (=follow
// project). Clamp to the file so a rounding overshoot cannot exceed it.
const double rangeSeconds = rangeEndSeconds - rangeStartSeconds;
if (rangeSeconds <= 0.0) return kNoTrim;
std::size_t rangeEndFrame = static_cast<std::size_t>(
rangeSeconds * static_cast<double>(layout.sampleRate) + 0.5);
if (rangeEndFrame > totalFrames) rangeEndFrame = totalFrames;
// Nothing recorded past the range end (the tail window was empty) -> nothing to
// trim; keep as-is. (Shouldn't happen for Auto, but total by construction.)
if (rangeEndFrame >= totalFrames) return kNoTrim;
// Scan ONLY the tail region (frames after the original range end). The trim never
// eats into the range body — the scan starts at rangeEndFrame.
const std::size_t tailFrames = totalFrames - rangeEndFrame;
const std::vector<reasampler::AudioSample> tailPcm =
extractFloatFrames(bytes, layout, rangeEndFrame, tailFrames);
if (tailPcm.empty()) return kNoTrim;
const float threshold = static_cast<float>(reasampler::autoTrimEndRatio());
const std::size_t lastAbove = reasampler::lastFrameAboveThreshold(
tailPcm, layout.channelCount, tailFrames, threshold);
// keptFrames: the total frame count the trimmed file retains.
// no audible tail frame -> trim back to the range end (rangeEndFrame frames)
// an audible frame at idx -> keep range body + up to and including that frame
// The "signal never falls below threshold" case falls out naturally: lastAbove is
// the final tail frame, so keptFrames == totalFrames (the full window is kept).
std::size_t keptFrames;
if (lastAbove == reasampler::kNoFrameAboveThreshold) {
keptFrames = rangeEndFrame;
} else {
keptFrames = rangeEndFrame + (lastAbove + 1);
}
if (keptFrames >= totalFrames) return kNoTrim; // full window kept -> no truncate
const reasampler::WavTruncatePlan plan = planWavTruncate(layout, keptFrames);
if (!plan.valid) return kNoTrim;
// Patch the RIFF + data size fields in the in-memory buffer so they describe the
// kept frame count, then rewrite the file as exactly the first newFileByteLength
// bytes (header + patched sizes + retained PCM). A single truncating write is the
// simplest correct truncate — no separate resize step, no partial-write window
// where the on-disk sizes and length disagree. The result is a valid, playable WAV
// of the kept frames (verified by the wav_trim re-parse test).
writeU32LE(bytes, plan.dataSizeFieldOffset, plan.newDataSize);
writeU32LE(bytes, plan.riffSizeFieldOffset, plan.newRiffSize);
// NOTE (DAW-verify, best-effort): a truncating write that fails MID-write (a full
// disk, a yanked drive) would leave a short file while we return kNoTrim, so the
// Sample length would overstate the file. Vanishingly unlikely for a just-recorded
// local bank file, and realtime tail is a convenience path, so a temp-file+atomic-
// rename is not warranted here; flagged rather than built.
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out) return kNoTrim; // could not reopen to rewrite — leave the full file
out.write(reinterpret_cast<const char*>(bytes.data()),
static_cast<std::streamsize>(plan.newFileByteLength));
if (!out) return kNoTrim;
out.close();
// The trimmed length in seconds for the Sample metadata.
return static_cast<double>(keptFrames) / static_cast<double>(layout.sampleRate);
}
// Builds a CaptureResult for a finalized recording: discover the recorded file,
// move it into the bank, populate the Sample via the pure mapping. Returns Ok +
// Sample on success, or a RenderFailed result. Does NOT restore — the caller
// restores unconditionally afterward (finalize + restore are separate steps so a
// finalize failure still restores).
CaptureResult finalizeRecording(RealtimeCaptureState& st) {
CaptureResult result;
const std::string recorded = normSlashes(recordedFilePath(st.temp_));
if (recorded.empty() || !std::filesystem::exists(recorded)) {
result.status = CaptureStatus::RenderFailed;
result.message = "Realtime record produced no file (check transport/record "
"settings in the DAW).";
return result;
}
std::error_code ec;
std::filesystem::create_directories(st.paths_.absoluteDir, ec);
const std::string destPath = st.paths_.absoluteDir + "/" + st.paths_.fileName;
std::filesystem::rename(recorded, destPath, ec);
if (ec) {
// Cross-volume rename can fail; fall back to copy+remove.
ec.clear();
std::filesystem::copy_file(
recorded, destPath,
std::filesystem::copy_options::overwrite_existing, ec);
if (ec) {
result.status = CaptureStatus::RenderFailed;
result.message = "Recorded file could not be moved into the bank: " +
ec.message();
return result;
}
std::error_code rmEc;
std::filesystem::remove(recorded, rmEc); // best-effort
}
// TAIL (Auto): trim the trailing decay of the recorded window in place — on the
// BANK file we now own (destPath), never the project. Best-effort: an unreadable /
// unknown-format / short file skips the trim (keeps the full window) rather than
// corrupt the capture. Only Auto trims; None recorded exact bounds and Manual is a
// fixed window (spec §The realtime path). Returns the trimmed length in seconds,
// or < 0 for "no trim applied".
double trimmedLenSeconds = -1.0;
if (st.request_.tailMode == TailMode::Auto) {
trimmedLenSeconds = trimAutoTailInPlace(destPath,
st.request_.startSeconds,
st.request_.endSeconds);
}
RecordedCapture cap;
cap.relativePath = st.paths_.relativePath;
cap.uniqueTag = st.uniqueTag_;
cap.sourceMode = SourceMode::Realtime;
cap.startSeconds = st.request_.startSeconds;
cap.endSeconds = st.request_.endSeconds;
cap.wetDry = st.request_.wetDry;
cap.displayName = st.request_.baseName;
cap.trackGuids = st.request_.trackGuids;
cap.channelCount = st.request_.channelCount;
cap.sampleRate = (st.request_.sampleRate > 0)
? st.request_.sampleRate
: static_cast<int>(GetSetProjectInfo(st.proj_, "PROJECT_SRATE", 0.0, false));
cap.captureTempo = Master_GetTempo();
// Time signature at the record range's START (L7 F1). TimeMap_GetTimeSigAtTime
// (reaper_plugin_functions.h:7130) reads the meter effective at that project time;
// proj=st.proj_ pins the recording's own project. tempoOut ignored (captureTempo is
// the master tempo above). Leaves 0/0 (unstamped) on any failure.
{
int tsNum = 0, tsDenom = 0;
double tsTempo = 0.0;
TimeMap_GetTimeSigAtTime(st.proj_, st.request_.startSeconds, &tsNum, &tsDenom, &tsTempo);
cap.captureTimeSigNum = tsNum;
cap.captureTimeSigDenom = tsDenom;
}
cap.createdTimestamp = static_cast<std::int64_t>(std::time(nullptr));
result.status = CaptureStatus::Ok;
result.sample = sampleFromRecordedCapture(cap);
// Content hash: WAV-aware FNV-1a over the (possibly trimmed) bank file's fmt+data
// chunks so hashReferencedElsewhere can identify copies in other banks and suppress
// the last-reference confirm when another bank still holds the same file. Using
// hashWavContent (not the raw hashBytes) skips render-varying metadata chunks
// (bext origination timestamp, iXML, LIST/INFO, etc.) so two records of identical
// audio collapse to the same hash. Best-effort: an unreadable file leaves
// contentHash empty — the safe, confirm-eliciting direction (bank_model treats
// "" as non-participating).
{
const std::vector<std::uint8_t> fileBytes = readFileBytes(destPath);
if (!fileBytes.empty()) {
result.sample.contentHash = hashWavContent(fileBytes);
}
}
// The recorded file's true length differs from the request range when a tail was
// recorded, so the Sample length must reflect the FILE, not the range:
// Auto with a trim applied -> the trimmed length trimAutoTailInPlace returned.
// Auto with no trim, or Manual -> the full recorded window (end - start).
// None -> the exact range (unchanged; recordWindowEnd_ == endSeconds).
// sampleFromRecordedCapture already set lengthSeconds = end - start; override it
// to the recorded/trimmed length so downstream (thumbnail, placement) matches disk.
if (trimmedLenSeconds >= 0.0) {
result.sample.lengthSeconds = trimmedLenSeconds;
} else {
result.sample.lengthSeconds =
st.recordWindowEnd_ - st.request_.startSeconds;
}
result.message = "Realtime-captured [" +
std::to_string(st.request_.startSeconds) + "s, " +
std::to_string(st.request_.endSeconds) + "s] (recorded " +
std::to_string(result.sample.lengthSeconds) + "s) -> " +
st.paths_.relativePath;
return result;
}
} // namespace
// The FILE-SIDE finalize half (recorded-file discovery, move-into-bank, the
// Auto-tail PCM decay-scan trim, and the finished-Sample population) lives in
// capture_realtime_finalize.cpp (T4-08). This TU owns only the async lifecycle.
// ============================================================================
// begin — start the record, snapshot, return immediately (no UI block)
@@ -625,7 +369,7 @@ RealtimeRecordBackend::begin(const CaptureRequest& request,
RealtimeCaptureHandle st(new RealtimeCaptureState());
st->proj_ = proj;
st->request_ = request;
st->uniqueTag_ = makeUniqueTag();
st->uniqueTag_ = makeUniqueTag("rt-"); // shared mint (T1-11 monotonic counter)
st->paths_ = deriveBankPaths(projectDir, request.baseName, st->uniqueTag_);
// The recorded window end: extended past the range end for a tail mode (Auto/Manual),
@@ -788,7 +532,9 @@ RealtimeTickResult RealtimeRecordBackend::tick(RealtimeCaptureState& state) {
// ALL snapshotted state — the non-destructive gate, idempotent + unconditional.
CaptureResult res;
if (state.phase_ == RecordPhase::Done) {
res = finalizeRecording(state);
res = finalizeRecording(state.proj_, state.temp_, state.request_,
state.paths_, state.uniqueTag_,
state.recordWindowEnd_);
} else {
res.status = CaptureStatus::RenderFailed;
res.message = "Realtime record timed out waiting for the recorded file to "
@@ -844,7 +590,9 @@ RealtimeTickResult RealtimeRecordBackend::abort(RealtimeCaptureState& state) {
// is the one that must be flush-safe.
state.stopOwnTransport();
CaptureResult res = finalizeRecording(state);
CaptureResult res = finalizeRecording(state.proj_, state.temp_, state.request_,
state.paths_, state.uniqueTag_,
state.recordWindowEnd_);
state.markFinalized();
state.restore(); // the non-destructive gate — always runs
@@ -855,4 +603,4 @@ RealtimeTickResult RealtimeRecordBackend::abort(RealtimeCaptureState& state) {
return out;
}
} // namespace reasampler
} // namespace reasampler::capture
+101
View File
@@ -0,0 +1,101 @@
// realtime_lifecycle.cpp — the in-flight realtime-capture state machine + globals
// (Q-W3 hoist out of main.cpp; the code moved verbatim, the session threaded as a
// parameter). See the header.
//
// Compiled into the reaper_reasampler MODULE. Includes reaper_plugin_functions.h
// WITHOUT REAPERAPI_IMPLEMENT — main.cpp is the one TU that defines the API
// pointers; here they are extern (CLAUDE.md §contract).
#include "shell/capture/realtime_lifecycle.h"
#include "persist.h" // ReaSamplerSession
#define REAPERAPI_MINIMAL
#define REAPERAPI_WANT_EnumProjects
#define REAPERAPI_WANT_ShowConsoleMsg
#include "reaper_plugin_functions.h"
namespace reasampler::capture {
// --- M8 in-flight realtime capture (async, timer-driven) --------------------
RealtimeRecordBackend g_rtBackend;
RealtimeCaptureHandle g_rtCapture;
ReaProject* g_rtCaptureProject = nullptr;
// Commit a finished realtime capture (a Done tick/abort with an Ok result): add the
// Sample to the ACTIVE bank (session.bank() resolves to book.activeIndex() — B2),
// persist + MarkProjectDirty. Shared by the tick-completion path and the abort
// paths. On a non-Ok result, logs the failure only.
void CommitRealtimeResult(ReaSamplerSession& session, const CaptureResult& res)
{
if (res.status != CaptureStatus::Ok)
{
ShowConsoleMsg(("ReaSampler realtime capture failed: " + res.message + "\n").c_str());
return;
}
session.bank().add(res.sample);
// B-cap: record the file the capture created in the owned-file manifest, at the same
// point the Sample is added and before the same persist. Recorded regardless of the
// index AddResult — even a hash-collapse still WROTE a file the tool owns, and the
// manifest dedups a repeat path itself (Phase R prune reconciles manifest vs index).
session.owned().add(res.sample.relativePath);
// S9: a capture add changes what a live instance could play (a new sample landed in the
// active bank) -> bump before the persist so the stamped generation refreshes instances.
session.bumpBankGeneration();
session.saveToActiveProject(); // persist book + manifest + generation + MarkProjectDirty (travels with .rpp)
}
// Advance any in-flight realtime capture one tick. Cheap when none is running (a
// null check) and fast even mid-record (tick() only reads the transport until the
// terminal tick). Detects a project switch mid-capture and aborts+restores so the
// capture never leaks across projects. Called from OnTimer BEFORE session.poll() so
// poll's project-switch handling sees a cleaned-up project.
void DriveRealtimeCapture(ReaSamplerSession& session)
{
if (!g_rtCapture) return;
// Project switch guard: if the active project is no longer the one the capture
// belongs to, a new/other project became active mid-record — abort + restore
// (into the ORIGINAL project the state is bound to) and drop it. Do NOT finalize
// into the new project.
ReaProject* active = EnumProjects(-1, nullptr, 0);
if (active != g_rtCaptureProject)
{
RealtimeTickResult r = g_rtBackend.abort(*g_rtCapture);
// Only commit if the ORIGINAL project is still open and active would be it —
// on a switch we restored into the original but must not persist into the
// now-active foreign project. Log the outcome without persisting. On a Failed
// abort surface abort()'s own message — it distinguishes a clean tab-switch
// abort from the closed-project DROP (the captured project was closed mid-record,
// review §1: nothing restored because the pointers were already freed).
if (r.status == RealtimeTickStatus::Done)
ShowConsoleMsg("ReaSampler realtime capture: project switched mid-record -- "
"captured audio restored into the original project; not "
"persisted to avoid crossing projects.\n");
else
ShowConsoleMsg(("ReaSampler realtime capture: project changed mid-record -- " +
r.result.message + "\n").c_str());
g_rtCapture.reset();
g_rtCaptureProject = nullptr;
return;
}
RealtimeTickResult r = g_rtBackend.tick(*g_rtCapture);
if (r.status == RealtimeTickStatus::InProgress) return;
// Terminal (Done or Failed): commit/log and drop the in-flight state.
CommitRealtimeResult(session, r.result);
g_rtCapture.reset();
g_rtCaptureProject = nullptr;
}
void AbortRealtimeCaptureForUnload(ReaSamplerSession& session)
{
if (!g_rtCapture) return;
RealtimeTickResult r = g_rtBackend.abort(*g_rtCapture);
CommitRealtimeResult(session, r.result);
g_rtCapture.reset();
g_rtCaptureProject = nullptr;
}
} // namespace reasampler::capture
+56
View File
@@ -0,0 +1,56 @@
#pragma once
// realtime_lifecycle — the in-flight realtime-capture state machine + globals
// (Q-W3 hoist out of main.cpp). A realtime record spans many timer ticks (it takes
// end-start wall-clock seconds and must NOT block REAPER's UI): the action STARTS
// it (capture_orchestrator::RunCaptureRealtimeTrack -> g_rtBackend.begin), OnTimer
// drives it here (DriveRealtimeCapture -> g_rtBackend.tick) each tick until a
// terminal verdict, then the handle is cleared.
//
// The three globals are EXPOSED (extern) rather than wrapped: the action bodies in
// capture_orchestrator manipulate them exactly as main.cpp did (zero-behavior-change
// move), and — load-bearing (CONTEXT.md §Phase Q hot-path guardrail) — the timer's
// IDLE FAST-PATH stays a SINGLE POINTER TEST at the call site:
// if (capture::g_rtCapture) capture::DriveRealtimeCapture(g_session);
// No per-tick cross-TU call, no accessor indirection, when nothing is recording.
//
// REAPER-facing: the .cpp includes reaper_plugin_functions.h WITHOUT
// REAPERAPI_IMPLEMENT (main.cpp owns the API pointers — CLAUDE.md §contract).
#include "shell/capture/capture.h" // RealtimeRecordBackend / RealtimeCaptureHandle
namespace reasampler {
class ReaSamplerSession;
}
namespace reasampler::capture {
// The realtime backend + the in-flight capture handle. Non-null handle == a
// capture is in progress (used to reject a second one, to drive the per-tick
// advance, and to abort on project switch / unload).
extern RealtimeRecordBackend g_rtBackend;
extern RealtimeCaptureHandle g_rtCapture;
// The ReaProject* the in-flight capture belongs to (opaque, compare-only) — lets
// OnTimer detect a project switch mid-capture and abort+restore rather than leak the
// temp track/arm/transport into or across projects. Only meaningful when
// g_rtCapture != nullptr.
extern ReaProject* g_rtCaptureProject;
// Commit a finished realtime capture (a Done tick/abort with an Ok result): add the
// Sample to the ACTIVE bank, record the owned file, bump the generation, persist +
// MarkProjectDirty. On a non-Ok result, logs the failure only.
void CommitRealtimeResult(ReaSamplerSession& session, const CaptureResult& res);
// Advance any in-flight realtime capture one tick. Cheap when none is running (a
// null check — though the caller already guards, see the header note) and fast even
// mid-record. Detects a project switch mid-capture and aborts+restores so the
// capture never leaks across projects. Called from OnTimer BEFORE session.poll().
void DriveRealtimeCapture(ReaSamplerSession& session);
// Unload teardown: abort any in-flight capture while the API pointers are still
// live — finalize-or-abort + restore so we never leave a temp track, an armed
// track, or an altered transport/cursor in the user's project on unload. Commits
// whatever was captured (best effort) before tearing down. No-op when idle.
void AbortRealtimeCaptureForUnload(ReaSamplerSession& session);
} // namespace reasampler::capture
+242
View File
@@ -0,0 +1,242 @@
// scope_resolve.cpp — scope/source resolution for the capture action family
// (Q-W3 hoist out of main.cpp; the code moved verbatim, session state threaded as
// parameters). See the header.
//
// Compiled into the reaper_reasampler MODULE. Includes reaper_plugin_functions.h
// WITHOUT REAPERAPI_IMPLEMENT — main.cpp is the one TU that defines the API
// pointers; here they are extern (CLAUDE.md §contract).
#include "shell/capture/scope_resolve.h"
#include <filesystem> // project-dir derivation for provenance parent resolution
#include <utility>
#include "shell/capture/provenance_shell.h" // fxChainIdentity* / *SourceFiles / bankFileRefs
#include "shell/capture/track_guid.h" // guidString
#define REAPERAPI_MINIMAL
#define REAPERAPI_WANT_GetSet_LoopTimeRange
#define REAPERAPI_WANT_CountTracks
#define REAPERAPI_WANT_GetTrack
#define REAPERAPI_WANT_GetSetMediaTrackInfo_String
#define REAPERAPI_WANT_EnumProjects
#define REAPERAPI_WANT_CountSelectedMediaItems
#define REAPERAPI_WANT_GetSelectedMediaItem
#define REAPERAPI_WANT_GetMediaItem_Track
#define REAPERAPI_WANT_CountSelectedTracks
#define REAPERAPI_WANT_GetSelectedTrack
#include "reaper_plugin_functions.h"
namespace reasampler::capture {
namespace {
// Time selection -> exact bounds (no rounding). GetSet_LoopTimeRange(isSet=false,
// isLoop=false) reads the current time selection.
bool resolveTimeSelection(double& start, double& end)
{
start = 0.0; end = 0.0;
GetSet_LoopTimeRange(false, false, &start, &end, false);
return end > start;
}
// Maps a capture FX scope onto the pure provenance scope (kept decoupled so the
// pure provenance module does not depend on render_settings).
model::ProvenanceScope provenanceScopeFor(CaptureScope scope)
{
return scope == CaptureScope::Item ? model::ProvenanceScope::Item
: model::ProvenanceScope::Track;
}
// Collects the tracks that own the selected items (Item scope) into
// out.sourceTracks (deduped) — these are the tracks whose FX must be bypassed so an
// item capture hears take/item FX only. GetMediaItem_Track(item) gives the owning
// track (SDK header, verify). GUIDs recorded for provenance.
bool collectSelectedItemTracks(ResolvedSource& out)
{
const int n = CountSelectedMediaItems(nullptr);
if (n <= 0) return false;
for (int i = 0; i < n; ++i)
{
MediaItem* it = GetSelectedMediaItem(nullptr, i);
if (!it) continue;
MediaTrack* tr = GetMediaItem_Track(it);
if (!tr) continue;
// Dedup: several selected items can share a track.
bool seen = false;
for (MediaTrack* t : out.sourceTracks) if (t == tr) { seen = true; break; }
if (seen) continue;
out.sourceTracks.push_back(tr);
std::string g = guidString(tr);
if (!g.empty()) out.trackGuids.push_back(std::move(g));
}
return !out.sourceTracks.empty();
}
} // namespace
// Reads every track's P_RAZOREDITS (SDK header ~2899: space-separated triples of
// start, end, envGuidString), parses the track-audio areas (pure parseRazorEdits),
// and returns the union bound. Reads only — never clears the razor selection.
// Returns false when no track-audio razor area exists on any track.
bool resolveRazorRange(double& start, double& end)
{
std::vector<RazorRange> allRanges;
const int n = CountTracks(nullptr);
for (int i = 0; i < n; ++i)
{
MediaTrack* tr = GetTrack(nullptr, i);
if (!tr) continue;
std::vector<char> buf(8192, '\0');
if (!GetSetMediaTrackInfo_String(tr, "P_RAZOREDITS", buf.data(), false))
continue;
std::vector<RazorRange> ranges = parseRazorEdits(std::string(buf.data()));
for (auto& r : ranges) allRanges.push_back(r);
}
if (allRanges.empty()) return false;
RazorRange u = razorUnionBounds(allRanges);
start = u.startSeconds;
end = u.endSeconds;
return end > start;
}
// Infers the render RANGE for any scope: razor union when a razor area is present,
// else the time selection (pure inferRangeSource decides which). Orthogonal to
// scope. Returns false (with a reason) when neither yields a non-empty range.
bool resolveRange(double& start, double& end, std::string& why)
{
double rzStart = 0.0, rzEnd = 0.0;
const bool hasRazor = resolveRazorRange(rzStart, rzEnd);
if (inferRangeSource(hasRazor) == RangeSource::Razor)
{
start = rzStart; end = rzEnd;
return true; // resolveRazorRange already verified end > start
}
if (resolveTimeSelection(start, end)) return true;
why = "make a razor area or a time selection first";
return false;
}
// Collects the selected tracks (Track scope) into out.sourceTracks + GUIDs.
bool collectSelectedTracks(ResolvedSource& out)
{
const int n = CountSelectedTracks(nullptr); // nullptr = active project
if (n <= 0) return false;
for (int i = 0; i < n; ++i)
{
MediaTrack* tr = GetSelectedTrack(nullptr, i);
if (!tr) continue;
out.sourceTracks.push_back(tr);
std::string g = guidString(tr);
if (!g.empty()) out.trackGuids.push_back(std::move(g));
}
return !out.sourceTracks.empty();
}
// Resolves the source for a scope: the selection tracks (item/track), plus the
// inferred range. Returns false with a reason on nothing to do.
bool ResolveScopeSource(CaptureScope scope, ResolvedSource& out, std::string& why)
{
switch (scope)
{
case CaptureScope::Item:
if (!collectSelectedItemTracks(out)) {
why = "select at least one media item"; return false;
}
break;
case CaptureScope::Track:
if (!collectSelectedTracks(out)) {
why = "select at least one track"; return false;
}
break;
}
return resolveRange(out.startSeconds, out.endSeconds, why);
}
// Current project's directory (parent of its .rpp), forward-slashed, no trailing
// slash — the same derivation capture.cpp does internally, needed here so M10 can
// resolve the bank's relative paths to absolute for parent detection. Empty for an
// unsaved project (EnumProjects writes an empty .rpp path), which makes every bank
// file resolve empty -> no false parentage. Read-only; mutates nothing.
std::string currentProjectDir()
{
std::vector<char> buf(4096, '\0');
EnumProjects(-1, buf.data(), static_cast<int>(buf.size()));
const std::string rpp(buf.data());
if (rpp.empty()) return {};
namespace fs = std::filesystem;
std::string dir = fs::path(rpp).parent_path().string();
for (char& c : dir) if (c == '\\') c = '/';
if (dir.size() > 1 && dir.back() == '/') dir.pop_back();
return dir;
}
// Builds the M10 provenance for a capture IF it genuinely resamples from a bank
// sample, else returns nullopt (the common, non-resample case). Detection rule
// (stated honestly): the capture's source item media file(s) must all resolve, by
// exact normalized absolute path, to ONE bank sample's file (detectParent). On a
// match, records that sample's id as the parent plus a THIN capture-recipe
// fingerprint (P1=a) — scope + source mode + exact range + tail + rate + channels +
// source track GUIDs + the in-scope source FX-chain identity — so "re-capture from
// source" can replay the request and report drift. NEVER a serialized chain to
// restore. Item scope reads the active take's TakeFX chain (via TakeFX_*) per
// selected item, combined in item order; Track scope reads the track FX chain.
std::optional<model::Provenance> buildCaptureProvenance(
const BankBook& book, const CaptureRequest& req,
CaptureScope scope, const ResolvedSource& src)
{
const std::string projectDir = currentProjectDir();
const std::vector<model::BankFileRef> bankFiles = bankFileRefs(book, projectDir);
// The "what audio is being captured" source set depends on scope: item scope uses
// the SELECTED items (the user picked them); track scope uses the range-overlapping
// items ON the source tracks (the user picked the track, not the item).
const std::vector<std::string> sourceFiles =
scope == CaptureScope::Item
? selectedItemSourceFiles()
: trackItemSourceFiles(src.sourceTracks, req.startSeconds,
req.endSeconds);
const std::optional<std::string> parentId =
model::detectParent(sourceFiles, bankFiles);
if (!parentId) return std::nullopt; // not a resample-from-sample — no provenance
model::CaptureRecipe recipe;
recipe.scope = provenanceScopeFor(scope);
recipe.sourceMode = static_cast<int>(req.sourceMode);
recipe.startSeconds = req.startSeconds;
recipe.endSeconds = req.endSeconds;
recipe.tailMode = static_cast<int>(req.tailMode);
recipe.tailMs = req.tailMs;
recipe.sampleRate = req.sampleRate;
recipe.channelCount = req.channelCount;
recipe.trackGuids = req.trackGuids;
// The in-scope FX-chain identity:
// Track scope — per-track chains combined in track order (TrackFX_*).
// Item scope — per-item active-take chains combined in item order (TakeFX_*);
// the owning track's FX chain is OUT OF SCOPE for an item capture and must
// not be fingerprinted here (it is bypassed during render, not heard).
if (scope == CaptureScope::Item) {
const int n = CountSelectedMediaItems(nullptr);
std::vector<MediaItem*> items;
items.reserve(static_cast<std::size_t>(n < 0 ? 0 : n));
for (int i = 0; i < n; ++i) {
MediaItem* it = GetSelectedMediaItem(nullptr, i);
if (it) items.push_back(it);
}
recipe.fxChainIdentity = fxChainIdentityForItems(items);
} else {
std::vector<std::string> perTrack;
perTrack.reserve(src.sourceTracks.size());
for (MediaTrack* tr : src.sourceTracks)
perTrack.push_back(fxChainIdentityForTrack(tr));
recipe.fxChainIdentity = model::combineChainIdentities(perTrack);
}
model::Provenance prov;
prov.parentSampleId = *parentId;
prov.fxChainSnapshot = model::buildFingerprint(recipe);
return prov;
}
} // namespace reasampler::capture
+71
View File
@@ -0,0 +1,71 @@
#pragma once
// scope_resolve — scope/source resolution for the capture action family (Q-W3
// hoist out of main.cpp). The three concerns every capture entry point shares:
// * RANGE inference — razor union else time selection (razor-else-time),
// orthogonal to scope;
// * SOURCE-TRACK collection — the selected tracks (Track scope) or the selected
// items' owning tracks (Item scope), deduped, with canonical GUIDs;
// * PROVENANCE ASSEMBLY inputs — the M10 resample-from-sample detection + the
// thin capture-recipe fingerprint built from the LIVE (un-bypassed) chain.
//
// All reads are non-destructive: selection, razor, and time selection are read,
// never mutated. REAPER-facing: the .cpp includes reaper_plugin_functions.h
// WITHOUT REAPERAPI_IMPLEMENT (main.cpp owns the API pointers — CLAUDE.md
// §contract). MediaTrack is forward-declared (via capture.h) so this header stays
// SDK-lite.
#include <optional>
#include <string>
#include <vector>
#include "shell/capture/capture.h" // CaptureRequest, MediaTrack fwd
#include "core/capture/render_settings.h" // CaptureScope
#include "core/model/provenance.h" // model::Provenance
namespace reasampler {
class BankBook;
}
namespace reasampler::capture {
// The resolved source: exact bounds + the source tracks (for FX-bypass + Sample
// provenance GUIDs). `sourceTracks` holds the item-owning tracks (Item scope) or the
// selected tracks (Track scope).
struct ResolvedSource
{
double startSeconds = 0.0;
double endSeconds = 0.0;
std::vector<MediaTrack*> sourceTracks; // item-owning tracks / selected tracks
std::vector<std::string> trackGuids; // canonical GUIDs of sourceTracks
};
// Reads every track's P_RAZOREDITS, parses the track-audio areas (pure
// parseRazorEdits), and returns the union bound. Reads only — never clears the
// razor selection. Returns false when no track-audio razor area exists on any track.
bool resolveRazorRange(double& start, double& end);
// Infers the render RANGE for any scope: razor union when a razor area is present,
// else the time selection (pure inferRangeSource decides which). Orthogonal to
// scope. Returns false (with a reason) when neither yields a non-empty range.
bool resolveRange(double& start, double& end, std::string& why);
// Collects the selected tracks (Track scope) into out.sourceTracks + GUIDs.
bool collectSelectedTracks(ResolvedSource& out);
// Resolves the source for a scope: the selection tracks (item/track), plus the
// inferred range. Returns false with a reason on nothing to do.
bool ResolveScopeSource(CaptureScope scope, ResolvedSource& out, std::string& why);
// Current project's directory (parent of its .rpp), forward-slashed, no trailing
// slash. Empty for an unsaved project (no false parentage). Read-only.
std::string currentProjectDir();
// Builds the M10 provenance for a capture IF it genuinely resamples from a bank
// sample (detectParent over `book`'s resolved file refs), else returns nullopt (the
// common, non-resample case). Must run BEFORE the FxBypassGuard neutralizes the
// in-scope chain — the source FX-chain identity is read from the LIVE chain.
std::optional<model::Provenance> buildCaptureProvenance(
const BankBook& book, const CaptureRequest& req,
CaptureScope scope, const ResolvedSource& src);
} // namespace reasampler::capture