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) Content-addressed project bundle

Egor Khindikaynen6b5edf6de824
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 31454aa9..6a091b3f 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -160,6 +160,16 @@ referenced samples into `samples/` and plugin state blobs into `plugin-states/`,
writes `project.json` atomically (temp file + rename) with an auto-backup. Loading
replays the document through the same structural-edit operations the UI uses.
+The binaries are **content-addressed** (`BundleContent`): `samples/<hash>.wav` and
+`plugin-states/<hash>.bin`, where `<hash>` is the first 128 bits of a SHA-256 of the
+content. Identical content shares one file, a save skips files already on disk (new ones
+are written temp + rename), names stay stable across sessions, and after the manifest is
+replaced the files it no longer references are deleted. Hashing a sample reads its whole
+buffer, so hashes are cached per engine sample id and seeded from the file names on load.
+The dirty check captures with session names instead (`contentNames: false`) and reads no
+audio. Older bundles (`sample-N.wav`, `state-N.bin`) load as is and migrate on their next
+save.
+
`analysis/` holds a cache of imported audio — each file's waveform overview (min/max per
512 frames) and detected tempo, as `<content fingerprint>.npk` — so re-importing a file
is instant. It is disposable: delete it and entries are rebuilt on the next import. While
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3b7593f6..df40a9ed 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,12 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
+### Changed
+- **Faster saves of projects with audio:** a save now writes only new recordings and
+ imports instead of every sample again, and the same audio used in several places is
+ stored once. Background autosave no longer rewrites the project's audio either. Older
+ projects are converted on their next save.
+
## [0.42.2] — 2026-09-30
### Highlights
diff --git a/src/managed/Nota.Infrastructure/Persistence/BundleContent.cs b/src/managed/Nota.Infrastructure/Persistence/BundleContent.cs
new file mode 100644
index 00000000..84fc2e3e
--- /dev/null
+++ b/src/managed/Nota.Infrastructure/Persistence/BundleContent.cs
@@ -0,0 +1,115 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Content-addressed names for the binary files of a `.nota` bundle: a sample is
+// stored as `samples/<hash>.wav` and a plugin state blob as `plugin-states/<hash>.bin`,
+// where <hash> is the first 128 bits of the SHA-256 of the content. The same content
+// always gets the same name, so a save skips files already on disk, identical buffers
+// dedup to one file, and names stay stable across sessions (the ground for project
+// version history).
+
+using System;
+using System.Collections.Concurrent;
+using System.IO;
+using System.Runtime.InteropServices;
+using System.Security.Cryptography;
+using System.Text.RegularExpressions;
+
+namespace Nota.Infrastructure;
+
+internal static partial class BundleContent
+{
+ public const string SamplesDir = "samples";
+ public const string StatesDir = "plugin-states";
+
+ private const int HashBytes = 16; // 32 hex chars
+
+ // Engine sample id -> content hash. Sample ids are process-unique (never reused, see
+ // SampleBuffer::nextId) and a buffer's audio is fixed once it is in the graph, so an
+ // entry stays valid for the whole process; frames/channels guard against surprises.
+ private static readonly ConcurrentDictionary<long, (long Frames, int Channels, string Hash)> SampleHashes = new();
+
+ public static string SampleRel(string hash) => $"{SamplesDir}/{hash}.wav";
+ public static string StateRel(string hash) => $"{StatesDir}/{hash}.bin";
+
+ /// <summary>Content hash of a live engine sample, or null if it is missing or empty.
+ /// Hashing reads the whole buffer, so the result is cached per sample id.</summary>
+ public static string? SampleHash(IAudioEngine engine, long sampleId, in NotaSampleInfo info)
+ {
+ if (SampleHashes.TryGetValue(sampleId, out var c) && c.Frames == info.Frames && c.Channels == info.Channels)
+ return c.Hash;
+ var data = engine.ReadSample(sampleId);
+ if (data.Length == 0) return null;
+
+ using var sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
+ sha.AppendData("nota-sample-v1"u8);
+ sha.AppendData(BitConverter.GetBytes(info.Channels));
+ sha.AppendData(BitConverter.GetBytes(WavSampleRate(info)));
+ sha.AppendData(BitConverter.GetBytes(info.Frames));
+ sha.AppendData(MemoryMarshal.AsBytes(data.AsSpan()));
+ string hash = Hex(sha.GetHashAndReset());
+ SampleHashes[sampleId] = (info.Frames, info.Channels, hash);
+ return hash;
+ }
+
+ /// <summary>After a load, record that <paramref name="sampleId"/> came from the
+ /// content-named file <paramref name="relative"/>, so the next save reuses the name
+ /// instead of re-hashing the audio. No-op for legacy names (<c>sample-N.wav</c>).</summary>
+ public static void SeedSample(IAudioEngine engine, long sampleId, string relative)
+ {
+ if (sampleId <= 0 || !engine.TryGetSampleInfo(sampleId, out var info)) return;
+ var m = SampleNameRx().Match(relative);
+ if (m.Success) SampleHashes[sampleId] = (info.Frames, info.Channels, m.Groups[1].Value);
+ }
+
+ public static string BlobHash(byte[] blob) => Hex(SHA256.HashData(blob));
+
+ /// <summary>The sample rate a sample is written to WAV with (and hashed with).</summary>
+ public static int WavSampleRate(in NotaSampleInfo info)
+ => info.SampleRate > 0 ? (int)Math.Round(info.SampleRate) : 44100;
+
+ /// <summary>Writes <paramref name="path"/> through a temp file and a rename, so a crash
+ /// mid-write never leaves a truncated file under a content name (which a later save
+ /// would trust and skip).</summary>
+ public static void WriteAtomic(string path, Action<string> write)
+ {
+ string tmp = path + ".tmp";
+ try
+ {
+ write(tmp);
+ File.Move(tmp, path, overwrite: true);
+ }
+ finally
+ {
+ try { if (File.Exists(tmp)) File.Delete(tmp); } catch { /* best-effort */ }
+ }
+ }
+
+ /// <summary>Deletes files in <c>samples/</c> and <c>plugin-states/</c> that the saved
+ /// document no longer references: superseded content, legacy <c>sample-N.wav</c> /
+ /// <c>state-N.bin</c> names, and temp files left by an interrupted save.</summary>
+ public static void PruneUnreferenced(string bundleDir, ProjectDocument doc)
+ {
+ Prune(Path.Combine(bundleDir, SamplesDir), SamplesDir, doc.SampleRefs.ContainsKey, ".wav");
+ Prune(Path.Combine(bundleDir, StatesDir), StatesDir, doc.StateBlobs.ContainsKey, ".bin");
+ }
+
+ private static void Prune(string dir, string relDir, Func<string, bool> referenced, string ext)
+ {
+ if (!Directory.Exists(dir)) return;
+ foreach (var file in Directory.EnumerateFiles(dir))
+ {
+ string name = Path.GetFileName(file);
+ // Only touch what a save writes; anything else in the folder isn't ours.
+ if (!name.EndsWith(ext, StringComparison.OrdinalIgnoreCase)
+ && !name.EndsWith(ext + ".tmp", StringComparison.OrdinalIgnoreCase)) continue;
+ if (referenced($"{relDir}/{name}")) continue;
+ try { File.Delete(file); } catch { /* in use or read-only: leave it for the next save */ }
+ }
+ }
+
+ private static string Hex(ReadOnlySpan<byte> hash) => Convert.ToHexString(hash[..HashBytes]).ToLowerInvariant();
+
+ [GeneratedRegex(@"^samples/([0-9a-f]{32})\.wav$")]
+ private static partial Regex SampleNameRx();
+}
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
index 249efa9a..5403d4ea 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -40,6 +40,12 @@ public sealed class ProjectDocument
/// <summary>Plugin state blobs: relative bundle path -&gt; bytes. Populated by
/// Capture, written to <c>plugin-states/</c> by Save; not serialized.</summary>
[JsonIgnore] public Dictionary<string, byte[]> StateBlobs { get; } = new();
+
+ /// <summary>Name binaries by live id / position (<c>sample-N.wav</c>, <c>state-N.bin</c>)
+ /// instead of by content hash. Cheap — nothing is read or hashed — but only stable within
+ /// a session, so it is for change detection (<see cref="ProjectService.Capture"/> with
+ /// <c>contentNames: false</c>) and never for a document that is saved.</summary>
+ [JsonIgnore] internal bool SessionNames { get; init; }
}
public sealed class MasterDto
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index a5ecc0ec..6011b872 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -47,11 +47,15 @@ public sealed class ProjectService
/// <summary>Snapshots the engine's current state into a document. Content the
/// format can't represent yet (hosted plugins) is appended to
/// <paramref name="warnings"/>. Referenced samples are recorded in
- /// <see cref="ProjectDocument.SampleRefs"/> for <see cref="Save"/> to write.</summary>
- public static ProjectDocument Capture(IAudioEngine engine, TransportState transport, List<string> warnings)
+ /// <see cref="ProjectDocument.SampleRefs"/> for <see cref="Save"/> to write.
+ /// <paramref name="contentNames"/> = false names binaries by session id instead of by
+ /// content hash — cheap, for change detection only; such a document must not be saved.</summary>
+ public static ProjectDocument Capture(IAudioEngine engine, TransportState transport, List<string> warnings,
+ bool contentNames = true)
{
var doc = new ProjectDocument
{
+ SessionNames = !contentNames,
SceneCount = engine.SceneCount,
Transport = new TransportDto
{
@@ -498,7 +502,11 @@ public sealed class ProjectService
{
int pc = engine.PluginParamCount(id, -1);
for (int p = 0; p < sd.Params.Length && p < pc; p++) engine.PluginParamSet(id, -1, p, sd.Params[p]);
- if (sd.Name.Length > 0 && engine.TryGetSamplerInfo(id, out var nsi)) engine.SetSampleName(nsi.SampleId, sd.Name);
+ if (engine.TryGetSamplerInfo(id, out var nsi))
+ {
+ BundleContent.SeedSample(engine, nsi.SampleId, sd.Sample);
+ if (sd.Name.Length > 0) engine.SetSampleName(nsi.SampleId, sd.Name);
+ }
}
}
else if (t.Instrument is { Kind: 10, Sampler: { } gd }) // Nota Grain: sample + params
@@ -506,7 +514,9 @@ public sealed class ProjectService
id = engine.AddGrainSynthTrack();
if (id > 0)
{
- if (gd.Sample.Length > 0) engine.SetTrackGrainSample(id, ResolveInBundle(bundleDir, gd.Sample), gd.RootNote);
+ if (gd.Sample.Length > 0 && engine.SetTrackGrainSample(id, ResolveInBundle(bundleDir, gd.Sample), gd.RootNote)
+ && engine.TryGetGrainInfo(id, out var ggi))
+ BundleContent.SeedSample(engine, ggi.SampleId, gd.Sample);
int pc = engine.PluginParamCount(id, -1);
for (int p = 0; p < gd.Params.Length && p < pc; p++) engine.PluginParamSet(id, -1, p, gd.Params[p]);
}
@@ -564,8 +574,13 @@ public sealed class ProjectService
if (vs.Sample is not { Length: > 0 }) continue;
if (!engine.SetRhythmVoiceSample(id, vs.Voice, ResolveInBundle(bundleDir, vs.Sample)))
warnings.Add($"Couldn't reload Rhythm voice sample \"{vs.Sample}\".");
- else if (vs.Synth)
- engine.InstrumentAction(id, RhythmModel.A_SetSource, vs.Voice, 0f); // loading switches to Sample
+ else
+ {
+ if (engine.TryGetRhythmVoiceInfo(id, vs.Voice, out var rvi))
+ BundleContent.SeedSample(engine, rvi.SampleId, vs.Sample);
+ if (vs.Synth)
+ engine.InstrumentAction(id, RhythmModel.A_SetSource, vs.Voice, 0f); // loading switches to Sample
+ }
}
}
}
@@ -638,6 +653,7 @@ public sealed class ProjectService
int ci = engine.AddAudioClipEx(id, ResolveInBundle(bundleDir, ac.Sample),
ac.StartBeat, ac.SourceOffsetFrames, ac.LengthFrames, ac.Gain);
if (ci < 0) { warnings.Add($"Couldn't reload audio clip \"{ac.Sample}\"."); continue; }
+ if (engine.TryGetAudioClipInfo(id, ci, out var lci)) BundleContent.SeedSample(engine, lci.SampleId, ac.Sample);
if (ac.Name is { Length: > 0 } acn) engine.SetClipName(id, ci, acn);
if (!ac.Active) engine.SetClipActive(id, ci, false); // clip deactivate (v17)
if (ac.PitchSemitones != 0) engine.SetClipPitch(id, ci, ac.PitchSemitones);
@@ -679,6 +695,8 @@ public sealed class ProjectService
if (!engine.AddSessionAudioClip(id, sl.Scene, ResolveInBundle(bundleDir, sa.Sample),
sl.LengthBeats, sa.SourceOffsetFrames, sa.LengthFrames, sa.Gain))
warnings.Add($"Couldn't reload session take \"{sa.Sample}\".");
+ else if (engine.TryGetSessionAudioSlot(id, sl.Scene, out var lsa))
+ BundleContent.SeedSample(engine, lsa.SampleId, sa.Sample);
}
else
{
@@ -822,25 +840,33 @@ public sealed class ProjectService
// --- disk I/O ----------------------------------------------------------
/// <summary>Writes the document (and its referenced samples) into the `.nota`
- /// bundle folder. Atomic manifest (temp + rename); backs up any existing
- /// manifest into <c>backups/</c>. Sample data is read from
- /// <paramref name="engine"/> (the one <see cref="Capture"/> read from).</summary>
+ /// bundle folder. Binaries are content-named, so ones already on disk are skipped;
+ /// each new one is written temp + rename. Atomic manifest (temp + rename); backs up
+ /// any existing manifest into <c>backups/</c>; then deletes binaries the manifest no
+ /// longer references. Sample data is read from <paramref name="engine"/> (the one
+ /// <see cref="Capture"/> read from).</summary>
public static void Save(ProjectDocument doc, string bundleDir, IAudioEngine engine)
{
+ if (doc.SessionNames)
+ throw new InvalidOperationException("A change-detection capture (contentNames: false) can't be saved.");
Directory.CreateDirectory(bundleDir);
if (doc.SampleRefs.Count > 0)
{
- Directory.CreateDirectory(Path.Combine(bundleDir, "samples"));
+ Directory.CreateDirectory(Path.Combine(bundleDir, BundleContent.SamplesDir));
foreach (var kv in doc.SampleRefs)
WriteSampleWav(engine, kv.Value, ResolveInBundle(bundleDir, kv.Key));
}
if (doc.StateBlobs.Count > 0)
{
- Directory.CreateDirectory(Path.Combine(bundleDir, "plugin-states"));
+ Directory.CreateDirectory(Path.Combine(bundleDir, BundleContent.StatesDir));
foreach (var kv in doc.StateBlobs)
- File.WriteAllBytes(ResolveInBundle(bundleDir, kv.Key), kv.Value);
+ {
+ string path = ResolveInBundle(bundleDir, kv.Key);
+ if (File.Exists(path) && new FileInfo(path).Length == kv.Value.Length) continue;
+ BundleContent.WriteAtomic(path, tmp => File.WriteAllBytes(tmp, kv.Value));
+ }
}
string manifest = Path.Combine(bundleDir, ManifestName);
@@ -855,6 +881,9 @@ public sealed class ProjectService
string tmp = manifest + ".tmp";
File.WriteAllText(tmp, SerializeManifest(doc));
File.Move(tmp, manifest, overwrite: true); // atomic replace (NFR-8)
+
+ // Only now that the new manifest is in place: nothing on disk points at these any more.
+ BundleContent.PruneUnreferenced(bundleDir, doc);
}
/// <summary>Serializes just the manifest JSON (same options Save uses). Used by
@@ -884,40 +913,53 @@ public sealed class ProjectService
// --- helpers -----------------------------------------------------------
- // Records `sampleId` under a bundle-relative path (deduped by id) and returns
- // that path, or null if the sample is missing from the live graph.
+ // Records `sampleId` under a bundle-relative path named by its content hash
+ // (identical audio shares one file) and returns that path, or null if the sample
+ // is missing from the live graph.
private static string? RegisterSample(ProjectDocument doc, IAudioEngine engine, long sampleId, List<string> warnings)
{
if (sampleId <= 0) return null;
- string rel = $"samples/sample-{sampleId}.wav";
- if (!doc.SampleRefs.ContainsKey(rel))
+ if (!engine.TryGetSampleInfo(sampleId, out var info))
{
- if (!engine.TryGetSampleInfo(sampleId, out _))
- {
- warnings.Add("A referenced sample was missing and was skipped.");
- return null;
- }
- doc.SampleRefs[rel] = sampleId;
+ warnings.Add("A referenced sample was missing and was skipped.");
+ return null;
}
+ string rel;
+ if (doc.SessionNames) rel = $"{BundleContent.SamplesDir}/sample-{sampleId}.wav";
+ else if (BundleContent.SampleHash(engine, sampleId, info) is { } hash) rel = BundleContent.SampleRel(hash);
+ else
+ {
+ warnings.Add("A referenced sample was empty and was skipped.");
+ return null;
+ }
+ doc.SampleRefs.TryAdd(rel, sampleId);
return rel;
}
+ // Writes a sample unless its content-named file is already complete on disk.
private static void WriteSampleWav(IAudioEngine engine, long sampleId, string path)
{
if (!engine.TryGetSampleInfo(sampleId, out var info) || info.Channels <= 0 || info.Frames <= 0) return;
+ long dataBytes = info.Frames * info.Channels * sizeof(float);
+ if (File.Exists(path) && new FileInfo(path).Length >= dataBytes) return;
var data = engine.ReadSample(sampleId);
if (data.Length == 0) return;
- int sr = info.SampleRate > 0 ? (int)Math.Round(info.SampleRate) : 44100;
- using var w = new WavWriter(path, sr, info.Channels, WavBitDepth.Float32);
- w.WriteFrames(data, (int)info.Frames);
+ BundleContent.WriteAtomic(path, tmp =>
+ {
+ using var w = new WavWriter(tmp, BundleContent.WavSampleRate(info), info.Channels, WavBitDepth.Float32);
+ w.WriteFrames(data, (int)info.Frames);
+ });
}
- // Records a plugin state blob under a unique bundle-relative path, or null if empty.
+ // Records a plugin state blob under a bundle-relative path named by its content hash
+ // (identical states share one file), or null if empty.
private static string? RegisterBlob(ProjectDocument doc, byte[] blob)
{
if (blob.Length == 0) return null;
- string rel = $"plugin-states/state-{doc.StateBlobs.Count}.bin";
- doc.StateBlobs[rel] = blob;
+ string rel = doc.SessionNames
+ ? $"{BundleContent.StatesDir}/state-{doc.StateBlobs.Count}.bin"
+ : BundleContent.StateRel(BundleContent.BlobHash(blob));
+ doc.StateBlobs.TryAdd(rel, blob);
return rel;
}
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectStore.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectStore.cs
index 03215fe5..0ce18177 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectStore.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectStore.cs
@@ -56,5 +56,7 @@ public sealed class ProjectStore : IProjectStore
}
public string Fingerprint(IAudioEngine engine, TransportState transport)
- => ProjectService.SerializeManifest(ProjectService.Capture(engine, transport, new List<string>()));
+ // Session names: no audio is read or hashed on this frequent path. Edits inside a
+ // plugin's own state aren't seen here (as before) — only structural/param changes.
+ => ProjectService.SerializeManifest(ProjectService.Capture(engine, transport, new List<string>(), contentNames: false));
}
diff --git a/tests/Nota.SmokeTest/BundleContentTests.cs b/tests/Nota.SmokeTest/BundleContentTests.cs
new file mode 100644
index 00000000..3650392e
--- /dev/null
+++ b/tests/Nota.SmokeTest/BundleContentTests.cs
@@ -0,0 +1,120 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Content-addressed `.nota` bundles: samples and plugin states are named by a hash of
+// their content, identical content shares a file, a re-save skips what's on disk, names
+// survive a reload, legacy `sample-N.wav` bundles migrate, and stale files are pruned.
+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --bundle`.
+
+using System.Text.RegularExpressions;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class BundleContentTests
+{
+ private static readonly Regex HashWav = new(@"^[0-9a-f]{32}\.wav$");
+ private static readonly Regex HashBin = new(@"^[0-9a-f]{32}\.bin$");
+
+ public static IEnumerable<(bool Ok, string Label)> Run()
+ {
+ string tmp = Path.GetTempPath();
+ string wav = Path.Combine(tmp, "nota_smoke_bundle_sine.wav");
+ WavWriter.WriteSine(wav, seconds: 0.5, freq: 330, sampleRate: 44100);
+ string dir = Path.Combine(tmp, "nota-smoke-bundle-" + Guid.NewGuid().ToString("N") + ".nota");
+ string legacy = Path.Combine(tmp, "nota-smoke-bundle-legacy-" + Guid.NewGuid().ToString("N") + ".nota");
+ var transport = new TransportState(120.0, 1.0, false, false);
+ try
+ {
+ using var src = new NotaEngine();
+ int aTrk = src.AddAudioTrack();
+ src.AddAudioClipEx(aTrk, wav, startBeat: 0, sourceOffsetFrames: 0, lengthFrames: 0, gain: 1f);
+ src.AddAudioClipEx(aTrk, wav, startBeat: 4, sourceOffsetFrames: 0, lengthFrames: 0, gain: 1f);
+ src.AddSamplerTrack(wav, rootNote: 60, loop: false);
+ src.AddInstrumentTrack();
+ src.AddInstrumentTrack(); // two default Synths: identical state blobs
+
+ var w = new List<string>();
+ var doc = ProjectService.Capture(src, transport, w);
+ yield return (w.Count == 0, $"capture without warnings ({w.Count})");
+ ProjectService.Save(doc, dir, src);
+
+ string samples = Path.Combine(dir, "samples"), states = Path.Combine(dir, "plugin-states");
+ var wavs = Directory.GetFiles(samples).Select(Path.GetFileName).ToArray();
+ yield return (wavs.Length == 1 && HashWav.IsMatch(wavs[0]!),
+ $"one decode of one file → one content-named sample ({string.Join(", ", wavs)})");
+ var bins = Directory.Exists(states) ? Directory.GetFiles(states).Select(Path.GetFileName).ToArray() : [];
+ yield return (bins.Length >= 1 && bins.All(b => HashBin.IsMatch(b!)), $"plugin states are content-named ({bins.Length})");
+ int synthRefs = Regex.Matches(File.ReadAllText(Path.Combine(dir, ProjectService.ManifestName)), "plugin-states/").Count;
+ yield return (synthRefs > bins.Length, $"identical states share a file ({synthRefs} refs → {bins.Length} files)");
+
+ // Re-save with nothing changed: the binaries are not rewritten.
+ string wavPath = Path.Combine(samples, wavs[0]!);
+ var stamp = DateTime.UtcNow.AddHours(-1);
+ File.SetLastWriteTimeUtc(wavPath, stamp);
+ ProjectService.Save(ProjectService.Capture(src, transport, new List<string>()), dir, src);
+ yield return (File.GetLastWriteTimeUtc(wavPath) == stamp, "re-save skips a sample already on disk");
+
+ // Stray files: an old-style sample and a temp are pruned, a foreign file is kept.
+ File.WriteAllText(Path.Combine(samples, "sample-99.wav"), "x");
+ File.WriteAllText(Path.Combine(samples, wavs[0] + ".tmp"), "x");
+ File.WriteAllText(Path.Combine(samples, "notes.txt"), "x");
+ ProjectService.Save(ProjectService.Capture(src, transport, new List<string>()), dir, src);
+ yield return (!File.Exists(Path.Combine(samples, "sample-99.wav")) && !File.Exists(Path.Combine(samples, wavs[0] + ".tmp")),
+ "unreferenced samples and temp files are pruned");
+ yield return (File.Exists(Path.Combine(samples, "notes.txt")), "files a save didn't write are left alone");
+
+ // Reload, re-save: names are reused (seeded from the file names), nothing new appears.
+ string manifestBefore = File.ReadAllText(Path.Combine(dir, ProjectService.ManifestName));
+ using (var dst = new NotaEngine())
+ {
+ var aw = ProjectService.Apply(ProjectService.Load(dir), dst, dir);
+ yield return (aw.Count == 0 && dst.TrackCount == 4, $"content-named bundle reloads ({aw.Count} warnings, {dst.TrackCount} tracks)");
+ ProjectService.Save(ProjectService.Capture(dst, transport, new List<string>()), dir, dst);
+ }
+ string manifestAfter = File.ReadAllText(Path.Combine(dir, ProjectService.ManifestName));
+ yield return (Regex.Matches(manifestAfter, "samples/[0-9a-f]{32}\\.wav").Cast<Match>().Select(m => m.Value).Distinct()
+ .SequenceEqual(Regex.Matches(manifestBefore, "samples/[0-9a-f]{32}\\.wav").Cast<Match>().Select(m => m.Value).Distinct()),
+ "sample names survive a reload + re-save");
+ yield return (Directory.GetFiles(samples, "*.wav").Length == 1, "reload + re-save adds no sample files");
+
+ // Legacy bundle (sample-N.wav, no seeding possible): the audio hashes back to the same name.
+ CopyDir(dir, legacy);
+ string lSamples = Path.Combine(legacy, "samples");
+ File.Move(Path.Combine(lSamples, wavs[0]!), Path.Combine(lSamples, "sample-7.wav"));
+ string lManifest = Path.Combine(legacy, ProjectService.ManifestName);
+ File.WriteAllText(lManifest, File.ReadAllText(lManifest).Replace("samples/" + wavs[0], "samples/sample-7.wav"));
+ using (var le = new NotaEngine())
+ {
+ var lw = ProjectService.Apply(ProjectService.Load(legacy), le, legacy);
+ yield return (lw.Count == 0, $"legacy-named bundle loads ({lw.Count} warnings)");
+ ProjectService.Save(ProjectService.Capture(le, transport, new List<string>()), legacy, le);
+ }
+ var lWavs = Directory.GetFiles(lSamples, "*.wav").Select(Path.GetFileName).ToArray();
+ yield return (lWavs.Length == 1 && lWavs[0] == wavs[0],
+ $"legacy sample migrates to the same content name ({string.Join(", ", lWavs)})");
+
+ // A change-detection capture is never saved.
+ var cheap = ProjectService.Capture(src, transport, new List<string>(), contentNames: false);
+ bool threw = false;
+ try { ProjectService.Save(cheap, Path.Combine(tmp, "nota-smoke-never-" + Guid.NewGuid().ToString("N")), src); }
+ catch (InvalidOperationException) { threw = true; }
+ yield return (threw, "saving a session-named (change-detection) capture is refused");
+ }
+ finally
+ {
+ try { Directory.Delete(dir, true); } catch { }
+ try { Directory.Delete(legacy, true); } catch { }
+ try { File.Delete(wav); } catch { }
+ }
+ }
+
+ private static void CopyDir(string from, string to)
+ {
+ foreach (var d in Directory.GetDirectories(from, "*", SearchOption.AllDirectories))
+ Directory.CreateDirectory(d.Replace(from, to));
+ Directory.CreateDirectory(to);
+ foreach (var f in Directory.GetFiles(from, "*", SearchOption.AllDirectories))
+ File.Copy(f, f.Replace(from, to));
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 2c6aa1a4..7f470ae5 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -132,6 +132,15 @@ if (args.Length >= 1 && args[0] == "--audition")
return failures == 0 ? 0 : 1;
}
+// Content-addressed bundle alone (fast iteration): `--bundle`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--bundle")
+{
+ Console.WriteLine("-- project: content-addressed bundle --");
+ foreach (var (ok, label) in BundleContentTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "BUNDLE PASSED" : $"BUNDLE FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
+
// Opt-in hosted-plugin check (M3-3): `--hostcheck <path-to-nota-scanworker>`.
// Loads a hosted AU instrument and effect and confirms audio flows through them.
if (args.Length >= 2 && args[0] == "--hostcheck")
@@ -3374,7 +3383,7 @@ Console.WriteLine("-- Sampler --");
Check(ne.PluginParamGet(st, -1, ni["loopmode"]) == 0.5f, "reloading the sample keeps a forward loop");
Reset();
- // The name round-trips through a project (the bundle stores sample-N.wav).
+ // The name round-trips through a project (the bundle names the file by content hash).
var nw = new System.Collections.Generic.List<string>();
var ndoc = ProjectService.Capture(ne, new TransportState(120.0, 1.0, false, false), nw);
string nb = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "nota-sampname-" + System.Guid.NewGuid().ToString("N") + ".nota");
@@ -8189,7 +8198,8 @@ Console.WriteLine("-- M7-6b: audio round-trip --");
ProjectService.Save(doc, dir, src);
int wavCount = System.IO.Directory.Exists(System.IO.Path.Combine(dir, "samples"))
? System.IO.Directory.GetFiles(System.IO.Path.Combine(dir, "samples"), "*.wav").Length : 0;
- Check(wavCount >= 3, $"sample files written to samples/ ({wavCount})");
+ // One file decoded three times: identical audio → one content-named file.
+ Check(wavCount >= 1, $"sample files written to samples/ ({wavCount})");
var loaded = ProjectService.Load(dir);
using var dst = new NotaEngine();
@@ -13577,6 +13587,10 @@ Console.WriteLine("-- background audio import --");
Console.WriteLine("-- browser: preset audition --");
foreach (var (ok, label) in AuditionTests.Run()) Check(ok, label);
+// --- project: content-addressed bundle (samples / plugin states named by hash) ---
+Console.WriteLine("-- project: content-addressed bundle --");
+foreach (var (ok, label) in BundleContentTests.Run()) Check(ok, label);
+
// --- get plug-ins: registry index, install/uninstall from local archives ---
Console.WriteLine("-- get plug-ins: registry store --");
foreach (var (ok, label) in PluginStoreTests.Run()) Check(ok, label);