Avoid repeated payload and sample-table regrowth during segment fragment splitting

perfloop-oss/mp4ff · Allocation In Hot Loop

https://perfloop.ai/t/oss/case_sczkwfr32t

Verdict

VERIFIED · settled 2026-11-24 · pull request opened as Eyevinn/mp4ff#734

What happened: The paired measurements met the required improvement.

Hypothesis

Splitting an MP4 media segment into shorter fragments appends samples one at a time, even though every input fragment's complete sample slice is already in memory. Because each new output fragment starts with an empty payload buffer and an empty sample table, appending samples repeatedly reallocates and copies both slices, multiplying memory traffic up to more than five times the media payload size. Real-world call frequency and end-to-end production savings remain unmeasured.

In `mp4/mediasegment.go:176-218`, `MediaSegment.Fragmentify` decodes each input fragment's samples via `inFrag.GetFullSamples(trex)` at line 192, then loops sample by sample calling `of.AddFullSampleToTrack(s, trackID)` at line 206. That delegates to `TrunBox.AddSample` and `MdatBox.AddSampleData`, both appending into initially empty slices. Because Go's `runtime.growslice` grows large slices geometrically by roughly 1.25x to 1.5x, building a multi-sample output fragment allocates and recopies the accumulated payload bytes multiple times. This cost applies only after successful `GetFullSamples` retrieval on fragments with a non-nil `Traf` and `Mfhd`; early error exits do not reach the append loop.

Running `go test ./mp4 -run '^$' -bench '^BenchmarkHuntFragmentify$' -benchmem -count=1 -cpuprofile=/tmp/frag_cpu.prof -memprofile=/tmp/frag_mem.prof` in this checkout measured the unmodified code across committed `testdata/1.m4s` and synthetic 7 KB/sample video segments: - `testdata/1.m4s` (60 samples, 24,516 payload bytes, split into 4 fragments): 42,805 ns/op, 72,088 B/op (2.94x payload), 106 allocs/op. - 16 samples, 1 fragment (112,000 payload bytes): 156,415 ns/op, 405,657 B/op (3.62x payload), 31 allocs/op. - 96 samples, 4 fragments (672,000 payload bytes): 945,300 ns/op, 2,969,472 B/op (4.42x payload), 132 allocs/op. - 96 samples, 1 fragment (672,000 payload bytes): 1,228,152 ns/op, 3,526,179 B/op (5.25x payload), 42 allocs/op. - 240 samples, 4 fragments (1,680,000 payload bytes): 2,496,078 ns/op, 8,617,096 B/op (5.13x payload), 152 allocs/op. In the allocation-space profile (`go tool pprof -top -alloc_space -cum /tmp/frag_mem.prof`), `MdatBox.AddSampleData` accounts for 17,664.64 MB of 18,045.18 MB total (97.89%) and `TrunBox.AddSample` for 94.52 MB (0.52%). In the CPU profile (`go tool pprof -top -cum /tmp/frag_cpu.prof`, 11.38s total samples), `MediaSegment.Fragmentify` accounts for 5.21s cumulative, of which `AddFullSampleToTrack` is 4.69s and `runtime.growslice` is 4.41s (`MdatBox.AddSampleData` 4.36s), while background GC (`runtime.gcBgMarkWorker`) accounts for 3.17s. These are scoped benchmark attributions, not a production workload share.

The deterministic replay check `go test ./mp4 -run '^TestPerfloopFragmentifyAllocReplay$' -count=1 -v` compares `testing.AllocsPerRun` for 1-sample versus 64-sample single-fragment splits (7,000 bytes per sample) after checking sample metadata and payload equality. On current code it fails with 39 allocs/op for 64 samples versus 20 allocs/op for 1 sample (delta +19, bound <= +2). A broader provisional sweep over N in {4, 16, 64, 96} and committed `testdata/1.m4s` also fails every case on current code, and a small experimental exact-size batch-reservation edit in `MediaSegment.Fragmentify` reduces all synthetic 1-fragment cases to 20 allocs/op (delta 0, ~1.02x-1.06x payload bytes) and `testdata/1.m4s` from 106 allocs / 72,088 B to 76 allocs / 32,376 B while passing `TestMediaSegmentFragmentation` and `TestFragmentifyMissingBoxes`.

An upstream open-PR read returned zero open PRs on `Eyevinn/mp4ff`, and `git log` on `mp4/mediasegment.go` shows no prior Fragmentify pre-allocation change. Prior finding `hyp_689x5dg6yc` addresses `examples/stream-encrypt/refragment.go` (`createFragmentFromSamples`); `MediaSegment.Fragmentify` is a separate exported library method in package `mp4`.

The Case proof target is to reproduce the allocation and byte-overhead reduction on `testdata/1.m4s` and multi-sample / multi-input-fragment segments, verify whole-call elapsed-time and memory gains across single- and multi-fragment splits, and verify byte-exact encoded output, sample metadata, `TestMediaSegmentFragmentation`, and payload-buffer independence if retaining copy-owning semantics (or explicitly evaluate whether borrowing via `AddFullSamples` would alter caller aliasing expectations). The replay test layout and exact-size copy edit are provisional, not extra frozen requirements.

Change to test: Group each output fragment's sample batch from the decoded input samples and reserve its payload and sample-table capacity once before appending. Preserve output fragment boundaries, metadata, encoded bytes, and copy-owning payload independence from the input segment.

Where it lives

perfloop-oss/mp4ff

Evidence

Fragmentify single fragment · 15 sample pairs

metric baseline candidate paired median change confidence range required result
ns/op 34672 10355 −70.7% (−24506) −29541 to −20940 gain > 0 PASSED
B/op 109080 29480 −73% (−79600) −79601 to −79600 gain > 0 PASSED
allocs/op 33 20 −39.4% (−13) −13 to −13 gain > 0 PASSED

Fragmentify split fragments · 15 sample pairs

metric baseline candidate paired median change confidence range required result
ns/op 30242 13812 −56.3% (−17025) −19909 to −14542 gain > 0 PASSED
B/op 72088 32376 −55.1% (−39712) −39714 to −39712 gain > 0 PASSED
allocs/op 106 76 −28.3% (−30) −30 to −30 gain > 0 PASSED

Fragmentify joined fragments · 25 sample pairs

metric baseline candidate paired median change confidence range required result
ns/op 37671 34308 −9.7% (−3642) −6177 to −769 gain > 0 PASSED
B/op 109080 103288 −5.3% (−5792) −5792 to −5792 gain > 0 PASSED
allocs/op 36 28 −22.2% (−8) −8 to −8 gain > 0 PASSED

Checks: 3 of 3 passed. Verification: no defect found.

Timeline