From f0e2306cebfef9d0776221e5276d12166e021869 Mon Sep 17 00:00:00 2001 From: gravity-zero Date: Sat, 21 Nov 2026 18:10:32 +0100 Subject: [PATCH 1/2] feat(hls): Options.SignedCompositionOffsets writes signed composition offsets with no shift and no video edit list --- CHANGELOG.md | 8 +++ cmd/mkvgo/commands/cli03_parity_test.go | 4 +- cmd/mkvgo/commands/helpers.go | 4 +- cmd/mkvgo/commands/hls.go | 33 +++++----- docs/cli.md | 5 +- docs/library.md | 2 +- mp4/composition_shift_unit_test.go | 2 +- mp4/fragment.go | 11 ++-- mp4/gridwindow_test.go | 6 +- mp4/growinghls.go | 4 +- mp4/hls.go | 2 +- mp4/hlspack.go | 6 +- mp4/hlsplan_mp4.go | 2 +- mp4/hlsplan_probe.go | 4 +- mp4/options.go | 12 ++++ mp4/stride_direction_test.go | 2 +- mp4/tied_boundary_test.go | 82 +++++++++++++++++++++++++ scripts/apple-check.sh | 12 ++-- 18 files changed, 160 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5cb8ef28..832e4e7c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,14 @@ its series' file in [changelog/](changelog/) when a newer one ships. ## [Unreleased] +### Added + +- `Options.SignedCompositionOffsets` (`--signed-offsets` on `to-hls` and + `hls-segment`): a reordered video's composition offsets are written signed, + with no composition shift and no video edit list. A player that ignores the + edit list showed the picture late by the reordering depth (84 ms on a + two-frame pyramid); it now shows it on time. Off by default. + ### Changed - The HLS/DASH init segment no longer carries the cover art (`RemuxToHLS`, diff --git a/cmd/mkvgo/commands/cli03_parity_test.go b/cmd/mkvgo/commands/cli03_parity_test.go index 20cba3b2..ae4437b2 100644 --- a/cmd/mkvgo/commands/cli03_parity_test.go +++ b/cmd/mkvgo/commands/cli03_parity_test.go @@ -95,6 +95,8 @@ func oldParseHLSFlags(args []string) hlsFlags { f.skipUnsupported = true case "--no-iframes": f.noIFrames = true + case "--signed-offsets": + f.signedOffsets = true case "--damage-bytes": needValue(args, &i) n, err := strconv.ParseInt(args[i], 10, 64) @@ -231,7 +233,7 @@ func TestCLI03_HLSFlagsParity(t *testing.T) { "--keep-tracks": {"1,2", "1, x"}, "--keep-lang": {"fre,ENG", " , "}, "--audio-lang": {"spa"}, "--sub-offset": {"-500", "x"}, "--damage-bytes": {"100", "0", "-1"}, "--source-access": {"auto", "local", "network", "nfs"}, "--audio-shift": {"2=500", "bad"}, } - bools := []string{"--single-file", "--chapter-markers", "--skip-unsupported", "-skip-unsupported", "--no-iframes", "--synthesize-index", "--cenc-inline-key"} + bools := []string{"--single-file", "--chapter-markers", "--skip-unsupported", "-skip-unsupported", "--no-iframes", "--signed-offsets", "--synthesize-index", "--cenc-inline-key"} operands := []string{"in.mkv", "master.m3u8", "-", "--bogus", "-x"} var flags []string for k := range values { diff --git a/cmd/mkvgo/commands/helpers.go b/cmd/mkvgo/commands/helpers.go index e3c41c14..90a5cd56 100644 --- a/cmd/mkvgo/commands/helpers.go +++ b/cmd/mkvgo/commands/helpers.go @@ -146,8 +146,8 @@ var CmdUsage = map[string]string{ "to-mp4": "mkvgo to-mp4 [--faststart] [--skip-unsupported] [--strict] [--flatten-subs] [--webvtt-native] [--mp3-container-delay] [--hash] (an MP4/MOV input is rewritten fast start, sample for sample)", "from-mp4": "mkvgo from-mp4 [--skip-unsupported] [--strict] [--mp3-container-delay] ", "to-webm": "mkvgo to-webm ", - "to-hls": "mkvgo to-hls -o [-segment 6] [--skip-unsupported] [--strict] [--keep-tracks 1,2 | --keep-lang fre] [--sub-offset ms] [--audio-shift track=ms] [--chapter-markers] [--no-iframes] (fragmented-MP4 HLS; virtual track subset by ID or language; virtual subtitle/audio resync; opt-in chapter/ad-insertion markers)", - "hls-segment": "mkvgo hls-segment [-o out] [-segment 6] [--keep-tracks 1,2 | --keep-lang fre] [--sub-offset ms] [--audio-shift track=ms] [--synthesize-index] [--chapter-markers] [--no-iframes] [--damage-bytes n] (build one HLS resource on demand; --synthesize-index serves a no-Cue source by walking it once)", + "to-hls": "mkvgo to-hls -o [-segment 6] [--skip-unsupported] [--strict] [--keep-tracks 1,2 | --keep-lang fre] [--sub-offset ms] [--audio-shift track=ms] [--chapter-markers] [--no-iframes] [--signed-offsets] (fragmented-MP4 HLS; virtual track subset by ID or language; virtual subtitle/audio resync; opt-in chapter/ad-insertion markers)", + "hls-segment": "mkvgo hls-segment [-o out] [-segment 6] [--keep-tracks 1,2 | --keep-lang fre] [--sub-offset ms] [--audio-shift track=ms] [--synthesize-index] [--chapter-markers] [--no-iframes] [--signed-offsets] [--damage-bytes n] (build one HLS resource on demand; --synthesize-index serves a no-Cue source by walking it once)", "to-abr": "mkvgo to-abr -o [...] [-segment 6] [--keep-tracks 1,2 | --keep-lang fre] [--sub-offset ms] [--chapter-markers] [--no-iframes] (multi-variant HLS master from pre-encoded qualities)", "abr-segment": "mkvgo abr-segment [...] [-o out] [-segment 6] [--keep-tracks 1,2 | --keep-lang fre] [--sub-offset ms] [--chapter-markers] [--no-iframes] [--damage-bytes n] (build one ABR resource on demand)", "cmaf-mpd": "mkvgo cmaf-mpd -o [ ...] [--audio ]... (DASH manifest over CMAF rungs an external encoder produced: each dir holds one rendition's init.mp4 + .m4s segments; rungs are checked segment-aligned first)", diff --git a/cmd/mkvgo/commands/hls.go b/cmd/mkvgo/commands/hls.go index dea60c23..a235feac 100644 --- a/cmd/mkvgo/commands/hls.go +++ b/cmd/mkvgo/commands/hls.go @@ -29,6 +29,7 @@ type hlsFlags struct { subOffset int64 chapterMarkers bool noIFrames bool + signedOffsets bool damageBytes int64 skipUnsupported bool sourceAccess mp4.SourceAccess @@ -94,6 +95,7 @@ func parseHLSFlags(args []string) hlsFlags { fl.Bool(&f.chapterMarkers, "--chapter-markers") fl.Bool(&f.skipUnsupported, "--skip-unsupported", "-skip-unsupported") fl.Bool(&f.noIFrames, "--no-iframes") + fl.Bool(&f.signedOffsets, "--signed-offsets") fl.Func(damageBytesFlag(&f.damageBytes), "--damage-bytes") fl.Func(func(v string) { switch v { @@ -240,21 +242,22 @@ func (f hlsFlags) options(src string) mp4.Options { keep = resolveKeepLangs(src, f.keepLangs) } o := mp4.Options{ - FS: sourceFS(src), - SegmentMs: f.segMs, - Encrypt: f.encrypt, - CENC: f.cenc, - SingleFile: f.singleFile, - KeepTracks: keep, - SubtitleOffsetMs: f.subOffset, - ChapterMarkers: f.chapterMarkers, - NoIFrames: f.noIFrames, - DamageBytes: f.damageBytes, - SkipUnsupported: f.skipUnsupported, - Strict: Strict, - SynthesizeIndex: f.synthIndex, - AudioPresentationShift: f.audioShift, - SourceAccess: f.sourceAccess, + FS: sourceFS(src), + SegmentMs: f.segMs, + Encrypt: f.encrypt, + CENC: f.cenc, + SingleFile: f.singleFile, + KeepTracks: keep, + SubtitleOffsetMs: f.subOffset, + ChapterMarkers: f.chapterMarkers, + NoIFrames: f.noIFrames, + SignedCompositionOffsets: f.signedOffsets, + DamageBytes: f.damageBytes, + SkipUnsupported: f.skipUnsupported, + Strict: Strict, + SynthesizeIndex: f.synthIndex, + AudioPresentationShift: f.audioShift, + SourceAccess: f.sourceAccess, } if f.prefix != "" { prefix := f.prefix diff --git a/docs/cli.md b/docs/cli.md index 3c561649..3ec1d623 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1147,7 +1147,7 @@ Package a media file - **MKV/WebM or MP4/MOV** (sniffed from the first bytes) Text subtitle tracks (SRT, WebVTT, ASS/SSA flattened to plain text) ride as segmented **WebVTT renditions** (`subN.m3u8` + `subN_*.vtt`), declared in the master playlist with their language/name/default/forced flags; bitmap subtitles (PGS/VOBSUB) are dropped with a reason. This is the CMAF "copy rung" of an HLS ladder - the packaging, not the encoding: bitrate variants (real adaptive streaming) still require a transcoder. ``` -mkvgo to-hls -o [-segment 6] [--skip-unsupported] [--strict] [--sub-offset ] [--audio-shift =] [--chapter-markers] [--no-iframes] +mkvgo to-hls -o [-segment 6] [--skip-unsupported] [--strict] [--sub-offset ] [--audio-shift =] [--chapter-markers] [--no-iframes] [--signed-offsets] ``` Every track the presentation leaves out - a secondary video track (one video rendition is carried), a bitmap subtitle (PGS, VobSub), an unsupported codec under `--skip-unsupported`, an encrypted track - is printed on stderr as `dropped track N (codec): reason`, the exit code staying 0; `--strict` fails the packaging by name on any of them, whatever `--skip-unsupported` says (`serve` and the ABR commands take the same two flags). `tracks -json` says ahead of time, per track, whether `to-hls` and `serve` carry it (`to_hls`, `to_hls_refusal`). @@ -1162,6 +1162,7 @@ Every track the presentation leaves out - a secondary video track (one video ren | `--audio-shift` | Re-base an audio track in presentation (`track=ms`, repeatable; positive = the track's content starts late and is presented earlier - feed it `diagnose`'s per-track delay). The samples are copied verbatim and the media segments are byte-identical with or without the shift: only the init segment's edit list moves, so a constant A/V desync is cancelled in the served stream without touching the source. Over-shifts clamp to the presentation start. The persistent repair remains `mkvgo retime` | | `--chapter-markers` | Opt-in: expose the source's chapters as `EXT-X-DATERANGE` lines in the video media playlist and a chapter `EventStream` in `manifest.mpd` - chapter navigation and ad-insertion cue points, no re-segmentation. See [streaming.md](streaming.md#chapter-markers-and-ad-insertion-points) | | `--no-iframes` | Drop the trick-play I-frame stream: no `EXT-X-I-FRAME-STREAM-INF` in the master, no `iframe.m3u8` nor `iframeNNNNN.m4s` written or served (`hls-segment iframe` refuses it). For players that scrub with their own trickplay images. Segments and the other playlists are unchanged. Also on `hls-segment`, `to-abr`, `abr-segment`. See [streaming.md](streaming.md#trick-play-scrubbing) | +| `--signed-offsets` | Write a reordered video's composition offsets signed, with no composition shift and no video edit list (CMAF `cmf2` form): a player that ignores the edit list presents the picture on time instead of late by the reordering depth. Init and segments both change: use one setting per presentation. Also on `hls-segment` | ```bash mkvgo to-hls video.mkv -o stream/ @@ -1275,7 +1276,7 @@ and reading only that window - first-play latency is milliseconds and storage cost is zero, whatever the file size. ``` -mkvgo hls-segment [-o out] [-segment 6] [--sub-offset ] [--audio-shift =] [--synthesize-index] [--chapter-markers] [--no-iframes] [--damage-bytes ] +mkvgo hls-segment [-o out] [-segment 6] [--sub-offset ] [--audio-shift =] [--synthesize-index] [--chapter-markers] [--no-iframes] [--signed-offsets] [--damage-bytes ] ``` Without `-o` the resource goes to stdout (pipe it from a server handler). diff --git a/docs/library.md b/docs/library.md index 35f1653c..bc909961 100644 --- a/docs/library.md +++ b/docs/library.md @@ -232,7 +232,7 @@ Memory use scales with the sample count, not the file size: sample data is strea err := mp4.RemuxToHLS(ctx, "in.mkv", "stream/", mp4.Options{SegmentMs: 6000}) ``` -Writes a fragmented-MP4 / CMAF presentation into the output directory, served through two manifests over the same segments: HLS (`master.m3u8` + per-rendition media playlists) and DASH (`manifest.mpd`). Tracks are demuxed - the video rendition (`playlist.m3u8`, `init.mp4`, `seg00001.m4s` …) plus one rendition per audio track (`audio1.m3u8`, `init_a1.mp4`, `seg_a1_00001.m4s` …, an `EXT-X-MEDIA` AUDIO group / one MPD AdaptationSet each) - so multi-audio sources get native language selection. Each `.m4s` is `styp` + `moof` + `mdat`; each init is ftyp + moov with `mvex`/`trex` and empty sample tables (movie metadata - title and tags - rides on the video init; the cover art stays out of it, since a player downloads the init before its first frame). No transcoding - samples are copied verbatim, so the codec set matches `RemuxToMP4`. +Writes a fragmented-MP4 / CMAF presentation into the output directory, served through two manifests over the same segments: HLS (`master.m3u8` + per-rendition media playlists) and DASH (`manifest.mpd`). Tracks are demuxed - the video rendition (`playlist.m3u8`, `init.mp4`, `seg00001.m4s` …) plus one rendition per audio track (`audio1.m3u8`, `init_a1.mp4`, `seg_a1_00001.m4s` …, an `EXT-X-MEDIA` AUDIO group / one MPD AdaptationSet each) - so multi-audio sources get native language selection. Each `.m4s` is `styp` + `moof` + `mdat`; each init is ftyp + moov with `mvex`/`trex` and empty sample tables (movie metadata - title and tags - rides on the video init; the cover art stays out of it, since a player downloads the init before its first frame). `Options.SignedCompositionOffsets` writes a reordered video's composition offsets signed, with no composition shift and no video edit list (the CMAF `cmf2` form), for players that ignore the edit list and would show the picture late by the reordering depth; the default keeps non-negative offsets and the edit list. No transcoding - samples are copied verbatim, so the codec set matches `RemuxToMP4`. Segments are cut on video keyframes at roughly `Options.SegmentMs` (default 6 s) and each is independently decodable, so a player seeks by fetching the segment plus `init.mp4`. Text subtitle tracks (SRT, WebVTT, ASS/SSA flattened) become segmented WebVTT renditions declared in the master playlist; bitmap subtitles are dropped (reported via `Options.OnDrop`). This is the CMAF *copy rung* of an HLS ladder - the packaging; bitrate variants (real ABR) remain a transcoder's job. diff --git a/mp4/composition_shift_unit_test.go b/mp4/composition_shift_unit_test.go index 0da348f6..01521ab8 100644 --- a/mp4/composition_shift_unit_test.go +++ b/mp4/composition_shift_unit_test.go @@ -181,7 +181,7 @@ func TestFillFragTimingLateReorderKeepsEveryPTS(t *testing.T) { samples = append(samples, fragSample{ptsMs: int64(30+4*g+k) * 1001 / 24}) } } - _, _, _, shift := fillFragTimingTS(samples, nil, 42, movieTimescale, 0, nil, 2, false) + _, _, _, shift := fillFragTimingTS(samples, nil, 42, movieTimescale, 0, nil, 2, false, false) if shift != 84 { t.Fatalf("shift = %d, want 84 (two frames)", shift) } diff --git a/mp4/fragment.go b/mp4/fragment.go index 1c8a853b..571fa1e8 100644 --- a/mp4/fragment.go +++ b/mp4/fragment.go @@ -424,7 +424,7 @@ func measuredShiftTS(ptsTS []int64) int64 { // DTS is rebased so the track's first sample is 0; the presentation offset (the // smallest PTS) is returned so the caller can emit it as an edit list. func fillFragTiming(samples []fragSample, lastDurMs int64, mts uint32, gridTS int64) (offsetMs int64, hasCTS bool, totalTS int64, ctsShiftTS int64) { - return fillFragTimingTS(samples, nil, lastDurMs, mts, gridTS, nil, 0, false) + return fillFragTimingTS(samples, nil, lastDurMs, mts, gridTS, nil, 0, false, false) } // fillFragTimingTS is fillFragTiming with, when ptsTS is not nil, each @@ -437,8 +437,9 @@ func fillFragTiming(samples []fragSample, lastDurMs int64, mts uint32, gridTS in // bounds, when not nil, are the segment starts (ms): grid-timed audio is then // timed window by window (gridTimeWindows), as an on-demand plan times it. // reorder is the track's declared reordering depth (compositionShiftTS); video says the track is the video one, -// whose windows a frame tied with a boundary keyframe stays out of (tiedBeforeKey). -func fillFragTimingTS(samples []fragSample, ptsTS []int64, lastDurMs int64, mts uint32, gridTS int64, bounds []int64, reorder int, video bool) (offsetMs int64, hasCTS bool, totalTS int64, ctsShiftTS int64) { +// whose windows a frame tied with a boundary keyframe stays out of (tiedBeforeKey); signed is +// Options.SignedCompositionOffsets. +func fillFragTimingTS(samples []fragSample, ptsTS []int64, lastDurMs int64, mts uint32, gridTS int64, bounds []int64, reorder int, video, signed bool) (offsetMs int64, hasCTS bool, totalTS int64, ctsShiftTS int64) { n := len(samples) if n == 0 { return 0, false, 0, 0 @@ -544,7 +545,9 @@ func fillFragTimingTS(samples []fragSample, ptsTS []int64, lastDurMs int64, mts prefix = append(prefix, pts(i)) syncs = append(syncs, samples[i].sync) } - ctsShiftTS = compositionShiftTS(prefix, syncs, reorder) + if !signed { // Options.SignedCompositionOffsets: no shift, the offsets go below zero instead + ctsShiftTS = compositionShiftTS(prefix, syncs, reorder) + } for i := 0; i < n-1; i++ { samples[i].durTS = dts[i+1] - dts[i] } diff --git a/mp4/gridwindow_test.go b/mp4/gridwindow_test.go index 5997e538..65926d45 100644 --- a/mp4/gridwindow_test.go +++ b/mp4/gridwindow_test.go @@ -97,8 +97,8 @@ func TestGridWindowsOnTheirTimecodesAfterARunAhead(t *testing.T) { bounds := []int64{0, 2000, 4000, 6000, 8000, 10000} clean, whole := build(false), build(false) - fillFragTimingTS(clean, nil, 0, 44100, g, bounds, 0, false) - fillFragTimingTS(whole, nil, 0, 44100, g, nil, 0, false) + fillFragTimingTS(clean, nil, 0, 44100, g, bounds, 0, false, false) + fillFragTimingTS(whole, nil, 0, 44100, g, nil, 0, false, false) for i := range clean { if clean[i].dtsTS != whole[i].dtsTS || clean[i].durTS != whole[i].durTS { t.Fatalf("on the grid: frame %d timed %d+%d by window, %d+%d whole", i, clean[i].dtsTS, clean[i].durTS, whole[i].dtsTS, whole[i].durTS) @@ -106,7 +106,7 @@ func TestGridWindowsOnTheirTimecodesAfterARunAhead(t *testing.T) { } s := build(true) - _, _, total, _ := fillFragTimingTS(s, nil, 0, 44100, g, bounds, 0, false) + _, _, total, _ := fillFragTimingTS(s, nil, 0, 44100, g, bounds, 0, false, false) anchor := scale(s[0].blockPtsMs) for i := range s { if s[i].blockPtsMs < 4000 { diff --git a/mp4/growinghls.go b/mp4/growinghls.go index e22eb62e..288b37a8 100644 --- a/mp4/growinghls.go +++ b/mp4/growinghls.go @@ -526,7 +526,9 @@ func (p *GrowingHLSPlan) settleLeadLocked() { for i, ms := range p.leadPts { ts[i] = scale(ms) } - pt.ft.ctsShiftTS = compositionShiftTS(ts, p.leadSync, declaredReorderDepth(&pt.ft.outTrack.mkv)) + if !p.opts.SignedCompositionOffsets { + pt.ft.ctsShiftTS = compositionShiftTS(ts, p.leadSync, declaredReorderDepth(&pt.ft.outTrack.mkv)) + } } // extendHeadLocked folds one block into head resolution: the track's first diff --git a/mp4/hls.go b/mp4/hls.go index bde1ba9d..648929e9 100644 --- a/mp4/hls.go +++ b/mp4/hls.go @@ -377,7 +377,7 @@ func remuxToHLSInto(ctx context.Context, srcPath, outputDir string, op *Options) if grid == 0 && ps.mv != nil { grid = mp4FrameGridTS(ps, ft.outTrack, ft.timescale) } - off, hasCTS, totalTS, ctsShift := fillFragTimingTS(ft.samples, ft.ptsTS, ft.outTrack.frameDurMs, ft.timescale, grid, gridBounds, declaredReorderDepth(&ft.outTrack.mkv), ft.outTrack.spec.video) + off, hasCTS, totalTS, ctsShift := fillFragTimingTS(ft.samples, ft.ptsTS, ft.outTrack.frameDurMs, ft.timescale, grid, gridBounds, declaredReorderDepth(&ft.outTrack.mkv), ft.outTrack.spec.video, o.SignedCompositionOffsets) ft.ptsTS = nil ft.offsetMs, ft.hasCTS, ft.durMediaTS = off, hasCTS, totalTS ft.ctsShiftTS = ctsShift diff --git a/mp4/hlspack.go b/mp4/hlspack.go index 59f49e28..caaa79a2 100644 --- a/mp4/hlspack.go +++ b/mp4/hlspack.go @@ -198,8 +198,8 @@ const planCtxEvery = 4096 // mp4PlanTracks builds the on-demand plan state for an MP4 source: each // track's fragment samples fully timed from the sample table (head-only) plus // the parallel file offsets Segment reads through. Returns the fragTracks in -// planTracks order and the per-track sample offsets. -func mp4PlanSamples(ctx context.Context, ps *packagingSource, media []*outTrack) (fts []*fragTrack, offsets [][]int64, err error) { +// planTracks order and the per-track sample offsets. signed is Options.SignedCompositionOffsets. +func mp4PlanSamples(ctx context.Context, ps *packagingSource, media []*outTrack, signed bool) (fts []*fragTrack, offsets [][]int64, err error) { for _, t := range media { if err := ctx.Err(); err != nil { return nil, nil, err @@ -257,7 +257,7 @@ func mp4PlanSamples(ctx context.Context, ps *packagingSource, media []*outTrack) if grid == 0 { grid = mp4FrameGridTS(ps, t, ft.timescale) } - off, hasCTS, totalTS, ctsShift := fillFragTimingTS(ft.samples, ptsTS, t.frameDurMs, ft.timescale, grid, nil, declaredReorderDepth(&t.mkv), t.spec.video) + off, hasCTS, totalTS, ctsShift := fillFragTimingTS(ft.samples, ptsTS, t.frameDurMs, ft.timescale, grid, nil, declaredReorderDepth(&t.mkv), t.spec.video, signed) if err := ctx.Err(); err != nil { return nil, nil, err } diff --git a/mp4/hlsplan_mp4.go b/mp4/hlsplan_mp4.go index ffcddf82..b3557726 100644 --- a/mp4/hlsplan_mp4.go +++ b/mp4/hlsplan_mp4.go @@ -88,7 +88,7 @@ func planHLSFromMP4(ctx context.Context, ps *packagingSource, srcPath string, fs p.subScan = make([]subScanState, len(p.subs)) p.mp4subs = mp4SubTables(ps, p.subs) - fts, offs, err := mp4PlanSamples(ctx, ps, media) + fts, offs, err := mp4PlanSamples(ctx, ps, media, p.opts.SignedCompositionOffsets) if err != nil { return nil, err } diff --git a/mp4/hlsplan_probe.go b/mp4/hlsplan_probe.go index 90770b0a..fd5e55e1 100644 --- a/mp4/hlsplan_probe.go +++ b/mp4/hlsplan_probe.go @@ -343,7 +343,9 @@ func (p *HLSPlan) probeCompositionShift(ctx context.Context) error { for i, ms := range pts { ts[i] = scale(ms) } - pt.ft.ctsShiftTS = compositionShiftTS(ts, sync, declaredReorderDepth(&pt.ft.outTrack.mkv)) + if !p.opts.SignedCompositionOffsets { + pt.ft.ctsShiftTS = compositionShiftTS(ts, sync, declaredReorderDepth(&pt.ft.outTrack.mkv)) + } p.opensOnKeyframe = len(sync) > 0 && sync[0] return nil } diff --git a/mp4/options.go b/mp4/options.go index 852b0d4b..0fcde9ae 100644 --- a/mp4/options.go +++ b/mp4/options.go @@ -307,6 +307,18 @@ type Options struct { // either way. NoIFrames bool + // SignedCompositionOffsets writes a reordered video's composition offsets + // signed, around a first frame that presents when it decodes, with no + // composition shift and no edit list to take one back (RemuxToHLS, + // PlanHLS, PlanGrowingHLS and their MP4-source counterparts) - the CMAF + // 'cmf2' form. A player that ignores the video edit list then presents + // the picture on time, where the default form (non-negative offsets + // pushed up by the reordering depth, an edit list taking it back) shows + // it late by that depth; a reader that pulls its decode clock back for a + // negative offset shows it late with this one instead. Off by default. + // Init and segments both change with it: one setting per presentation. + SignedCompositionOffsets bool + // DamageBytes is how far past an unreadable element an on-demand window // walk (PlanHLS, PlanABR) looks for the next Cluster before refusing the // window: a damaged region shorter than this is passed over, a longer one diff --git a/mp4/stride_direction_test.go b/mp4/stride_direction_test.go index fdd63a2f..3c97b33f 100644 --- a/mp4/stride_direction_test.go +++ b/mp4/stride_direction_test.go @@ -21,7 +21,7 @@ func TestStrideErrorDirection(t *testing.T) { } deviation := func(gridTS int64) float64 { s := build() - fillFragTimingTS(s, nil, 0, mts, gridTS, nil, 0, false) + fillFragTimingTS(s, nil, 0, mts, gridTS, nil, 0, false, false) var worst float64 for i := 0; i < len(s); i += frames { if d := float64(s[i].dtsTS)*1000/mts - float64(s[i].blockPtsMs-s[0].blockPtsMs); d > worst || -d > worst { diff --git a/mp4/tied_boundary_test.go b/mp4/tied_boundary_test.go index 0752b26d..ee7618cf 100644 --- a/mp4/tied_boundary_test.go +++ b/mp4/tied_boundary_test.go @@ -199,3 +199,85 @@ func lowestTrunOffset(seg []byte) int64 { } return low } + +// Options.SignedCompositionOffsets: a B-pyramid's offsets go below zero around a first frame that presents when it +// decodes, the init carries no edit list for the video, and both paths write the same bytes. Without the option the +// same source gets its edit list and no negative offset. +func TestSignedCompositionOffsets(t *testing.T) { + w, h := uint32(320), uint32(240) + path := filepath.Join(t.TempDir(), "in.mkv") + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + const scale = 1_000_000 + m := writer.NewMKVWriter(f) + tracks := []mkv.Track{{ID: 1, Type: mkv.VideoTrack, Codec: "h264", CodecPrivate: fakeAVCC, Width: &w, Height: &h}} + c := &mkv.Container{Info: mkv.SegmentInfo{TimecodeScale: scale, MuxingApp: "mkvgo-test", WritingApp: "mkvgo-test"}} + if err := m.WriteStart(); err != nil { + t.Fatal(err) + } + if err := m.WriteMetadata(c, tracks, 149*40); err != nil { + t.Fatal(err) + } + for g := 0; g < 6; g++ { // one cluster a GOP: a keyframe, then groups decoded P B b b + base := g * 25 + order := []int{0} + for k := 1; k < 25; k += 4 { + order = append(order, k+3, k+1, k, k+2) + } + var blks []mkv.Block + for _, i := range order { + blks = append(blks, mkv.Block{TrackNumber: 1, Timecode: int64(base+i) * 40, Keyframe: i == 0, Data: []byte{0, 0, 0, 1, 0x41, byte(base + i)}}) + } + if err := m.WriteClusterWithCues(int64(g)*1000, scale, blks); err != nil { + t.Fatal(err) + } + } + if err := m.Finalize(); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + ctx := context.Background() + for _, signed := range []bool{false, true} { + o := Options{SegmentMs: 2000, SignedCompositionOffsets: signed} + dir := t.TempDir() + if err := RemuxToHLS(ctx, path, dir, o); err != nil { + t.Fatal(err) + } + plan, err := PlanHLS(ctx, path, o) + if err != nil { + t.Fatal(err) + } + init, err := os.ReadFile(filepath.Join(dir, "init.mp4")) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(plan.InitSegment(), init) { + t.Errorf("signed=%v: the plan's init differs from the full pass", signed) + } + if got := bytes.Contains(init, []byte("elst")); got == signed { + t.Errorf("signed=%v: init carries an edit list = %v", signed, got) + } + lowest := int64(0) + for n := 0; n < plan.NumSegments(); n++ { + full, err := os.ReadFile(filepath.Join(dir, plan.SegmentName(n))) + if err != nil { + t.Fatal(err) + } + od, err := plan.Segment(ctx, n) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(od, full) { + t.Errorf("signed=%v segment %d: on demand differs from the full pass", signed, n) + } + lowest = min(lowest, lowestTrunOffset(full)) + } + if want := map[bool]int64{false: 0, true: -80}[signed]; lowest != want { + t.Errorf("signed=%v: lowest composition offset %d, want %d", signed, lowest, want) + } + } +} diff --git a/scripts/apple-check.sh b/scripts/apple-check.sh index a6156489..00c2c896 100644 --- a/scripts/apple-check.sh +++ b/scripts/apple-check.sh @@ -6,6 +6,7 @@ # late the parameter sets declare the reordering, the opening frames show none: a positive shift, taken back # by the init's edit list; # undeclared the header declares no reordering and the stream reorders after its first GOP: negative offsets. +# Both are read again under --signed-offsets: no shift, no edit list, negative offsets from the first B-frame on. # The same source remuxed by ffmpeg to a plain MP4 is read the same way and printed for reference. # # Usage: sh scripts/apple-check.sh (ffmpeg, ffprobe, go, swiftc and python3 on PATH) @@ -91,19 +92,20 @@ read_back() { # read_back -> prints the stored } failed=0 -check() { # check - name=$1; want=$2 +check() { # check [mkvgo to-hls flags...] + name=$1; want=$2; shift 2 ffprobe -v error -select_streams v:0 -show_entries packet=pts_time -of csv=p=0 "$TMP/$name.mkv" | tr -d ',\r' | sort -n > "$TMP/$name.want" cp "$TMP/$name.want" "$TMP/$name-reference.want" if [ "$(sort -u "$TMP/$name.want" | wc -l)" -ne "$(wc -l < "$TMP/$name.want")" ] || [ "$(wc -l < "$TMP/$name.want")" -ne 144 ]; then echo " FAIL $name: the fixture has $(wc -l < "$TMP/$name.want") frames and $(sort -u "$TMP/$name.want" | wc -l) distinct presentation times, 144 of each expected"; failed=1; return fi - "$TMP/mkvgo" to-hls "$TMP/$name.mkv" -o "$TMP/$name.hls" -segment 2 >/dev/null 2>"$TMP/$name.log" || { cat "$TMP/$name.log" >&2; exit 1; } + rm -rf "$TMP/$name.hls" + "$TMP/mkvgo" to-hls "$TMP/$name.mkv" -o "$TMP/$name.hls" -segment 2 "$@" >/dev/null 2>"$TMP/$name.log" || { cat "$TMP/$name.log" >&2; exit 1; } cat "$TMP/$name.hls/init.mp4" "$TMP/$name.hls"/seg*.m4s > "$TMP/$name.mp4" ffmpeg -nostdin -v error -y -i "$TMP/$name.mkv" -c copy "$TMP/$name-reference.mp4" echo " $name, the reference muxer's plain MP4:" read_back "$name-reference" "$TMP/$name-reference.mp4" - - echo " $name, mkvgo's HLS:" + echo " $name, mkvgo's HLS $*:" read_back "$name" "$TMP/$name.mp4" "$TMP/$name.mp4" lowest=$(python3 "$TMP/compare.py" "$TMP/$name.mp4" "$TMP/$name.want" "$TMP/$name.want" | sed 's/.*lowest composition offset \(-*[0-9]*\).*/\1/') if [ "$want" = negative ] && [ "$lowest" -ge 0 ]; then echo " FAIL $name: no negative composition offset, the fixture does not test what it names"; failed=1; fi @@ -114,5 +116,7 @@ check() { # check echo "== AVFoundation against the source" check late positive check undeclared negative +check late negative --signed-offsets +check undeclared negative --signed-offsets [ "$failed" = 0 ] || { echo "apple-check: FAILED" >&2; exit 1; } echo "apple-check: ALL PASS" From c61dedd4b743d2ae43bd81f56fbdb2b0238e899e Mon Sep 17 00:00:00 2001 From: gravity-zero Date: Sat, 21 Nov 2026 19:38:06 +0100 Subject: [PATCH 2/2] feat(cli): --signed-offsets on serve and serve-growing --- CHANGELOG.md | 4 ++-- cmd/mkvgo/commands/helpers.go | 4 ++-- cmd/mkvgo/commands/sec08_serve_test.go | 6 ++++++ cmd/mkvgo/commands/servegrowing.go | 4 +++- docs/cli.md | 6 +++--- 5 files changed, 16 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 832e4e7c..8ad04db9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,8 +11,8 @@ its series' file in [changelog/](changelog/) when a newer one ships. ### Added -- `Options.SignedCompositionOffsets` (`--signed-offsets` on `to-hls` and - `hls-segment`): a reordered video's composition offsets are written signed, +- `Options.SignedCompositionOffsets` (`--signed-offsets` on `to-hls`, + `hls-segment`, `serve` and `serve-growing`): a reordered video's composition offsets are written signed, with no composition shift and no video edit list. A player that ignores the edit list showed the picture late by the reordering depth (84 ms on a two-frame pyramid); it now shows it on time. Off by default. diff --git a/cmd/mkvgo/commands/helpers.go b/cmd/mkvgo/commands/helpers.go index 90a5cd56..43cee7f9 100644 --- a/cmd/mkvgo/commands/helpers.go +++ b/cmd/mkvgo/commands/helpers.go @@ -141,8 +141,8 @@ var CmdUsage = map[string]string{ "track-ends": "mkvgo track-ends [-json] (where each track's content really ends: statistics tags when they describe the file, else a bounded header-only tail walk; picture end and audio shortfall)", "cue-health": "mkvgo cue-health [-json] [-probe] (head-only seek-index triage: which tracks the cues reference; -probe looks inside each hole; exit 1 when unhealthy)", "diagnose": "mkvgo diagnose [--deep-verify] [-json] (one-call triage with a remedy per finding; MKV: index health + audio delay + size coherence; MP4: box layout + edit-list delays; exit 1 on findings)", - "serve": "mkvgo serve [-addr 127.0.0.1:8478] [--strict] [--direct | --auto [-target mse-generic]] [--window-cache |off] [--window-bytes |off] [--max-walks N] [--max-in-flight N] [--max-waiting N] [--memory-limit ] [--buffered] [--cors] [--source-access auto|local|network] (serve one file's on-demand HLS plan over HTTP, or the raw file for a direct-play client)", - "serve-growing": "mkvgo serve-growing [-addr 127.0.0.1:8478] [-segment 6] [--cors] [--max-in-flight 64] [--max-waiting 1024] [--memory-limit ] (play while downloading: serve a still-growing file as HLS, EVENT playlist until it finishes)", + "serve": "mkvgo serve [-addr 127.0.0.1:8478] [--strict] [--direct | --auto [-target mse-generic]] [--window-cache |off] [--window-bytes |off] [--max-walks N] [--max-in-flight N] [--max-waiting N] [--memory-limit ] [--buffered] [--cors] [--signed-offsets] [--source-access auto|local|network] (serve one file's on-demand HLS plan over HTTP, or the raw file for a direct-play client)", + "serve-growing": "mkvgo serve-growing [-addr 127.0.0.1:8478] [-segment 6] [--cors] [--signed-offsets] [--max-in-flight 64] [--max-waiting 1024] [--memory-limit ] (play while downloading: serve a still-growing file as HLS, EVENT playlist until it finishes)", "to-mp4": "mkvgo to-mp4 [--faststart] [--skip-unsupported] [--strict] [--flatten-subs] [--webvtt-native] [--mp3-container-delay] [--hash] (an MP4/MOV input is rewritten fast start, sample for sample)", "from-mp4": "mkvgo from-mp4 [--skip-unsupported] [--strict] [--mp3-container-delay] ", "to-webm": "mkvgo to-webm ", diff --git a/cmd/mkvgo/commands/sec08_serve_test.go b/cmd/mkvgo/commands/sec08_serve_test.go index d6af70b1..6d086a33 100644 --- a/cmd/mkvgo/commands/sec08_serve_test.go +++ b/cmd/mkvgo/commands/sec08_serve_test.go @@ -35,6 +35,12 @@ func TestSEC08_ServeGrowingCORSOptIn(t *testing.T) { if parseServeGrowingFlags([]string{"in.mkv"}).cors { t.Error("serve-growing: CORS on by default") } + if !parseServeGrowingFlags([]string{"in.mkv", "--signed-offsets"}).signed { + t.Error("serve-growing: --signed-offsets must set the option") + } + if !parseHLSFlags(parseServeFlags([]string{"in.mkv", "--signed-offsets"}).rest).options("in.mkv").SignedCompositionOffsets { + t.Error("serve: --signed-offsets must reach the plan's options") + } if !parseServeGrowingFlags([]string{"in.mkv", "--cors"}).cors { t.Error("serve-growing: --cors ignored") } diff --git a/cmd/mkvgo/commands/servegrowing.go b/cmd/mkvgo/commands/servegrowing.go index e25f4975..92908ad9 100644 --- a/cmd/mkvgo/commands/servegrowing.go +++ b/cmd/mkvgo/commands/servegrowing.go @@ -39,7 +39,7 @@ func CmdServeGrowing(args []string) { ctx, cancel := context.WithCancel(cliCtx) defer cancel() - plan, err := mp4.PlanGrowingHLS(ctx, src, mp4.Options{SegmentMs: segMs}) + plan, err := mp4.PlanGrowingHLS(ctx, src, mp4.Options{SegmentMs: segMs, SignedCompositionOffsets: cfg.signed}) if err != nil { FatalErr(err) } @@ -99,6 +99,7 @@ type serveGrowingFlags struct { addr string segMs int64 cors bool + signed bool // --signed-offsets: mp4.Options.SignedCompositionOffsets maxInFlight int // segments served at once (0 = no cap) maxWaiting int // requests queued behind them before a 503 memoryLimit int64 // the Go runtime's soft memory limit in bytes (0 = left as GOMEMLIMIT sets it) @@ -111,6 +112,7 @@ func parseServeGrowingFlags(args []string) serveGrowingFlags { fl := newFlags("serve-growing") fl.String(&cfg.addr, "-addr", "--addr") fl.Bool(&cfg.cors, "-cors", "--cors") + fl.Bool(&cfg.signed, "--signed-offsets") fl.Func(func(v string) { cfg.maxInFlight = countFlag(v, "--max-in-flight") }, "-max-in-flight", "--max-in-flight") fl.Func(func(v string) { cfg.maxWaiting = countFlag(v, "--max-waiting") }, "-max-waiting", "--max-waiting") fl.Func(func(v string) { cfg.memoryLimit = memoryLimitFlag(v) }, "-memory-limit", "--memory-limit") diff --git a/docs/cli.md b/docs/cli.md index 3ec1d623..79bdbc16 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1162,7 +1162,7 @@ Every track the presentation leaves out - a secondary video track (one video ren | `--audio-shift` | Re-base an audio track in presentation (`track=ms`, repeatable; positive = the track's content starts late and is presented earlier - feed it `diagnose`'s per-track delay). The samples are copied verbatim and the media segments are byte-identical with or without the shift: only the init segment's edit list moves, so a constant A/V desync is cancelled in the served stream without touching the source. Over-shifts clamp to the presentation start. The persistent repair remains `mkvgo retime` | | `--chapter-markers` | Opt-in: expose the source's chapters as `EXT-X-DATERANGE` lines in the video media playlist and a chapter `EventStream` in `manifest.mpd` - chapter navigation and ad-insertion cue points, no re-segmentation. See [streaming.md](streaming.md#chapter-markers-and-ad-insertion-points) | | `--no-iframes` | Drop the trick-play I-frame stream: no `EXT-X-I-FRAME-STREAM-INF` in the master, no `iframe.m3u8` nor `iframeNNNNN.m4s` written or served (`hls-segment iframe` refuses it). For players that scrub with their own trickplay images. Segments and the other playlists are unchanged. Also on `hls-segment`, `to-abr`, `abr-segment`. See [streaming.md](streaming.md#trick-play-scrubbing) | -| `--signed-offsets` | Write a reordered video's composition offsets signed, with no composition shift and no video edit list (CMAF `cmf2` form): a player that ignores the edit list presents the picture on time instead of late by the reordering depth. Init and segments both change: use one setting per presentation. Also on `hls-segment` | +| `--signed-offsets` | Write a reordered video's composition offsets signed, with no composition shift and no video edit list (CMAF `cmf2` form): a player that ignores the edit list presents the picture on time instead of late by the reordering depth. Init and segments both change: use one setting per presentation. Also on `hls-segment`, `serve` and `serve-growing` | ```bash mkvgo to-hls video.mkv -o stream/ @@ -1333,7 +1333,7 @@ mkvgo hls-segment https://nas/movie.mkv 3 # remote: reads only segment Serve one file's on-demand HLS presentation over plain HTTP -- `hls-segment` wrapped in a long-running `net/http` server (`mkvhttp.Handler`), so a player can be pointed straight at it: nothing is written to disk, every resource is built the first time it is requested. ``` -mkvgo serve [-addr 127.0.0.1:8478] [-segment 6] [--keep-tracks 1,2 | --keep-lang fre] [--window-cache |off] [--window-bytes |off] [--max-walks N] [--max-in-flight N] [--max-waiting N] [--memory-limit ] [--cors] +mkvgo serve [-addr 127.0.0.1:8478] [-segment 6] [--keep-tracks 1,2 | --keep-lang fre] [--window-cache |off] [--window-bytes |off] [--max-walks N] [--max-in-flight N] [--max-waiting N] [--memory-limit ] [--cors] [--signed-offsets] mkvgo serve [-addr 127.0.0.1:8478] --direct mkvgo serve [-addr 127.0.0.1:8478] --auto [-target mse-generic] ``` @@ -1375,7 +1375,7 @@ See `docs/library.md` (`mkvhttp.Handler`, `mkvhttp.FileHandler`) for the full ca Play while downloading: serve a file that may still be growing (a download landing on disk) as HLS -- `mp4.PlanGrowingHLS` wrapped in the same long-running server `serve` uses. The media playlist is `EVENT`-typed and lengthens as new whole clusters land; once the source finishes (a Cues index appears, or the file simply stops growing and `Complete()` is signalled), it switches to `VOD` + `ENDLIST`. ``` -mkvgo serve-growing [-addr 127.0.0.1:8478] [-segment 6] [--max-in-flight N] [--max-waiting N] [--memory-limit ] [--cors] +mkvgo serve-growing [-addr 127.0.0.1:8478] [-segment 6] [--max-in-flight N] [--max-waiting N] [--memory-limit ] [--cors] [--signed-offsets] ``` - `-addr` sets the listen address (default `127.0.0.1:8478`, this machine only, as for `serve`); `-segment` sets the target segment duration in seconds (default 6), like `serve`/`to-hls`.