Skip to content

perf: Copy path saves in 64 KB chunks - #156

Merged
decriptor merged 1 commit into
mainfrom
perf/ogg-page-save
Nov 26, 2026
Merged

decriptor merged 1 commit into
mainfrom
perf/ogg-page-save

Conversation

@decriptor

@decriptor decriptor commented Nov 26, 2026 •

Copy link
Copy Markdown
Owner

Description

A path save used to read the whole file into one buffer, render another, and write that out. SaveToFile and SaveToFileAsync now copy the audio from the source in a rented 64 KB buffer and write the same bytes as today's Render.

SaveToFile(path, span), Render, and ReadFromFile still build one buffer. That is the in-memory contract. ReadFromFile is unchanged by this pull request. #120 already stopped the read path from loading every sample. #20 was reopened because a save still did.

Motivation and Context

#20 is the report that scanning or tagging a library retains large buffers. The part this pull request addresses is the save. Adding a tag to about 200 Ogg files, 1 GB in total, was reported to push the process toward 3 GB. A byte array larger than 85,000 bytes lands on the large object heap, which the GC collects less often, so a save that allocates the whole file looks like a leak even after the buffer is no longer referenced.

The allocation is the cost that matters. The file still has to be written, so wall time barely moves. After a full GC on the earlier Ogg pass, the heap was 0.2 MB on both builds. The traffic is temporary, and it is large enough to matter while a library is being saved.

Fixes #20

What a path save does now

SaveToFile(path) and the async path overload copy sample bytes with StreamCopy. Each read and each write is at most 64 KB (StreamCopy.ChunkSize). The rented array may be longer. Only the first 64 KB are used. The copy does not call Stream.Length inside the loop. On Unix that call is an fstat.

The saved file is the same bytes as Render of the same edit. A synthetic pin, larger than 64 KB, refuses any read or write bigger than one chunk and asserts the save allocates less than half the file. A real-file hash compare is below.

These path saves stream:

  • Ogg Vorbis, Opus, and Ogg FLAC, one page at a time
  • MP3, native FLAC, ASF/WMA, raw AAC, MPEG program stream, Audible
  • Monkey's Audio, WavPack, and Musepack, through one APE writer
  • DSF when the samples were left on disk. A file that still holds its bytes writes those bytes and does not reopen the source
  • MP4, including a chapter edit. Chapter samples are read in chunks. The media payload is not loaded as one buffer
  • WAV and AIFF, including an odd-length chunk and its pad byte
  • AVI. idx1 and OpenDML indexes are patched from values read off the source. Sample bytes are copied in chunks
  • Matroska. Cluster payloads stay in the file and are copied in chunks. A dirty cluster is read twice, both times in 64 KB windows
  • DFF. The form is walked in chunks. ID3 is dropped, an ID3v1 or APE trailer is copied, DSTI is rebased, and the form size is patched

The source is closed when the destination is never created, including when creating the temp file throws. A render failure is returned before an already-cancelled token can hide it. Cancellation is reported after the file has been opened and after that format's size or length check, and before the destination is replaced.

Why these choices

64 KB, not a bigger buffer. 64 KB is under the 85 KB large-object threshold, so the rented chunk stays off the large object heap. A 200 MB sequential copy, five runs, Release net8, warm cache, on this machine:

Read buffer Write buffer Flush to disk Median
4 KB 4 KB yes 52.9 ms
4 KB 64 KB yes 53.9 ms
64 KB 4 KB yes 45.9 ms
64 KB 64 KB yes 49.7 ms
64 KB 64 KB no 44.2 ms

That is about 4 GB/s. The ranges overlap. Once the user write is already 64 KB, a larger write buffer does not help, because that write is already larger than the 4 KB FileStream buffer. DefaultFileSystem.OpenRead stays at 4096.

The flush stays. AtomicFileWriter still calls Flush(flushToDisk: true) before the temp file replaces the destination. Skipping it saved about 5 ms on that 200 MB copy and was not a reliable win. It is the crash safety of the replace.

Not an APFS clone. A clone plus a patched tag is faster when the new tag occupies the same byte range as the old one. Re-rendering the tag that was just read, with no field change, produced a different length for every ID3v2 tag in a 4,662-file MP3 library. Render() always appends 1,024 bytes of padding. Setting the title to Changed matched the old tag length for the one ID3v1-only file and for no ID3v2 tag. Over the 4,661 files whose ID3v2 tag grew or shrank, the length delta was p50 +995 bytes, p95 +1,017, min −3,259, max +1,052.

