Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(feat) count in metronome

Egor Khindikaynene832d0b709b1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dc81f6b6..5cfd56e6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -58,6 +58,11 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
keeps its trim and warp. Right-click a column header, a slot or the empty grid to add an
instrument, audio or return track (or rename / delete one). All of it is saved with the
project and reachable over MCP.
+- **Count-in:** right-click the metronome button to set 1, 2 or 4 bars of clicks before
+ playback starts. Play and Record from stop count in first — the clicks sound even with the
+ metronome off, the position readout counts −2.1 … −1.4 up to the start, and Stop cancels it.
+ A take begins when the transport rolls, so the count-in is never recorded; exports and
+ freezes never count in. The setting is remembered across sessions.
### Changed
- **Import audio** moved to ⌘⇧I — ⌘I now inserts a scene in the Session view. Launch
diff --git a/src/managed/Nota.App/MainWindow.axaml b/src/managed/Nota.App/MainWindow.axaml
index 3bf05430..43416feb 100644
--- a/src/managed/Nota.App/MainWindow.axaml
+++ b/src/managed/Nota.App/MainWindow.axaml
@@ -225,7 +225,9 @@
engaged state turns the glyph brass through the base ToggleButton:checked. -->
<StackPanel Grid.Column="3" Orientation="Horizontal" Spacing="4" VerticalAlignment="Center" Margin="14,0,0,0">
<!-- Metronome: body, pendulum rod, weight -->
- <ToggleButton Classes="tp-icon" IsChecked="{Binding Transport.MetronomeOn}" ToolTip.Tip="Turn the metronome on or off (M)">
+ <ToggleButton x:Name="MetronomeBtn" Classes="tp-icon" IsChecked="{Binding Transport.MetronomeOn}"
+ ContextRequested="OnMetronomeContext"
+ ToolTip.Tip="Turn the metronome on or off (M) · right-click for count-in">
<Viewbox Width="15" Height="15">
<Canvas Width="24" Height="24">
<Path Stroke="{Binding $parent[ToggleButton].Foreground}" StrokeThickness="1.7"
diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.cs
index 13c0bc24..ca30a0c5 100644
--- a/src/managed/Nota.App/MainWindow.axaml.cs
+++ b/src/managed/Nota.App/MainWindow.axaml.cs
@@ -291,6 +291,7 @@ public partial class MainWindow : Window
// Arrangement view options (View menu) persist the same way.
Timeline.ClipLabels = (ClipLabelMode)Math.Clamp(vm.Settings.Current.ArrangementClipLabels, 0, 2);
Timeline.ShowSections = vm.Settings.Current.ArrangementShowSections;
+ vm.Transport.CountInBars = Math.Clamp(vm.Settings.Current.CountInBars, 0, 4);
Timeline.Waveform = (WaveformStyle)Math.Clamp(vm.Settings.Current.ArrangementWaveform, 0, 1);
// Settings → Appearance can switch the waveform style while the arrangement is open.
vm.Settings.Changed += () => Timeline.Waveform = (WaveformStyle)Math.Clamp(vm.Settings.Current.ArrangementWaveform, 0, 1);
@@ -565,6 +566,30 @@ public partial class MainWindow : Window
KeyLabel.BindResource(TextBlock.ForegroundProperty, k is null ? "Brush.TextTertiary" : "Brush.TextPrimary");
}
+ private static readonly (int Bars, string Label)[] CountInSteps =
+ [(0, "No count-in"), (1, "Count-in: 1 bar"), (2, "Count-in: 2 bars"), (4, "Count-in: 4 bars")];
+
+ // Right-click on the metronome: how many bars of clicks precede Play / Record from stop.
+ // The count-in sounds whether or not the metronome itself is on.
+ private void OnMetronomeContext(object? sender, ContextRequestedEventArgs e)
+ {
+ e.Handled = true;
+ if (_vm is not { } vm) return;
+ var f = new MenuFlyout();
+ foreach (var (bars, label) in CountInSteps)
+ {
+ var mi = new MenuItem { Header = label, ToggleType = MenuItemToggleType.Radio, IsChecked = vm.Transport.CountInBars == bars };
+ mi.Click += (_, _) =>
+ {
+ vm.Transport.CountInBars = bars;
+ vm.Settings.Current.CountInBars = bars;
+ vm.Settings.Save();
+ };
+ f.Items.Add(mi);
+ }
+ f.ShowAt(MetronomeBtn);
+ }
+
private void OnCycleSnap(object? sender, RoutedEventArgs e)
{
_snapIndex = (_snapIndex + 1) % SnapSteps.Length;
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index 3d21bc02..4d57d981 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -1039,6 +1039,7 @@ public sealed partial class PreferencesWindow : NotaWindow
("MOUSE", new[]
{
("Double-click clip", "Open in the clip editor"),
+ ("Right-click the metronome", "Count-in before Play / Record: off · 1 · 2 · 4 bars"),
("Drag an audio clip's ADSR handle", "Shape attack · decay + sustain · release (top corners and the dot on hover) · double-click resets the stage"),
("⇧-click track header", "Add the track to the selection · again to remove it"),
("Right-click track headers", "A multi-selection gets its own menu: group, colour, freeze, copy, duplicate, delete"),
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index fa31d324..7d8a4f2f 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -22,6 +22,13 @@ public interface IAudioEngine : IDisposable
// --- Transport ---------------------------------------------------------
void Play();
+ /// <summary>Play, preceded by the count-in when one is set and the transport is stopped.
+ /// For user-initiated starts; exports / freezes use <see cref="Play"/>.</summary>
+ void PlayWithCountIn();
+ /// <summary>Count-in length in bars (0 = off). Also applies to Record started from stop.</summary>
+ void SetCountIn(int bars);
+ /// <summary>Beats of count-in still to click (0 = not counting in).</summary>
+ double CountInBeats { get; }
void StopTransport();
void SetBpm(double bpm);
double Bpm { get; }
diff --git a/src/managed/Nota.Application/Settings.cs b/src/managed/Nota.Application/Settings.cs
index 89835672..96710f01 100644
--- a/src/managed/Nota.Application/Settings.cs
+++ b/src/managed/Nota.Application/Settings.cs
@@ -36,6 +36,9 @@ public sealed class Settings
public bool ShowWelcomeOnStartup { get; set; } = true;
/// <summary>Record a project version on every save (the History tab). On by default.</summary>
public bool KeepVersionHistory { get; set; } = true;
+ /// <summary>Bars of metronome count-in before Play / Record from stop (0 = off). Set from
+ /// the metronome button's right-click menu.</summary>
+ public int CountInBars { get; set; }
/// <summary>Run the built-in MCP server so an AI (Claude Desktop / Claude Code) can drive the
/// live app. Off by default; loopback-only. Toggled in Preferences.</summary>
public bool McpEnabled { get; set; }
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
index 96938e28..a76b6e9d 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
@@ -69,6 +69,15 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_transport_set_loop")]
internal static partial NotaResult SetLoop(IntPtr engine, int enabled, double startBeat, double endBeat);
+ [LibraryImport(Lib, EntryPoint = "nota_transport_play_count_in")]
+ internal static partial NotaResult TransportPlayCountIn(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_transport_set_count_in")]
+ internal static partial NotaResult SetCountIn(IntPtr engine, int bars);
+
+ [LibraryImport(Lib, EntryPoint = "nota_transport_count_in_beats")]
+ internal static partial double CountInBeats(IntPtr engine);
+
[LibraryImport(Lib, EntryPoint = "nota_transport_set_metronome")]
internal static partial NotaResult SetMetronome(IntPtr engine, int enabled);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
index 8f00c877..ce9a72fe 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
@@ -67,6 +67,9 @@ public sealed partial class NotaEngine : IAudioEngine
// --- Transport ---------------------------------------------------------
public void Play() { ThrowIfDisposed(); Check(NativeMethods.TransportPlay(_handle)); }
+ public void PlayWithCountIn() { ThrowIfDisposed(); Check(NativeMethods.TransportPlayCountIn(_handle)); }
+ public void SetCountIn(int bars) { ThrowIfDisposed(); Check(NativeMethods.SetCountIn(_handle, Math.Max(0, bars))); }
+ public double CountInBeats { get { ThrowIfDisposed(); return NativeMethods.CountInBeats(_handle); } }
public void StopTransport() { ThrowIfDisposed(); Check(NativeMethods.TransportStop(_handle)); }
public void SetBpm(double bpm) { ThrowIfDisposed(); Check(NativeMethods.SetBpm(_handle, bpm)); }
public double Bpm { get { ThrowIfDisposed(); return NativeMethods.TransportBpm(_handle); } }
diff --git a/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs b/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs
index 8466bd59..4b6ca76e 100644
--- a/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs
+++ b/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs
@@ -33,6 +33,10 @@ public partial class TransportViewModel(IAudioEngine engine) : ObservableObject
[ObservableProperty] private double _masterVolume = 1.0;
[ObservableProperty] private string _masterDbText = "0.0\u2009dB";
[ObservableProperty] private bool _metronomeOn;
+ /// <summary>Bars of count-in before Play / Record from stop (0 = off).</summary>
+ [ObservableProperty] private int _countInBars;
+ /// <summary>The count-in is clicking (the transport hasn't rolled yet).</summary>
+ [ObservableProperty] private bool _isCountingIn;
[ObservableProperty] private bool _loopOn;
[ObservableProperty] private string _loopRangeText = "1.1 – 5.1";
[ObservableProperty] private bool _recordOn;
@@ -71,6 +75,7 @@ public partial class TransportViewModel(IAudioEngine engine) : ObservableObject
: (20.0 * Math.Log10(value)).ToString("0.0", CultureInfo.CurrentCulture) + "\u2009dB";
}
partial void OnMetronomeOnChanged(bool value) => _engine.SetMetronome(value);
+ partial void OnCountInBarsChanged(int value) => _engine.SetCountIn(value);
partial void OnLoopOnChanged(bool value)
{
@@ -135,19 +140,19 @@ public partial class TransportViewModel(IAudioEngine engine) : ObservableObject
[RelayCommand]
private void PlayStop()
{
- if (_engine.IsPlaying || RecordOn) StopAll();
- else _engine.Play();
+ if (_engine.IsPlaying || _engine.CountInBeats > 0 || RecordOn) StopAll();
+ else _engine.PlayWithCountIn();
}
[RelayCommand]
- private void Play() => _engine.Play();
+ private void Play() => _engine.PlayWithCountIn();
[RelayCommand]
private void Stop()
{
// First press stops (pause at position); a second press while already
// stopped returns the playhead to the start (1.1) — classic DAW behaviour.
- if (!_engine.IsPlaying && !RecordOn) { _engine.Seek(0); return; }
+ if (!_engine.IsPlaying && !RecordOn && _engine.CountInBeats <= 0) { _engine.Seek(0); return; }
StopAll();
}
@@ -170,6 +175,7 @@ public partial class TransportViewModel(IAudioEngine engine) : ObservableObject
public void ToggleTimeDisplay()
{
ShowTimeDisplay = !ShowTimeDisplay;
+ if (IsCountingIn) return; // the readout is showing the count-in; Tick restores it
PositionUnitText = ShowTimeDisplay ? "time" : "bars";
UpdatePositionText(_lastBeats); // reflect immediately, don't wait for the next tick
}
@@ -179,11 +185,27 @@ public partial class TransportViewModel(IAudioEngine engine) : ObservableObject
{
double beats = _engine.PositionBeats;
_lastBeats = beats;
- UpdatePositionText(beats);
- IsPlaying = _engine.IsPlaying;
+ double countIn = _engine.CountInBeats;
+ bool wasCounting = IsCountingIn;
+ IsCountingIn = countIn > 0;
+ if (IsCountingIn) PositionText = CountInText(countIn);
+ else UpdatePositionText(beats);
+ if (IsCountingIn != wasCounting) PositionUnitText = IsCountingIn ? "count-in" : ShowTimeDisplay ? "time" : "bars";
+ IsPlaying = _engine.IsPlaying || IsCountingIn; // the Play button lights from the first click
PlayLabel = IsPlaying ? "■ Stop" : "▶ Play";
}
+ /// <summary>The count-in as negative bars counting up to the start: −2.1 … −2.4, −1.1 … −1.4.</summary>
+ private string CountInText(double remainingBeats)
+ {
+ int bpb = Math.Max(1, TimeSigNumerator);
+ int left = (int)Math.Ceiling(remainingBeats - 1e-6); // beats left, the sounding one included
+ if (left < 1) left = 1;
+ int bar = (left + bpb - 1) / bpb;
+ int beat = bpb - (left - 1) % bpb;
+ return $"\u2212{bar}.{beat}";
+ }
+
private void UpdatePositionText(double beats)
{
if (ShowTimeDisplay)
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index 5b816555..23fb8b25 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -417,6 +417,12 @@ NOTA_API float nota_engine_cpu_load(const NotaEngine* engine);
/* ---- Transport (M1) ------------------------------------------------------ */
NOTA_API NotaResult nota_transport_play(NotaEngine* engine);
NOTA_API NotaResult nota_transport_stop(NotaEngine* engine);
+/* Count-in: `bars` of clicks (0 = off) before a play_count_in / a record started from
+ * stop rolls the transport. Plain nota_transport_play never counts in (exports etc.).
+ * count_in_beats = beats still to click (0 when not counting in). */
+NOTA_API NotaResult nota_transport_play_count_in(NotaEngine* engine);
+NOTA_API NotaResult nota_transport_set_count_in(NotaEngine* engine, int32_t bars);
+NOTA_API double nota_transport_count_in_beats(const NotaEngine* engine);
NOTA_API NotaResult nota_transport_set_bpm(NotaEngine* engine, double bpm);
NOTA_API double nota_transport_bpm(const NotaEngine* engine);
NOTA_API NotaResult nota_transport_set_time_signature(NotaEngine* engine, int32_t num, int32_t denom);
diff --git a/src/native/nota.engine/src/Engine.cpp b/src/native/nota.engine/src/Engine.cpp
index be938b02..f16b7cc7 100644
--- a/src/native/nota.engine/src/Engine.cpp
+++ b/src/native/nota.engine/src/Engine.cpp
@@ -389,6 +389,19 @@ void Engine::setFrequency(float hz) {
void Engine::playClock() { Command c; c.type = CommandType::TransportPlay; commands_.push(c); }
// Main Play (and arrangement record) roll the Arrangement; session launches use playClock().
void Engine::transportPlay() { arrangementActive_.store(true, std::memory_order_relaxed); playClock(); }
+// Play preceded by the count-in (when one is set and the transport is stopped). The audio
+// thread clicks it out and rolls the transport sample-accurately at its end.
+void Engine::transportPlayCountIn() {
+ if (uiCountIn_.load(std::memory_order_relaxed) > 0.0) return; // already counting in
+ const int32_t bars = countInBars();
+ if (bars <= 0 || transport_.uiIsPlaying()) { transportPlay(); return; }
+ arrangementActive_.store(true, std::memory_order_relaxed);
+ captureGate_.store(false, std::memory_order_relaxed);
+ // Mirror it now so a poll before the audio thread picks the command up already sees
+ // the count-in (Play pressed again = stop, not a second start).
+ uiCountIn_.store(static_cast<double>(bars) * transport_.beatsPerBar(), std::memory_order_relaxed);
+ Command c; c.type = CommandType::TransportPlay; c.i0 = bars; commands_.push(c);
+}
void Engine::transportStop() {
arrangementActive_.store(false, std::memory_order_relaxed);
finalizeSessionRecord(false); // don't lose an in-progress session take on a global stop
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index e09f1e60..9eb9f42d 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -23,6 +23,7 @@
#include "Transport.h"
#include "nota/nota_engine.h" // NotaNoteData
+#include <algorithm>
#include <array>
#include <atomic>
#include <functional>
@@ -261,6 +262,14 @@ public:
// --- transport (M1) ---
void transportPlay();
void transportStop();
+ // Count-in: N bars of clicks before the transport rolls (0 = off). Only a user Play
+ // (transportPlayCountIn) and a Record from stop use it — exports / freezes / session
+ // launches roll immediately. The clicks sound whether or not the metronome is on.
+ void setCountInBars(int32_t bars) { countInBars_.store(std::clamp(bars, 0, 8), std::memory_order_relaxed); }
+ int32_t countInBars() const { return countInBars_.load(std::memory_order_relaxed); }
+ void transportPlayCountIn();
+ // Beats of count-in still to click (0 = not counting in). UI poll.
+ double countInBeatsRemaining() const { return uiCountIn_.load(std::memory_order_relaxed); }
// Session vs Arrangement (M5): the Arrangement is "active" when the main Play (or an
// arrangement record) started it. Launching a Session clip starts the clock WITHOUT
// activating the Arrangement, so non-session tracks stay silent (session-only jam).
@@ -978,6 +987,10 @@ private:
// sampling by beat (frame = beat·frozenSpb) with linear interpolation.
void fillFrozen(Track& t, float* dst, int32_t frames, double blockStart, double spb);
void renderMetronome(float* out, int32_t numFrames, double blockStartSamples);
+ // Click the count-in for numFrames and advance it; true once it has run out.
+ bool renderCountIn(float* out, int32_t numFrames, double spb);
+ void endCountIn(); // audio thread: drop the count-in state and reopen the capture gate
+ void renderClick(float* out, int32_t i, int clickLen, double sr); // one sample of the click voice
void renderTone(float* out, int32_t numFrames);
void applyAutomation(Graph* g, double beat); // M9: eval lanes -> target atomics
@@ -1172,6 +1185,12 @@ private:
// Arrangement playback active (M5): true after main Play / arrangement record; false in a
// session-only jam. Read on the audio thread to gate arrangement clip content per track.
std::atomic<bool> arrangementActive_{false};
+ std::atomic<int32_t> countInBars_{0}; // count-in length setting (bars)
+ std::atomic<double> uiCountIn_{0.0}; // beats of count-in left (UI mirror)
+ // False while a count-in runs: takes started from stop don't capture the clicks-only
+ // pre-roll (the hardware tap and the internal-resampling tap both honour it).
+ std::atomic<bool> captureGate_{true};
+ bool recordCountIn_ = false; // setRecording → startAudioRecording: count-in pending
void playClock(); // push a TransportPlay command without touching arrangementActive_
void finalizeSessionRecord(bool relaunch); // materialise an in-progress session take
// Build a fresh graph with a new scene count, cloning tracks so slot vectors resize safely.
@@ -1246,6 +1265,10 @@ private:
double tonePhase_ = 0.0;
float toneLevel_ = 0.0f; // 0..1 fade so start/stop don't click
int64_t lastBeatEmitted_ = -1;
+ bool countInActive_ = false; // clicking the count-in; the transport starts when it runs out
+ double countInPos_ = 0.0; // beats clicked so far
+ double countInTotal_ = 0.0; // beats to click
+ int64_t lastCountInBeat_ = -1;
int clickRemaining_ = 0;
double clickPhase_ = 0.0;
double clickFreq_ = 1000.0;
diff --git a/src/native/nota.engine/src/Engine_Recording.cpp b/src/native/nota.engine/src/Engine_Recording.cpp
index e38960e6..363d96c8 100644
--- a/src/native/nota.engine/src/Engine_Recording.cpp
+++ b/src/native/nota.engine/src/Engine_Recording.cpp
@@ -71,7 +71,8 @@ bool Engine::ensureAudioInput() {
return input_->start([this](const float* s, int32_t n) {
if (n > inputBlockFrames_.load(std::memory_order_relaxed))
inputBlockFrames_.store(n, std::memory_order_relaxed);
- if (hwRecordTap_.load(std::memory_order_relaxed)) {
+ // The gate is shut while a count-in clicks: the take starts when the transport rolls.
+ if (hwRecordTap_.load(std::memory_order_relaxed) && captureGate_.load(std::memory_order_relaxed)) {
int64_t dropped = 0;
for (int32_t i = 0; i < n; ++i)
if (!inputQueue_.push(InputFrame{ s[i * 2], s[i * 2 + 1] })) ++dropped;
@@ -217,6 +218,9 @@ void Engine::setRecording(bool on) {
}
if (!audioT && !instT) { recording_.store(false, std::memory_order_relaxed); recordStartStatus_ = 1; return; }
+ // A take started from stop gets the count-in (if one is set); the capture taps stay
+ // gated until it runs out, so the clicks-only pre-roll isn't recorded.
+ recordCountIn_ = !wasPlaying && !recordSessionAudio_ && countInBars() > 0;
bool audioOk = true;
if (audioT) audioOk = startAudioRecording(audioT->id());
@@ -246,7 +250,10 @@ void Engine::setRecording(bool on) {
recordReturnBeat_ = playhead;
recordStartedTransport_ = !wasPlaying;
}
- if (!wasPlaying) transportPlay(); // roll so the take advances (idempotent if already rolling)
+ if (!wasPlaying) { // roll so the take advances (idempotent if already rolling)
+ if (recordCountIn_) transportPlayCountIn(); else transportPlay();
+ }
+ recordCountIn_ = false;
recordStartStatus_ = (audioT && !audioOk && !instT) ? 2 : 0;
}
@@ -353,7 +360,7 @@ bool Engine::startAudioRecording(int32_t trackId) {
recordReturnBeat_ = audioRecordStartBeat_;
recordStartedTransport_ = !transport_.uiIsPlaying();
}
- if (!transport_.uiIsPlaying()) transportPlay();
+ if (!transport_.uiIsPlaying() && !recordCountIn_) transportPlay();
return true;
}
@@ -371,7 +378,7 @@ bool Engine::startAudioRecording(int32_t trackId) {
recordReturnBeat_ = audioRecordStartBeat_;
recordStartedTransport_ = !transport_.uiIsPlaying();
}
- if (!transport_.uiIsPlaying()) transportPlay();
+ if (!transport_.uiIsPlaying() && !recordCountIn_) transportPlay(); // else setRecording counts in
return true;
}
diff --git a/src/native/nota.engine/src/Engine_Render.cpp b/src/native/nota.engine/src/Engine_Render.cpp
index 1562bf90..1e5040bd 100644
--- a/src/native/nota.engine/src/Engine_Render.cpp
+++ b/src/native/nota.engine/src/Engine_Render.cpp
@@ -216,14 +216,31 @@ void Engine::renderOffline(float* out, int32_t frames) {
processBlock(out, frames);
}
+void Engine::endCountIn() {
+ countInActive_ = false;
+ uiCountIn_.store(0.0, std::memory_order_relaxed);
+ captureGate_.store(true, std::memory_order_relaxed);
+}
+
void Engine::drainCommands() {
Command c;
while (commands_.pop(c)) {
switch (c.type) {
case CommandType::SetToneEnabled: toneEnabled_ = (c.i0 != 0); break;
case CommandType::SetFrequency: frequency_ = c.f0; break;
- case CommandType::TransportPlay: transport_.play(); break;
- case CommandType::TransportStop: transport_.stop(); break;
+ case CommandType::TransportPlay:
+ if (c.i0 > 0 && !transport_.isPlaying()) { // count-in first (i0 = bars)
+ countInActive_ = true;
+ countInPos_ = 0.0;
+ countInTotal_ = static_cast<double>(c.i0) * std::max(1, transport_.beatsPerBar());
+ lastCountInBeat_ = -1;
+ uiCountIn_.store(countInTotal_, std::memory_order_relaxed);
+ } else {
+ endCountIn();
+ transport_.play();
+ }
+ break;
+ case CommandType::TransportStop: endCountIn(); transport_.stop(); break;
case CommandType::SetBpm: transport_.setBpm(c.d0); break;
case CommandType::SetTimeSignature: transport_.setTimeSignature(c.i0, c.i1); break;
case CommandType::SetLoop: transport_.setLoop(c.i0 != 0, c.d0, c.d1); break;
@@ -723,7 +740,7 @@ void Engine::processBlock(float* out, int32_t numFrames) {
const double sr = transport_.sampleRate();
const double spb = transport_.samplesPerBeat();
- const bool playing = transport_.isPlaying();
+ bool playing = transport_.isPlaying(); // flips to true mid-block when a count-in runs out
drainLiveMidi(transport_.playheadSamples() / spb, playing);
@@ -766,13 +783,29 @@ void Engine::processBlock(float* out, int32_t numFrames) {
const double toEnd = transport_.loopEndSamples() - transport_.playheadSamples();
if (toEnd > 0.5 && toEnd < seg) seg = std::max(1, static_cast<int32_t>(std::lround(toEnd)));
}
+ // End the segment where the count-in runs out, so the transport rolls on that sample.
+ if (countInActive_ && spb > 0.0) {
+ const double left = (countInTotal_ - countInPos_) * spb;
+ if (left < seg) seg = std::max(1, static_cast<int32_t>(std::lround(left)));
+ }
const double segStart = transport_.playheadSamples();
chaseNotes_ = chase;
if (g && sr > 0.0) mixGraph(g, out + done * 2, seg, segStart, playing, spb);
chaseNotes_ = chase = false;
+ bool countInDone = false;
if (playing) renderMetronome(out + done * 2, seg, segStart);
+ else if (countInActive_) countInDone = renderCountIn(out + done * 2, seg, spb);
transport_.advanceBy(seg);
done += seg;
+ if (countInDone) {
+ endCountIn();
+ transport_.play();
+ // Let the metronome click the beat we launch on (not when starting mid-beat).
+ const double b = transport_.playheadSamples() / spb;
+ const int64_t fb = static_cast<int64_t>(std::floor(b));
+ lastBeatEmitted_ = (b - fb < 1e-6) ? fb - 1 : fb;
+ playing = chase = renderWasPlaying_ = true;
+ }
}
// Declick each loop seam: the playhead jumps and sounding voices are cut at the
@@ -881,7 +914,7 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
// Internal resampling (record from another track/send/master): tap the source's
// post-fader output into the input ring while a take is rolling.
- const int32_t recSrc = internalRecordSource_.load(std::memory_order_relaxed);
+ const int32_t recSrc = countInActive_ ? 0 : internalRecordSource_.load(std::memory_order_relaxed);
// Live input monitoring: this segment's hardware input (shared by every track
// monitoring it), and the set of tracks whose output some monitoring track hears —
@@ -1255,6 +1288,16 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b
}
}
+void Engine::renderClick(float* out, int32_t i, int clickLen, double sr) {
+ if (clickRemaining_ <= 0) return;
+ const float env = static_cast<float>(clickRemaining_) / static_cast<float>(clickLen);
+ const float s = static_cast<float>(std::sin(clickPhase_)) * env * kMetroGain;
+ out[i * 2] += s; out[i * 2 + 1] += s;
+ clickPhase_ += kTwoPi * clickFreq_ / sr;
+ if (clickPhase_ >= kTwoPi) clickPhase_ -= kTwoPi;
+ --clickRemaining_;
+}
+
void Engine::renderMetronome(float* out, int32_t numFrames, double blockStartSamples) {
if (!transport_.metronomeEnabled()) return;
const double sr = transport_.sampleRate();
@@ -1273,15 +1316,33 @@ void Engine::renderMetronome(float* out, int32_t numFrames, double blockStartSam
clickFreq_ = (beat % beatsPerBar == 0) ? 1500.0 : 1000.0;
}
}
- if (clickRemaining_ > 0) {
- const float env = static_cast<float>(clickRemaining_) / static_cast<float>(clickLen);
- const float s = static_cast<float>(std::sin(clickPhase_)) * env * kMetroGain;
- out[i * 2] += s; out[i * 2 + 1] += s;
- clickPhase_ += kTwoPi * clickFreq_ / sr;
- if (clickPhase_ >= kTwoPi) clickPhase_ -= kTwoPi;
- --clickRemaining_;
+ renderClick(out, i, clickLen, sr);
+ }
+}
+
+// Count-in clicks: same voice as the metronome, accent on each bar's first beat. Sounds
+// regardless of the metronome switch; the transport is stopped meanwhile.
+bool Engine::renderCountIn(float* out, int32_t numFrames, double spb) {
+ const double sr = transport_.sampleRate();
+ const int beatsPerBar = std::max(1, transport_.beatsPerBar());
+ const int clickLen = static_cast<int>(0.03 * sr);
+ const double inc = spb > 0.0 ? 1.0 / spb : 0.0;
+
+ for (int32_t i = 0; i < numFrames; ++i) {
+ if (countInPos_ < countInTotal_) {
+ const int64_t beat = static_cast<int64_t>(countInPos_ + 1e-9);
+ if (beat != lastCountInBeat_) {
+ lastCountInBeat_ = beat;
+ clickRemaining_ = clickLen;
+ clickPhase_ = 0.0;
+ clickFreq_ = (beat % beatsPerBar == 0) ? 1500.0 : 1000.0;
+ }
}
+ renderClick(out, i, clickLen, sr);
+ countInPos_ += inc;
}
+ uiCountIn_.store(std::max(0.0, countInTotal_ - countInPos_), std::memory_order_relaxed);
+ return inc <= 0.0 || countInPos_ >= countInTotal_ - 0.5 * inc;
}
void Engine::renderTone(float* out, int32_t numFrames) {
diff --git a/src/native/nota.engine/src/nota_engine_core.cpp b/src/native/nota.engine/src/nota_engine_core.cpp
index 7d61d7c8..0e07d4d1 100644
--- a/src/native/nota.engine/src/nota_engine_core.cpp
+++ b/src/native/nota.engine/src/nota_engine_core.cpp
@@ -108,6 +108,15 @@ float nota_engine_cpu_load(const NotaEngine* e) {
NotaResult nota_transport_play(NotaEngine* e) {
if (!e) return NOTA_ERR_INVALID_ARG; ENG(e)->transportPlay(); return NOTA_OK;
}
+NotaResult nota_transport_play_count_in(NotaEngine* e) {
+ if (!e) return NOTA_ERR_INVALID_ARG; ENG(e)->transportPlayCountIn(); return NOTA_OK;
+}
+NotaResult nota_transport_set_count_in(NotaEngine* e, int32_t bars) {
+ if (!e || bars < 0) return NOTA_ERR_INVALID_ARG; ENG(e)->setCountInBars(bars); return NOTA_OK;
+}
+double nota_transport_count_in_beats(const NotaEngine* e) {
+ return e ? CENG(e)->countInBeatsRemaining() : 0.0;
+}
NotaResult nota_transport_stop(NotaEngine* e) {
if (!e) return NOTA_ERR_INVALID_ARG; ENG(e)->transportStop(); return NOTA_OK;
}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index cce59a01..0ccf2ed5 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -575,6 +575,53 @@ Check(Rms(buf, frames) > 1e-3f, "metronome produces clicks");
engine.SetMetronome(false);
engine.SetTrackMute(track, false);
+// --- count-in: clicks first, then the transport rolls on the exact sample ---
+{
+ engine.SetTrackMute(track, true);
+ engine.StopTransport();
+ engine.Seek(2.0);
+ engine.RenderOffline(buf, 256); // drain the stop/seek
+ double sr = engine.SampleRate > 0 ? engine.SampleRate : 44100.0, spb = sr * 60.0 / 120.0; // offline default rate
+ int ciFrames = (int)Math.Round(4 * spb); // 1 bar of 4/4 at 120 BPM
+ engine.Play(); // plain Play never counts in (exports, freezes)
+ engine.RenderOffline(buf, 256);
+ Check(engine.IsPlaying && engine.CountInBeats == 0, "count-in: plain Play rolls at once");
+ engine.StopTransport(); engine.Seek(2.0); engine.RenderOffline(buf, 256);
+
+ engine.SetCountIn(1);
+ engine.PlayWithCountIn();
+ Check(engine.CountInBeats > 0, "count-in: armed immediately");
+ const int chunk = 512;
+ var cbuf = new float[chunk * 2];
+ int rendered = 0; float clickRms = 0; bool silentStop = true;
+ while (!engine.IsPlaying && rendered < ciFrames * 2)
+ {
+ engine.RenderOffline(cbuf, chunk);
+ rendered += chunk;
+ clickRms = Math.Max(clickRms, Rms(cbuf, chunk));
+ if (!engine.IsPlaying && Math.Abs(engine.PositionBeats - 2.0) > 1e-9) silentStop = false;
+ }
+ Check(clickRms > 1e-3f, "count-in: clicks sound with the metronome off");
+ Check(silentStop, "count-in: playhead holds while counting in");
+ Check(engine.IsPlaying && engine.CountInBeats == 0, $"count-in: transport rolls after the bar ({rendered} frames)");
+ double rolled = (engine.PositionBeats - 2.0) * spb;
+ Check(Math.Abs(rendered - ciFrames - rolled) <= 1.0,
+ $"count-in: starts sample-accurately (rolled {rolled:F1} of {rendered - ciFrames} frames)");
+
+ engine.StopTransport(); engine.Seek(2.0); engine.RenderOffline(buf, 256);
+ engine.PlayWithCountIn();
+ engine.RenderOffline(cbuf, chunk);
+ engine.StopTransport(); // Stop cancels a running count-in
+ engine.RenderOffline(cbuf, chunk);
+ Check(!engine.IsPlaying && engine.CountInBeats == 0, "count-in: Stop cancels it");
+ engine.RenderOffline(buf, ciFrames > frames ? frames : ciFrames);
+ Check(!engine.IsPlaying, "count-in: cancelled count-in never starts the transport");
+
+ engine.SetCountIn(0);
+ engine.Seek(0);
+ engine.SetTrackMute(track, false);
+}
+
// --- loop region mirror (for the arrangement highlight + transport bar) ---
engine.SetLoop(true, 4.0, 12.0);
Check(engine.LoopEnabled && Math.Abs(engine.LoopStart - 4.0) < 1e-9 && Math.Abs(engine.LoopEnd - 12.0) < 1e-9,
@@ -11940,6 +11987,33 @@ Console.WriteLine("-- record from another track --");
Check(Rms(pb, 8192) > 0.001f, $"recorded internal clip plays back audible (RMS {Rms(pb, 8192):F3})");
}
+// ============ record with a count-in: the take starts when the transport rolls ====
+Console.WriteLine("-- record with count-in --");
+{
+ using var re = new NotaEngine();
+ re.SetBpm(120); re.SetTimeSignature(4, 4);
+ int rinst = re.AddBassSynthTrack();
+ int mc = re.AddMidiClip(rinst, 0, 8);
+ re.SetClipNotes(rinst, mc, new[] { new NotaNote(36, 0.0, 8.0, 1.0f) });
+ int rrec = re.AddAudioTrack();
+ re.SetTrackRecordInput(rrec, rinst);
+ re.SetTrackArmed(rrec, true);
+ re.SetCountIn(1);
+ re.Seek(0);
+ re.SetRecording(true);
+ Check(!re.IsPlaying && re.CountInBeats > 0, "record count-in: the take waits for the count-in");
+ const int blk = 2048, blocks = 60; // 122880 frames; the bar takes 88200 @ 44.1k
+ var cap = new float[blk * 2];
+ for (int b = 0; b < blocks; b++) { re.RenderOffline(cap, blk); re.Poll(); }
+ Check(re.IsPlaying, "record count-in: transport rolled after the bar");
+ re.SetRecording(false);
+ re.Poll();
+ double expect = (blk * blocks - 4 * 22050.0) / 22050.0; // beats captured after the count-in
+ Check(re.TryGetClipInfo(rrec, 0, out var rci) && Math.Abs(rci.StartBeat) < 1e-6
+ && Math.Abs(rci.LengthBeats - expect) < 0.1,
+ $"record count-in: take excludes the count-in (start {rci.StartBeat:F3}, {rci.LengthBeats:F3} ≈ {expect:F3} beats)");
+}
+
// ============ record-input source survives a project round-trip ============
Console.WriteLine("-- record input project round-trip --");
{