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) Add ADSR for audio clips

Egor Khindikaynen3dc740ad388f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ad906a48..c8154142 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,11 @@ created, and the build-and-publish run starts.
Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
### Added
+- **ADSR for audio clips.** Every audio clip now has attack, decay, sustain and release.
+ Hover a clip in the arrangement and drag the handles — the squares in the top corners
+ set the attack and release, the dot sets the decay and the sustain level — or open the
+ clip editor's new ADSR tab for the same handles and exact sliders. Both places stay in
+ sync. A new clip still plays the whole sample at full volume.
- **Nota Grain has 50 factory presets, and each one brings its own sound.** Until now every
Grain preset played the same built-in pad. Now a preset loads a source made for it: a
choir, bowed strings, a church bell, a kalimba, a vowel that moves from "a" to "u", a drum
diff --git a/FEATURES.md b/FEATURES.md
index 98a7f60e..b11e5699 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -203,6 +203,15 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).
sounds — the editor mirrors the whole view (brackets, warp markers, BPM chips, grid and
cursor included) so the screen reads left-to-right in playing order — and trims and
splits mirror, so the audible head and tail follow the edit.
+- **ADSR per audio clip**: attack, decay, sustain and release shape the clip's level in
+ played time. Every audio clip in the arrangement carries three handles, shown on hover or
+ selection — attack and release squares at the top corners, a decay/sustain dot — and the
+ clip editor has an ADSR tab with the same handles over the waveform plus ATTACK / DECAY /
+ SUSTAIN / RELEASE sliders. The waveform is drawn shaped the way it sounds. By default the
+ sample plays its full length at full level; double-click a handle to reset its stage.
+ Editing in either place updates the other, each edit is one undo step, split keeps the
+ attack on the left piece and the release on the right, and the shape is saved with the
+ project.
- **Warp / time-stretch**: **Complex** and **Complex Pro** modes (the latter with formant
preservation, correct even when the sample rate and the device rate differ), plus
transient detection. A grid-snap toggle governs trimming a warped clip.
diff --git a/src/managed/Nota.App/ArrangementView.LaneControl.cs b/src/managed/Nota.App/ArrangementView.LaneControl.cs
index de95d5d5..76e57733 100644
--- a/src/managed/Nota.App/ArrangementView.LaneControl.cs
+++ b/src/managed/Nota.App/ArrangementView.LaneControl.cs
@@ -44,6 +44,41 @@ public sealed partial class ArrangementView
private double _rpMTotal, _rpS0, _rpS1; // material total + committed window (frames for unwarped, beats for warped)
private const double EdgePx = 6;
+ // ADSR handles on audio clips (shown on hover / selection). A drag previews on the
+ // ClipVM and commits one engine edit (one undo step) on release.
+ private AdsrHandle _adsrDrag;
+ private ClipVM? _adsrClip;
+ private int _adsrTrackId;
+ private ClipAdsr _adsrStart;
+ private double _adsrAnchorBeat, _adsrAnchorLevel;
+ private Point _adsrPress;
+ private int _adsrHoverTrack = -1, _adsrHoverClip = -1;
+ private AdsrHandle _adsrHoverHandle;
+ private static readonly Cursor HandCursor = new(StandardCursorType.Hand);
+
+ // The clip's ADSR frame: its span sideways, the content area (under the colour band) for level.
+ private AdsrFrame AdsrFrameOf(ClipVM c, int row)
+ {
+ double top = RowTop(row) + 2 + BandH, bottom = RowTop(row) + RowH(row) - 2;
+ return new AdsrFrame(_o.BeatToX(c.StartBeat), _o.BeatToX(c.StartBeat + c.LengthBeats),
+ top + 4, bottom - 3, c.LengthBeats);
+ }
+
+ // The ADSR handle under `p` on an audio clip (lanes view, not automation).
+ private (TrackVM track, ClipVM clip, int row, AdsrHandle handle)? HitAdsr(Point p)
+ {
+ int row = _o.RowAtY(p.Y);
+ if (row < 0 || _o._tracks[row].IsInstrument || _o._tracks[row].IsGroup) return null;
+ var t = _o._tracks[row];
+ foreach (var c in t.Clips)
+ {
+ if (c.IsMidi) continue;
+ var h = ClipAdsrKit.Hit(p, AdsrFrameOf(c, row), c.Adsr);
+ if (h != AdsrHandle.None) return (t, c, row, h);
+ }
+ return null;
+ }
+
// Press-pending: a clip was pressed but the 4px drag threshold isn't crossed yet, so
// it's still a potential click (select / narrow selection), not a drag (req 2.3/2.12).
private bool _pending;
@@ -175,6 +210,28 @@ public sealed partial class ArrangementView
return;
}
+ // ADSR handle: double-click resets its stage, a press starts a handle drag. Checked
+ // before the edge trims so the top corners belong to attack/release (as in Ableton).
+ if (HitAdsr(pt.Position) is { } ah)
+ {
+ if (e.ClickCount == 2)
+ {
+ CommitAdsr(ah.track.Id, ah.clip, ClipAdsrKit.Reset(ah.handle, ah.clip.Adsr.Fit(ah.clip.LengthBeats)));
+ return;
+ }
+ _o.Select(ah.track.Id, ah.clip.ClipIndex);
+ _adsrDrag = ah.handle;
+ _adsrClip = ah.clip;
+ _adsrTrackId = ah.track.Id;
+ _adsrStart = ah.clip.Adsr.Fit(ah.clip.LengthBeats);
+ (_adsrAnchorBeat, _adsrAnchorLevel) = ClipAdsrKit.Anchor(ah.handle, _adsrStart, ah.clip.LengthBeats);
+ _adsrPress = pt.Position;
+ _lastPos = pt.Position;
+ e.Pointer.Capture(this);
+ InvalidateVisual();
+ return;
+ }
+
if (e.ClickCount == 2)
{
// Keep the selection in sync with the opened editor (without firing
@@ -267,6 +324,25 @@ public sealed partial class ArrangementView
_lastPos = pos;
_lastMods = e.KeyModifiers;
+ if (_adsrDrag != AdsrHandle.None && _adsrClip is { } ac)
+ {
+ double dx = pos.X - _adsrPress.X, dy = pos.Y - _adsrPress.Y;
+ if (_adsrDrag == AdsrHandle.AttackOrSustain)
+ {
+ if (Math.Abs(dx) < 3 && Math.Abs(dy) < 3) return;
+ _adsrDrag = ClipAdsrKit.Resolve(_adsrDrag, dx, dy);
+ (_adsrAnchorBeat, _adsrAnchorLevel) = ClipAdsrKit.Anchor(_adsrDrag, _adsrStart, ac.LengthBeats);
+ }
+ int row = _o._tracks.FindIndex(t => t.Id == _adsrTrackId);
+ if (row < 0) return;
+ var f = AdsrFrameOf(ac, row);
+ double beat = _adsrAnchorBeat + dx / Math.Max(1e-9, _o._pixelsPerBeat);
+ double level = _adsrAnchorLevel - dy / Math.Max(1, f.Bottom - f.Top);
+ ac.Adsr = ClipAdsrKit.Drag(_adsrDrag, _adsrStart, beat, level, ac.LengthBeats);
+ InvalidateVisual();
+ return;
+ }
+
if (_marqueeArmed)
{
if (_rangeActive || Math.Abs(pos.X - _marqueePress.X) >= DragThreshold
@@ -321,7 +397,7 @@ public sealed partial class ArrangementView
}
}
- if (_drag == Drag.None) { UpdateEdgeHover(pos); return; }
+ if (_drag == Drag.None) { if (!UpdateAdsrHover(pos)) UpdateEdgeHover(pos); return; }
EnsureAutoScroll();
UpdateActiveDrag(pos, e.KeyModifiers);
}
@@ -394,6 +470,17 @@ public sealed partial class ArrangementView
if (_o._automationMode) { AutoPointerReleased(e); return; }
var eng = _o._engine;
+ if (_adsrDrag != AdsrHandle.None)
+ {
+ var clip = _adsrClip;
+ var start = _adsrStart;
+ _adsrDrag = AdsrHandle.None; _adsrClip = null;
+ e.Pointer.Capture(null);
+ if (clip is not null && !clip.Adsr.Equals(start)) CommitAdsr(_adsrTrackId, clip, clip.Adsr);
+ else InvalidateVisual();
+ return;
+ }
+
// A press that never crossed the drag threshold is a click on a clip: select it,
// or narrow a multi-selection down to just it (req 2.2/2.12). No model change.
if (_pending)
@@ -511,12 +598,14 @@ public sealed partial class ArrangementView
// that a PointerCaptureLost fired around button-up doesn't wipe the latch before
// OnPointerReleased turns it into a selection.
bool active = _drag != Drag.None || _groupMove is not null || _rangeActive
- || _autoDrag is not null || _bendLeft is not null || _rangeTrack is not null;
+ || _autoDrag is not null || _bendLeft is not null || _rangeTrack is not null
+ || _adsrDrag != AdsrHandle.None;
if (!active) return false;
_pending = false; _drag = Drag.None; _groupMove = null; _moveRowDelta = 0; _dragClip = null; _rpPeaks = null;
_marqueeArmed = false; _rangeActive = false; _marquee = null; _shiftClipTrack = -1; _shiftClipIndex = -1;
_autoDrag = null; _autoDragTrack = null; _bendLeft = _bendRight = null; _bendTrack = null;
_rangeTrack = null;
+ _adsrDrag = AdsrHandle.None; _adsrClip = null;
_autoScroll?.Stop();
SetResizeCursor(false);
_o.Refresh(); // reload authoritative clip/automation positions, discarding the preview
@@ -708,7 +797,46 @@ public sealed partial class ArrangementView
InvalidateVisual();
}
- protected override void OnPointerExited(PointerEventArgs e) { ClearHover(); ClearEdgeHover(); base.OnPointerExited(e); }
+ protected override void OnPointerExited(PointerEventArgs e) { ClearHover(); ClearEdgeHover(); ClearAdsrHover(); base.OnPointerExited(e); }
+
+ // One engine edit (one undo step); an open clip editor re-reads it, the lane reloads.
+ private void CommitAdsr(int trackId, ClipVM clip, ClipAdsr adsr)
+ {
+ if (_o._engine is not { } eng) return;
+ eng.SetClipAdsr(trackId, clip.ClipIndex, adsr);
+ _o.RaiseClipGeometryChanged(trackId, clip.ClipIndex);
+ _o.Refresh();
+ }
+
+ // Hover over audio clips: which clip shows its ADSR handles, and which handle is hot.
+ // Returns true while a handle is under the pointer (it then owns the cursor).
+ private bool UpdateAdsrHover(Point pos)
+ {
+ int ht = -1, hc = -1; var hh = AdsrHandle.None;
+ if (HitAdsr(pos) is { } a) { ht = a.track.Id; hc = a.clip.ClipIndex; hh = a.handle; }
+ else if (HitTest(pos, out _) is { } c && !c.clip.IsMidi) { ht = c.track.Id; hc = c.clip.ClipIndex; }
+ if (ht != _adsrHoverTrack || hc != _adsrHoverClip || hh != _adsrHoverHandle)
+ {
+ _adsrHoverTrack = ht; _adsrHoverClip = hc; _adsrHoverHandle = hh;
+ InvalidateVisual();
+ }
+ if (hh == AdsrHandle.None)
+ {
+ if (ReferenceEquals(Cursor, HandCursor)) Cursor = ArrowCursor;
+ return false;
+ }
+ ClearEdgeHover();
+ Cursor = HandCursor;
+ return true;
+ }
+
+ private void ClearAdsrHover()
+ {
+ if (ReferenceEquals(Cursor, HandCursor)) Cursor = ArrowCursor;
+ if (_adsrHoverTrack == -1 && _adsrHoverHandle == AdsrHandle.None) return;
+ _adsrHoverTrack = -1; _adsrHoverClip = -1; _adsrHoverHandle = AdsrHandle.None;
+ InvalidateVisual();
+ }
// Which edge (if any) a resize would grab at `pos` — mirrors the press logic so
// the highlight matches what a drag would do. Updates the resize cursor.
@@ -1087,7 +1215,7 @@ public sealed partial class ArrangementView
var edgeHi = Drag.None;
if (_hoverEdge != Drag.None && _hoverEdgeTrack == tid && _hoverEdgeClip == c.ClipIndex) edgeHi = _hoverEdge;
else if ((_drag == Drag.TrimL || _drag == Drag.TrimR) && _dragTrackId == tid && _dragClipIndex == c.ClipIndex) edgeHi = _drag;
- DrawClipBody(ctx, _o._tracks[i].ColorIndex, _o._tracks[i].Name, c, y, rh, _o.IsSelected(tid, c.ClipIndex), edgeHi, pitches);
+ DrawClipBody(ctx, _o._tracks[i].ColorIndex, _o._tracks[i].Name, c, y, rh, _o.IsSelected(tid, c.ClipIndex), edgeHi, pitches, tid, i);
}
// Imports still decoding: a translucent placeholder whose waveform fills in.
using (ctx.PushOpacity(0.5))
@@ -1188,6 +1316,17 @@ public sealed partial class ArrangementView
ctx.DrawText(ft, new Point(tx, ty));
}
+ // ADSR drag readout: the stage being edited, in time and dB.
+ if (_adsrDrag is not (AdsrHandle.None or AdsrHandle.AttackOrSustain) && _adsrClip is { } adc)
+ {
+ var ft = new FormattedText(ClipAdsrKit.Readout(_adsrDrag, adc.Adsr, _o._engine?.Bpm ?? 120), CultureInfo.InvariantCulture,
+ FlowDirection.LeftToRight, Typeface.Default, 10, TooltipText);
+ double tx = Math.Clamp(_lastPos.X + 12, 6, Math.Max(6, w - ft.Width - 10));
+ double ty = Math.Max(4, _lastPos.Y - 24);
+ ctx.DrawRectangle(TooltipBg, null, new Rect(tx - 5, ty - 3, ft.Width + 10, ft.Height + 6), 3, 3);
+ ctx.DrawText(ft, new Point(tx, ty));
+ }
+
// NB: the loop band + playhead are drawn on LaneOverlayControl (a hit-transparent
// layer above the lanes) so the 30 Hz transport tick doesn't repaint this whole
// clip/waveform surface — only the overlay's few strokes.
@@ -1316,7 +1455,8 @@ public sealed partial class ArrangementView
}
private void DrawClipBody(DrawingContext ctx, int colorIndex, string label, ClipVM c, double y,
- double rowH, bool selected, Drag edgeHi = Drag.None, (int lo, int hi)? pitches = null)
+ double rowH, bool selected, Drag edgeHi = Drag.None, (int lo, int hi)? pitches = null,
+ int trackId = -1, int row = -1)
{
double w = Bounds.Width;
double x0 = _o.BeatToX(c.StartBeat);
@@ -1361,6 +1501,8 @@ public sealed partial class ArrangementView
ctx.DrawText(ft, new Point(rect.X + 5, rect.Y + BandH + 2));
}
+ if (!c.IsMidi && row >= 0) DrawAdsr(ctx, c, trackId, row, selected, content, NotaPalette.BgSunken);
+
// Deactivated clip (key 0): grey it out with a dark scrim so it reads as "off"
// while still showing its content/geometry. Inset so the (selection) border stays.
if (!c.Active)
@@ -1369,6 +1511,24 @@ public sealed partial class ArrangementView
private const double BandH = 2; // clip colour band along the top edge
+ // The clip's ADSR: the curve whenever it shapes the clip, the handles while the clip is
+ // hovered, selected or being edited. Drawn in the clip's own colour; the hot handle is brass.
+ private void DrawAdsr(DrawingContext ctx, ClipVM c, int trackId, int row, bool selected, IBrush ink, IBrush body)
+ {
+ bool editing = _adsrDrag != AdsrHandle.None && ReferenceEquals(c, _adsrClip);
+ bool hovered = _adsrHoverTrack == trackId && _adsrHoverClip == c.ClipIndex;
+ bool handles = editing || hovered || selected;
+ if (c.Adsr.IsIdentity && !handles) return;
+ var f = AdsrFrameOf(c, row);
+ if (f.Right - f.Left < 12) return;
+ using var _ = ctx.PushClip(new Rect(f.Left, RowTop(row) + 2, f.Right - f.Left, RowH(row) - 4));
+ var a = c.Adsr.Fit(c.LengthBeats);
+ if (!a.IsIdentity) ClipAdsrKit.DrawCurve(ctx, f, a, new Pen(ink, 1.2));
+ if (!handles) return;
+ var hot = editing ? _adsrDrag : hovered ? _adsrHoverHandle : AdsrHandle.None;
+ ClipAdsrKit.DrawHandles(ctx, f, a, hot, ink, NotaPalette.Accent, new Pen(body, 1));
+ }
+
// Which clips carry their name (design 1a's "labels" choice). A clip that was named by
// hand always shows it — that name was authored to be read.
private bool ShowsLabel(ClipVM c) => _o.ClipLabels switch
@@ -1454,8 +1614,10 @@ public sealed partial class ArrangementView
// that fall in it. This keeps the waveform solid on wide/zoomed clips instead
// of leaving gaps between sparse fixed-position bars.
double vx0 = Math.Max(r.X, 0), vx1 = Math.Min(r.Right, Bounds.Width);
+ var adsr = c.Adsr.Fit(c.LengthBeats);
+ bool shaped = !adsr.IsIdentity;
var geo = new StreamGeometry();
- using (var g = geo.Open())
+ using (var gc = geo.Open())
for (double px = vx0; px < vx1; px += 1)
{
int b0 = Math.Clamp((int)((px - r.X) / r.Width * c.PeakCount), 0, c.PeakCount - 1);
@@ -1463,9 +1625,11 @@ public sealed partial class ArrangementView
float min = 1f, max = -1f;
for (int b = b0; b < b1; b++) { min = Math.Min(min, c.Peaks[b * 2]); max = Math.Max(max, c.Peaks[b * 2 + 1]); }
if (min > max) continue;
- // Clip gain scales the drawn waveform, matching the clip editor.
- min = Math.Clamp(min * c.Gain, -1f, 1f); max = Math.Clamp(max * c.Gain, -1f, 1f);
- AddRect(g, px, mid - max * amp, 1, Math.Max(1, (max - min) * amp));
+ // Clip gain (and the ADSR shape) scales the drawn waveform, matching the clip editor.
+ float g = c.Gain;
+ if (shaped) g *= (float)adsr.GainAt((px + 0.5 - r.X) / r.Width * c.LengthBeats, c.LengthBeats);
+ min = Math.Clamp(min * g, -1f, 1f); max = Math.Clamp(max * g, -1f, 1f);
+ AddRect(gc, px, mid - max * amp, 1, Math.Max(1, (max - min) * amp));
}
ctx.DrawGeometry(brush, null, geo);
}
diff --git a/src/managed/Nota.App/ArrangementView.Vms.cs b/src/managed/Nota.App/ArrangementView.Vms.cs
index 97226542..2fc69659 100644
--- a/src/managed/Nota.App/ArrangementView.Vms.cs
+++ b/src/managed/Nota.App/ArrangementView.Vms.cs
@@ -77,6 +77,8 @@ public sealed partial class ArrangementView
public int PeakCount;
/// <summary>Clip gain (linear) — peaks are raw material, the lane scales them by this.</summary>
public float Gain = 1f;
+ /// <summary>Audio clip ADSR amplitude shape (identity = full length, full level).</summary>
+ public ClipAdsr Adsr = ClipAdsr.Identity;
public NotaNote[]? Notes;
public string Name = "";
/// <summary>True when no clip on the same track ends where this one begins — the head
diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.cs
index dd477f7e..63ed887c 100644
--- a/src/managed/Nota.App/ArrangementView.cs
+++ b/src/managed/Nota.App/ArrangementView.cs
@@ -753,7 +753,11 @@ public sealed partial class ArrangementView : UserControl
cvm.PeakCount = eng.GetClipPeaks(ti.Id, c, peaks, buckets);
cvm.Peaks = peaks;
}
- if (!ci.IsMidi && eng.TryGetAudioClipInfo(ti.Id, c, out var ai)) cvm.Gain = ai.Gain;
+ if (!ci.IsMidi && eng.TryGetAudioClipInfo(ti.Id, c, out var ai))
+ {
+ cvm.Gain = ai.Gain;
+ cvm.Adsr = eng.GetClipAdsr(ti.Id, c);
+ }
tvm.Clips.Add(cvm);
}
MarkClipRuns(tvm);
diff --git a/src/managed/Nota.App/AudioClipEditorView.cs b/src/managed/Nota.App/AudioClipEditorView.cs
index 301c4152..e3b12a1e 100644
--- a/src/managed/Nota.App/AudioClipEditorView.cs
+++ b/src/managed/Nota.App/AudioClipEditorView.cs
@@ -6,7 +6,9 @@
// editing one, the Snap switch, the file's format) over the 232px inspector (CLIP,
// PLAYBACK, WARP) and the waveform canvas: a beat ruler, a 22px warp-marker strip, and
// the wave in the track colour, everything past the clip's played region darkened rather
-// than hidden. Envelope is a mode of the canvas, not a checkbox.
+// than hidden. Envelope and ADSR are modes of the canvas, not checkboxes. ADSR edits the
+// clip's amplitude shape with the same handles the arrangement shows on the clip
+// (ClipAdsrKit), so an edit in either place shows up in the other.
using System;
using System.Globalization;
@@ -40,6 +42,11 @@ public sealed class AudioClipEditorView : UserControl
private readonly TextBlock _hint = Hint("");
private readonly Border _envTargetDrop;
private Action _syncGain = () => { }, _syncReverse = () => { }, _syncWarp = () => { }, _syncSnap = () => { };
+ private Action _syncAttack = () => { }, _syncDecay = () => { }, _syncSustain = () => { }, _syncRelease = () => { };
+ private ClipAdsr _adsr = ClipAdsr.Identity;
+ private int _mode; // 0 = Sample, 1 = Envelope, 2 = ADSR
+ private readonly ContentControl _inspectorBody = new();
+ private Control _sampleSections = null!, _adsrSections = null!;
private double _startBeat;
private double _lengthBeats = 4;
@@ -88,6 +95,7 @@ public sealed class AudioClipEditorView : UserControl
else _engine.SetClipVolumeEnvelope(TrackId, ClipIndex, pts);
_onChanged();
};
+ _wave.AdsrCommitted = SetAdsr;
// CLIP — where it sits, and its length (± one beat).
var clip = Section("CLIP",
@@ -123,7 +131,28 @@ public sealed class AudioClipEditorView : UserControl
var warp = Section(SectionTitle("WARP", _markerCount), 8,
warpRow, Pair(detect, transients), Card(KeyValue("Detected", _detectedText)));
- var inspector = Inspector(Sections(clip, playback, warp), _hint);
+ // ADSR — the clip's amplitude shape (the ADSR tab swaps the inspector to it). Times
+ // run on a square-law slider over the clip length, so short attacks stay fine-grained.
+ var attack = SliderRow("ATTACK", 52, () => TimeNorm(_adsr.AttackBeats),
+ v => SetAdsrStage(AdsrHandle.Attack, NormTime(v), _adsr.Sustain), () => AdsrTime(_adsr.AttackBeats), out _syncAttack,
+ reset: () => SetAdsr(ClipAdsrKit.Reset(AdsrHandle.Attack, _adsr)), valueW: 52);
+ var decay = SliderRow("DECAY", 52, () => TimeNorm(_adsr.DecayBeats),
+ v => SetAdsrStage(AdsrHandle.DecaySustain, _adsr.AttackBeats + NormTime(v), _adsr.Sustain), () => AdsrTime(_adsr.DecayBeats), out _syncDecay,
+ reset: () => { var a = _adsr; a.DecayBeats = 0; SetAdsr(a); }, valueW: 52);
+ var sustain = SliderRow("SUSTAIN", 52, () => _adsr.Sustain,
+ v => SetAdsrStage(AdsrHandle.DecaySustain, _adsr.AttackBeats + _adsr.DecayBeats, v), () => ClipAdsrKit.SustainText(_adsr.Sustain), out _syncSustain,
+ reset: () => { var a = _adsr; a.Sustain = 1f; SetAdsr(a); }, valueW: 52);
+ var release = SliderRow("RELEASE", 52, () => TimeNorm(_adsr.ReleaseBeats),
+ v => SetAdsrStage(AdsrHandle.Release, _lengthBeats - NormTime(v), _adsr.Sustain), () => AdsrTime(_adsr.ReleaseBeats), out _syncRelease,
+ reset: () => SetAdsr(ClipAdsrKit.Reset(AdsrHandle.Release, _adsr)), valueW: 52);
+ var resetAll = ClipEditorKit.Button("Reset", () => SetAdsr(ClipAdsr.Identity));
+ ToolTip.SetTip(resetAll, "Play the whole sample at full level");
+ var adsr = Section(SectionTitle("ADSR"), 10, attack, decay, sustain, release, resetAll);
+
+ _sampleSections = Sections(clip, playback, warp);
+ _adsrSections = Sections(adsr);
+ _inspectorBody.Content = _sampleSections;
+ var inspector = Inspector(_inspectorBody, _hint);
// Column 1: the waveform (row 0), a horizontal zoom scrollbar (row 1), and a
// floating overlay (Canvas with null background → clicks pass through except the
@@ -156,8 +185,8 @@ public sealed class AudioClipEditorView : UserControl
Grid.SetColumn(col1, 1);
grid.Children.Add(col1);
- // Header: Sample | Envelope, the target while editing an envelope, Snap, the format.
- var tabs = Segments(new[] { "Sample", "Envelope" }, 0, i => SetEnvMode(i == 1), out _);
+ // Header: Sample | Envelope | ADSR, the target while editing an envelope, Snap, the format.
+ var tabs = Segments(new[] { "Sample", "Envelope", "ADSR" }, 0, SetMode, out _);
_envTargetDrop = Dropdown(_envTargetText, a => ShowMenu(a, EnvTargets, _envTarget, SetEnvTarget));
_envTargetDrop.IsVisible = false;
var snap = SwitchRow("Snap", () => _snapToGrid, ToggleSnap, out _syncSnap);
@@ -292,6 +321,7 @@ public sealed class AudioClipEditorView : UserControl
// Clip envelope: clip-local domain = warpBeats when warped, else clip length.
LoadEnvelope();
+ LoadAdsr();
SyncWaveScroll();
}
@@ -381,14 +411,45 @@ public sealed class AudioClipEditorView : UserControl
_detectedText.Foreground = found ? NotaPalette.TextPrimary : NotaPalette.TextDisabled;
}
- private void SetEnvMode(bool on)
+ private void SetMode(int mode)
{
- _envMode = on;
- _envTargetDrop.IsVisible = on;
- _wave.SetEnvMode(on);
+ _mode = mode;
+ _envMode = mode == 1;
+ _envTargetDrop.IsVisible = _envMode;
+ _wave.SetEnvMode(_envMode);
+ _wave.SetAdsrMode(mode == 2);
+ _inspectorBody.Content = mode == 2 ? _adsrSections : _sampleSections;
PaintHint();
}
+ // ---- ADSR ----------------------------------------------------------------
+ private void LoadAdsr()
+ {
+ _adsr = _engine.GetClipAdsr(TrackId, ClipIndex);
+ _wave.SetAdsr(_adsr, _lengthBeats, _engine.Bpm);
+ SyncAdsr();
+ }
+
+ private void SyncAdsr() { _syncAttack(); _syncDecay(); _syncSustain(); _syncRelease(); }
+
+ // One engine edit (one undo step); the arrangement reloads and draws the same shape.
+ private void SetAdsr(ClipAdsr a)
+ {
+ _adsr = a.Fit(_lengthBeats);
+ _engine.SetClipAdsr(TrackId, ClipIndex, _adsr);
+ _wave.SetAdsr(_adsr, _lengthBeats, _engine.Bpm);
+ SyncAdsr();
+ _onChanged();
+ }
+
+ // A slider moves one stage the way its handle would (it stops at its neighbours).
+ private void SetAdsrStage(AdsrHandle h, double beat, double level)
+ => SetAdsr(ClipAdsrKit.Drag(h, _adsr, beat, level, _lengthBeats));
+
+ private double TimeNorm(double beats) => _lengthBeats > 0 ? Math.Sqrt(Math.Clamp(beats / _lengthBeats, 0, 1)) : 0;
+ private double NormTime(double v) => v * v * _lengthBeats;
+ private string AdsrTime(double beats) => NotaNum.Time(beats * 60.0 / Math.Max(1, _engine.Bpm));
+
private void SetEnvTarget(int target)
{
_envTarget = target;
@@ -396,9 +457,12 @@ public sealed class AudioClipEditorView : UserControl
LoadEnvelope();
}
- private void PaintHint() => _hint.Text = _envMode
- ? "Click — point · drag — move · right-click — delete"
- : "Double-click the wave — marker · drag — align";
+ private void PaintHint() => _hint.Text = _mode switch
+ {
+ 1 => "Click — point · drag — move · right-click — delete",
+ 2 => "Drag a handle · double-click — reset",
+ _ => "Double-click the wave — marker · drag — align",
+ };
// Loads the active target's envelope into the waveform with its value axis.
private void LoadEnvelope()
@@ -504,6 +568,37 @@ public sealed class AudioClipEditorView : UserControl
private int _selMk = -1; // marker picked by a click (its position shows in the strip)
private EnvPt? _envBend; // segment being bent (M9-D)
+ // ADSR (the ADSR tab): the clip's amplitude shape over the PLAYED region, handles from
+ // ClipAdsrKit. Like the envelope it runs in played time, so it never mirrors.
+ private ClipAdsr _adsr = ClipAdsr.Identity;
+ private double _adsrLen = 1, _bpm = 120;
+ private bool _adsrMode;
+ private AdsrHandle _adsrDrag, _adsrHover;
+ private ClipAdsr _adsrStart;
+ private double _adsrAnchorBeat, _adsrAnchorLevel;
+ private Point _adsrPress;
+ private static readonly Cursor HandCur = new(StandardCursorType.Hand);
+ /// <summary>Raised when an ADSR handle drag ends (or a handle is reset) with the new shape.</summary>
+ public Action<ClipAdsr>? AdsrCommitted;
+
+ public void SetAdsrMode(bool on) { _adsrMode = on; _adsrHover = AdsrHandle.None; Cursor = ArrowCur; _curKind = StandardCursorType.Arrow; InvalidateVisual(); }
+ public void SetAdsr(ClipAdsr a, double lenBeats, double bpm)
+ {
+ if (_adsrDrag != AdsrHandle.None) return; // don't yank a handle out from under the hand
+ _adsr = a; _adsrLen = Math.Max(1e-6, lenBeats); _bpm = bpm;
+ InvalidateVisual();
+ }
+
+ // The played region on screen (left→right in playing order) over the wave's value axis.
+ private AdsrFrame AdsrFrameNow(double w, double h)
+ {
+ double xa, xb;
+ if (_srcMode && _srcTotal > 0) { xa = SrcToX(_srcOff, w); xb = SrcToX(_srcOff + _srcLen, w); }
+ else if (_trimMode && _trimTotal > 0) { xa = BeatToX(_trimStart, w); xb = BeatToX(_trimEnd, w); }
+ else { xa = FracToXView(0, w); xb = FracToXView(1, w); }
+ return new AdsrFrame(Math.Min(xa, xb), Math.Max(xa, xb), WaveTop + 6, h - 6, _adsrLen);
+ }
+
/// <summary>Raised when markers change (drag/add/delete) with the full sorted list.</summary>
public Action<double[], double[]>? MarkersCommitted;
/// <summary>Raised when the envelope changes, with the full sorted (beats, values, curves).</summary>
@@ -674,6 +769,31 @@ public sealed class AudioClipEditorView : UserControl
{
double W = Bounds.Width, H = Bounds.Height;
+ // ADSR mode takes over the pointer: grab a handle (double-click resets its stage).
+ if (_adsrMode)
+ {
+ if (e.GetCurrentPoint(this).Properties.IsRightButtonPressed) return;
+ var p = e.GetPosition(this);
+ var hit = ClipAdsrKit.Hit(p, AdsrFrameNow(W, H), _adsr);
+ if (hit == AdsrHandle.None) return;
+ if (e.ClickCount == 2)
+ {
+ _adsr = ClipAdsrKit.Reset(hit, _adsr.Fit(_adsrLen));
+ AdsrCommitted?.Invoke(_adsr);
+ }
+ else
+ {
+ _adsrDrag = hit;
+ _adsrStart = _adsr.Fit(_adsrLen);
+ (_adsrAnchorBeat, _adsrAnchorLevel) = ClipAdsrKit.Anchor(hit, _adsrStart, _adsrLen);
+ _adsrPress = p;
+ e.Pointer.Capture(this);
+ }
+ e.Handled = true;
+ InvalidateVisual();
+ return;
+ }
+
// BPM chip: drag up/down to scrub the segment tempo (like the global BPM),
// double-click to type an exact value.
if (!_envMode && !e.GetCurrentPoint(this).Properties.IsRightButtonPressed)
@@ -790,6 +910,31 @@ public sealed class AudioClipEditorView : UserControl
protected override void OnPointerMoved(PointerEventArgs e)
{
+ if (_adsrDrag != AdsrHandle.None)
+ {
+ var p = e.GetPosition(this);
+ double dx = p.X - _adsrPress.X, dy = p.Y - _adsrPress.Y;
+ if (_adsrDrag == AdsrHandle.AttackOrSustain)
+ {
+ if (Math.Abs(dx) < 3 && Math.Abs(dy) < 3) return;
+ _adsrDrag = ClipAdsrKit.Resolve(_adsrDrag, dx, dy);
+ (_adsrAnchorBeat, _adsrAnchorLevel) = ClipAdsrKit.Anchor(_adsrDrag, _adsrStart, _adsrLen);
+ }
+ var f = AdsrFrameNow(Bounds.Width, Bounds.Height);
+ double beat = _adsrAnchorBeat + dx / Math.Max(1, f.Right - f.Left) * _adsrLen;
+ double level = _adsrAnchorLevel - dy / Math.Max(1, f.Bottom - f.Top);
+ _adsr = ClipAdsrKit.Drag(_adsrDrag, _adsrStart, beat, level, _adsrLen);
+ InvalidateVisual();
+ return;
+ }
+ if (_adsrMode) // ADSR mode: light the handle under the pointer
+ {
+ var hv = ClipAdsrKit.Hit(e.GetPosition(this), AdsrFrameNow(Bounds.Width, Bounds.Height), _adsr);
+ if (hv != _adsrHover) { _adsrHover = hv; InvalidateVisual(); }
+ Cursor = hv != AdsrHandle.None ? HandCur : ArrowCur;
+ _curKind = StandardCursorType.Arrow;
+ return;
+ }
if (_bpmScrubSeg >= 0) // drag up = faster (0.5 BPM/px, like the global BPM)
{
double dy = _bpmScrubStartY - e.GetPosition(this).Y;
@@ -864,6 +1009,14 @@ public sealed class AudioClipEditorView : UserControl
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
+ if (_adsrDrag != AdsrHandle.None)
+ {
+ _adsrDrag = AdsrHandle.None;
+ e.Pointer.Capture(null);
+ if (!_adsr.Equals(_adsrStart)) AdsrCommitted?.Invoke(_adsr);
+ InvalidateVisual();
+ return;
+ }
if (_bpmScrubSeg >= 0) { _bpmScrubSeg = -1; e.Pointer.Capture(null); Commit(); return; } // push the scrubbed warp (one undo step)
if (_envDrag >= 0 || _envBend is not null) { _envDrag = -1; _envBend = null; e.Pointer.Capture(null); CommitEnv(); return; }
if (_srcDrag >= 0)
@@ -884,7 +1037,8 @@ public sealed class AudioClipEditorView : UserControl
protected override void OnPointerExited(PointerEventArgs e)
{
- if (_hoverMk != -1 || _bpmHoverSeg != -1 || _envHover != -1) { _hoverMk = -1; _bpmHoverSeg = -1; _envHover = -1; InvalidateVisual(); }
+ if (_hoverMk != -1 || _bpmHoverSeg != -1 || _envHover != -1 || _adsrHover != AdsrHandle.None)
+ { _hoverMk = -1; _bpmHoverSeg = -1; _envHover = -1; _adsrHover = AdsrHandle.None; InvalidateVisual(); }
SetCursorKind(StandardCursorType.Arrow);
base.OnPointerExited(e);
}
@@ -984,6 +1138,9 @@ public sealed class AudioClipEditorView : UserControl
// zooming magnifies the waveform and only the visible slice is drawn.
double mid = top + wh / 2;
ctx.DrawLine(MidPen, new Point(0, mid), new Point(w, mid));
+ var adsrF = AdsrFrameNow(w, h);
+ var adsrFit = _adsr.Fit(_adsrLen);
+ bool shaped = !adsrFit.IsIdentity;
if (_peaks is not null && _count > 0 && wh > 4)
{
double amp = wh / 2 - 6;
@@ -995,8 +1152,15 @@ public sealed class AudioClipEditorView : UserControl
if (_reversed) fx -= bw;
if (fx + bw < 0) { if (_reversed) break; continue; }
if (fx > w) { if (_reversed) continue; break; }
- float mn = (float)Math.Clamp(_peaks[i * 2] * _gain, -1.0, 1.0);
- float mx = (float)Math.Clamp(_peaks[i * 2 + 1] * _gain, -1.0, 1.0);
+ // The ADSR shapes the played region the way it sounds (outside it is darkened anyway).
+ double g = _gain;
+ if (shaped)
+ {
+ double bt = adsrF.Beat(fx + bw / 2);
+ if (bt >= 0 && bt <= _adsrLen) g *= adsrFit.GainAt(bt, _adsrLen);
+ }
+ float mn = (float)Math.Clamp(_peaks[i * 2] * g, -1.0, 1.0);
+ float mx = (float)Math.Clamp(_peaks[i * 2 + 1] * g, -1.0, 1.0);
ctx.FillRectangle(_wave, new Rect(fx, mid - mx * amp, bw, Math.Max(1, (mx - mn) * amp)));
}
}
@@ -1118,6 +1282,26 @@ public sealed class AudioClipEditorView : UserControl
}
}
+ // ADSR: in its tab the wave dims under a wash and the shape is drawn in brass with its
+ // handles (plus the stage readout while dragging); otherwise a quiet line keeps it in view.
+ if (_adsrMode)
+ {
+ ctx.FillRectangle(EnvWash, new Rect(0, top, w, wh));
+ ClipAdsrKit.DrawCurve(ctx, adsrF, adsrFit, EnvPen);
+ var hot = _adsrDrag != AdsrHandle.None ? _adsrDrag : _adsrHover;
+ ClipAdsrKit.DrawHandles(ctx, adsrF, adsrFit, hot, NodeFill, NodeHot, NodeRing);
+ if (_adsrDrag is not (AdsrHandle.None or AdsrHandle.AttackOrSustain))
+ {
+ var ft = new FormattedText(ClipAdsrKit.Readout(_adsrDrag, adsrFit, _bpm), NotaNum.Culture, FlowDirection.LeftToRight, GridFace, 9, ChipInkHot);
+ double cw = ft.Width + 12;
+ var chip = new Rect(Math.Clamp(adsrF.Left + 8, 2, Math.Max(2, w - cw - 2)), top + 6, cw, 16);
+ ctx.DrawRectangle(ChipBgHot, ChipEdgeHot, chip.Deflate(0.5), 3, 3);
+ ctx.DrawText(ft, new Point(chip.X + 6, chip.Y + (16 - ft.Height) / 2));
+ }
+ }
+ else if (shaped && !_envMode)
+ ClipAdsrKit.DrawCurve(ctx, adsrF, adsrFit, EnvPenDim);
+
if (_frac >= 0 && _frac <= 1)
{
// _frac runs over the PLAYED window, so on a reversed clip it walks the region
diff --git a/src/managed/Nota.App/ClipAdsrKit.cs b/src/managed/Nota.App/ClipAdsrKit.cs
new file mode 100644
index 00000000..1ee85d3e
--- /dev/null
+++ b/src/managed/Nota.App/ClipAdsrKit.cs
@@ -0,0 +1,157 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Audio-clip ADSR handles, shared by the arrangement lane and the audio clip editor so the
+// two read and behave the same. Three handles, in played time over the clip:
+// Attack — a square on the top edge at A (drag sideways);
+// D · S — a dot at (A+D, sustain) (drag both ways: decay time + sustain level);
+// Release — a square on the sustain line at len−R (drag sideways).
+// At the identity (0, 0, 1, 0) the attack square and the D·S dot share the top-left corner:
+// the first move decides — sideways grabs the attack, up/down grabs the sustain.
+// Double-click on a handle resets its stage.
+
+using System;
+using System.Collections.Generic;
+using Avalonia;
+using Avalonia.Media;
+using Nota.Application;
+
+namespace Nota.App;
+
+internal enum AdsrHandle { None, Attack, DecaySustain, Release, AttackOrSustain }
+
+/// <summary>Maps the clip's played time (beats 0..Len) and level (0..1) onto a view.</summary>
+internal readonly record struct AdsrFrame(double Left, double Right, double Top, double Bottom, double Len)
+{
+ public double X(double beat) => Left + (Len > 0 ? beat / Len : 0) * (Right - Left);
+ public double Beat(double x) => Right > Left ? (x - Left) / (Right - Left) * Len : 0;
+ public double Y(double level) => Bottom - Math.Clamp(level, 0, 1) * (Bottom - Top);
+ public double Level(double y) => Bottom > Top ? (Bottom - y) / (Bottom - Top) : 1;
+}
+
+internal static class ClipAdsrKit
+{
+ public const double HitPx = 6;
+ private const double Square = 7, Dot = 4;
+
+ public static Point AttackPt(in AdsrFrame f, ClipAdsr a) => new(f.X(a.AttackBeats), f.Top);
+ public static Point DecayPt(in AdsrFrame f, ClipAdsr a) => new(f.X(a.AttackBeats + a.DecayBeats), f.Y(a.Sustain));
+ public static Point ReleasePt(in AdsrFrame f, ClipAdsr a) => new(f.X(f.Len - a.ReleaseBeats), f.Y(a.Sustain));
+
+ private static bool Near(Point p, Point q) => Math.Abs(p.X - q.X) <= HitPx && Math.Abs(p.Y - q.Y) <= HitPx;
+
+ /// <summary>The handle under <paramref name="p"/>. The stages are fitted to the clip first so a
+ /// clip shortened below A+D+R still shows grabbable handles.</summary>
+ public static AdsrHandle Hit(Point p, in AdsrFrame f, ClipAdsr a)
+ {
+ if (f.Right - f.Left < 12) return AdsrHandle.None;
+ a = a.Fit(f.Len);
+ bool att = Near(p, AttackPt(f, a)), dec = Near(p, DecayPt(f, a));
+ if (att && dec) return AdsrHandle.AttackOrSustain;
+ if (dec) return AdsrHandle.DecaySustain;
+ if (att) return AdsrHandle.Attack;
+ if (Near(p, ReleasePt(f, a))) return AdsrHandle.Release;
+ return AdsrHandle.None;
+ }
+
+ /// <summary>Settles a shared-corner grab by the first move: sideways = attack, up/down = sustain.</summary>
+ public static AdsrHandle Resolve(AdsrHandle h, double dx, double dy)
+ => h != AdsrHandle.AttackOrSustain ? h : Math.Abs(dy) > Math.Abs(dx) ? AdsrHandle.DecaySustain : AdsrHandle.Attack;
+
+ /// <summary>Where a handle sits (clip-local beat, level) — the drag reference at press.</summary>
+ public static (double beat, double level) Anchor(AdsrHandle h, ClipAdsr a, double len)
+ {
+ a = a.Fit(len);
+ return h switch
+ {
+ AdsrHandle.DecaySustain => (a.AttackBeats + a.DecayBeats, a.Sustain),
+ AdsrHandle.Release => (len - a.ReleaseBeats, a.Sustain),
+ _ => (a.AttackBeats, 1.0),
+ };
+ }
+
+ /// <summary>Moves handle <paramref name="h"/> to (beat, level); the other stages stay put and
+ /// the moved one stops where it would cross them or leave the clip.</summary>
+ public static ClipAdsr Drag(AdsrHandle h, ClipAdsr start, double beat, double level, double len)
+ {
+ var a = start.Fit(len);
+ switch (h)
+ {
+ case AdsrHandle.Attack:
+ a.AttackBeats = Math.Clamp(beat, 0, Math.Max(0, len - a.DecayBeats - a.ReleaseBeats));
+ break;
+ case AdsrHandle.DecaySustain:
+ a.DecayBeats = Math.Clamp(beat - a.AttackBeats, 0, Math.Max(0, len - a.ReleaseBeats - a.AttackBeats));
+ a.Sustain = (float)Math.Clamp(level, 0, 1);
+ break;
+ case AdsrHandle.Release:
+ a.ReleaseBeats = Math.Clamp(len - beat, 0, Math.Max(0, len - a.AttackBeats - a.DecayBeats));
+ break;
+ }
+ return a;
+ }
+
+ /// <summary>Resets one stage to its identity value (double-click on a handle).</summary>
+ public static ClipAdsr Reset(AdsrHandle h, ClipAdsr a)
+ {
+ switch (h)
+ {
+ case AdsrHandle.Attack: a.AttackBeats = 0; break;
+ case AdsrHandle.DecaySustain: a.DecayBeats = 0; a.Sustain = 1f; break;
+ case AdsrHandle.Release: a.ReleaseBeats = 0; break;
+ case AdsrHandle.AttackOrSustain: a.AttackBeats = 0; a.DecayBeats = 0; a.Sustain = 1f; break;
+ }
+ return a;
+ }
+
+ /// <summary>The rendered gain curve (engine semantics, so overlapping stages draw as they sound).</summary>
+ public static void DrawCurve(DrawingContext ctx, in AdsrFrame f, ClipAdsr a, IPen pen)
+ {
+ double len = f.Len;
+ if (len <= 0) return;
+ var ts = new List<double> { 0, a.AttackBeats, a.AttackBeats + a.DecayBeats, len - a.ReleaseBeats, len };
+ if (a.ReleaseBeats > 0) // the release multiplies the ADS stage: sample it where it may curve
+ for (int i = 1; i < 16; i++) ts.Add(len - a.ReleaseBeats * i / 16.0);
+ ts.RemoveAll(t => t < 0 || t > len);
+ ts.Sort();
+ var geo = new StreamGeometry();
+ using (var g = geo.Open())
+ {
+ g.BeginFigure(new Point(f.X(0), f.Y(a.GainAt(0, len))), false);
+ foreach (double t in ts)
+ g.LineTo(new Point(f.X(t), f.Y(a.GainAt(t, len))));
+ g.LineTo(new Point(f.X(len), f.Bottom));
+ g.EndFigure(false);
+ }
+ ctx.DrawGeometry(null, pen, geo);
+ }
+
+ /// <summary>The three handles; <paramref name="hot"/> takes the brass fill.</summary>
+ public static void DrawHandles(DrawingContext ctx, in AdsrFrame f, ClipAdsr a, AdsrHandle hot, IBrush fill, IBrush hotFill, IPen? ring)
+ {
+ if (f.Right - f.Left < 12) return;
+ a = a.Fit(f.Len);
+ bool hotA = hot is AdsrHandle.Attack or AdsrHandle.AttackOrSustain;
+ bool hotD = hot is AdsrHandle.DecaySustain or AdsrHandle.AttackOrSustain;
+ var r = ReleasePt(f, a);
+ ctx.DrawRectangle(hot == AdsrHandle.Release ? hotFill : fill, ring, new Rect(r.X - Square / 2, r.Y - Square / 2, Square, Square));
+ ctx.DrawEllipse(hotD ? hotFill : fill, ring, DecayPt(f, a), Dot, Dot);
+ var p = AttackPt(f, a);
+ ctx.DrawRectangle(hotA ? hotFill : fill, ring, new Rect(p.X - Square / 2, p.Y - Square / 2, Square, Square));
+ }
+
+ /// <summary>"Attack 120 ms" / "Sustain −6.0 dB" — the drag readout for a handle.</summary>
+ public static string Readout(AdsrHandle h, ClipAdsr a, double bpm)
+ {
+ string T(double beats) => NotaNum.Time(beats * 60.0 / Math.Max(1, bpm));
+ return h switch
+ {
+ AdsrHandle.Attack => "Attack " + T(a.AttackBeats),
+ AdsrHandle.DecaySustain => "Decay " + T(a.DecayBeats) + " · Sustain " + SustainText(a.Sustain),
+ AdsrHandle.Release => "Release " + T(a.ReleaseBeats),
+ _ => "",
+ };
+ }
+
+ public static string SustainText(double s) => NotaNum.Db(s <= 0.0011 ? double.NegativeInfinity : AudioMath.LinToDb(s));
+}
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index 7185c6f1..8d0e8194 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -717,6 +717,7 @@ public sealed class PreferencesWindow : NotaWindow
("MOUSE", new[]
{
("Double-click clip", "Open in the clip editor"),
+ ("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"),
("Drag sections lane", "Mark a new section over the dragged bars"),
diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.cs
index fd289ba2..69efabc3 100644
--- a/src/managed/Nota.Application/Engine/EngineContracts.cs
+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs
@@ -72,6 +72,48 @@ public struct NotaAudioClipInfo
public int Reversed; // 0/1: plays back-to-front (non-destructive)
}
+/// <summary>Audio-clip ADSR amplitude shape in played time (clip-local beats). Matches native
+/// NotaClipAdsr. Attack ramps 0→1 from the clip start, decay falls to <see cref="Sustain"/>,
+/// release fades to 0 over the clip's last <see cref="ReleaseBeats"/>. <see cref="Identity"/>
+/// (the default for every clip) plays the sample at its full length and level.</summary>
+[StructLayout(LayoutKind.Sequential)]
+public struct ClipAdsr
+{
+ public double AttackBeats;
+ public double DecayBeats;
+ public double ReleaseBeats;
+ public float Sustain; // 0..1 linear gain
+ public int Reserved;
+
+ public static ClipAdsr Identity => new() { Sustain = 1f };
+
+ public readonly bool IsIdentity => AttackBeats <= 0 && DecayBeats <= 0 && ReleaseBeats <= 0 && Sustain >= 1f;
+
+ /// <summary>Gain at clip-local beat <paramref name="t"/> of a clip <paramref name="len"/> beats
+ /// long — the same shape the engine renders (see Track.h ClipAdsr::gainAt).</summary>
+ public readonly double GainAt(double t, double len)
+ {
+ double g = t < AttackBeats ? t / AttackBeats
+ : t < AttackBeats + DecayBeats ? 1 - (1 - Sustain) * ((t - AttackBeats) / DecayBeats)
+ : Sustain;
+ if (ReleaseBeats > 0 && t > len - ReleaseBeats) g *= Math.Max(0, (len - t) / ReleaseBeats);
+ return Math.Clamp(g, 0, 1);
+ }
+
+ /// <summary>Fits the stages into a clip <paramref name="len"/> beats long: attack+decay and
+ /// release each stay within the clip and never cross each other.</summary>
+ public readonly ClipAdsr Fit(double len)
+ {
+ var a = this;
+ len = Math.Max(0, len);
+ a.Sustain = Math.Clamp(a.Sustain, 0f, 1f);
+ a.AttackBeats = Math.Clamp(a.AttackBeats, 0, len);
+ a.DecayBeats = Math.Clamp(a.DecayBeats, 0, len - a.AttackBeats);
+ a.ReleaseBeats = Math.Clamp(a.ReleaseBeats, 0, len - a.AttackBeats - a.DecayBeats);
+ return a;
+ }
+}
+
/// <summary>Decoded-sample metadata. Matches native NotaSampleInfo (M7-6b).</summary>
[StructLayout(LayoutKind.Sequential)]
public struct NotaSampleInfo
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index abe625a3..a682ab5d 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -130,6 +130,11 @@ public interface IAudioEngine : IDisposable
void SetClipWarpTrim(int trackId, int clipIndex, double playStart, double playEnd);
/// <summary>Sets an audio clip's linear playback gain (runtime).</summary>
void SetClipGain(int trackId, int clipIndex, float gain);
+ /// <summary>An audio clip's ADSR amplitude shape (<see cref="ClipAdsr.Identity"/> for a
+ /// MIDI clip or a bad index).</summary>
+ ClipAdsr GetClipAdsr(int trackId, int clipIndex);
+ /// <summary>Sets an audio clip's ADSR amplitude shape (one undo step).</summary>
+ void SetClipAdsr(int trackId, int clipIndex, ClipAdsr adsr);
/// <summary>Clip deactivate (key 0): an inactive clip stays on the timeline but plays
/// nothing (audio or MIDI). Works on audio and instrument tracks.</summary>
void SetClipActive(int trackId, int clipIndex, bool active);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
index 3ed20c39..a2eeb887 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Tracks.cs
@@ -102,6 +102,12 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_clip_set_gain")]
internal static partial NotaResult ClipSetGain(IntPtr engine, int trackId, int clipIndex, float gain);
+ [LibraryImport(Lib, EntryPoint = "nota_clip_get_adsr")]
+ internal static partial int ClipGetAdsr(IntPtr engine, int trackId, int clipIndex, out ClipAdsr adsr);
+
+ [LibraryImport(Lib, EntryPoint = "nota_clip_set_adsr")]
+ internal static partial NotaResult ClipSetAdsr(IntPtr engine, int trackId, int clipIndex, in ClipAdsr adsr);
+
[LibraryImport(Lib, EntryPoint = "nota_clip_set_active")]
internal static partial NotaResult ClipSetActive(IntPtr engine, int trackId, int clipIndex, int active);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
index 0f086c61..211f60bc 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Tracks.cs
@@ -132,6 +132,15 @@ public sealed partial class NotaEngine
public void SetClipGain(int trackId, int clipIndex, float gain)
{ ThrowIfDisposed(); Check(NativeMethods.ClipSetGain(_handle, trackId, clipIndex, gain)); }
+ public ClipAdsr GetClipAdsr(int trackId, int clipIndex)
+ {
+ ThrowIfDisposed();
+ return NativeMethods.ClipGetAdsr(_handle, trackId, clipIndex, out var a) != 0 ? a : ClipAdsr.Identity;
+ }
+
+ public void SetClipAdsr(int trackId, int clipIndex, ClipAdsr adsr)
+ { ThrowIfDisposed(); Check(NativeMethods.ClipSetAdsr(_handle, trackId, clipIndex, in adsr)); }
+
/// <summary>Clip deactivate (key 0): an inactive clip stays on the timeline but plays
/// nothing (audio or MIDI). Works on audio and instrument tracks.</summary>
public void SetClipActive(int trackId, int clipIndex, bool active)
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
index 9cafa720..e9019535 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectMigrations.cs
@@ -80,6 +80,9 @@ public static class ProjectMigrations
// v18 -> v19: audio clips gain Reversed (non-destructive reverse). Absent in v18
// documents; the default (false = plays forwards) matches old behaviour — no-op.
new Migration(18, _ => { }),
+ // v19 -> v20: audio clips gain an ADSR amplitude shape (AudioClipDto.Adsr). Absent in
+ // v19 documents; null = identity (full length, full level) matches old behaviour — no-op.
+ new Migration(19, _ => { }),
};
/// <summary>Migrates <paramref name="root"/> up to <see cref="ProjectService.CurrentFormatVersion"/>
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
index 5a1e12fc..249efa9a 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -231,10 +231,25 @@ public sealed class AudioClipDto
public double WarpPlayStart { get; set; } // warped clip trim window start (beats, v11)
public double WarpPlayEnd { get; set; } // warped clip trim window end (0 = full, v11)
public bool Reversed { get; set; } // plays back-to-front (v19); default false
+ public ClipAdsrDto? Adsr { get; set; } // ADSR amplitude shape (v20); null = identity
[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
}
+/// <summary>An audio clip's ADSR amplitude shape (v20): stage times in clip-local beats,
+/// sustain as linear gain 0..1.</summary>
+public sealed class ClipAdsrDto
+{
+ public double Attack { get; set; }
+ public double Decay { get; set; }
+ public float Sustain { get; set; } = 1f;
+ public double Release { get; set; }
+
+ public ClipAdsrDto() { }
+ public ClipAdsrDto(ClipAdsr a) { Attack = a.AttackBeats; Decay = a.DecayBeats; Sustain = a.Sustain; Release = a.ReleaseBeats; }
+ public ClipAdsr ToAdsr() => new() { AttackBeats = Attack, DecayBeats = Decay, Sustain = Sustain, ReleaseBeats = Release };
+}
+
/// <summary>A warp marker: source-frame position tied to a musical beat (v6).</summary>
public sealed class WarpMarkerDto
{
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 12702d77..a5ecc0ec 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -30,7 +30,7 @@ public sealed class ProjectService
/// per-segment curvature (automationPoint.curve). v5 adds audio-clip pitch + warp
/// (pitchSemitones / warpEnabled / warpMode / warpBeats). v6 adds warp markers.</summary>
/// v18 (Phase 3) adds CV modulation: per-track LFO modulators + CV links to device params.
- public const int CurrentFormatVersion = 19;
+ public const int CurrentFormatVersion = 20;
/// <summary>Manifest file name inside the bundle folder.</summary>
public const string ManifestName = "project.json";
@@ -229,6 +229,8 @@ public sealed class ProjectService
if (env.Length > 0) dto.VolumeEnvelope = System.Array.ConvertAll(env, p => new AutomationPointDto(p));
var penv = engine.GetClipPanEnvelope(ti.Id, c); // clip pan envelope (v9)
if (penv.Length > 0) dto.PanEnvelope = System.Array.ConvertAll(penv, p => new AutomationPointDto(p));
+ var adsr = engine.GetClipAdsr(ti.Id, c); // ADSR (v20); identity is omitted
+ if (!adsr.IsIdentity) dto.Adsr = new ClipAdsrDto(adsr);
t.AudioClips.Add(dto);
}
}
@@ -657,6 +659,8 @@ public sealed class ProjectService
engine.SetClipVolumeEnvelope(id, ci, System.Array.ConvertAll(venv, p => p.ToPoint()));
if (ac.PanEnvelope is { Length: > 0 } penv) // clip pan envelope (v9)
engine.SetClipPanEnvelope(id, ci, System.Array.ConvertAll(penv, p => p.ToPoint()));
+ if (ac.Adsr is { } adsr) // ADSR (v20)
+ engine.SetClipAdsr(id, ci, adsr.ToAdsr());
}
// Freeze (M7): restore the frozen-audio buffer so the track re-opens frozen
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index 9b88df52..1bf0c6d2 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -96,6 +96,19 @@ typedef struct NotaAudioClipInfo {
int32_t reversed; /* 0/1: play the region back-to-front (non-destructive) */
} NotaAudioClipInfo;
+/* Audio-clip ADSR amplitude shape, in played time (clip-local beats). Attack ramps
+ * 0->1 from the clip start, decay falls 1->sustain, sustain holds, release fades to 0
+ * over the last release_beats before the clip end (multiplying the ADS stage, so
+ * overlapping stages on a short clip stay smooth). The default {0,0,0,1} is the
+ * identity: the sample plays its full length at full level. */
+typedef struct NotaClipAdsr {
+ double attack_beats;
+ double decay_beats;
+ double release_beats;
+ float sustain; /* 0..1 linear gain */
+ int32_t reserved; /* 0 */
+} NotaClipAdsr;
+
/* Decoded-sample metadata (M7-6b). */
typedef struct NotaSampleInfo {
int32_t channels;
@@ -791,6 +804,10 @@ NOTA_API NotaResult nota_clip_set_warp_trim(NotaEngine* engine, int32_t track_id
/* Audio-clip runtime edits: gain (linear) and varispeed transpose (semitones). */
NOTA_API NotaResult nota_clip_set_gain(NotaEngine* engine, int32_t track_id, int32_t clip_index, float gain);
NOTA_API NotaResult nota_clip_set_pitch(NotaEngine* engine, int32_t track_id, int32_t clip_index, float semitones);
+/* Audio-clip ADSR (see NotaClipAdsr). get returns 1 if the clip is audio, else 0.
+ * set clamps times to >= 0 and sustain to 0..1; one undo step. */
+NOTA_API int32_t nota_clip_get_adsr(const NotaEngine* engine, int32_t track_id, int32_t clip_index, NotaClipAdsr* out);
+NOTA_API NotaResult nota_clip_set_adsr(NotaEngine* engine, int32_t track_id, int32_t clip_index, const NotaClipAdsr* adsr);
/* Reverse an audio clip (non-destructive): the played region is read back-to-front.
* The sample and any warp cache stay in file order — only the read direction flips — so
* this is as cheap as a gain change and composes with gain/pitch/warp/clip envelopes.
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index 87ba57ff..dcec9bb5 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -512,6 +512,8 @@ public:
// Full geometry of an audio clip (false if the clip isn't audio).
bool audioClipInfo(int32_t trackId, int32_t clipIndex, NotaAudioClipInfo* out) const;
bool setClipGain(int32_t trackId, int32_t clipIndex, float gain); // audio clip runtime gain
+ bool clipAdsr(int32_t trackId, int32_t clipIndex, NotaClipAdsr* out) const; // audio clip ADSR
+ bool setClipAdsr(int32_t trackId, int32_t clipIndex, const NotaClipAdsr& adsr);
bool setClipActive(int32_t trackId, int32_t clipIndex, bool active); // clip deactivate (key 0): audio+MIDI
bool setClipPitch(int32_t trackId, int32_t clipIndex, float semitones); // audio clip varispeed transpose
bool setClipReverse(int32_t trackId, int32_t clipIndex, bool reversed); // audio clip plays back-to-front
diff --git a/src/native/nota.engine/src/Engine_Render.cpp b/src/native/nota.engine/src/Engine_Render.cpp
index 12ed239f..e76544d6 100644
--- a/src/native/nota.engine/src/Engine_Render.cpp
+++ b/src/native/nota.engine/src/Engine_Render.cpp
@@ -575,9 +575,12 @@ void Engine::renderAudioClipsRaw(const std::vector<AudioClip>& clips, float* dst
// law (unity at centre) so it composes with the track's own pan stage.
const bool hasVol = !clip.volumeEnvelope.points.empty();
const bool hasPan = !clip.panEnvelope.points.empty();
- const bool hasEnv = hasVol || hasPan;
+ const bool hasAdsr = !clip.adsr.isIdentity();
+ const bool hasEnv = hasVol || hasPan || hasAdsr;
+ double lenBeats = 0.0; // played length (beats) for the ADSR release — set per path below
auto applyEnv = [&](double p, float& l, float& r) {
const double b = (p - startSamples) / spb;
+ if (hasAdsr) { const float g = clip.adsr.gainAt(b, lenBeats); l *= g; r *= g; }
if (hasVol) { const float g = std::clamp(clip.volumeEnvelope.valueAt(b), 0.0f, 1.0f); l *= g; r *= g; }
if (hasPan) {
const float pan = std::clamp(clip.panEnvelope.valueAt(b), -1.0f, 1.0f);
@@ -593,6 +596,7 @@ void Engine::renderAudioClipsRaw(const std::vector<AudioClip>& clips, float* dst
if (clip.warpEnabled && clip.warpCache && clip.warpCache->frames > 0) {
const WarpCache& wc = *clip.warpCache;
const double clipDeviceLen = static_cast<double>(wc.frames);
+ lenBeats = clipDeviceLen / spb;
const double ovStart = std::max(blockStart, startSamples);
const double ovEnd = std::min(blockStart + frames, startSamples + clipDeviceLen);
if (ovEnd <= ovStart) continue;
@@ -626,6 +630,7 @@ void Engine::renderAudioClipsRaw(const std::vector<AudioClip>& clips, float* dst
const double ratio = sb.sourceSampleRate / sr * clip.pitchRatio();
const int64_t len = clip.effectiveLength();
const double clipDeviceLen = len / ratio;
+ lenBeats = clipDeviceLen / spb;
for (int32_t i = 0; i < frames; ++i) {
const double p = blockStart + i;
if (p < startSamples || p >= startSamples + clipDeviceLen) continue;
diff --git a/src/native/nota.engine/src/Engine_Tracks.cpp b/src/native/nota.engine/src/Engine_Tracks.cpp
index 7ce7a120..931c7665 100644
--- a/src/native/nota.engine/src/Engine_Tracks.cpp
+++ b/src/native/nota.engine/src/Engine_Tracks.cpp
@@ -87,6 +87,37 @@ bool Engine::setClipGain(int32_t trackId, int32_t clipIndex, float gain) {
return true;
}
+bool Engine::clipAdsr(int32_t trackId, int32_t clipIndex, NotaClipAdsr* out) const {
+ if (!out) return false;
+ auto t = findTrackAuthoring(trackId);
+ if (!t || t->type() != TrackType::Audio) return false;
+ if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(t->clips.size())) return false;
+ const ClipAdsr& a = t->clips[clipIndex].adsr;
+ out->attack_beats = a.attack;
+ out->decay_beats = a.decay;
+ out->release_beats = a.release;
+ out->sustain = a.sustain;
+ out->reserved = 0;
+ return true;
+}
+
+// ADSR is plain clip data (no cache to rebuild), so this is as cheap as a gain change.
+bool Engine::setClipAdsr(int32_t trackId, int32_t clipIndex, const NotaClipAdsr& in) {
+ auto old = findTrackAuthoring(trackId);
+ if (!old || old->type() != TrackType::Audio) return false;
+ if (clipIndex < 0 || clipIndex >= static_cast<int32_t>(old->clips.size())) return false;
+ auto finite = [](double v) { return std::isfinite(v) ? std::max(0.0, v) : 0.0; };
+ ClipAdsr a;
+ a.attack = finite(in.attack_beats);
+ a.decay = finite(in.decay_beats);
+ a.release = finite(in.release_beats);
+ a.sustain = std::isfinite(in.sustain) ? std::clamp(in.sustain, 0.0f, 1.0f) : 1.0f;
+ auto nt = cloneTrack(*old);
+ nt->clips[clipIndex].adsr = a;
+ republishWithTrack(trackId, nt);
+ return true;
+}
+
// clip deactivate (key 0): an inactive clip stays on the timeline but plays no
// audio / emits no MIDI. Works on both audio and instrument tracks.
bool Engine::setClipActive(int32_t trackId, int32_t clipIndex, bool active) {
@@ -984,6 +1015,7 @@ MidiClip midiCarveRight(const MidiClip& src, double startLocal) { // keep [sta
// region's end, so keeping the first beats keeps the region's tail and vice versa.
AudioClip audioCarveLeft(const AudioClip& src, double endLocal, double spb, double devSR) {
AudioClip left = src;
+ left.adsr.release = 0.0; // the cut is a new, hard end: the tail's release stays with the right piece
if (src.warpEnabled && src.warpMarkers.size() >= 2 && src.warpBeats > 0.0) {
if (src.reversed) {
left.warpPlayStart = std::max(0.0, src.warpPlayEndEff() - endLocal);
@@ -1002,6 +1034,7 @@ AudioClip audioCarveLeft(const AudioClip& src, double endLocal, double spb, doub
}
AudioClip audioCarveRight(const AudioClip& src, double startLocal, double spb, double devSR) {
AudioClip right = src; right.startBeat = src.startBeat + startLocal;
+ right.adsr.attack = 0.0; right.adsr.decay = 0.0; // the head's attack/decay stay with the left piece
if (src.warpEnabled && src.warpMarkers.size() >= 2 && src.warpBeats > 0.0) {
if (src.reversed) {
right.warpPlayStart = src.warpPlayStart;
diff --git a/src/native/nota.engine/src/Track.h b/src/native/nota.engine/src/Track.h
index 545fbfea..8ac0e0da 100644
--- a/src/native/nota.engine/src/Track.h
+++ b/src/native/nota.engine/src/Track.h
@@ -28,6 +28,31 @@
namespace nota {
+// Per-clip ADSR amplitude shape for audio clips, in PLAYED time (clip-local beats, so it
+// follows trims/reverse the way the ear hears the clip). Attack ramps 0→1 from the clip
+// start, decay falls 1→sustain, sustain holds, and release fades to 0 over the last
+// `release` beats before the clip end. The release multiplies the ADS stage, so on a clip
+// shorter than A+D+R the stages overlap smoothly instead of jumping. The default
+// (0, 0, 1, 0) is the identity: the sample plays its full length at full level.
+struct ClipAdsr {
+ double attack = 0.0; // beats
+ double decay = 0.0; // beats
+ float sustain = 1.0f; // 0..1 linear gain
+ double release = 0.0; // beats
+
+ bool isIdentity() const { return attack <= 0.0 && decay <= 0.0 && sustain >= 1.0f && release <= 0.0; }
+
+ // Gain at clip-local beat `t` of a clip `len` beats long.
+ float gainAt(double t, double len) const {
+ double g;
+ if (t < attack) g = t / attack;
+ else if (t < attack + decay) g = 1.0 - (1.0 - sustain) * ((t - attack) / decay);
+ else g = sustain;
+ if (release > 0.0 && t > len - release) g *= std::max(0.0, (len - t) / release);
+ return static_cast<float>(std::clamp(g, 0.0, 1.0));
+ }
+};
+
// A placed audio clip. `startBeat` is the musical anchor on the timeline; the
// audio itself plays at its natural rate (no time-stretch in MVP — AR/Non-Goal).
struct AudioClip {
@@ -69,6 +94,8 @@ struct AudioClip {
// Clip pan envelope (M9 follow-up): value -1..1 (balance law, unity at centre),
// applied per sample after the volume envelope. Empty = no envelope.
AutomationLane panEnvelope;
+ // ADSR amplitude shape (identity by default). Applied per sample with the envelopes.
+ ClipAdsr adsr;
int64_t effectiveLength() const {
if (!sample) return 0;
diff --git a/src/native/nota.engine/src/nota_engine_track.cpp b/src/native/nota.engine/src/nota_engine_track.cpp
index 2dfcb90f..60a545e0 100644
--- a/src/native/nota.engine/src/nota_engine_track.cpp
+++ b/src/native/nota.engine/src/nota_engine_track.cpp
@@ -325,6 +325,13 @@ NotaResult nota_clip_set_gain(NotaEngine* e, int32_t track_id, int32_t clip_inde
if (!e) return NOTA_ERR_INVALID_ARG;
return ENG(e)->setClipGain(track_id, clip_index, gain) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
}
+int32_t nota_clip_get_adsr(const NotaEngine* e, int32_t track_id, int32_t clip_index, NotaClipAdsr* out) {
+ return (e && CENG(e)->clipAdsr(track_id, clip_index, out)) ? 1 : 0;
+}
+NotaResult nota_clip_set_adsr(NotaEngine* e, int32_t track_id, int32_t clip_index, const NotaClipAdsr* adsr) {
+ if (!e || !adsr) return NOTA_ERR_INVALID_ARG;
+ return ENG(e)->setClipAdsr(track_id, clip_index, *adsr) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
+}
NotaResult nota_clip_set_active(NotaEngine* e, int32_t track_id, int32_t clip_index, int32_t active) {
if (!e) return NOTA_ERR_INVALID_ARG;
return ENG(e)->setClipActive(track_id, clip_index, active != 0) ? NOTA_OK : NOTA_ERR_INVALID_ARG;
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 815fd3bc..1866a3f1 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -891,6 +891,76 @@ Console.WriteLine("-- clip reverse --");
}
// ============== reverse on a WARPED clip (mirrors the stretch cache) =========
+// ============== clip ADSR (per-clip amplitude shape) =========================
+Console.WriteLine("-- clip ADSR --");
+{
+ // A steady sine makes the shape measurable: 4 beats at 120 BPM (2 s).
+ string adw = Path.Combine(Path.GetTempPath(), "nota_smoke_adsr.wav");
+ Nota.SmokeTest.WavWriter.WriteSine(adw, seconds: 2.0, freq: 440.0, sampleRate: 44100);
+ using var ae = new NotaEngine();
+ ae.SetBpm(120); ae.SetTimeSignature(4, 4);
+ int at = ae.AddAudioTrack();
+ int ac = ae.AddAudioClip(at, adw, 0.0);
+ Check(ae.GetClipAdsr(at, ac).IsIdentity, "ADSR is the identity by default (full length, full level)");
+ Check(ae.TryGetClipInfo(at, ac, out var aci) && aci.LengthBeats > 3.9, "ADSR: clip length known");
+ double aSpb = (ae.SampleRate > 0 ? ae.SampleRate : 48000.0) * 60.0 / 120.0;
+ int total = (int)Math.Round(aci.LengthBeats * aSpb);
+ var abuf = new float[(total + 64) * 2];
+ float Seg(double b0, double b1) // RMS over clip-local beats [b0, b1)
+ {
+ int f0 = (int)(b0 * aSpb), f1 = (int)(b1 * aSpb);
+ double sum = 0; for (int i = f0 * 2; i < f1 * 2; i++) sum += abuf[i] * (double)abuf[i];
+ return (float)Math.Sqrt(sum / Math.Max(1, (f1 - f0) * 2));
+ }
+ void RenderClip() { Array.Clear(abuf); ae.Seek(0); ae.Play(); ae.RenderOffline(abuf, total); ae.StopTransport(); }
+
+ RenderClip();
+ float full = Seg(0.5, 3.5);
+ Check(full > 0.1f, $"ADSR: identity clip plays at full level ({full:F3})");
+
+ // A=1, D=1 to sustain 0.5, R=1: silent start, full at the attack peak, half on sustain,
+ // quiet near the end.
+ ae.SetClipAdsr(at, ac, new Nota.Application.ClipAdsr { AttackBeats = 1, DecayBeats = 1, Sustain = 0.5f, ReleaseBeats = 1 });
+ var got = ae.GetClipAdsr(at, ac);
+ Check(Math.Abs(got.AttackBeats - 1) < 1e-9 && Math.Abs(got.DecayBeats - 1) < 1e-9
+ && Math.Abs(got.Sustain - 0.5f) < 1e-6 && Math.Abs(got.ReleaseBeats - 1) < 1e-9, "ADSR round-trips through the engine");
+ RenderClip();
+ float head = Seg(0.0, 0.1), peak = Seg(0.9, 1.1), sus = Seg(2.2, 2.8), tail = Seg(3.9, aci.LengthBeats);
+ Check(head < full * 0.15f, $"ADSR: attack starts silent ({head:F3})");
+ Check(Math.Abs(peak - full) < full * 0.15f, $"ADSR: attack reaches full level ({peak:F3} vs {full:F3})");
+ Check(Math.Abs(sus - full * 0.5f) < full * 0.1f, $"ADSR: decay settles on the sustain level ({sus:F3})");
+ Check(tail < full * 0.15f, $"ADSR: release fades to silence ({tail:F3})");
+
+ // Clamps: negative times and out-of-range sustain are sanitised.
+ ae.SetClipAdsr(at, ac, new Nota.Application.ClipAdsr { AttackBeats = -1, DecayBeats = 0, Sustain = 3f, ReleaseBeats = 0 });
+ Check(ae.GetClipAdsr(at, ac).IsIdentity, "ADSR: negative times / sustain > 1 clamp to the identity");
+
+ // Undo/redo: one structural edit per set.
+ ae.Undo();
+ Check(Math.Abs(ae.GetClipAdsr(at, ac).Sustain - 0.5f) < 1e-6, "ADSR: undo restores the previous shape");
+ ae.Redo();
+ Check(ae.GetClipAdsr(at, ac).IsIdentity, "ADSR: redo re-applies");
+ ae.Undo();
+
+ // Split: the left piece keeps attack/decay (no release at the cut), the right keeps the release.
+ Check(ae.SplitClip(at, ac, 2.0) == ac + 1, "ADSR: split");
+ var la = ae.GetClipAdsr(at, ac); var ra = ae.GetClipAdsr(at, ac + 1);
+ Check(la.AttackBeats > 0.99 && la.DecayBeats > 0.99 && la.ReleaseBeats == 0, "ADSR split: left keeps attack + decay, drops release");
+ Check(ra.AttackBeats == 0 && ra.DecayBeats == 0 && ra.ReleaseBeats > 0.99 && Math.Abs(ra.Sustain - 0.5f) < 1e-6,
+ "ADSR split: right keeps sustain + release, drops attack/decay");
+ ae.Undo();
+
+ // Warped clips shape the stretched output the same way.
+ ae.SetClipWarp(at, ac, true, 3);
+ ae.WarpBuildStep(int.MaxValue);
+ RenderClip();
+ Check(Seg(0.0, 0.1) < full * 0.15f && Seg(2.2, 2.8) > full * 0.3f, "ADSR shapes a warped clip too");
+
+ // A MIDI clip has no ADSR.
+ int mt = ae.AddInstrumentTrack();
+ Check(ae.GetClipAdsr(mt, 0).IsIdentity, "ADSR: non-audio clip reads as identity");
+}
+
Console.WriteLine("-- clip reverse (warped) --");
{
string rww = Path.Combine(Path.GetTempPath(), "nota_smoke_reverse_warp.wav");
@@ -8077,6 +8147,7 @@ Console.WriteLine("-- M7-6b: audio round-trip --");
{ new Nota.Application.AutomationPoint(0.0, 1.0f), new Nota.Application.AutomationPoint(2.0, 0.25f) });
src.SetClipPanEnvelope(aTrk, aClip, new[]
{ new Nota.Application.AutomationPoint(0.0, -0.5f), new Nota.Application.AutomationPoint(2.0, 0.5f) });
+ src.SetClipAdsr(aTrk, aClip, new Nota.Application.ClipAdsr { AttackBeats = 0.25, DecayBeats = 0.25, Sustain = 0.5f, ReleaseBeats = 0.5 }); // v20
int smpTrk = src.AddSamplerTrack(wav, rootNote: 62, loop: true);
Check(smpTrk > 0 && src.TrackInstrumentKind(smpTrk) == 1, "sampler track created");
@@ -8119,6 +8190,9 @@ Console.WriteLine("-- M7-6b: audio round-trip --");
var lpenv = dst.GetClipPanEnvelope(dAudio, 0);
Check(lpenv.Length == 2 && Math.Abs(lpenv[0].Value + 0.5f) < 1e-6 && Math.Abs(lpenv[1].Value - 0.5f) < 1e-6,
"clip pan envelope restored (v9)");
+ var ladsr = dst.GetClipAdsr(dAudio, 0);
+ Check(Math.Abs(ladsr.AttackBeats - 0.25) < 1e-9 && Math.Abs(ladsr.DecayBeats - 0.25) < 1e-9
+ && Math.Abs(ladsr.Sustain - 0.5f) < 1e-6 && Math.Abs(ladsr.ReleaseBeats - 0.5) < 1e-9, "clip ADSR restored (v20)");
var abuf = new float[2 * 8192];
dst.Seek(0); dst.Play(); dst.RenderOffline(abuf, 8192); dst.StopTransport();
Check(Rms(abuf, 8192) > 1e-3f, $"restored audio clip is audible (rms={Rms(abuf, 8192):F4})");