After a title edit Files Bytes What it means
Same length as the old tag 1 4.7 MB Audio stays put. This file is ID3v1 only
Frames fit, rendered tag is longer 4,383 23.29 GB Today's render shifts the audio
Frames fit, rendered tag is shorter 266 1.34 GB Today's render shifts the audio
Frames are larger than the old tag 12 66.6 MB The audio has to move

A same-slot write would cover 4,649 of 4,662 files, and the saved bytes would differ from today's Render wherever the padding is no longer 1,024. This pull request keeps byte identity with Render.

On the same build, warm, title set to Changed: forty MP3s of 2–10 MB (198 MB), median of three rounds, and three files of 10–200 MB (247 MB), one round.

Step 2–10 MB, p50 2–10 MB, sum 10–200 MB, sum
Tag render 0.01 ms 0.7 ms
SaveToFile 7.97 ms 333.4 ms 77.8 ms
64 KB copy, flush, rename 7.70 ms 318.1 ms 73.6 ms
clonefile, write the new tag, flush 5.47 ms 218.8 ms 14.6 ms

SaveToFile matches the raw copy. Rendering the tag is noise. On a typical library MP3 the flush and rename are most of the 8 ms. On the larger files the copy is the cost, and a clone only wins when the tag length does not change.

Benchmarks

Measured 2026-11-23 on this machine, warm file cache, Release net8.0. Baseline is a clean build of 50690256, which reads the whole file. Streaming is the path-save tree as it stood that day.

That tree did not yet stream DFF, Matroska, or AVI. In the 2026-11-23 tables below, DFF and Matroska stay at a ratio of 1 because they still allocated an output the size of the file, and AVI is not in that set. The fresh measurement of those three formats, on this commit, is in the next section.

For each file: MediaFile.Read, set the title to Changed when the tag allows it, SaveToFile to a temp path, SHA-256 the result, delete it. Allocation is GC.GetAllocatedBytesForCurrentThread around the save only. Wall time is a stopwatch around the same call. The two builds ran in separate processes. Paths containing malformed or corrupt were skipped. No sample and no library file was modified. A read that fails the same way on both builds is a shared failure, not a mismatch.

TaglibSharpSamples

443 audio files, about 2.8 GB. 0 hash mismatches. 9 shared read failures (four Opus files in channel-mapping families 2 and 3, which RFC 7845 reserves; two FLAC testbench files with no fLaC magic; two whose first block is not STREAMINFO; one WavPack file missing wvpk).

Extension Saved Input Baseline alloc Streaming alloc Ratio Baseline Streaming
aac 1 0.1 MB 0.3 MB 0.0 MB 0.058 5.2 ms 5.3 ms
aif 2 201.8 MB 1063.1 MB 0.0 MB 0.000 154.3 ms 52.6 ms
ape 15 5.2 MB 10.5 MB 0.2 MB 0.015 70.6 ms 71.6 ms
dff 1 63.5 MB 444.8 MB 444.8 MB 1.000 48.6 ms 46.8 ms
dsf 5 649.4 MB 2599.8 MB 1.3 MB 0.000 369.4 ms 236.5 ms
flac 112 682.5 MB 1955.7 MB 404.6 MB 0.207 859.0 ms 808.7 ms
m4a 10 16.3 MB 79.9 MB 8.5 MB 0.106 59.3 ms 62.3 ms
mkv 8 176.5 MB 594.4 MB 594.4 MB 1.000 134.2 ms 139.3 ms
mp3 28 17.0 MB 36.7 MB 0.5 MB 0.014 143.6 ms 142.7 ms
mp4 18 11.1 MB 49.2 MB 2.1 MB 0.043 97.5 ms 96.4 ms
mpc 34 141.2 MB 282.7 MB 0.6 MB 0.002 221.9 ms 248.3 ms
oga 3 6.4 MB 26.1 MB 0.7 MB 0.026 36.0 ms 24.5 ms
ogg 105 434.3 MB 1374.2 MB 18.6 MB 0.014 1904.0 ms 1641.0 ms
opus 39 37.0 MB 119.2 MB 16.3 MB 0.137 293.1 ms 283.2 ms
wav 8 197.3 MB 1429.6 MB 0.1 MB 0.000 179.2 ms 83.5 ms
wma 2 2.0 MB 7.9 MB 0.1 MB 0.015 11.8 ms 13.0 ms
wv 43 115.2 MB 231.4 MB 1.5 MB 0.007 270.4 ms 274.1 ms

