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.

(style) Redesign of preview player

Egor Khindikaynend9ecfa0ccc81
diff --git a/CHANGELOG.md b/CHANGELOG.md
index adc268c5..910db418 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,14 @@ created, and the build-and-publish run starts.
Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
### Added
+- A new sample player at the bottom of the browser's Files tab. It shows the file's real
+ waveform: click it to play from that point, hover to see the time. It also has Play / Stop,
+ a time readout, Loop, Auto (a file plays as soon as you select it) and a preview volume
+ fader (double-click it for 0 dB). With the Files list focused, ↑ ↓ move through the
+ files and Space plays or stops the selected one. Auto, Loop and the volume are remembered.
+ In a narrow browser the player tightens instead of overlapping: Auto becomes just its dot,
+ the total time and then Loop hide, and the volume folds into the speaker icon (click it
+ for the fader).
- Factory presets in the browser are sorted into folders inside each device, on the
Instruments, Audio Effects and MIDI Effects tabs. Instruments use Pads, Bass, Leads,
Keys & Plucks, Bells & Mallets and more. Effects use Vocals, Drums, Mix & Bus, Mastering,
diff --git a/src/managed/Nota.App/BrowserView.cs b/src/managed/Nota.App/BrowserView.cs
index c4eba75f..94b19fa7 100644
--- a/src/managed/Nota.App/BrowserView.cs
+++ b/src/managed/Nota.App/BrowserView.cs
@@ -9,8 +9,8 @@
// type sits at the right edge as a quiet tag. A search box filters the active list
// live, a ⋮ button holds the view options, chips filter by favorite/tag, a status
// line counts what is on screen, and a pinned preview footer auditions the selected
-// sample (Files tab). Double-clicking an item raises ItemActivated; the footer ▶ (or
-// Auto-audition on selection) raises PreviewRequested. Brushes bind via
+// sample (Files tab, see PreviewPlayer). Double-clicking an item raises ItemActivated.
+// Brushes bind via
// GetResourceObservable (the control is built during MainWindow's XAML load, before
// it is attached). Rows are drag sources (M7-5).
@@ -189,19 +189,13 @@ public sealed class BrowserView : UserControl
private readonly Border _emptyWrap;
// Pinned preview footer + the status line under it.
- private readonly Button _previewBtn;
- private readonly Path _previewIcon;
- private readonly TextBlock _previewName;
- private readonly TextBlock _previewSub;
- private readonly ToggleButton _autoAudition;
- private readonly PreviewWaveform _previewWave;
- private readonly Border _previewFooter; // sample auditioner — Files tab only
+ private readonly PreviewPlayer _previewFooter; // sample auditioner — Files tab only
private readonly Border _statusBar;
private readonly TextBlock _statusText;
- private BrowserItem? _footerItem;
public event Action<BrowserItem>? ItemActivated;
- public event Action<BrowserItem>? PreviewRequested;
+ /// <summary>The Files tab's sample player (status messages ride its StatusChanged).</summary>
+ public PreviewPlayer Preview => _previewFooter;
/// <summary>Reveal a sample / folder / project in the system file manager.</summary>
public event Action<BrowserItem>? RevealRequested;
/// <summary>Delete a project bundle (moves to Trash after confirmation).</summary>
@@ -326,8 +320,7 @@ public sealed class BrowserView : UserControl
_chipsPanel = new ChipStrip(_overflowChip, _overflowText);
_chipsHost = new Border { Margin = new Thickness(8, 0, 8, 7), Child = _chipsPanel };
- _previewFooter = BuildPreviewFooter(out _previewBtn, out _previewIcon, out _previewName,
- out _previewSub, out _autoAudition, out _previewWave);
+ _previewFooter = new PreviewPlayer();
// Status line: what the active tab is showing, counted.
_statusText = new TextBlock { FontSize = 9, VerticalAlignment = VerticalAlignment.Center };
@@ -955,75 +948,14 @@ public sealed class BrowserView : UserControl
return mi;
}
- // --- preview footer --------------------------------------------------------
-
- private Border BuildPreviewFooter(out Button playBtn, out Path playIcon, out TextBlock name,
- out TextBlock sub, out ToggleButton auto, out PreviewWaveform wave)
- {
- // Row 1: filename + format info (mono).
- name = new TextBlock { Text = "—", FontSize = 10, VerticalAlignment = VerticalAlignment.Bottom };
- name.BindResource(TextBlock.ForegroundProperty, "Brush.TextPrimary");
- sub = new TextBlock { Text = "", FontSize = 9, VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(6, 0, 0, 0) };
- sub.Classes.Add("Mono");
- sub.BindResource(TextBlock.ForegroundProperty, "Brush.TextTertiary");
- var infoRow = new StackPanel { Orientation = Orientation.Horizontal, Margin = new Thickness(0, 0, 0, 6), Children = { name, sub } };
-
- // Row 2: play button + waveform strip.
- playIcon = new Path { Data = Geometry.Parse(IconPlay), Stretch = Stretch.Uniform, Width = 10, Height = 10, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center };
- // A raised button with a brass glyph: the transport's Play is the main window's one solid brass action.
- playIcon.BindResource(Shape.FillProperty, "Brush.AccentBright");
- playBtn = new Button { Content = playIcon, Width = 26, Height = 26, Padding = new Thickness(0), IsEnabled = false, VerticalAlignment = VerticalAlignment.Center };
- var pb = playBtn;
- pb.Click += (_, _) => { if (_footerItem is { } it && it.Kind == BrowserItemKind.Sample) PreviewRequested?.Invoke(it); };
- wave = new PreviewWaveform { Height = 30, Margin = new Thickness(8, 0, 0, 0), VerticalAlignment = VerticalAlignment.Center };
- var playRow = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };
- Grid.SetColumn(pb, 0);
- Grid.SetColumn(wave, 1);
- playRow.Children.Add(pb);
- playRow.Children.Add(wave);
-
- // Row 3: Auto-audition chip + preview volume bar (decorative — not wired).
- auto = new ToggleButton { Content = "Auto-audition", FontSize = 9, Padding = new Thickness(6, 0), Height = 18, VerticalAlignment = VerticalAlignment.Center };
- ToolTip.SetTip(auto, "Audition a sample when it is selected");
- var volFillOuter = new Border { Width = 50, Height = 3, CornerRadius = NotaRadius.Clip, VerticalAlignment = VerticalAlignment.Center };
- volFillOuter.BindResource(Border.BackgroundProperty, "Brush.BgSunken");
- var volFill = new Border { Width = 32, Height = 3, CornerRadius = NotaRadius.Clip, HorizontalAlignment = HorizontalAlignment.Left };
- volFill.BindResource(Border.BackgroundProperty, "Brush.BorderStrong");
- volFillOuter.Child = volFill;
- ToolTip.SetTip(volFillOuter, "Set the preview volume (not available yet)");
- var row3 = new StackPanel
- {
- Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 6, 0, 0),
- VerticalAlignment = VerticalAlignment.Center, Children = { auto, Caption("vol"), volFillOuter },
- };
-
- var footer = new Border
- {
- BorderThickness = new Thickness(0, 1, 0, 0),
- Padding = new Thickness(10, 8),
- Child = new StackPanel { Children = { infoRow, playRow, row3 } },
- };
- footer.BindResource(Border.BackgroundProperty, "Brush.Panel");
- footer.BindResource(Border.BorderBrushProperty, "Brush.BorderDefault");
- return footer;
- }
-
- private void UpdateFooter(BrowserItem? item)
+ /// <summary>Space while the Files list has focus: the player's Play / Stop. False when
+ /// the key isn't the browser's (another tab, nothing to play) so it falls to the transport.</summary>
+ public bool TryTogglePreview(object? source)
{
- _footerItem = item;
- bool isSample = item is { Kind: BrowserItemKind.Sample };
- _previewName.Text = item?.Name ?? "—";
- _previewSub.Text = isSample && !string.IsNullOrEmpty(item!.Sub) ? "· " + item.Sub : "";
- _previewBtn.IsEnabled = isSample;
- _previewWave.SetSample(isSample ? item!.Name : null);
- if (isSample && (_autoAudition.IsChecked ?? false)) PreviewRequested?.Invoke(item!);
- }
-
- private TextBlock Caption(string text)
- {
- var t = new TextBlock { Text = text, FontSize = 9, VerticalAlignment = VerticalAlignment.Center };
- t.BindResource(TextBlock.ForegroundProperty, "Brush.TextTertiary");
- return t;
+ if (_active != FilesTab || !_previewFooter.HasSample) return false;
+ for (var c = source as StyledElement; c is not null; c = c.Parent)
+ if (c == _pages[FilesTab] || c == _previewFooter) { _previewFooter.Toggle(); return true; }
+ return false;
}
private ListBox NewList(IDataTemplate itemTemplate) => new()
@@ -1046,7 +978,7 @@ public sealed class BrowserView : UserControl
{
// Section headers are chrome: never let one become the selection.
if (list.SelectedItem is BrowserItem { IsGroup: true }) { list.SelectedItem = null; return; }
- if (_active >= 0 && list == _pages[_active]) UpdateFooter(list.SelectedItem as BrowserItem);
+ if (list == _pages[FilesTab]) _previewFooter.SetItem(list.SelectedItem as BrowserItem);
};
// Drag source (M7-5): start a copy-drag when the pointer leaves the row.
// Must use handledEventsToo — ListBoxItem marks PointerPressed as Handled for
diff --git a/src/managed/Nota.App/MainWindow.Browser.cs b/src/managed/Nota.App/MainWindow.Browser.cs
index 5e9a6ac8..345c228b 100644
--- a/src/managed/Nota.App/MainWindow.Browser.cs
+++ b/src/managed/Nota.App/MainWindow.Browser.cs
@@ -288,20 +288,6 @@ public partial class MainWindow
await new TagEditorWindow(lib, key).ShowDialog(this);
}
- private void OnBrowserPreview(BrowserItem item)
- {
- if (_vm is null || string.IsNullOrEmpty(item.Path)) return;
- try
- {
- Engine.PreviewFile(item.Path);
- _vm.StatusText = $"Previewing {item.Name}";
- }
- catch (Exception ex)
- {
- _vm.StatusText = $"Preview failed: {ex.Message}";
- }
- }
-
private async void OnSavePreset(int deviceIndex)
{
if (_vm is null || _deviceChain is null) return;
diff --git a/src/managed/Nota.App/MainWindow.Input.cs b/src/managed/Nota.App/MainWindow.Input.cs
index d5138a69..117d7a38 100644
--- a/src/managed/Nota.App/MainWindow.Input.cs
+++ b/src/managed/Nota.App/MainWindow.Input.cs
@@ -45,6 +45,8 @@ public partial class MainWindow
if (e.Key == Key.Space)
{
+ // In the Files list Space auditions the selected sample instead.
+ if (Browser.TryTogglePreview(e.Source)) { e.Handled = true; return; }
_vm.Transport.PlayStopCommand.Execute(null);
e.Handled = true;
}
diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.cs
index 0eb47409..a9207772 100644
--- a/src/managed/Nota.App/MainWindow.axaml.cs
+++ b/src/managed/Nota.App/MainWindow.axaml.cs
@@ -280,7 +280,8 @@ public partial class MainWindow : Window
Timeline.ShowSections = vm.Settings.Current.ArrangementShowSections;
Browser.SetViewModel(vm.Browser);
Browser.ItemActivated += OnBrowserItemActivated;
- Browser.PreviewRequested += OnBrowserPreview;
+ Browser.Preview.Attach(vm.Engine, vm.Settings);
+ Browser.Preview.StatusChanged += msg => { if (_vm is not null) _vm.StatusText = msg; };
Browser.RevealRequested += OnBrowserReveal;
Browser.DeleteProjectRequested += OnBrowserDeleteProject;
Browser.EditTagsRequested += OnBrowserEditTags;
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index 55e9d588..c3d4d61f 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -640,7 +640,8 @@ public sealed class PreferencesWindow : NotaWindow
// NB: this list mirrors the real key handlers — keep the two in sync (see the
// `nota-shortcuts` skill). Bindings live in MainWindow.Input.cs (transport, global
- // editing, computer-keyboard notes) and PianoRollView.cs (note editing). ⌘ = Meta on
+ // editing, computer-keyboard notes), PianoRollView.cs (note editing) and PreviewPlayer.cs
+ // (the Files tab's sample player). ⌘ = Meta on
// macOS / Ctrl on Windows.
private static readonly (string Title, (string Key, string Action)[] Rows)[] ShortcutGroups =
{
@@ -695,6 +696,13 @@ public sealed class PreferencesWindow : NotaWindow
("Z / X", "Shift octave down / up"),
("C / V", "Lower / raise velocity"),
}),
+ ("BROWSER · FILES", new[]
+ {
+ ("↑ ↓", "Move through the files · with Auto on, each one plays as it is selected"),
+ ("Space", "Play / stop the selected sample (while the Files list has focus)"),
+ ("Click waveform", "Play from that point"),
+ ("Double-click volume", "Reset the preview volume to 0\u2009dB"),
+ }),
("GAMEPAD (MACOS)", new[]
{
("Face buttons", "Play C4 D4 E4 F4"),
diff --git a/src/managed/Nota.App/PreviewPlayer.cs b/src/managed/Nota.App/PreviewPlayer.cs
new file mode 100644
index 00000000..4b3450ae
--- /dev/null
+++ b/src/managed/Nota.App/PreviewPlayer.cs
@@ -0,0 +1,738 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// The sample auditioner pinned under the browser's Files tab ("Nota Preview Player",
+// strip 1a): the file's name and format, its real waveform in a well (click = seek,
+// hover = time tag, a brass playhead while it plays), then Play/Stop, the time readout,
+// Loop, Auto (selecting a file plays it) and a preview-volume fader (double-click =
+// 0 dB). The waveform is decoded off the UI thread through the engine's background
+// import; playback is the engine's audition voice, polled for its playhead while live.
+// Auto / Loop / volume persist in Settings. In a narrow browser the strip sheds by need
+// (see Adapt): Auto drops its label, the total time goes (the meta line carries it), the
+// fader folds into a speaker that pops it up, then Loop, then the time readout.
+
+using System;
+using System.Collections.Generic;
+using File = System.IO.File;
+using BinaryReader = System.IO.BinaryReader;
+using System.Threading;
+using System.Threading.Tasks;
+using Avalonia;
+using Avalonia.Controls;
+using Avalonia.Controls.Shapes;
+using Avalonia.Input;
+using Avalonia.Layout;
+using Avalonia.Media;
+using Avalonia.Threading;
+using Nota.Application;
+using Nota.Presentation;
+
+namespace Nota.App;
+
+public sealed class PreviewPlayer : UserControl
+{
+ private const string IconLoop = "M17 3 l3 3 l-3 3 M20 6 H8 a4 4 0 0 0 -4 4 v1 M7 21 l-3 -3 l3 -3 M4 18 h12 a4 4 0 0 0 4 -4 v-1";
+ private const string IconSpeaker = "M4 9 h4 l5 -4 v14 l-5 -4 h-4 z";
+ private const string WavesMute = "M16 9 l5 6 M21 9 l-5 6";
+ private const string WavesLow = "M16 9.5 a3.5 3.5 0 0 1 0 5";
+ private const string WavesHigh = "M16 9.5 a3.5 3.5 0 0 1 0 5 M18.5 7 a7 7 0 0 1 0 10";
+ private const double DefaultVolume = 0.7;
+
+ private readonly TextBlock _name, _meta, _timeNow, _timeTotal;
+ private readonly PreviewWaveform _wave;
+ private readonly Border _playBtn, _loopBtn, _autoBtn;
+ private readonly Path _playGlyph, _stopGlyph, _loopIcon, _volWaves;
+ private readonly Ellipse _autoDot;
+ private readonly TextBlock _autoText;
+ private readonly PreviewVolume _volume, _volumePop;
+ private readonly Border _volIconBtn;
+ private readonly StackPanel _time;
+ private readonly Flyout _volFlyout;
+ private string[] _metaParts = Array.Empty<string>();
+ private bool _volCompact;
+ private readonly DispatcherTimer _poll;
+
+ private IAudioEngine? _engine;
+ private ISettingsService? _settings;
+ private BrowserItem? _item;
+ private double _duration; // seconds; 0 until the header is read
+ private double _pos; // seconds into the file
+ private bool _playing, _loop, _auto = true;
+ private int _loadGen;
+
+ // Decoded overviews by path, so arrowing back through a folder doesn't re-decode.
+ private readonly Dictionary<string, FileInfoCache> _cache = new(StringComparer.Ordinal);
+ private readonly Queue<string> _cacheOrder = new();
+ private const int CacheMax = 64;
+ private const int PeakPoints = 512;
+
+ // Meta is the format line split in parts, most important first (length, rate, depth, channels).
+ private sealed record FileInfoCache(double Duration, string[] Meta, float[]? Peaks);
+
+ /// <summary>Audition failed or started — for the status line.</summary>
+ public event Action<string>? StatusChanged;
+
+ public PreviewPlayer()
+ {
+ // Row 1: name · format.
+ _name = new TextBlock
+ {
+ Text = "—", FontSize = 12, FontWeight = FontWeight.SemiBold,
+ Foreground = NotaPalette.TextPrimary, TextTrimming = TextTrimming.CharacterEllipsis,
+ VerticalAlignment = VerticalAlignment.Bottom,
+ };
+ _meta = new TextBlock
+ {
+ FontSize = 9, FontFamily = NotaFonts.MonoFamily, Foreground = NotaPalette.TextTertiary,
+ Margin = new Thickness(8, 0, 0, 1), VerticalAlignment = VerticalAlignment.Bottom,
+ };
+ var head = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };
+ head.Children.Add(_name);
+ Grid.SetColumn(_meta, 1);
+ head.Children.Add(_meta);
+
+ // Row 2: the waveform well.
+ _wave = new PreviewWaveform { Height = 46 };
+ _wave.SeekRequested += f => { if (_item is not null && _duration > 0) Play(f * _duration); };
+
+ // Row 3: transport.
+ _playGlyph = new Path
+ {
+ Data = Geometry.Parse("M1.5 1 L10 6 L1.5 11 Z"), Width = 11, Height = 12,
+ StrokeThickness = 1, StrokeJoin = PenLineJoin.Round,
+ HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,
+ };
+ _stopGlyph = new Path
+ {
+ Data = new RectangleGeometry(new Rect(1, 1, 8, 8), 1, 1), Width = 10, Height = 10,
+ Fill = NotaPalette.TextOnAccent, IsVisible = false,
+ HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,
+ };
+ _playBtn = Chip(new Panel { Children = { _playGlyph, _stopGlyph } }, 28, 28, 5);
+ ToolTip.SetTip(_playBtn, "Play / Stop (Space)");
+ _playBtn.PointerPressed += (_, e) => { if (IsLeft(e)) { Toggle(); e.Handled = true; } };
+
+ _timeNow = new TextBlock { FontSize = 10, FontFamily = NotaFonts.MonoFamily, VerticalAlignment = VerticalAlignment.Center };
+ _timeTotal = new TextBlock { FontSize = 10, FontFamily = NotaFonts.MonoFamily, Foreground = NotaPalette.TextDisabled, VerticalAlignment = VerticalAlignment.Center };
+ var time = _time = new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 3, Margin = new Thickness(6, 0, 0, 0),
+ VerticalAlignment = VerticalAlignment.Center, Children = { _timeNow, _timeTotal },
+ };
+
+ _loopIcon = IconPath(IconLoop);
+ _loopBtn = Chip(Icon12(_loopIcon), 22, 22, 4);
+ ToolTip.SetTip(_loopBtn, "Loop");
+ _loopBtn.PointerPressed += (_, e) => { if (IsLeft(e)) { SetLoop(!_loop, persist: true); e.Handled = true; } };
+
+ _autoDot = new Ellipse { Width = 6, Height = 6, VerticalAlignment = VerticalAlignment.Center };
+ _autoText = new TextBlock { Text = "Auto", FontSize = 10, FontWeight = FontWeight.SemiBold, VerticalAlignment = VerticalAlignment.Center };
+ _autoBtn = Chip(new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center,
+ Children = { _autoDot, _autoText },
+ }, double.NaN, 22, 4);
+ _autoBtn.Padding = new Thickness(7, 0);
+ ToolTip.SetTip(_autoBtn, "Auto-audition: play on select");
+ _autoBtn.PointerPressed += (_, e) => { if (IsLeft(e)) { SetAuto(!_auto, persist: true); e.Handled = true; } };
+
+ var speaker = IconPath(IconSpeaker);
+ speaker.Stroke = NotaPalette.TextMuted;
+ _volWaves = IconPath(WavesHigh);
+ _volWaves.Stroke = NotaPalette.TextMuted;
+ _volume = new PreviewVolume { Width = 46, Height = 16, VerticalAlignment = VerticalAlignment.Center };
+ _volume.ValueChanged += (v, done) => ApplyVolume(v, persist: done);
+ // Folded (narrow browser) the speaker alone stays; a click pops the fader up.
+ _volumePop = new PreviewVolume { Width = 110, Height = 16 };
+ _volumePop.ValueChanged += (v, done) => ApplyVolume(v, persist: done);
+ _volFlyout = new Flyout { Content = _volumePop, Placement = PlacementMode.Top };
+ _volIconBtn = new Border
+ {
+ Width = 12, Height = 22, Background = Brushes.Transparent,
+ Child = Icon12(new Panel { Children = { speaker, _volWaves } }),
+ };
+ _volIconBtn.PointerPressed += (_, e) =>
+ {
+ if (!_volCompact || !IsLeft(e)) return;
+ _volFlyout.ShowAt(_volIconBtn);
+ e.Handled = true;
+ };
+ var vol = new StackPanel
+ {
+ Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center,
+ Children = { _volIconBtn, _volume },
+ };
+ _volumeBox = vol;
+
+ var controls = new DockPanel { LastChildFill = false };
+ DockPanel.SetDock(_playBtn, Dock.Left);
+ DockPanel.SetDock(time, Dock.Left);
+ DockPanel.SetDock(vol, Dock.Right);
+ DockPanel.SetDock(_autoBtn, Dock.Right);
+ DockPanel.SetDock(_loopBtn, Dock.Right);
+ _autoBtn.Margin = new Thickness(6, 0);
+ controls.Children.Add(_playBtn);
+ controls.Children.Add(time);
+ controls.Children.Add(vol);
+ controls.Children.Add(_autoBtn);
+ controls.Children.Add(_loopBtn);
+
+ Content = new Border
+ {
+ Background = NotaPalette.SurfaceInset,
+ BorderBrush = NotaPalette.BorderDefault,
+ BorderThickness = new Thickness(0, 1, 0, 0),
+ Padding = new Thickness(10),
+ Child = new StackPanel { Spacing = 8, Children = { head, _wave, controls } },
+ };
+
+ SizeChanged += (_, _) => Adapt();
+
+ _poll = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(30) };
+ _poll.Tick += (_, _) => Poll();
+
+ SetLoop(false, persist: false);
+ SetAuto(true, persist: false);
+ ApplyVolume(DefaultVolume, persist: false);
+ Refresh();
+ }
+
+ private readonly StackPanel _volumeBox;
+
+ /// <summary>Wire the engine (playback, decode) and the settings (Auto / Loop / volume).</summary>
+ public void Attach(IAudioEngine engine, ISettingsService settings)
+ {
+ _engine = engine;
+ _settings = settings;
+ SetAuto(settings.Current.BrowserPreviewAuto, persist: false);
+ SetLoop(settings.Current.BrowserPreviewLoop, persist: false);
+ ApplyVolume(Math.Clamp(settings.Current.BrowserPreviewVolume, 0, 1), persist: false);
+ }
+
+ /// <summary>The browser selection moved. A sample loads its waveform (and plays, with Auto
+ /// on); anything else empties the player and stops what it was playing.</summary>
+ public void SetItem(BrowserItem? item)
+ {
+ var sample = item is { Kind: BrowserItemKind.Sample } && !string.IsNullOrEmpty(item.Path) ? item : null;
+ if (sample is not null && _item is not null && sample.Path == _item.Path) return;
+ bool wasPlaying = _playing;
+ _item = sample;
+ _pos = 0;
+ _duration = 0;
+ _metaParts = Array.Empty<string>();
+ _wave.SetPeaks(null);
+ if (sample is null)
+ {
+ if (wasPlaying) Stop();
+ Refresh();
+ return;
+ }
+ LoadInfo(sample.Path);
+ if (_auto) Play(0);
+ else { if (wasPlaying) Stop(); Refresh(); }
+ }
+
+ /// <summary>Space in the Files list: play the selected sample, or stop it.</summary>
+ public void Toggle()
+ {
+ if (_playing) Stop();
+ else Play(0);
+ }
+
+ public bool HasSample => _item is not null;
+
+ // --- playback -------------------------------------------------------------
+
+ private void Play(double from)
+ {
+ if (_engine is null || _item is null) return;
+ try
+ {
+ _engine.SetPreviewLoop(_loop);
+ _engine.SetPreviewGain((float)(_volume.Value * _volume.Value));
+ _engine.PreviewFileAt(_item.Path, Math.Max(0, from));
+ _playing = true;
+ _pos = from;
+ _poll.Start();
+ StatusChanged?.Invoke($"Previewing {_item.Name}");
+ }
+ catch (Exception ex)
+ {
+ _playing = false;
+ StatusChanged?.Invoke($"Preview failed: {ex.Message}");
+ }
+ Refresh();
+ }
+
+ private void Stop()
+ {
+ try { _engine?.StopPreview(); } catch { /* engine gone */ }
+ _playing = false;
+ _pos = 0;
+ _poll.Stop();
+ Refresh();
+ }
+
+ private void Poll()
+ {
+ if (_engine is null || !_playing) { _poll.Stop(); return; }
+ if (!_engine.IsPreviewActive)
+ {
+ // Ran off the end (or something else stopped the audition — a project load).
+ _playing = false;
+ _pos = 0;
+ _poll.Stop();
+ }
+ else _pos = _engine.PreviewPosition;
+ Refresh();
+ }
+
+ private void SetLoop(bool on, bool persist)
+ {
+ _loop = on;
+ try { _engine?.SetPreviewLoop(on); } catch { }
+ _loopBtn.Background = on ? NotaPalette.AccentSubtle : Brushes.Transparent;
+ _loopBtn.BorderBrush = on ? NotaPalette.AccentEdge : NotaPalette.BorderDefault;
+ _loopIcon.Stroke = on ? NotaPalette.Accent : NotaPalette.TextTertiary;
+ if (persist && _settings is not null) { _settings.Current.BrowserPreviewLoop = on; _settings.Save(); }
+ }
+
+ private void SetAuto(bool on, bool persist)
+ {
+ _auto = on;
+ _autoBtn.Background = on ? NotaPalette.AccentSubtle : Brushes.Transparent;
+ _autoBtn.BorderBrush = on ? NotaPalette.AccentEdge : NotaPalette.BorderDefault;
+ _autoDot.Fill = on ? NotaPalette.Accent : NotaPalette.BorderStrong;
+ _autoText.Foreground = on ? NotaPalette.AccentHover : NotaPalette.TextMuted;
+ if (persist && _settings is not null) { _settings.Current.BrowserPreviewAuto = on; _settings.Save(); }
+ }
+
+ // v is the fader position; the gain is v² (so the travel reads roughly in dB).
+ private void ApplyVolume(double v, bool persist)
+ {
+ v = Math.Clamp(v, 0, 1);
+ _volume.Value = v;
+ _volumePop.Value = v;
+ try { _engine?.SetPreviewGain((float)(v * v)); } catch { }
+ _volWaves.Data = Geometry.Parse(v <= 0.001 ? WavesMute : v < 0.5 ? WavesLow : WavesHigh);
+ var db = NotaNum.Db(v <= 0.001 ? double.NegativeInfinity : 40 * Math.Log10(v));
+ ToolTip.SetTip(_volumeBox, $"Preview volume {db} · double-click for 0{NotaNum.Thin}dB");
+ ToolTip.SetTip(_volumePop, $"Preview volume {db} · double-click for 0{NotaNum.Thin}dB");
+ if (persist && _settings is not null) { _settings.Current.BrowserPreviewVolume = v; _settings.Save(); }
+ }
+
+ private void Refresh()
+ {
+ bool has = _item is not null;
+ _name.Text = _item?.Name ?? "—";
+ _playGlyph.IsVisible = !_playing;
+ _stopGlyph.IsVisible = _playing;
+ _playBtn.Background = _playing ? NotaPalette.Accent : NotaPalette.SurfaceRaised;
+ _playBtn.BorderBrush = _playing ? NotaPalette.Accent : NotaPalette.BorderStrong;
+ var glyph = has ? NotaPalette.Accent : NotaPalette.TextDisabled;
+ _playGlyph.Fill = glyph;
+ _playGlyph.Stroke = glyph;
+ _playBtn.Cursor = has ? new Cursor(StandardCursorType.Hand) : Cursor.Default;
+ _timeNow.Text = Fmt(_pos);
+ _timeNow.Foreground = _playing ? NotaPalette.TextPrimary : NotaPalette.TextMuted;
+ _timeTotal.Text = "/ " + Fmt(_duration);
+ _wave.SetState(_duration, _pos, _playing);
+ Adapt();
+ }
+
+ // --- narrow widths ------------------------------------------------------------
+
+ // Fits the strip to the browser's width, shedding by need. Header: the name wins and the
+ // meta shortens ("0.50 s · 44.1k · 16-bit · M" → "0.50 s · 44.1k" → "0.50 s" → gone).
+ // Controls, cheapest loss first: Auto's label (the lit dot still reads), the total time
+ // (the meta line has it), the fader (folds into the speaker, which pops it up), Loop, then
+ // the time readout. Play, Auto and the speaker always stay.
+ private void Adapt()
+ {
+ double avail = Bounds.Width - 20; // the strip's padding
+ if (avail <= 0) return;
+
+ // Header.
+ double nameW = TextW(_name.Text ?? "", NotaFonts.SansSemiBold, 12);
+ string meta = "";
+ for (int n = _metaParts.Length; n >= 1; n--)
+ {
+ // A lone "unsupported" (or a full set) is all-or-nothing; the rest drops from the tail.
+ if (n < _metaParts.Length && n > 2) continue; // full, or length · rate, or length
+ var m = string.Join(" · ", _metaParts, 0, n);
+ if (nameW + 8 + TextW(m, NotaFonts.Mono, 9) <= avail) { meta = m; break; }
+ }
+ _meta.Text = meta;
+ _meta.IsVisible = meta.Length > 0;
+
+ // Controls.
+ const double gap = 6, minMiddle = 8;
+ double now = TextW(_timeNow.Text ?? "", NotaFonts.Mono, 10);
+ double total = 3 + TextW(_timeTotal.Text ?? "", NotaFonts.Mono, 10);
+ double autoFull = 2 + 7 + 6 + 5 + TextW("Auto", NotaFonts.SansSemiBold, 10) + 7, autoDot = 22;
+ double volFull = 12 + 5 + 46, volIcon = 22, loop = 22 + gap;
+
+ int level = 0;
+ for (; level < 5; level++)
+ {
+ double left = 28 + gap + now + (level < 2 ? total : 0);
+ double right = (level < 4 ? loop : 0) + gap + (level < 1 ? autoFull : autoDot) + gap + (level < 3 ? volFull : volIcon);
+ if (left + minMiddle + right <= avail) break;
+ }
+ _autoText.IsVisible = level < 1;
+ _autoBtn.Width = level < 1 ? double.NaN : autoDot;
+ _autoBtn.Padding = level < 1 ? new Thickness(7, 0) : new Thickness(0);
+ _timeTotal.IsVisible = level < 2;
+ _volCompact = level >= 3;
+ _volume.IsVisible = !_volCompact;
+ _volIconBtn.Width = _volCompact ? volIcon : 12;
+ _volIconBtn.Cursor = _volCompact ? HandCursor : Cursor.Default;
+ _loopBtn.IsVisible = level < 4;
+ _time.IsVisible = level < 5;
+ }
+
+ private static readonly Cursor HandCursor = new(StandardCursorType.Hand);
+
+ private static double TextW(string s, Typeface tf, double size)
+ => s.Length == 0 ? 0 : new FormattedText(s, NotaNum.Culture, FlowDirection.LeftToRight, tf, size, null).Width;
+
+ // "SS.cc" as the mockup prints it; a minute or more gets "M:SS.cc".
+ private static string Fmt(double s)
+ {
+ s = Math.Max(0, s);
+ int whole = (int)s, cs = (int)((s - whole) * 100);
+ return whole >= 60 ? $"{whole / 60}:{whole % 60:00}.{cs:00}" : $"{whole:00}.{cs:00}";
+ }
+
+ // --- waveform + format, decoded off the UI thread ---------------------------
+
+ private void LoadInfo(string path)
+ {
+ int gen = ++_loadGen;
+ if (_cache.TryGetValue(path, out var hit))
+ {
+ ShowInfo(hit);
+ if (hit.Peaks is not null) return;
+ }
+ var engine = _engine;
+ if (engine is null) return;
+ Task.Run(() =>
+ {
+ IAudioImport? job = null;
+ try
+ {
+ job = engine.OpenAudioImport(path);
+ if (job is null) { Post(gen, path, new FileInfoCache(0, new[] { "unsupported" }, null), final: true); return; }
+ double dur = job.SampleRate > 0 ? job.TotalFrames / job.SampleRate : 0;
+ var meta = FormatMeta(path, dur, job.SampleRate, job.Channels);
+ Post(gen, path, new FileInfoCache(dur, meta, null), final: false);
+ var peaks = new float[PeakPoints * 2];
+ var sw = System.Diagnostics.Stopwatch.StartNew();
+ while (true)
+ {
+ if (Volatile.Read(ref _loadGen) != gen) return; // selection moved on
+ int r = job.Step(1 << 16);
+ if (r < 0) return;
+ bool done = r == 0;
+ // Long files fill in progressively (every ~120 ms) rather than all at the end.
+ if (done || sw.ElapsedMilliseconds > 120)
+ {
+ int n = job.ReadPeaks(peaks, PeakPoints);
+ Post(gen, path, new FileInfoCache(dur, meta, ToAmplitudes(peaks, n)), final: done);
+ sw.Restart();
+ }
+ if (done) return;
+ }
+ }
+ catch { /* unreadable file: leave the well empty */ }
+ finally { job?.Dispose(); }
+ });
+ }
+
+ private void Post(int gen, string path, FileInfoCache info, bool final)
+ {
+ Dispatcher.UIThread.Post(() =>
+ {
+ if (final) Remember(path, info);
+ if (gen == _loadGen && _item?.Path == path) ShowInfo(info);
+ });
+ }
+
+ private void ShowInfo(FileInfoCache info)
+ {
+ _duration = info.Duration;
+ _metaParts = info.Meta;
+ _wave.SetPeaks(info.Peaks);
+ Refresh();
+ }
+
+ private void Remember(string path, FileInfoCache info)
+ {
+ if (!_cache.ContainsKey(path))
+ {
+ _cacheOrder.Enqueue(path);
+ while (_cacheOrder.Count > CacheMax) _cache.Remove(_cacheOrder.Dequeue());
+ }
+ _cache[path] = info;
+ }
+
+ // (min,max) pairs → peak magnitude per bucket; undecoded buckets (min > max) read as 0.
+ private static float[] ToAmplitudes(float[] minMax, int n)
+ {
+ var a = new float[n];
+ for (int i = 0; i < n; i++)
+ {
+ float mn = minMax[2 * i], mx = minMax[2 * i + 1];
+ a[i] = mn > mx ? 0 : Math.Max(Math.Abs(mn), Math.Abs(mx));
+ }
+ return a;
+ }
+
+ // "0.34 s · 44.1k · 24-bit · M"; the bit depth only where the header says (WAV).
+ private static string[] FormatMeta(string path, double dur, double sr, int channels)
+ {
+ var parts = new List<string>
+ {
+ // Truncated like the time readout, so "1.89 s" never meets "/ 01.89" rounded up to 1.90.
+ dur >= 60 ? Fmt(dur) : NotaNum.Unit(Math.Floor(dur * 100) / 100, "0.00", "s"),
+ NotaNum.Str(sr / 1000, "0.#") + "k",
+ };
+ var bits = WavBitDepth(path);
+ if (bits is not null) parts.Add(bits);
+ parts.Add(channels == 1 ? "M" : channels == 2 ? "S" : channels + "ch");
+ return parts.ToArray();
+ }
+
+ private static string? WavBitDepth(string path)
+ {
+ try
+ {
+ using var fs = File.OpenRead(path);
+ using var br = new BinaryReader(fs);
+ if (fs.Length < 12) return null;
+ var riff = new string(br.ReadChars(4));
+ br.ReadUInt32();
+ if ((riff != "RIFF" && riff != "RF64") || new string(br.ReadChars(4)) != "WAVE") return null;
+ while (fs.Position + 8 <= fs.Length)
+ {
+ var id = new string(br.ReadChars(4));
+ uint size = br.ReadUInt32();
+ if (id == "fmt " && size >= 16)
+ {
+ ushort format = br.ReadUInt16();
+ br.ReadBytes(12); // channels, rate, byte rate, block align
+ ushort bits = br.ReadUInt16();
+ if (format == 0xFFFE && size >= 26) // WAVE_FORMAT_EXTENSIBLE: the sub-format decides
+ {
+ br.ReadBytes(8);
+ format = br.ReadUInt16();
+ }
+ return format == 3 ? $"{bits}-bit float" : $"{bits}-bit";
+ }
+ fs.Position += size + (size & 1);
+ }
+ }
+ catch { }
+ return null;
+ }
+
+ // --- small builders ---------------------------------------------------------
+
+ private static bool IsLeft(PointerPressedEventArgs e) => e.GetCurrentPoint(null).Properties.IsLeftButtonPressed;
+
+ private static Border Chip(Control child, double w, double h, double radius) => new()
+ {
+ Width = w, Height = h,
+ CornerRadius = new CornerRadius(radius),
+ BorderThickness = new Thickness(1),
+ Cursor = new Cursor(StandardCursorType.Hand),
+ VerticalAlignment = VerticalAlignment.Center,
+ Child = new Panel { HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Children = { child } },
+ };
+
+ // A stroke glyph on the design's 24-unit grid (stroke 2 → 1px at 12px).
+ private static Path IconPath(string data) => new()
+ {
+ Data = Geometry.Parse(data), Width = 24, Height = 24, Stretch = Stretch.None,
+ StrokeThickness = 2, StrokeJoin = PenLineJoin.Round, StrokeLineCap = PenLineCap.Round,
+ };
+
+ private static Viewbox Icon12(Control grid24) => new()
+ {
+ Width = 12, Height = 12, Stretch = Stretch.Uniform,
+ Child = new Panel { Width = 24, Height = 24, Children = { grid24 } },
+ };
+}
+
+/// <summary>The player's waveform well: peak bars (played part in brass), a hover line with
+/// its time, and the playhead. A click asks to seek to that fraction of the file.</summary>
+public sealed class PreviewWaveform : Control
+{
+ private const double InsetX = 4, InsetY = 3;
+ private float[]? _peaks;
+ private double _duration, _pos;
+ private bool _playing;
+ private double? _hover; // 0..1
+
+ public event Action<double>? SeekRequested;
+
+ public PreviewWaveform()
+ {
+ Cursor = new Cursor(StandardCursorType.Hand);
+ ClipToBounds = true;
+ }
+
+ public void SetPeaks(float[]? peaks) { _peaks = peaks; InvalidateVisual(); }
+
+ public void SetState(double duration, double pos, bool playing)
+ {
+ _duration = duration; _pos = pos; _playing = playing;
+ InvalidateVisual();
+ }
+
+ private double Frac(Point p) => Math.Clamp((p.X - InsetX) / Math.Max(1, Bounds.Width - 2 * InsetX), 0, 1);
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ SeekRequested?.Invoke(Frac(e.GetPosition(this)));
+ e.Handled = true;
+ }
+
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ _hover = _duration > 0 ? Frac(e.GetPosition(this)) : null;
+ InvalidateVisual();
+ }
+
+ protected override void OnPointerExited(PointerEventArgs e)
+ {
+ base.OnPointerExited(e);
+ _hover = null;
+ InvalidateVisual();
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width, h = Bounds.Height;
+ if (w <= 0 || h <= 0) return;
+
+ var well = new Rect(0.5, 0.5, w - 1, h - 1);
+ ctx.DrawRectangle(NotaPalette.BgSunken, new Pen(NotaPalette.GraphBorder, 1), well, 4, 4);
+ ctx.FillRectangle(NotaPalette.GridBeat, new Rect(1, Math.Floor(h / 2), w - 2, 1));
+
+ double innerW = w - 2 * InsetX, innerH = h - 2 * InsetY, mid = h / 2;
+ double p = _duration > 0 ? Math.Clamp(_pos / _duration, 0, 1) : 0;
+ bool started = _playing || _pos > 0;
+
+ if (_peaks is { Length: > 0 } peaks && innerW > 8)
+ {
+ // ~3.8px a bar with a 1px gap, as in the mockup (72 bars across its 274px well).
+ int n = Math.Max(8, (int)((innerW + 1) / 3.8));
+ double bw = (innerW - (n - 1)) / n;
+ for (int b = 0; b < n; b++)
+ {
+ int s0 = b * peaks.Length / n, s1 = Math.Max(s0 + 1, (b + 1) * peaks.Length / n);
+ float m = 0;
+ for (int i = s0; i < s1 && i < peaks.Length; i++) m = Math.Max(m, peaks[i]);
+ double amp = Math.Max(0.04, Math.Pow(Math.Min(1, m), 0.55));
+ double x = (b + 0.5) / n;
+ IBrush c = started && x <= p ? NotaPalette.Accent
+ : _hover is { } hv && x <= hv && x > p ? NotaPalette.AccentMute
+ : _playing ? NotaPalette.AccentEdge
+ : NotaPalette.AccentMute;
+ double bh = innerH * amp;
+ ctx.FillRectangle(c, new Rect(InsetX + b * (bw + 1), mid - bh / 2, bw, bh), 1);
+ }
+ }
+
+ if (_hover is { } f)
+ {
+ double hx = InsetX + innerW * f;
+ ctx.FillRectangle(NotaPalette.TextTertiary, new Rect(Math.Round(hx), 0, 1, h));
+ var ft = new FormattedText(Fmt(f * _duration), NotaNum.Culture, FlowDirection.LeftToRight,
+ NotaFonts.Mono, 8, NotaPalette.TextPrimary);
+ double tw = ft.Width + 8, th = ft.Height + 2;
+ double tx = f > 0.75 ? hx - tw - 4 : hx + 4;
+ ctx.FillRectangle(NotaPalette.TrackOff, new Rect(tx, InsetY, tw, th), 2);
+ ctx.DrawText(ft, new Point(tx + 4, InsetY + 1));
+ }
+
+ if (started && _duration > 0)
+ ctx.FillRectangle(NotaPalette.AccentBright, new Rect(InsetX + innerW * p - 0.75, 0, 1.5, h));
+ }
+
+ private static string Fmt(double s)
+ {
+ s = Math.Max(0, s);
+ int whole = (int)s, cs = (int)((s - whole) * 100);
+ return whole >= 60 ? $"{whole / 60}:{whole % 60:00}.{cs:00}" : $"{whole:00}.{cs:00}";
+ }
+}
+
+/// <summary>The preview-volume fader: a thin track, a fill to the value and a small bar
+/// thumb. Drag anywhere to set; double-click resets to 0 dB (1.0).</summary>
+public sealed class PreviewVolume : Control
+{
+ private double _value = 0.7;
+ private bool _dragging;
+
+ /// <summary>(value, gesture finished) — persist on the second.</summary>
+ public event Action<double, bool>? ValueChanged;
+
+ public double Value
+ {
+ get => _value;
+ set { _value = Math.Clamp(value, 0, 1); InvalidateVisual(); }
+ }
+
+ public PreviewVolume()
+ {
+ Cursor = new Cursor(StandardCursorType.SizeWestEast);
+ DoubleTapped += (_, e) => { Value = 1; ValueChanged?.Invoke(1, true); e.Handled = true; };
+ }
+
+ private void SetFrom(Point p)
+ {
+ Value = p.X / Math.Max(1, Bounds.Width);
+ ValueChanged?.Invoke(_value, false);
+ }
+
+ protected override void OnPointerPressed(PointerPressedEventArgs e)
+ {
+ base.OnPointerPressed(e);
+ if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return;
+ _dragging = true;
+ e.Pointer.Capture(this);
+ SetFrom(e.GetPosition(this));
+ e.Handled = true;
+ }
+
+ protected override void OnPointerMoved(PointerEventArgs e)
+ {
+ base.OnPointerMoved(e);
+ if (_dragging) SetFrom(e.GetPosition(this));
+ }
+
+ protected override void OnPointerReleased(PointerReleasedEventArgs e)
+ {
+ base.OnPointerReleased(e);
+ if (!_dragging) return;
+ _dragging = false;
+ e.Pointer.Capture(null);
+ ValueChanged?.Invoke(_value, true);
+ }
+
+ public override void Render(DrawingContext ctx)
+ {
+ double w = Bounds.Width;
+ if (w <= 0) return;
+ ctx.FillRectangle(Brushes.Transparent, new Rect(Bounds.Size)); // whole box hit-tests
+ ctx.FillRectangle(NotaPalette.BorderDefault, new Rect(0, 7, w, 3), 2);
+ double x = w * _value;
+ ctx.FillRectangle(NotaPalette.TextSecondary, new Rect(0, 7, x, 3), 2);
+ ctx.FillRectangle(NotaPalette.TextPrimary, new Rect(x - 2, 3, 4, 11), 1);
+ }
+}
diff --git a/src/managed/Nota.App/PreviewWaveform.cs b/src/managed/Nota.App/PreviewWaveform.cs
deleted file mode 100644
index bd8ca011..00000000
--- a/src/managed/Nota.App/PreviewWaveform.cs
+++ /dev/null
@@ -1,56 +0,0 @@
-// SPDX-License-Identifier: AGPL-3.0-only
-// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
-//
-// The waveform strip in the browser's pinned preview footer (HANDOFF 1g). We
-// don't have decoded peaks for an arbitrary browser file (it isn't loaded as an
-// engine clip), so this draws a deterministic synthetic waveform seeded by the
-// filename — a stable, decorative time diagram per file. Colour matches the
-// mockup's sage preview accent.
-
-using Avalonia;
-using Avalonia.Controls;
-using Avalonia.Media;
-
-namespace Nota.App;
-
-public sealed class PreviewWaveform : Control
-{
- private static readonly IBrush Bar = NotaPalette.Sage; // sage (Track4)
- private static readonly IBrush Baseline = NotaPalette.SurfaceRaised; // Brush.SurfaceRaised
-
- private string _seed = "";
-
- public void SetSample(string? name)
- {
- _seed = name ?? "";
- InvalidateVisual();
- }
-
- public override void Render(DrawingContext ctx)
- {
- double w = Bounds.Width, h = Bounds.Height;
- if (w <= 0 || h <= 0) return;
-
- if (_seed.Length == 0)
- {
- ctx.FillRectangle(Baseline, new Rect(0, h / 2 - 0.5, w, 1));
- return;
- }
-
- // FNV-1a hash → LCG, so the bars are stable for a given filename.
- uint s = 2166136261u;
- foreach (char c in _seed) { s ^= c; s *= 16777619u; }
-
- double mid = h / 2, maxAmp = h / 2 - 1;
- int n = (int)(w / 3); // 2px bar + 1px gap
- for (int i = 0; i < n; i++)
- {
- s = s * 1664525u + 1013904223u;
- double r = ((s >> 8) & 0xFFFF) / 65535.0;
- // Gentle envelope so the middle reads louder, like a real hit.
- double env = 0.35 + 0.65 * System.Math.Sin(System.Math.PI * (i + 0.5) / n);
- double amp = (0.12 + 0.88 * r) * env * maxAmp;
- ctx.FillRectangle(Bar, new Rect(i * 3, mid - amp, 2, amp * 2));
- }
- }
-}
diff --git a/src/managed/Nota.App/Theme/NotaPalette.cs b/src/managed/Nota.App/Theme/NotaPalette.cs
index 1ca70ec1..6e522642 100644
--- a/src/managed/Nota.App/Theme/NotaPalette.cs
+++ b/src/managed/Nota.App/Theme/NotaPalette.cs
@@ -239,6 +239,7 @@ internal static class NotaPalette
public static readonly SolidColorBrush AccentDeep = T("#B08536", "#7A5008"); // Brush.AccentDeep — press, left half of the loop
public static readonly SolidColorBrush AccentDim = T("#8A6B2E", "#9C8034"); // Brush.AccentDim — eyebrows, mono section marks
public static readonly SolidColorBrush AccentEdge = T("#5E4A22", "#D3B173"); // Brush.AccentEdge — chip border, link underline
+ public static readonly SolidColorBrush AccentMute = T("#7A6130", "#C39B4F"); // between Edge and Dim — a waveform at rest, the part ahead of the hover
public static readonly SolidColorBrush AccentPale = T("#FCE5B8", "#5C3C04"); // hot edge highlight
// Opaque, not an alpha tint: the almanac wants one predictable colour, and
// alpha over two different grounds is not one.
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 603d4161..17cf2cf8 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -767,8 +767,17 @@ public interface IAudioEngine : IDisposable
// --- Audio preview / audition (M7-4a) ----------------------------------
void PreviewFile(string path);
+ /// <summary>Auditions <paramref name="path"/> from <paramref name="startSeconds"/> in;
+ /// the file already loaded is reused without a re-decode (waveform seek).</summary>
+ void PreviewFileAt(string path, double startSeconds);
void StopPreview();
bool IsPreviewActive { get; }
+ /// <summary>Loop the audition until stopped.</summary>
+ void SetPreviewLoop(bool on);
+ /// <summary>Audition level as linear gain (1 = unity).</summary>
+ void SetPreviewGain(float gain);
+ /// <summary>Audition playhead, seconds into the file.</summary>
+ double PreviewPosition { get; }
bool PreviewSelfTest();
// --- xrun / dropout telemetry (M7-8) -----------------------------------
diff --git a/src/managed/Nota.Application/Settings.cs b/src/managed/Nota.Application/Settings.cs
index 31dd6324..0f0b368c 100644
--- a/src/managed/Nota.Application/Settings.cs
+++ b/src/managed/Nota.Application/Settings.cs
@@ -56,6 +56,12 @@ public sealed class Settings
public bool BrowserFavoritesFirst { get; set; } = true;
/// <summary>The browser is folded down to its icon rail.</summary>
public bool BrowserCollapsed { get; set; }
+ /// <summary>Files tab player: selecting a sample auditions it.</summary>
+ public bool BrowserPreviewAuto { get; set; } = true;
+ /// <summary>Files tab player: loop the audition until stopped.</summary>
+ public bool BrowserPreviewLoop { get; set; }
+ /// <summary>Files tab player: fader position 0..1 (gain = v², so 0.7 ≈ −6 dB, 1 = 0 dB).</summary>
+ public double BrowserPreviewVolume { get; set; } = 0.7;
// --- arrangement view options (View menu) --------------------------------
/// <summary>How many clips print their name on the lane: 0 every clip, 1 the head of each
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
index 5ad4a217..b71d7cbb 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
@@ -171,6 +171,18 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_engine_preview_active")]
internal static partial int PreviewActive(IntPtr engine);
+ [LibraryImport(Lib, EntryPoint = "nota_engine_preview_file_at", StringMarshalling = StringMarshalling.Utf8)]
+ internal static partial NotaResult PreviewFileAt(IntPtr engine, string path, double startSeconds);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_set_preview_loop")]
+ internal static partial NotaResult SetPreviewLoop(IntPtr engine, int on);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_set_preview_gain")]
+ internal static partial NotaResult SetPreviewGain(IntPtr engine, float gain);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_preview_position")]
+ internal static partial double PreviewPosition(IntPtr engine);
+
[LibraryImport(Lib, EntryPoint = "nota_engine_preview_selftest")]
internal static partial int PreviewSelfTest(IntPtr engine);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
index 26bbec45..d50c16c6 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
@@ -170,6 +170,22 @@ public sealed partial class NotaEngine : IAudioEngine
public void PreviewFile(string path)
{ ThrowIfDisposed(); Check(NativeMethods.PreviewFile(_handle, path)); }
+ /// <summary>Auditions <paramref name="path"/> from <paramref name="startSeconds"/> in (reuses the loaded file).</summary>
+ public void PreviewFileAt(string path, double startSeconds)
+ { ThrowIfDisposed(); Check(NativeMethods.PreviewFileAt(_handle, path, startSeconds)); }
+
+ /// <summary>Loops the audition until stopped.</summary>
+ public void SetPreviewLoop(bool on)
+ { ThrowIfDisposed(); Check(NativeMethods.SetPreviewLoop(_handle, on ? 1 : 0)); }
+
+ /// <summary>Audition level, linear gain.</summary>
+ public void SetPreviewGain(float gain)
+ { ThrowIfDisposed(); Check(NativeMethods.SetPreviewGain(_handle, gain)); }
+
+ /// <summary>Audition playhead in seconds into the file.</summary>
+ public double PreviewPosition
+ { get { ThrowIfDisposed(); return NativeMethods.PreviewPosition(_handle); } }
+
/// <summary>Stops the current audition.</summary>
public void StopPreview()
{ ThrowIfDisposed(); Check(NativeMethods.StopPreview(_handle)); }
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index cbe9923d..fb283b00 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -156,6 +156,15 @@ NOTA_API double nota_engine_sample_rate(const NotaEngine* engine);
NOTA_API NotaResult nota_engine_preview_file(NotaEngine* engine, const char* path);
NOTA_API NotaResult nota_engine_stop_preview(NotaEngine* engine);
NOTA_API int32_t nota_engine_preview_active(const NotaEngine* engine);
+/* Audition from start_seconds into the file. Re-auditioning the file already loaded
+ * (a waveform seek, a replay) reuses its decoded buffer. */
+NOTA_API NotaResult nota_engine_preview_file_at(NotaEngine* engine, const char* path, double start_seconds);
+/* Loop the audition until stopped (1) or play it once (0). */
+NOTA_API NotaResult nota_engine_set_preview_loop(NotaEngine* engine, int32_t on);
+/* Audition level, linear gain (1 = unity), ramped over one block. */
+NOTA_API NotaResult nota_engine_set_preview_gain(NotaEngine* engine, float gain);
+/* Playhead of the audition in seconds into the file (last rendered block). */
+NOTA_API double nota_engine_preview_position(const NotaEngine* engine);
/* ---- xrun / dropout telemetry (M7-8) -------------------------------------
* Running count of audio-device overloads/dropouts since launch. The UI polls
diff --git a/src/native/nota.engine/src/Engine.cpp b/src/native/nota.engine/src/Engine.cpp
index 935725fd..a49df63e 100644
--- a/src/native/nota.engine/src/Engine.cpp
+++ b/src/native/nota.engine/src/Engine.cpp
@@ -185,14 +185,21 @@ bool Engine::applyMidiConfig() {
// --- audio preview / audition (M7-4a) ----------------------------------------
-bool Engine::previewFile(const std::string& path) {
- auto buf = decodeAudioFile(path); // message thread only
- if (!buf || buf->empty()) return false;
- // Retire the previous buffer so the audio thread can finish any block that
- // still holds its raw pointer, then publish the new one.
- if (previewHold_) previewRetired_.push_back(std::move(previewHold_));
- previewHold_ = buf;
- previewLive_.store(buf.get(), std::memory_order_release);
+bool Engine::previewFile(const std::string& path, double startSeconds) {
+ // Re-auditioning the loaded file (a waveform seek, a replay) skips the decode.
+ if (!previewHold_ || previewHold_->empty() || path != previewPath_) {
+ auto buf = decodeAudioFile(path); // message thread only
+ if (!buf || buf->empty()) return false;
+ // Retire the previous buffer so the audio thread can finish any block that
+ // still holds its raw pointer, then publish the new one.
+ if (previewHold_) previewRetired_.push_back(std::move(previewHold_));
+ previewHold_ = buf;
+ previewPath_ = path;
+ previewLive_.store(buf.get(), std::memory_order_release);
+ }
+ const double start = startSeconds > 0.0 ? startSeconds : 0.0;
+ previewStartSec_.store(start, std::memory_order_relaxed);
+ previewPosSec_.store(start, std::memory_order_relaxed); // the UI reads the new spot at once
previewRestart_.store(true, std::memory_order_release);
previewActive_.store(true, std::memory_order_release);
return true;
@@ -211,21 +218,33 @@ void Engine::renderPreview(float* out, int32_t numFrames) {
}
SampleBuffer* sb = previewLive_.load(std::memory_order_acquire);
if (!sb || sb->empty()) { previewActive_.store(false, std::memory_order_release); return; }
- if (previewRestart_.exchange(false, std::memory_order_acq_rel)) previewPos_ = 0.0;
+ const float target = previewGain_.load(std::memory_order_relaxed);
+ if (previewRestart_.exchange(false, std::memory_order_acq_rel)) {
+ previewPos_ = previewStartSec_.load(std::memory_order_relaxed) * sb->sourceSampleRate;
+ previewGainCur_ = target; // a fresh start jumps straight to the level, no fade-in
+ }
const double sr = transport_.sampleRate();
const double ratio = sr > 0 ? sb->sourceSampleRate / sr : 1.0; // source frames per device frame
+ const bool loop = previewLoop_.load(std::memory_order_relaxed);
+ const float g0 = previewGainCur_, dg = numFrames > 0 ? (target - g0) / numFrames : 0.0f;
for (int32_t i = 0; i < numFrames; ++i) {
+ if (loop && previewPos_ >= sb->frames) previewPos_ -= sb->frames;
const int64_t i0 = static_cast<int64_t>(previewPos_);
if (i0 < 0 || i0 >= sb->frames) { previewActive_.store(false, std::memory_order_release); break; }
const double frac = previewPos_ - i0;
float l0, r0, l1, r1;
sb->readStereo(i0, l0, r0);
- sb->readStereo(i0 + 1, l1, r1);
- out[i * 2] += static_cast<float>(l0 + (l1 - l0) * frac);
- out[i * 2 + 1] += static_cast<float>(r0 + (r1 - r0) * frac);
+ // Looping, the last frame interpolates into the first instead of into silence.
+ sb->readStereo(loop && i0 + 1 >= sb->frames ? 0 : i0 + 1, l1, r1);
+ const float g = g0 + dg * i;
+ out[i * 2] += g * static_cast<float>(l0 + (l1 - l0) * frac);
+ out[i * 2 + 1] += g * static_cast<float>(r0 + (r1 - r0) * frac);
previewPos_ += ratio;
}
+ previewGainCur_ = target;
+ previewPosSec_.store(sb->sourceSampleRate > 0 ? previewPos_ / sb->sourceSampleRate : 0.0,
+ std::memory_order_relaxed);
}
bool Engine::xrunSelfTest() {
@@ -243,16 +262,46 @@ bool Engine::previewSelfTest() {
buf->samples.assign(buf->frames * 2, 0.25f);
if (previewHold_) previewRetired_.push_back(std::move(previewHold_));
previewHold_ = buf;
+ previewPath_.clear();
previewLive_.store(buf.get(), std::memory_order_release);
+ previewStartSec_.store(0.0, std::memory_order_relaxed);
previewRestart_.store(true, std::memory_order_release);
previewActive_.store(true, std::memory_order_release);
- std::vector<float> out(256 * 2, 0.0f);
- renderPreview(out.data(), 256);
- double sum = 0.0;
- for (float v : out) sum += v * (double)v;
+ const bool loop0 = previewLoop_.load();
+ const float gain0 = previewGain_.load();
+ previewLoop_.store(false);
+ previewGain_.store(1.0f);
+ auto rms = [&](int32_t frames) {
+ std::vector<float> out(static_cast<size_t>(frames) * 2, 0.0f);
+ renderPreview(out.data(), frames);
+ double sum = 0.0;
+ for (float v : out) sum += v * (double)v;
+ return std::sqrt(sum / out.size());
+ };
+ const double unity = rms(256);
+ bool ok = unity > 1e-4;
+ // Gain scales the level (a restart jumps straight to it, no ramp).
+ previewGain_.store(0.5f);
+ previewStartSec_.store(0.0); previewRestart_.store(true); previewActive_.store(true);
+ ok = ok && std::abs(rms(256) - unity * 0.5) < unity * 0.01;
+ previewGain_.store(1.0f);
+ // A start offset lands there; played once, the voice runs off the end and stops.
+ previewStartSec_.store(0.05); previewRestart_.store(true); previewActive_.store(true);
+ rms(256);
+ ok = ok && previewPosSec_.load() > 0.05 && previewPosSec_.load() < 0.07;
+ for (int b = 0; b < 64 && previewActive_.load(); ++b) rms(256);
+ ok = ok && !previewActive_.load();
+ // Looped, it keeps sounding well past the buffer's 0.1 s.
+ previewLoop_.store(true);
+ previewStartSec_.store(0.0); previewRestart_.store(true); previewActive_.store(true);
+ for (int b = 0; b < 64; ++b) rms(256);
+ ok = ok && previewActive_.load() && rms(256) > 1e-4;
+
stopPreview();
- return std::sqrt(sum / out.size()) > 1e-4;
+ previewLoop_.store(loop0);
+ previewGain_.store(gain0);
+ return ok;
}
// --- debug tone ------------------------------------------------------------
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index 4d9f2c97..a6121356 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -108,8 +108,11 @@ public:
// --- audio preview / audition (M7-4a) ---
// Decode a file and mix it into the live output without a track, so the
// browser can audition samples. One preview at a time.
- bool previewFile(const std::string& path);
+ bool previewFile(const std::string& path, double startSeconds = 0.0);
void stopPreview();
+ void setPreviewLoop(bool on) { previewLoop_.store(on, std::memory_order_relaxed); }
+ void setPreviewGain(float g) { previewGain_.store(g < 0.0f ? 0.0f : g, std::memory_order_relaxed); }
+ double previewPosition() const { return previewPosSec_.load(std::memory_order_relaxed); }
bool isPreviewActive() const { return previewActive_.load(std::memory_order_relaxed); }
bool previewSelfTest(); // feed a synthetic buffer, render offline, no device
@@ -1073,7 +1076,13 @@ private:
std::atomic<SampleBuffer*> previewLive_{nullptr};
std::atomic<bool> previewActive_{false};
std::atomic<bool> previewRestart_{false};
+ std::atomic<double> previewStartSec_{0.0}; // where a restart begins (source seconds)
+ std::atomic<bool> previewLoop_{false};
+ std::atomic<float> previewGain_{1.0f}; // linear, ramped per block
+ std::atomic<double> previewPosSec_{0.0}; // playhead published for the UI
+ std::string previewPath_; // message thread: the file previewHold_ decodes
double previewPos_ = 0.0; // audio-thread only, source frames
+ float previewGainCur_ = 1.0f; // audio-thread only
// Undo/redo snapshot stacks (M6-6). Hold retained Graph snapshots; entries
// are cheap (metadata only — sample buffers are shared via shared_ptr).
diff --git a/src/native/nota.engine/src/nota_engine_core.cpp b/src/native/nota.engine/src/nota_engine_core.cpp
index c0547dc9..ade7b638 100644
--- a/src/native/nota.engine/src/nota_engine_core.cpp
+++ b/src/native/nota.engine/src/nota_engine_core.cpp
@@ -72,6 +72,23 @@ NotaResult nota_engine_stop_preview(NotaEngine* e) {
int32_t nota_engine_preview_active(const NotaEngine* e) {
return (e && CENG(e)->isPreviewActive()) ? 1 : 0;
}
+NotaResult nota_engine_preview_file_at(NotaEngine* e, const char* path, double start_seconds) {
+ if (!e || !path) return NOTA_ERR_INVALID_ARG;
+ return ENG(e)->previewFile(std::string(path), start_seconds) ? NOTA_OK : NOTA_ERR_UNKNOWN;
+}
+NotaResult nota_engine_set_preview_loop(NotaEngine* e, int32_t on) {
+ if (!e) return NOTA_ERR_INVALID_ARG;
+ ENG(e)->setPreviewLoop(on != 0);
+ return NOTA_OK;
+}
+NotaResult nota_engine_set_preview_gain(NotaEngine* e, float gain) {
+ if (!e) return NOTA_ERR_INVALID_ARG;
+ ENG(e)->setPreviewGain(gain);
+ return NOTA_OK;
+}
+double nota_engine_preview_position(const NotaEngine* e) {
+ return e ? CENG(e)->previewPosition() : 0.0;
+}
int32_t nota_engine_preview_selftest(NotaEngine* e) {
return (e && ENG(e)->previewSelfTest()) ? 1 : 0;
}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 40cf2f0d..263c535f 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -8176,7 +8176,7 @@ Console.WriteLine("-- M7-2: MIDI device settings --");
// the user's real presets folder).
Console.WriteLine("-- M7-4: browser preview + presets --");
{
- Check(engine.PreviewSelfTest(), "audio preview self-test (audible, device-free)");
+ Check(engine.PreviewSelfTest(), "audio preview self-test (audible, gain, start offset, one-shot end, loop; device-free)");
int pt = engine.AddInstrumentTrack();
int di = engine.AddBuiltinDevice(pt, 0); // EQ