FLAC's 404 MB is metadata. The testbench files whose bulk is a Vorbis comment, picture, seek table, or application block still have to be copied. A 105 MB stereo FLAC in the same set allocated under 0.1 MB. DSF dropped from 2.6 GB to 1.3 MB. WAV dropped from 1.4 GB to 0.1 MB. Vorbis dropped from 1.4 GB to 19 MB.

An earlier pass the same day, Ogg family only, 147 files and 478 MB, allocated 36 MB (0.075×) and took 1.8 s. 127 of 147 files were faster than the full-file baseline. None was more than 5 ms slower.

A music library

4,982 audio files, 29.3 GB. 0 hash mismatches. 6 shared read failures, all 0-byte MP3s, both builds returning "Invalid MP3 file: data too short".

Extension Saved Input Baseline alloc Streaming alloc Ratio Baseline Streaming
mp3 4,662 24.7 GB 67.5 GB 451 MB 0.007 39.9 s 37.0 s
wav 66 3.9 GB 20.9 GB 0.5 MB 0.000 3.0 s 2.2 s
m4a 219 697 MB 3.2 GB 181 MB 0.056 1.76 s 1.58 s
ogg 28 117 MB 376 MB 5.9 MB 0.016 0.54 s 0.41 s
wma 1 1.9 MB 7.6 MB 0.1 MB 0.009 5.2 ms 8.9 ms

For the 4,640 MP3s over 1 MB, median save time went from 8.04 ms to 7.79 ms, and p95 from 12.03 ms to 10.95 ms. The allocation ratio had a median of 0.0025 and a p95 of 0.019. Wall time barely moves because every save still writes the whole file.

One library M4A still allocated 3.5 MB of a 5.5 MB file. Its hash matched. An MP4 chapter save reads the chapter samples. Title and tag saves do not.

DFF, AVI, and Matroska, measured again

Measured 2026-11-26 on this machine, warm file cache, Release net8.0. Baseline is main at 50690256. Streaming is e20573c6. Each file was read once to warm the cache, then saved three times. The numbers below are the median of those three rounds. Allocation is GC.GetAllocatedBytesForCurrentThread around SaveToFile only. The title was set to Changed. SHA-256 of the saved file matched the baseline on every file and every round: 12 files, 3 rounds, 0 mismatches.

File Input Baseline alloc Streaming alloc Ratio Baseline Streaming
decaud-goldberg-var5-dsd64.dff 66.6 MB 466.7 MB 0.82 MB 0.002 87.0 ms 65.3 ms
test1.mkv 23.3 MB 93.4 MB 0.13 MB 0.001 28.1 ms 22.4 ms
test2.mkv 21.1 MB 63.5 MB 0.09 MB 0.001 24.3 ms 16.9 ms
test3.mkv 21.1 MB 63.2 MB 0.15 MB 0.002 26.3 ms 19.6 ms
test4.mkv 21.3 MB 85.3 MB 0.18 MB 0.002 33.6 ms 19.6 ms
test5.mkv 31.8 MB 95.3 MB 0.20 MB 0.002 39.9 ms 21.6 ms
test6.mkv 23.3 MB 93.4 MB 0.06 MB 0.001 25.1 ms 21.1 ms
test7.mkv 21.8 MB 65.6 MB 0.15 MB 0.002 18.1 ms 18.7 ms
test8.mkv 21.2 MB 63.7 MB 0.09 MB 0.001 20.4 ms 16.5 ms
sample.avi 0.1 MB 0.09 MB 0.03 MB 0.334 8.9 ms 7.7 ms
gen-720p45.avi 10.3 MB 10.3 MB 0.01 MB 0.001 10.9 ms 10.7 ms
gen-pcm180.avi 26.0 MB 26.0 MB 0.01 MB 0.000 24.2 ms 20.0 ms

Sums of those medians: DFF 466.7 MB to 0.82 MB (87 ms to 65 ms). The eight Matroska files, 185.0 MB of input, 623.3 MB to 1.06 MB (216 ms to 157 ms). The three AVIs, 36.4 MB of input, 36.5 MB to 0.06 MB (44 ms to 38 ms).

The DFF is the one real file in TaglibSharpSamples. The Matroska files are the official test1–test8 set. sample.avi is the 72 KB TagLib# sample, too small for the ratio to mean much. gen-720p45.avi and gen-pcm180.avi are generated test patterns, not library clips. There is no larger real AVI on this machine.

Type of Change

  • Performance improvement

Checklist

  • My code follows the project's code style (dotnet format TagLibSharp2.slnx --verify-no-changes exited 0)
  • I have added tests that prove my fix/feature works
  • All new and existing tests pass (dotnet test Debug net8.0, on this commit: 7303 passed, 57 skipped, 0 failed)
  • I have updated documentation as needed (CHANGELOG, ROADMAP, and docs/ROADMAP)
  • My changes generate no new warnings (Debug net8 build, with the existing WarningsNotAsErrors=CA2027)

Implementation guide

  • Design note with a tag behaviour table. This pull request does not change what a tag field stores
  • Twin table. Every path save listed above has a stream test that matches Render and bounds the copy
  • Kit run (fuzz, mutation, reader comparison) was not run for this change
  • Pre-review of the diff, findings fixed. The local review was not posted

Testing

macOS, SDK 11.0.100, Debug net8.0, commit e20573c6:

  • Full suite: 7303 passed, 57 skipped, 0 failed
  • dotnet format TagLibSharp2.slnx --verify-no-changes exited 0
  • dotnet list package --vulnerable --include-transitive reported no vulnerable packages

Not run locally on this commit: ubuntu, Windows, net10.0, and pack. CI covers those. The broad corpus tables are from 2026-11-23. DFF, AVI, and Matroska were measured again on 2026-11-26, Release net8.0, against main at 50690256.

Additional Notes

CHANGELOG, ROADMAP, and docs/ROADMAP record the path save.

@codecov

codecov Bot commented Nov 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 81.18101% with 1074 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.66%. Comparing base (5069025) to head (e20573c).

Files with missing lines Patch % Lines
...rc/TagLibSharp2/Matroska/MatroskaRewrite.Stream.cs 58.42% 276 Missing and 104 partials ⚠️
src/TagLibSharp2/Riff/AviRewrite.cs 67.61% 92 Missing and 45 partials ⚠️
src/TagLibSharp2/Mp4/Mp4File.cs 65.89% 55 Missing and 19 partials ⚠️
src/TagLibSharp2/Dff/DffFile.cs 70.09% 42 Missing and 22 partials ⚠️
src/TagLibSharp2/Riff/WavFile.cs 71.57% 43 Missing and 11 partials ⚠️
src/TagLibSharp2/Ape/ApeTagLocation.cs 68.14% 22 Missing and 14 partials ⚠️
src/TagLibSharp2/Audible/AudibleFile.cs 80.32% 21 Missing and 15 partials ⚠️
src/TagLibSharp2/Ogg/OggPageHelper.cs 68.57% 21 Missing and 12 partials ⚠️
...TagLibSharp2.Tests/Ogg/OggSaveStreamsAudioTests.cs 92.09% 23 Missing and 8 partials ⚠️
src/TagLibSharp2/Ogg/OggStreamSave.cs 77.46% 11 Missing and 5 partials ⚠️
... and 30 more
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #156      +/-   ##
==========================================
- Coverage   93.39%   92.66%   -0.74%     
==========================================
  Files         415      439      +24     
  Lines       88291    93658    +5367     
  Branches    10288    11200     +912     
==========================================
+ Hits        82462    86790    +4328     
- Misses       3429     4138     +709     
- Partials     2400     2730     +330     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

A path save loaded the whole file to rewrite a tag. SaveToFile and
SaveToFileAsync now copy the audio in a rented 64 KB buffer and write
the same bytes as Render. Span SaveToFile, Render, and ReadFromFile
still build one buffer.

The source is closed when the destination is never created. A render
failure is reported before an already-cancelled token. A read or write
one byte over 64 KB fails, and a write of exactly one chunk is kept.

CHANGELOG and ROADMAP record the path save.

Closes #20
@decriptor
decriptor merged commit 53f7940 into main Nov 26, 2026
8 checks passed
@decriptor
decriptor deleted the perf/ogg-page-save branch November 26, 2026 19:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: MediaFile.Read causes severe memory leak when scanning many audio files

1 participant