diff --git a/.github/workflows/apple.yml b/.github/workflows/apple.yml new file mode 100644 index 00000000..d3b40fff --- /dev/null +++ b/.github/workflows/apple.yml @@ -0,0 +1,32 @@ +name: Apple timestamps + +# What Apple's media stack reads in mkvgo's HLS output: no Linux tool answers for it, so a macOS runner does. +on: + push: + paths: + - 'mp4/**' + - 'scripts/apple-*' + - '.github/workflows/apple.yml' + +permissions: + contents: read + +jobs: + avfoundation: + runs-on: macos-latest + env: + GOTOOLCHAIN: local + HOMEBREW_NO_AUTO_UPDATE: 1 + HOMEBREW_NO_INSTALL_CLEANUP: 1 + steps: + - uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + - uses: actions/setup-go@924ae3a1cded613372ab5595356fb5720e22ba16 # v6.5.0 + with: + go-version: stable + cache: false + + - name: Install ffmpeg + run: brew install ffmpeg + + - name: AVFoundation reads mkvgo's HLS output + run: sh scripts/apple-check.sh diff --git a/CHANGELOG.md b/CHANGELOG.md index 25b1d67c..5cb8ef28 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,40 @@ its series' file in [changelog/](changelog/) when a newer one ships. ## [Unreleased] +### Changed + +- The HLS/DASH init segment no longer carries the cover art (`RemuxToHLS`, + `PlanHLS`, `PlanGrowingHLS`, `to-hls`, `serve`, `hls-segment`): a player + downloads the init before its first frame, and a large cover made it several + megabytes. Title and tags stay; `RemuxToMP4` still carries the cover. + +### Fixed + +- HLS/DASH from an H.264 or HEVC video whose opening frames are in + presentation order and which reorders frames only later: up to a quarter of + the frames shared a presentation time with a neighbour, and players dropped + them. The composition shift now covers the reordering depth the parameter + sets declare (`max_num_reorder_frames`, `sps_max_num_reorder_pics`), and + is measured past a first GOP of a frame or two, which showed none. + **Integration note**: for such a source, and for one that declares a deeper + reordering than its opening frames show, the init segment's edit list and + the segments' composition offsets change together - drop cached inits and + segments of the same source at once. +- A video that reorders deeper than its opening frames and its parameter sets + announce (parameter sets that change mid-file, or state no depth) keeps + every frame's presentation time in HLS/DASH: the composition offset of such + a frame is written negative (`trun` version 1) where it was clamped to zero + and the frame took its neighbour's time. A reader that pulls its decode + clock back for a negative offset presents that video later by the deepest + one (two frames on the files measured). A frame that presents before + more than 16 frames decoded ahead of it carries a broken timestamp, not a + reordered one: it presents at its decode time and moves no other frame's. +- HLS/DASH from a video where a frame shares the timestamp of the keyframe + after it: the segment opened on that frame instead of its keyframe, and + served on demand it lost the frames stored between the two. Such a frame + now stays in the segment it decodes in, full pass and on demand, and the + segment's last decode times end before the next segment's first. + ## [0.71.2] - 2026-11-20 ### Fixed diff --git a/docs/library.md b/docs/library.md index bb602303..35f1653c 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, tags, cover art - rides on the video init). 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). 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/cenc_slice.go b/mp4/cenc_slice.go index e63fe081..808455ef 100644 --- a/mp4/cenc_slice.go +++ b/mp4/cenc_slice.go @@ -642,6 +642,7 @@ type hevcSPS struct { ltUsed []bool // used_by_curr_pic_lt_sps_flag temporalMVP bool sao bool + numReorderPics int // sps_max_num_reorder_pics of the highest sub-layer } type hevcPPS struct { @@ -696,7 +697,9 @@ func parseHEVCSPS(r *nalReader) (uint32, *hevcSPS, bool) { } for i := first; i <= maxSubLayersMinus1; i++ { r.ue() - r.ue() + if n := r.ue(); n <= maxReorderDepth { // sps_max_num_reorder_pics: the highest sub-layer's is the stream's + sps.numReorderPics = int(n) + } r.ue() } log2MinCb := r.ue() + 3 diff --git a/mp4/composition_shift_unit_test.go b/mp4/composition_shift_unit_test.go index 1ac64944..0da348f6 100644 --- a/mp4/composition_shift_unit_test.go +++ b/mp4/composition_shift_unit_test.go @@ -1,9 +1,14 @@ package mp4 // The branches the end-to-end tests never reach: the prefix rule's edges, and the -// clamp that catches a stream reordering deeper than its opening GOP announced. +// stream reordering deeper than its opening GOP announced. -import "testing" +import ( + "encoding/hex" + "testing" + + "github.com/gravity-zero/mkvgo/mkv" +) func TestCompositionPrefixLen(t *testing.T) { cases := []struct { @@ -23,41 +28,91 @@ func TestCompositionPrefixLen(t *testing.T) { } } +// ordered is n frames in presentation order, step apart. +func ordered(step int64, n int) []int64 { + out := make([]int64, n) + for i := range out { + out[i] = int64(i) * step + } + return out +} + +// loneKeyThenReorder is a keyframe alone, a second keyframe, then groups decoded P B B (one frame of reordering). +func loneKeyThenReorder(step int64, n int) []int64 { + out := []int64{0, step} + for k := int64(2); len(out) < n; k += 3 { + out = append(out, (k+2)*step, k*step, (k+1)*step) + } + return out[:n] +} + +func loneKeySync(n int) []bool { + s := make([]bool, n) + s[0], s[1] = true, true + return s +} + +// pyramid is a keyframe then groups of four decoded P B b b, a B-pyramid two frames deep. +func pyramid(step int64, n int) []int64 { + out := []int64{0} + for k := int64(1); len(out) < n; k += 4 { + out = append(out, (k+3)*step, (k+1)*step, k*step, (k+2)*step) + } + return out[:n] +} + func TestCompositionShiftTS(t *testing.T) { cases := []struct { - name string - pts []int64 - sync []bool - want int64 + name string + pts []int64 + sync []bool + reorder int + want int64 }{ // Decode order I P B B: the B at 42ms decodes third, after the P that // presents at 126 - so it decodes at 84 and would present 42ms EARLIER // than it decodes. One frame of hold-back, which is exactly what a real // 1-level encoder measures (42ms at 23.976fps). - {"one reorder level", []int64{0, 126, 42, 84}, []bool{true, false, false, false}, 42}, - {"no reordering", []int64{0, 42, 84, 126}, []bool{true, false, false, false}, 0}, - {"a single sample cannot reorder", []int64{0}, []bool{true}, 0}, - {"nothing at all", nil, nil, 0}, + {"one reorder level", []int64{0, 126, 42, 84}, []bool{true, false, false, false}, 0, 42}, + {"no reordering", []int64{0, 42, 84, 126}, []bool{true, false, false, false}, 0, 0}, + {"a single sample cannot reorder", []int64{0}, []bool{true}, 0, 0}, + {"nothing at all", nil, nil, 0, 0}, + // The opening frames are in presentation order but the parameter sets declare two frames of reordering: + // the shift is two of the longest frame steps (41 and 42 ms at 23.976 fps on a millisecond clock). + {"declared depth, ordered prefix", []int64{0, 42, 83, 125}, []bool{true, false, false, false}, 2, 84}, + {"declared depth below the measure", []int64{0, 126, 42, 84}, []bool{true, false, false, false}, 1, 42}, + // The frame at 84 decodes later: its hole is not a frame duration. + {"declared depth, a hole in the prefix", []int64{0, 126, 42}, []bool{true, false, false}, 2, 84}, + {"declared depth, native ticks", []int64{0, 3754, 7508, 11261}, []bool{true, false, false, false}, 2, 7508}, + // A first GOP of one frame shows nothing: the frames after it are measured (two keyframes, then I P B B). + {"one-frame first GOP", loneKeyThenReorder(42, 30), loneKeySync(30), 0, 42}, + // Past compositionPrefix nothing is read: a reordering that starts there is not measured. + {"reordering past the prefix", append(ordered(42, 26), 1176, 1092, 1134), make([]bool, 29), 0, 0}, + // A first GOP longer than the prefix keeps what its 24 frames measured, as before (one frame over the two + // the pyramid needs: the prefix ends mid-group). + {"long first GOP keeps the prefix measure", pyramid(42, 28), append([]bool{true}, make([]bool, 27)...), 0, 126}, + // The same frames behind a one-frame first GOP are measured over their complete part: exactly two frames. + {"complete part is not inflated", append([]int64{-42}, pyramid(42, 28)...), append([]bool{true, true}, make([]bool, 27)...), 0, 84}, } for _, tc := range cases { - if got := compositionShiftTS(tc.pts, tc.sync); got != tc.want { + if got := compositionShiftTS(tc.pts, tc.sync, tc.reorder); got != tc.want { t.Errorf("%s: compositionShiftTS = %d, want %d", tc.name, got, tc.want) } } } -// TestFillFragTimingClampsDeeperReorder covers the safety branch: a stream whose -// first GOP shows one level of reordering but which later reorders deeper than the -// shift measured from it. The offsets must STILL come out non-negative - a single -// sample presenting at its decode time is a sub-frame error, whereas one negative -// offset would have a reader re-time the entire presentation. -func TestFillFragTimingClampsDeeperReorder(t *testing.T) { - // First GOP: I P B B (shift = 42, one frame). Then a frame thrown far further - // ahead in decode order than anything that first GOP justified. - samples := []fragSample{ - {ptsMs: 0, sync: true}, {ptsMs: 126}, {ptsMs: 42}, {ptsMs: 84}, - {ptsMs: 168, sync: true}, {ptsMs: 500}, {ptsMs: 210}, {ptsMs: 252}, - {ptsMs: 294}, {ptsMs: 336}, {ptsMs: 378}, {ptsMs: 420}, +// A stream whose opening frames show one level of reordering but which later reorders deeper, with no parameter set +// to announce it: the late frame's offset goes negative (trun version 1 is signed) and every frame keeps the +// presentation time the source gives it. Clamped to zero, it took its neighbour's and a player dropped it. +func TestFillFragTimingDeeperReorderKeepsPTS(t *testing.T) { + // First GOP: I P B B (shift = 42, one frame), then frames in order past the measured prefix, then a group + // reordered two frames deep. + samples := []fragSample{{ptsMs: 0, sync: true}, {ptsMs: 126}, {ptsMs: 42}, {ptsMs: 84}} + for i := 4; i < 30; i++ { + samples = append(samples, fragSample{ptsMs: int64(i) * 42, sync: i == 4}) + } + for _, k := range []int64{33, 31, 30, 32, 34, 35} { + samples = append(samples, fragSample{ptsMs: k * 42}) } _, hasCTS, _, shift := fillFragTiming(samples, 42, movieTimescale, 0) if shift != 42 { @@ -66,9 +121,154 @@ func TestFillFragTimingClampsDeeperReorder(t *testing.T) { if !hasCTS { t.Fatal("hasCTS = false on a reordered track") } + negative := 0 for i, s := range samples { if s.ctsTS < 0 { - t.Errorf("sample %d kept a negative composition offset (%d): the clamp did not hold", i, s.ctsTS) + negative++ + } + if pts := s.dtsTS + int64(s.ctsTS) - shift; pts != s.ptsMs { + t.Errorf("sample %d presents at %d, want %d", i, pts, s.ptsMs) + } + } + if negative == 0 { + t.Error("no offset went negative: the fixture does not reorder deeper than its first GOP") + } +} + +// The records are the ones libx264 and libx265 wrote for 320x180 encodes; the expected depths are the has_b_frames +// an independent parser reports for the same files. +func TestDeclaredReorderDepth(t *testing.T) { + unhex := func(s string) []byte { + b, err := hex.DecodeString(s) + if err != nil { + t.Fatal(err) + } + return b + } + x264Pyramid := unhex("0164000cffe100186764000cacd941419f9f011000003e90000bb800f142996001000668ebe3cb22c0fdf8f800") + x264NoB := unhex("0164000cffe100176764000cacb60a0cfcf808800001f480005dc0078a157001000668eac3cb22c0fdf8f800") + x265 := unhex("0101600000009000000000003cf000fcfdf8f800000f03200001001840010c01ffff01600000030090000003000003003c959809" + + "210001002942010101600000030090000003000003003ca00a080b9f796566924caf01680800001f480002ee0040" + + "22000100074401c172b46240") + cases := []struct { + name string + track mkv.Track + want int + }{ + {"x264 B-pyramid", mkv.Track{Codec: "h264", CodecPrivate: x264Pyramid}, 2}, + {"x264 without B-frames", mkv.Track{Codec: "h264", CodecPrivate: x264NoB}, 0}, + {"x265 B-pyramid", mkv.Track{Codec: "hevc", CodecPrivate: x265}, 2}, + {"no record", mkv.Track{Codec: "h264"}, 0}, + {"a truncated record", mkv.Track{Codec: "h264", CodecPrivate: x264Pyramid[:20]}, 0}, + {"another codec", mkv.Track{Codec: "vp9", CodecPrivate: x264Pyramid}, 0}, + } + for _, tc := range cases { + if got := declaredReorderDepth(&tc.track); got != tc.want { + t.Errorf("%s: declaredReorderDepth = %d, want %d", tc.name, got, tc.want) + } + } +} + +// A stream whose opening frames are in presentation order and which reorders two frames deep later, as its parameter +// sets declare: every frame keeps its own presentation time, none is clamped onto its decode time. +func TestFillFragTimingLateReorderKeepsEveryPTS(t *testing.T) { + var samples []fragSample + for i := 0; i < 30; i++ { + samples = append(samples, fragSample{ptsMs: int64(i) * 1001 / 24, sync: i == 0}) + } + for g := 0; g < 5; g++ { // decode order P B b b, a pyramid + for _, k := range []int{3, 1, 0, 2} { + samples = append(samples, fragSample{ptsMs: int64(30+4*g+k) * 1001 / 24}) + } + } + _, _, _, shift := fillFragTimingTS(samples, nil, 42, movieTimescale, 0, nil, 2, false) + if shift != 84 { + t.Fatalf("shift = %d, want 84 (two frames)", shift) + } + seen := map[int64]int{} + for i, s := range samples { + pts := s.dtsTS + int64(s.ctsTS) - shift + if pts != s.ptsMs { + t.Errorf("sample %d presents at %d, want %d", i, pts, s.ptsMs) + } + if j, dup := seen[pts]; dup { + t.Errorf("samples %d and %d share the presentation time %d", j, i, pts) + } + seen[pts] = i + } +} + +// FuzzDeclaredReorderDepth: a parameter set record of any bytes gives a depth within the codecs' bound, never a panic. +func FuzzDeclaredReorderDepth(f *testing.F) { + seed, _ := hex.DecodeString("0164000cffe100186764000cacd941419f9f011000003e90000bb800f142996001000668ebe3cb22c0fdf8f800") + f.Add(seed, false) + f.Add(seed, true) + f.Fuzz(func(t *testing.T, private []byte, hevc bool) { + tr := mkv.Track{Codec: "h264", CodecPrivate: private} + if hevc { + tr.Codec = "hevc" + } + if d := declaredReorderDepth(&tr); d < 0 || d > maxReorderDepth { + t.Fatalf("declaredReorderDepth = %d", d) + } + }) +} + +// A sample that presents before more than maxReorderDepth samples decoded ahead of it carries a broken timestamp: it is +// flagged and takes the latest time seen. A frame reordered across a long frame duration is not one - what counts is +// how many frames it is reordered across, not how long they last. +func TestStrayTimestamps(t *testing.T) { + ordered := func(n int) []int64 { + out := make([]int64, n) + for i := range out { + out[i] = int64(i) * 40 + } + return out + } + if got := strayTimestamps(ordered(100)); got != nil { + t.Errorf("frames in order: flagged %v", got) + } + + late := append(ordered(60), 100) // decoded last, stamped 2.3 s back: 57 frames decoded ahead of it present later + stray := strayTimestamps(late) + if stray == nil || !stray[60] || late[60] != 59*40 { + t.Errorf("stray stamp: flagged=%v, rewritten to %d, want flagged and %d", stray != nil && stray[60], late[60], 59*40) + } + for i := 0; i < 60; i++ { + if stray[i] || late[i] != int64(i)*40 { + t.Fatalf("sample %d was touched: flagged=%v time=%d", i, stray[i], late[i]) + } + } + + deep := ordered(40) // the deepest reordering there is: one frame presenting before the 16 decoded ahead of it + deep = append(deep, 2000, 2040, 2080, 2120, 2160, 2200, 2240, 2280, 2320, 2360, 2400, 2440, 2480, 2520, 2560, 2600, 1960) + if got := strayTimestamps(deep); got != nil { + t.Errorf("16 frames of reordering: flagged %v", got) + } + + gap := append(ordered(30), 5000, 3000) // an anchor after a long frame, then the B-frame two seconds before it + if got := strayTimestamps(gap); got != nil { + t.Errorf("one frame of reordering across a long frame duration: flagged %v", got) + } +} + +// A B-frame across a long frame duration keeps its presentation time, however far before its anchor it presents. +func TestFillFragTimingLongFrameReorderKeepsPTS(t *testing.T) { + var samples []fragSample + for i := 0; i < 30; i++ { + samples = append(samples, fragSample{ptsMs: int64(i) * 40, sync: i == 0}) + } + samples = append(samples, fragSample{ptsMs: 5000}, fragSample{ptsMs: 3000}, fragSample{ptsMs: 5040}) + _, _, _, shift := fillFragTiming(samples, 40, movieTimescale, 0) + seen := map[int64]bool{} + for i, s := range samples { + pts := s.dtsTS + int64(s.ctsTS) - shift + if pts != s.ptsMs { + t.Errorf("sample %d presents at %d, want %d", i, pts, s.ptsMs) + } + if seen[pts] { + t.Errorf("sample %d shares the presentation time %d", i, pts) } + seen[pts] = true } } diff --git a/mp4/coverart_lazy_test.go b/mp4/coverart_lazy_test.go index 84d631f6..7c863902 100644 --- a/mp4/coverart_lazy_test.go +++ b/mp4/coverart_lazy_test.go @@ -10,9 +10,10 @@ import ( "github.com/gravity-zero/mkvgo/mkv" ) -// The remux and the packagers carry only the cover art out of a source's -// attachments: a font set stays on disk, never read. Measured through a -// counting FS on a source whose font dwarfs its media. +// The remux carries only the cover art out of a source's attachments, and the +// packagers none of them (a player fetches the init before its first frame): a +// font set stays on disk, never read. Measured through a counting FS on a +// source whose font dwarfs its media. func TestRemuxAndPackagingSkipFontPayloads(t *testing.T) { ctx := context.Background() font := make([]byte, 4<<20) @@ -54,8 +55,8 @@ func TestRemuxAndPackagingSkipFontPayloads(t *testing.T) { if err != nil { t.Fatal(err) } - if !bytes.Contains(plan.InitSegment(), cover) { - t.Error("the cover art must ride on the plan's init segment") + if bytes.Contains(plan.InitSegment(), cover) { + t.Error("the cover art must stay out of the plan's init segment") } if tally.bytes > budget { t.Errorf("PlanHLS read %d KB, the font (%d KB) was loaded", tally.bytes>>10, len(font)>>10) @@ -70,8 +71,8 @@ func TestRemuxAndPackagingSkipFontPayloads(t *testing.T) { if err != nil { t.Fatal(err) } - if !bytes.Contains(init, cover) { - t.Error("the cover art must ride on the packaged init segment") + if bytes.Contains(init, cover) { + t.Error("the cover art must stay out of the packaged init segment") } if tally.bytes > budget { t.Errorf("RemuxToHLS read %d KB, the font (%d KB) was loaded", tally.bytes>>10, len(font)>>10) diff --git a/mp4/fragment.go b/mp4/fragment.go index bb551fd7..1c8a853b 100644 --- a/mp4/fragment.go +++ b/mp4/fragment.go @@ -315,14 +315,92 @@ func compositionPrefixLen(sync []bool) int { // arriving one to two frames late. So the offsets must be non-negative before // they are written, and an edit list must then take back the shift that made them // so (buildEdts). -func compositionShiftTS(ptsTS []int64, sync []bool) int64 { - n := compositionPrefixLen(sync) - if n > len(ptsTS) { - n = len(ptsTS) +// +// reorder is the depth the track's parameter sets declare (declaredReorderDepth): +// a stream may open on frames in presentation order and reorder only later, so +// the shift is never less than that many frames of the prefix's frame duration. +// +// The first GOP may be a frame or two long and show nothing: the frames past it, +// up to compositionPrefix, are measured too, over the part of them that is +// complete (completePrefixLen), so a short first GOP hides no reordering. +func compositionShiftTS(ptsTS []int64, sync []bool, reorder int) int64 { + if len(ptsTS) > compositionPrefix { + ptsTS = ptsTS[:compositionPrefix] + } + n := min(compositionPrefixLen(sync), len(ptsTS)) + shift := measuredShiftTS(ptsTS[:n]) + shift = max(shift, measuredShiftTS(ptsTS[:completePrefixLen(ptsTS)])) + return max(shift, int64(reorder)*prefixFrameTS(ptsTS)) +} + +// strayTimestamps rewrites, in decode order, the presentation times decode times are derived from, and reports the +// samples it rewrote; nil when it rewrote none. A sample that presents before more than maxReorderDepth samples +// decoded ahead of it is not reordered - no codec reorders that deep - its timestamp is broken (a muxer's stray +// stamp, seconds back at the end of a GOP). It takes the latest time seen so far, so it keeps its place in decode +// order and moves no other sample's decode time; it then presents at its decode time (compositionOffsetTS). +func strayTimestamps(pts []int64) []bool { + var ( + top [maxReorderDepth + 1]int64 // the latest presentation times seen, ascending + n int + stray []bool + ) + for i, p := range pts { + if n == len(top) && p < top[0] { + if stray == nil { + stray = make([]bool, len(pts)) + } + stray[i] = true + pts[i] = top[n-1] + continue + } + if n < len(top) { + top[n] = p + n++ + } else if p > top[0] { + top[0] = p + } else { + continue + } + for k := n - 1; k > 0 && top[k] < top[k-1]; k-- { // one insertion step keeps top sorted + top[k], top[k-1] = top[k-1], top[k] + } + for k := 0; k < n-1 && top[k] > top[k+1]; k++ { + top[k], top[k+1] = top[k+1], top[k] + } } - if n < 2 { + return stray +} + +// compositionOffsetTS is a sample's composition offset: negative when the stream reorders deeper than the shift +// covers, so the frame keeps its own presentation time; 0 for a stray timestamp (strayTimestamps), which a reader +// that pulls its decode clock back by the deepest negative offset would otherwise follow by seconds. +func compositionOffsetTS(pts, dts, shift int64, stray bool) int64 { + if stray { return 0 } + return pts - dts + shift +} + +// completePrefixLen is how many leading samples (decode order) are sure to hold every frame presented before their +// last: the samples before the last one that presents later than all before it. The frames decoded after such a +// sample present after the ones before it, so nothing is missing from that part and its measure is exact; past it, a +// frame not read yet would be counted as a reordering. A slice shorter than compositionPrefix is the whole track. +func completePrefixLen(ptsTS []int64) int { + if len(ptsTS) < compositionPrefix { + return len(ptsTS) + } + last, top := 0, int64(0) + for i, pts := range ptsTS { + if i == 0 || pts > top { + last, top = i, pts + } + } + return last +} + +// measuredShiftTS is max(DTS - PTS) over the samples given, DTS being their sorted PTS. +func measuredShiftTS(ptsTS []int64) int64 { + n := len(ptsTS) dts := make([]int64, n) copy(dts, ptsTS[:n]) sort.Slice(dts, func(i, j int) bool { return dts[i] < dts[j] }) @@ -340,13 +418,13 @@ func compositionShiftTS(ptsTS []int64, sync []bool) int64 { // offset (in the track's media timescale), from the presentation timestamps - // the same reconstruction the progressive path uses (sample.go reconstructTiming): // DTS is the sorted PTS in decode order, durations are the diffs, ctts = PTS - DTS -// plus the track's composition shift, which keeps every offset non-negative (see +// plus the track's composition shift, which keeps the offsets non-negative for the reordering the stream announces (see // compositionShiftTS; the init's edit list takes the shift back out, so the // presentation still starts where the source does). // 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) + return fillFragTimingTS(samples, nil, lastDurMs, mts, gridTS, nil, 0, false) } // fillFragTimingTS is fillFragTiming with, when ptsTS is not nil, each @@ -358,7 +436,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. -func fillFragTimingTS(samples []fragSample, ptsTS []int64, lastDurMs int64, mts uint32, gridTS int64, bounds []int64) (offsetMs int64, hasCTS bool, totalTS int64, ctsShiftTS int64) { +// 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) { n := len(samples) if n == 0 { return 0, false, 0, 0 @@ -444,13 +524,18 @@ func fillFragTimingTS(samples []fragSample, ptsTS []int64, lastDurMs int64, mts for i := range samples { dts[i] = pts(i) } + stray := windowedStrays(samples, dts, bounds, video) sort.Slice(dts, func(i, j int) bool { return dts[i] < dts[j] }) - strictlyIncreasing(dts) + if bounds == nil { + strictlyIncreasing(dts) + } else { + windowedIncreasing(samples, dts, bounds, video) + } base := dts[0] for i := range samples { samples[i].dtsTS = dts[i] - base } - // The shift that keeps every composition offset non-negative, measured over + // The shift that keeps the composition offsets non-negative, measured over // the SAME bounded prefix the on-demand plan measures it over, so both derive // the same init. prefix := make([]int64, 0, compositionPrefix) @@ -459,7 +544,7 @@ func fillFragTimingTS(samples []fragSample, ptsTS []int64, lastDurMs int64, mts prefix = append(prefix, pts(i)) syncs = append(syncs, samples[i].sync) } - ctsShiftTS = compositionShiftTS(prefix, syncs) + ctsShiftTS = compositionShiftTS(prefix, syncs, reorder) for i := 0; i < n-1; i++ { samples[i].durTS = dts[i+1] - dts[i] } @@ -476,15 +561,11 @@ func fillFragTimingTS(samples []fragSample, ptsTS []int64, lastDurMs int64, mts if samples[i].ptsMs < offsetMs { offsetMs = samples[i].ptsMs } - off := pts(i) - dts[i] + ctsShiftTS - if off < 0 { - // Only a stream that reorders deeper later than it does in its first - // GOPs can land here. Clamping keeps the offsets non-negative - the - // invariant the whole shift exists to hold - at the price of that one - // sample presenting at its decode time, a sub-frame error, instead of - // letting a reader re-shift the ENTIRE presentation. - off = 0 - } + // A stream that reorders deeper than its opening frames and its parameter + // sets announce (they changed mid-file, or state nothing) lands below + // zero here: the offset stays signed (trun version 1), so the frame keeps + // its own presentation time instead of taking its neighbour's. + off := compositionOffsetTS(pts(i), dts[i], ctsShiftTS, stray != nil && stray[i]) samples[i].ctsTS = int32(off) if off != 0 { hasCTS = true @@ -494,6 +575,57 @@ func fillFragTimingTS(samples []fragSample, ptsTS []int64, lastDurMs int64, mts return offsetMs, hasCTS, totalTS, ctsShiftTS } +// windowedStrays is strayTimestamps window by window, as an on-demand plan sees them (timeSegmentWindow): the whole +// track is one window when bounds is nil. pts is rewritten in place. +func windowedStrays(samples []fragSample, pts []int64, bounds []int64, video bool) []bool { + if bounds == nil { + return strayTimestamps(pts) + } + var stray []bool + start := 0 + for k := 1; k <= len(bounds) && start < len(pts); k++ { + end := len(pts) + if k < len(bounds) { + end = windowEndIndex(samples, start, bounds[k], video) + } + if w := strayTimestamps(pts[start:end]); w != nil { + if stray == nil { + stray = make([]bool, len(pts)) + } + copy(stray[start:end], w) + } + start = end + } + return stray +} + +// windowedIncreasing is strictlyIncreasing window by window, as an on-demand plan times them (timeSegmentWindow): a +// tie inside a window moves the later sample one tick on, and a window whose last times reach the next window's first +// ends before it (endBefore), so no window's times depend on the one before it. +func windowedIncreasing(samples []fragSample, dts []int64, bounds []int64, video bool) { + start := 0 + for k := 1; k <= len(bounds) && start < len(dts); k++ { + end := len(dts) + if k < len(bounds) { + end = windowEndIndex(samples, start, bounds[k], video) + } + strictlyIncreasing(dts[start:end]) + if end < len(dts) { + endBefore(dts[start:end], dts[end]) + } + start = end + } +} + +// endBefore pulls a window's last decode times back until they end before limit, the next window's first: two samples +// share a timestamp across the boundary. +func endBefore(dts []int64, limit int64) { + for x := len(dts) - 1; x >= 0 && dts[x] >= limit; x-- { + limit-- + dts[x] = limit + } +} + // strictlyIncreasing makes sorted decode times strictly increasing: a time equal to the one before - two blocks // stamped alike - moves one tick past it, so no two samples share a decode time, nor a 'cenc' IV. func strictlyIncreasing(dts []int64) { diff --git a/mp4/gridwindow_test.go b/mp4/gridwindow_test.go index 90b26983..5997e538 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) - fillFragTimingTS(whole, nil, 0, 44100, g, nil) + fillFragTimingTS(clean, nil, 0, 44100, g, bounds, 0, false) + fillFragTimingTS(whole, nil, 0, 44100, g, nil, 0, 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) + _, _, total, _ := fillFragTimingTS(s, nil, 0, 44100, g, bounds, 0, 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 78a556f0..e22eb62e 100644 --- a/mp4/growinghls.go +++ b/mp4/growinghls.go @@ -212,10 +212,6 @@ func PlanGrowingHLS(ctx context.Context, srcPath string, opts ...Options) (*Grow if err != nil { return nil, err } - cover, err := loadCoverArt(fs, c.Attachments) - if err != nil { - return nil, err - } if len(c.Tracks) == 0 { return nil, errf("%s: no Tracks element yet (the downloader must write the head before play-while-downloading can start)", shown.Path(srcPath)) } @@ -239,7 +235,7 @@ func PlanGrowingHLS(ctx context.Context, srcPath string, opts ...Options) (*Grow p := &GrowingHLSPlan{ srcPath: srcPath, fs: fs, opts: o, segMs: segMs, segStart: c.SegmentStart, segDeclaredEnd: -1, - meta: movieMeta{title: c.Info.Title, tags: globalTags(c), cover: cover}, + meta: movieMeta{title: c.Info.Title, tags: globalTags(c)}, } p.full = &HLSPlan{srcPath: srcPath, fs: fs, tcScale: c.Info.TimecodeScale, opts: o, trackDurs: reader.TrackDefaultDurations(c.Tracks)} @@ -495,8 +491,8 @@ func (p *GrowingHLSPlan) walkCluster(ctx context.Context, src mkv.ReadSeekCloser } // extendLeadLocked folds one video block into the composition-shift prefix: the -// opening frames, up to the second keyframe (the first GOP shows the whole reorder -// pattern) or compositionPrefix, whichever comes first. The shift is settled before +// opening frames, up to compositionPrefix (a first GOP of a frame or two shows no +// reordering, so the prefix does not stop on it). The shift is settled before // a single output is published, because the edit list it produces lives in the INIT // - a byte a player fetches once and caches, and which therefore may never change // under it mid-session. @@ -504,7 +500,7 @@ func (p *GrowingHLSPlan) extendLeadLocked(b mkv.Block) { if p.leadDone { return } - if (len(p.leadPts) > 0 && b.Keyframe) || len(p.leadPts) >= compositionPrefix { + if len(p.leadPts) >= compositionPrefix { p.settleLeadLocked() return } @@ -530,7 +526,7 @@ func (p *GrowingHLSPlan) settleLeadLocked() { for i, ms := range p.leadPts { ts[i] = scale(ms) } - pt.ft.ctsShiftTS = compositionShiftTS(ts, p.leadSync) + 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 98db696b..bde1ba9d 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) + off, hasCTS, totalTS, ctsShift := fillFragTimingTS(ft.samples, ft.ptsTS, ft.outTrack.frameDurMs, ft.timescale, grid, gridBounds, declaredReorderDepth(&ft.outTrack.mkv), ft.outTrack.spec.video) ft.ptsTS = nil ft.offsetMs, ft.hasCTS, ft.durMediaTS = off, hasCTS, totalTS ft.ctsShiftTS = ctsShift @@ -399,11 +399,8 @@ func remuxToHLSInto(ctx context.Context, srcPath, outputDir string, op *Options) // (every audio sample is a sync point, so the same cut applies). bounds := segmentBoundaries(fts[primaryIndex(fts)].samples, segMs) - cover, err := loadCoverArt(fs, c.Attachments) - if err != nil { - return nil, err - } - meta := movieMeta{title: c.Info.Title, tags: globalTags(c), cover: cover} + // No cover art: a player downloads the init before its first frame and shows none of it. + meta := movieMeta{title: c.Info.Title, tags: globalTags(c)} var segs []segInfo var rends []sfRendition @@ -865,13 +862,10 @@ func audioIndex(fts []*fragTrack, i int) int { } // segmentWindow returns track i's cursor window for boundary k, advancing the -// cursor: the samples from the cursor to the first one at/past segEnd. +// cursor: the samples from the cursor to the first one at/past segEnd (windowEndIndex). func segmentWindow(ft *fragTrack, cursor *int, segStart, segEnd int64) trackSegment { start := *cursor - j := start - for j < len(ft.samples) && ft.samples[j].blockPtsMs < segEnd { - j++ - } + j := windowEndIndex(ft.samples, start, segEnd, ft.outTrack.spec.video) *cursor = j seg := trackSegment{ trackID: ft.outTrack.mp4ID, @@ -1498,3 +1492,13 @@ func refusePackagedSource(outputDir string, sources ...string) error { } return nil } + +// windowEndIndex is where the window opening at start ends: the first sample at or past segEnd, a video frame tied +// with the boundary keyframe excepted (tiedBeforeKey). +func windowEndIndex(samples []fragSample, start int, segEnd int64, video bool) int { + j := start + for j < len(samples) && (samples[j].blockPtsMs < segEnd || tiedBeforeKey(video, samples[j].sync, samples[j].blockPtsMs, segEnd)) { + j++ + } + return j +} diff --git a/mp4/hlspack.go b/mp4/hlspack.go index 2760b82a..59f49e28 100644 --- a/mp4/hlspack.go +++ b/mp4/hlspack.go @@ -50,8 +50,7 @@ func openPackagingSource(ctx context.Context, srcPath string, fs *mkv.FS, moovLi } if head[0] == 0x1A && head[1] == 0x45 && head[2] == 0xDF && head[3] == 0xA3 { f.Close() // Matroska: the existing reader owns its own handle - // Attachment payloads stay on disk: the packager carries only the - // cover art, read on its own by loadCoverArt. + // Attachment payloads stay on disk: the packager carries none of them. c, err := reader.OpenWithFS(ctx, srcPath, fs, reader.WithoutAttachmentData(), reader.WithInBandColourFallback(), reader.WithInBandChannels()) if err != nil { return nil, err @@ -258,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) + off, hasCTS, totalTS, ctsShift := fillFragTimingTS(ft.samples, ptsTS, t.frameDurMs, ft.timescale, grid, nil, declaredReorderDepth(&t.mkv), t.spec.video) if err := ctx.Err(); err != nil { return nil, nil, err } diff --git a/mp4/hlsplan.go b/mp4/hlsplan.go index 283ca641..3e0e2f0d 100644 --- a/mp4/hlsplan.go +++ b/mp4/hlsplan.go @@ -660,14 +660,8 @@ func planHLS(ctx context.Context, srcPath string, opts ...Options) (*HLSPlan, er } p.mpd = buildDASHManifest(&o, fts, p.subs, p.durs, videoBandwidth(segs, fts), chapters, trick) } - if err := ctx.Err(); err != nil { // the cover read does not see ctx - return nil, err - } - cover, err := loadCoverArt(fs, c.Attachments) - if err != nil { - return nil, err - } - meta := movieMeta{title: c.Info.Title, tags: globalTags(c), cover: cover} + // No cover art: a player downloads the init before its first frame and shows none of it. + meta := movieMeta{title: c.Info.Title, tags: globalTags(c)} for i, ft := range fts { m := movieMeta{} if ft.outTrack.spec.video { diff --git a/mp4/hlsplan_ahead.go b/mp4/hlsplan_ahead.go index 048fbf0f..60db92cc 100644 --- a/mp4/hlsplan_ahead.go +++ b/mp4/hlsplan_ahead.go @@ -176,7 +176,10 @@ func (p *HLSPlan) coldAhead(ctx context.Context, src io.ReadSeeker, br *reader.B if !p.tracks[ti].ft.outTrack.spec.video { p.learnAhead(pos, b) } - if b.BlockTimecode >= segStart { + // Once a track's window has opened, every later block of the track is the window's, as in the full pass: a + // reordered frame after it presents before segStart when the opening frame shares the keyframe's timestamp. + tied := n > 0 && tiedBeforeKey(p.tracks[ti].ft.outTrack.spec.video, b.Keyframe, b.BlockTimecode, segStart) + if (b.BlockTimecode >= segStart && !tied) || len(ahead[ti]) > 0 { ahead[ti] = append(ahead[ti], aheadBlock{b: b, pos: pos}) } } diff --git a/mp4/hlsplan_far.go b/mp4/hlsplan_far.go index fcf4f3c0..84327de5 100644 --- a/mp4/hlsplan_far.go +++ b/mp4/hlsplan_far.go @@ -464,10 +464,11 @@ func (p *HLSPlan) farTrackIn(ctx context.Context, src io.ReadSeeker, i int, rg t } continue } - if b.BlockTimecode < segStart || (b.BlockTimecode <= lastMs && b.DataOffset <= lastOff) { + video := pt.ft.outTrack.spec.video + if (len(out) == 0 && (b.BlockTimecode < segStart || (n > 0 && tiedBeforeKey(video, b.Keyframe, b.BlockTimecode, segStart)))) || (b.BlockTimecode <= lastMs && b.DataOffset <= lastOff) { continue // before the window, or a block the walk already holds (a later block may carry an earlier time: reordered video) } - if b.BlockTimecode >= segEnd { + if b.BlockTimecode >= segEnd && !tiedBeforeKey(video, b.Keyframe, b.BlockTimecode, segEnd) { crossed = true peek = startPeek(b.Timecode, pt.ft.outTrack.spec.video) p.learnSegPos(n+1, pos) // the next window opens here at the latest: a linear walk of it must not start past this block diff --git a/mp4/hlsplan_probe.go b/mp4/hlsplan_probe.go index 98a8ec95..90770b0a 100644 --- a/mp4/hlsplan_probe.go +++ b/mp4/hlsplan_probe.go @@ -322,8 +322,8 @@ func (p *HLSPlan) synthesizeVideoCues(ctx context.Context, srcPath string, fs *m // the opening frames alone, HEADER-ONLY: block headers carry the timecodes and the // keyframe flag, and no sample byte is read. The full pass measures the same shift // over the same prefix of the same track (compositionShiftTS), so the two inits -// stay byte-identical while this one costs a handful of headers, not a GOP of -// video. +// stay byte-identical while this one costs compositionPrefix headers, not a GOP +// of video. func (p *HLSPlan) probeCompositionShift(ctx context.Context) error { pt := p.tracks[p.videoIndex()] var ( @@ -331,9 +331,6 @@ func (p *HLSPlan) probeCompositionShift(ctx context.Context) error { sync []bool ) err := p.walkVideoHeadersOnly(ctx, func(b mkv.Block) (bool, error) { - if len(pts) > 0 && b.Keyframe { - return false, nil // the GOP closed: the reorder pattern is fully in hand - } pts = append(pts, b.Timecode) sync = append(sync, b.Keyframe) return len(pts) < compositionPrefix, nil @@ -346,7 +343,7 @@ func (p *HLSPlan) probeCompositionShift(ctx context.Context) error { for i, ms := range pts { ts[i] = scale(ms) } - pt.ft.ctsShiftTS = compositionShiftTS(ts, sync) + pt.ft.ctsShiftTS = compositionShiftTS(ts, sync, declaredReorderDepth(&pt.ft.outTrack.mkv)) p.opensOnKeyframe = len(sync) > 0 && sync[0] return nil } diff --git a/mp4/hlsplan_test.go b/mp4/hlsplan_test.go index a90345e5..3836f9b8 100644 --- a/mp4/hlsplan_test.go +++ b/mp4/hlsplan_test.go @@ -101,9 +101,9 @@ func TestPlanHLSMatchesFullPass(t *testing.T) { t.Errorf("master missing %q:\n%s", want, master) } } - // The init must carry the cover art, like the full pass (byte-checked above). - if !bytes.Contains(plan.InitSegment(), []byte("covr")) { - t.Error("init segment misses the covr cover-art atom") + // The init carries no cover art, like the full pass (byte-checked above). + if bytes.Contains(plan.InitSegment(), []byte("covr")) { + t.Error("init segment carries the covr cover-art atom") } // Resource() is the declarative entry point: every listed name resolves, diff --git a/mp4/hlsplan_timing.go b/mp4/hlsplan_timing.go index 0b26631e..d07387fc 100644 --- a/mp4/hlsplan_timing.go +++ b/mp4/hlsplan_timing.go @@ -168,15 +168,15 @@ func timeSegmentWindow(window []fragSample, pt *planTrack, nextPts int64, span g for x := range window { dts[x] = scale(window[x].ptsMs) } + stray := strayTimestamps(dts) // the full pass's windowedStrays sort.Slice(dts, func(a, b int) bool { return dts[a] < dts[b] }) strictlyIncreasing(dts) + if nextPts >= 0 && !window[len(window)-1].cut { + endBefore(dts, scale(nextPts)) // the full pass's windowedIncreasing + } for x := range window { window[x].dtsTS = dts[x] - base - off := scale(window[x].ptsMs) - dts[x] + pt.ft.ctsShiftTS - if off < 0 { - off = 0 // fillFragTiming's clamp, window-local (same rule, same bytes) - } - window[x].ctsTS = int32(off) + window[x].ctsTS = int32(compositionOffsetTS(scale(window[x].ptsMs), dts[x], pt.ft.ctsShiftTS, stray != nil && stray[x])) // fillFragTiming's rule } for x := 0; x < len(window)-1; x++ { window[x].durTS = dts[x+1] - dts[x] diff --git a/mp4/hlsplan_walk.go b/mp4/hlsplan_walk.go index 0dd3ed76..85a0b33d 100644 --- a/mp4/hlsplan_walk.go +++ b/mp4/hlsplan_walk.go @@ -279,8 +279,9 @@ func (p *HLSPlan) walkWindow(ctx context.Context, n int, segStart, segEnd int64, } continue } + video := p.tracks[ti].ft.outTrack.spec.video if !started[ti] { - if b.BlockTimecode < segStart { + if b.BlockTimecode < segStart || (n > 0 && tiedBeforeKey(video, b.Keyframe, b.BlockTimecode, segStart)) { continue // interleaved leftovers of the previous window } started[ti] = true @@ -294,7 +295,7 @@ func (p *HLSPlan) walkWindow(ctx context.Context, n int, segStart, segEnd int64, if !pt.ft.outTrack.spec.video { p.learnAhead(br.Pos(), b) } - if b.BlockTimecode >= segEnd { + if b.BlockTimecode >= segEnd && !tiedBeforeKey(video, b.Keyframe, b.BlockTimecode, segEnd) { if needKey[ti] && len(windows[ti]) == 0 { if b.Keyframe { k, err := sampleOf(pt, b, structure && (!keepAudio || pt.ft.outTrack.spec.video)) @@ -352,6 +353,13 @@ func (p *HLSPlan) walkWindow(ctx context.Context, n int, segStart, segEnd int64, return windows, nextPts, inPlace, nil } +// tiedBeforeKey reports a video frame that is no keyframe and is stamped exactly on a segment boundary: two frames +// share that timestamp, and this one decodes in the GOP before the keyframe that makes the boundary. It stays in the +// window it decodes in, so every segment opens on its keyframe. +func tiedBeforeKey(video, keyframe bool, ms, bound int64) bool { + return video && !keyframe && ms == bound +} + // reorderLookahead bounds the blocks a peek reads past a boundary (no codec reorders deeper). const reorderLookahead = 16 @@ -600,7 +608,7 @@ func (p *HLSPlan) walkScatteredWindow(ctx context.Context, src io.ReadSeeker, n if !pt.ft.outTrack.spec.video { p.learnAhead(br.Pos(), b) } - if b.BlockTimecode >= segEnd { + if b.BlockTimecode >= segEnd && !tiedBeforeKey(pt.ft.outTrack.spec.video, b.Keyframe, b.BlockTimecode, segEnd) { crossed = true peek = startPeek(b.Timecode, pt.ft.outTrack.spec.video) p.learnSegPos(n+1, br.Pos()) diff --git a/mp4/reorder_depth.go b/mp4/reorder_depth.go new file mode 100644 index 00000000..f05de216 --- /dev/null +++ b/mp4/reorder_depth.go @@ -0,0 +1,138 @@ +package mp4 + +// reorder_depth.go - the frame reordering depth a video track's parameter sets declare. + +import ( + "sort" + + "github.com/gravity-zero/mkvgo/mkv" +) + +// maxReorderDepth is the deepest reordering H.264 and HEVC allow (their decoded picture buffer holds 16 frames). +const maxReorderDepth = 16 + +// declaredReorderDepth is how many frames the track's H.264/HEVC parameter sets allow to precede a frame in decode +// order and follow it in output order (max_num_reorder_frames, sps_max_num_reorder_pics); 0 when nothing states it. +func declaredReorderDepth(t *mkv.Track) int { + hevc := t.Codec == "hevc" + if !hevc && t.Codec != "h264" { + return 0 + } + sets, _, ok := configParameterSets(hevc, t.CodecPrivate) + if !ok { + return 0 + } + depth := 0 + for _, nal := range sets { + switch { + case hevc && len(nal) > 2 && nal[0]>>1&0x3f == 33: + if _, sps, ok := parseHEVCSPS(newNALReader(nal[2:])); ok { + depth = max(depth, sps.numReorderPics) + } + case !hevc && len(nal) > 1 && nal[0]&0x1f == 7: + depth = max(depth, avcReorderFrames(newNALReader(nal[1:]))) + } + } + return depth +} + +// avcReorderFrames reads an H.264 SPS through its VUI to max_num_reorder_frames (ITU-T H.264 E.1.1); 0 when the SPS +// carries no bitstream restriction or cannot be read. +func avcReorderFrames(r *nalReader) int { + _, sps, ok := parseAVCSPS(r) + if !ok { + return 0 + } + if !sps.frameMbsOnly { + r.skip(1) // mb_adaptive_frame_field_flag + } + r.skip(1) // direct_8x8_inference_flag + if r.flag() { // frame_cropping_flag + r.ue() + r.ue() + r.ue() + r.ue() + } + if !r.flag() { // vui_parameters_present_flag + return 0 + } + if r.flag() && r.u(8) == 255 { // aspect_ratio_info_present_flag, Extended_SAR + r.skip(32) + } + if r.flag() { // overscan_info_present_flag + r.skip(1) + } + if r.flag() { // video_signal_type_present_flag + r.skip(4) + if r.flag() { // colour_description_present_flag + r.skip(24) + } + } + if r.flag() { // chroma_loc_info_present_flag + r.ue() + r.ue() + } + if r.flag() { // timing_info_present_flag + r.skip(65) + } + nalHRD := r.flag() + if nalHRD { + skipAVCHRD(r) + } + vclHRD := r.flag() + if vclHRD { + skipAVCHRD(r) + } + if nalHRD || vclHRD { + r.skip(1) // low_delay_hrd_flag + } + r.skip(1) // pic_struct_present_flag + if !r.flag() { // bitstream_restriction_flag + return 0 + } + r.skip(1) // motion_vectors_over_pic_boundaries_flag + r.ue() // max_bytes_per_pic_denom + r.ue() // max_bits_per_mb_denom + r.ue() // log2_max_mv_length_horizontal + r.ue() // log2_max_mv_length_vertical + n := r.ue() + if r.err || n > maxReorderDepth { + return 0 + } + return int(n) +} + +func skipAVCHRD(r *nalReader) { + cnt := r.ueMax(31) // cpb_cnt_minus1 + r.skip(8) // bit_rate_scale, cpb_size_scale + for i := uint32(0); i <= cnt && !r.err; i++ { + r.ue() + r.ue() + r.skip(1) + } + r.skip(20) +} + +// prefixFrameTS is the longest step between two neighbouring frames of the prefix, once in presentation order. A step +// of two frames or more is a frame the prefix does not hold yet (it decodes later), not a frame duration. +func prefixFrameTS(ptsTS []int64) int64 { + if len(ptsTS) < 2 { + return 0 + } + sorted := make([]int64, len(ptsTS)) + copy(sorted, ptsTS) + sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] }) + var shortest int64 + for i := 1; i < len(sorted); i++ { + if d := sorted[i] - sorted[i-1]; d > 0 && (shortest == 0 || d < shortest) { + shortest = d + } + } + var longest int64 + for i := 1; i < len(sorted); i++ { + if d := sorted[i] - sorted[i-1]; d > longest && d < 2*shortest { + longest = d + } + } + return longest +} diff --git a/mp4/stride_direction_test.go b/mp4/stride_direction_test.go index 36c74eac..fdd63a2f 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) + fillFragTimingTS(s, nil, 0, mts, gridTS, nil, 0, 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 new file mode 100644 index 00000000..0752b26d --- /dev/null +++ b/mp4/tied_boundary_test.go @@ -0,0 +1,201 @@ +package mp4 + +import ( + "bytes" + "context" + "encoding/binary" + "fmt" + "os" + "path/filepath" + "testing" + + "github.com/gravity-zero/mkvgo/mkv" + "github.com/gravity-zero/mkvgo/mkv/writer" +) + +// A frame that is no keyframe carries the timestamp of the keyframe after it, and two frames that present before it +// follow it in decode order, in the cluster before the keyframe's - how a muxer that opens a cluster on each keyframe +// stores them. All three belong to the segment they decode in, and the next one opens on its keyframe. Cut on time +// alone, the full pass opened the next segment on the tied frame, and a window served cold lost the two after it. +func TestSegmentOpensOnItsKeyframeWhenAFrameSharesItsTimestamp(t *testing.T) { + w, h := uint32(320), uint32(240) + payload := func(i int) []byte { return []byte{0x00, 0x00, 0x00, 0x01, 0x41, 0x7E, byte(i), 0x7E, byte(i), 0x7E} } + 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, 74*40); err != nil { + t.Fatal(err) + } + for g := 0; g < 3; g++ { // one cluster a GOP of 25 frames, 40 ms each + var blks []mkv.Block + for i := g * 25; i < g*25+25; i++ { + pts := int64(i) * 40 + switch i { // decode order: 47 stamped like keyframe 50, then 48 and 49 presenting before it + case 47: + pts = 2000 + case 48: + pts = 1880 + case 49: + pts = 1920 + } + blks = append(blks, mkv.Block{TrackNumber: 1, Timecode: pts, Keyframe: i%25 == 0, Data: payload(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() + dir := t.TempDir() + if err := RemuxToHLS(ctx, path, dir, Options{SegmentMs: 2000}); err != nil { + t.Fatal(err) + } + for n := 0; n < 2; n++ { + plan, err := PlanHLS(ctx, path, Options{SegmentMs: 2000}) // a fresh plan: the window is served cold + if err != nil { + t.Fatal(err) + } + if plan.NumSegments() != 2 { + t.Fatalf("plan has %d segments, want 2", plan.NumSegments()) + } + 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) + } + for _, i := range []int{47, 48, 49, 50} { + want := (i < 50) == (n == 0) + if got := bytes.Contains(full, payload(i)[4:]); got != want { + t.Errorf("full pass: segment %d holds frame %d = %v, want %v", n, i, got, want) + } + if got := bytes.Contains(od, payload(i)[4:]); got != want { + t.Errorf("on demand: segment %d holds frame %d = %v, want %v", n, i, got, want) + } + } + if !bytes.Equal(od, full) { + t.Errorf("segment %d: on demand differs from the full pass (%d vs %d bytes)", n, len(od), len(full)) + } + } +} + +// The last frame of a GOP is stamped two seconds back, as a muxer's stray timestamp, inside its own segment or in the +// span of the segment before: both paths give every sample the same times, and no composition offset goes below zero. +func TestStrayTimestampSameOnBothPaths(t *testing.T) { + for _, stamp := range []int64{2010, 1970} { + t.Run(fmt.Sprintf("stamped %d", stamp), func(t *testing.T) { strayTimestampParity(t, stamp) }) + } +} + +func strayTimestampParity(t *testing.T, stamp int64) { + 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 of 25 frames, 40 ms each + var blks []mkv.Block + for i := g * 25; i < g*25+25; i++ { + pts := int64(i) * 40 + if i == 99 { + pts = stamp // the frame before the keyframe at 4 s + } + blks = append(blks, mkv.Block{TrackNumber: 1, Timecode: pts, Keyframe: i%25 == 0, Data: []byte{0, 0, 0, 1, 0x41, byte(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() + dir := t.TempDir() + if err := RemuxToHLS(ctx, path, dir, Options{SegmentMs: 2000}); err != nil { + t.Fatal(err) + } + for n := 0; n < 3; n++ { + plan, err := PlanHLS(ctx, path, Options{SegmentMs: 2000}) + if err != nil { + t.Fatal(err) + } + 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("segment %d: on demand differs from the full pass (%d vs %d bytes)", n, len(od), len(full)) + } + if low := lowestTrunOffset(full); low < 0 { + t.Errorf("segment %d: a composition offset of %d ms for a stray timestamp", n, low) + } + } +} + +// lowestTrunOffset is the lowest composition offset of a segment's first trun (0 when it carries none). +func lowestTrunOffset(seg []byte) int64 { + i := bytes.Index(seg, []byte("trun")) + if i < 0 || i+16 > len(seg) { + return 0 + } + flags := binary.BigEndian.Uint32(seg[i+4:i+8]) & 0xFFFFFF + n := int(binary.BigEndian.Uint32(seg[i+8 : i+12])) + p := i + 12 + if flags&1 != 0 { + p += 4 + } + if flags&4 != 0 { + p += 4 + } + var low int64 + for k := 0; k < n; k++ { + for _, f := range []uint32{0x100, 0x200, 0x400} { + if flags&f != 0 { + p += 4 + } + } + if flags&0x800 != 0 { + if p+4 > len(seg) { + return low + } + low = min(low, int64(int32(binary.BigEndian.Uint32(seg[p:p+4])))) + p += 4 + } + } + return low +} diff --git a/scripts/apple-check.sh b/scripts/apple-check.sh new file mode 100644 index 00000000..a6156489 --- /dev/null +++ b/scripts/apple-check.sh @@ -0,0 +1,118 @@ +#!/usr/bin/env sh +# apple-check.sh - what Apple's media stack makes of the composition offsets mkvgo writes (macOS only). +# +# ffmpeg encodes two sources, mkvgo packages them as HLS, AVFoundation decodes the init and segments back +# (scripts/apple-pts.swift), and every frame must present where the prober reads it in the source: +# 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. +# 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) +set -eu + +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT + +echo "== build" +CGO_ENABLED=0 go build -o "$TMP/mkvgo" ./cmd/mkvgo +swiftc -O -o "$TMP/apple-pts" scripts/apple-pts.swift 2>"$TMP/swiftc.log" || { cat "$TMP/swiftc.log" >&2; exit 1; } + +echo "== fixtures" +enc() { # enc + out=$1; frames=$2; shift 2 + ffmpeg -nostdin -v error -y -f lavfi -i "testsrc2=size=320x180:rate=24000/1001" -frames:v "$frames" \ + -c:v libx264 -preset medium -pix_fmt yuv420p "$@" "$TMP/$out" +} +join() { # join + printf "file '%s'\nfile '%s'\n" "$1" "$2" > "$TMP/list.txt" + ffmpeg -nostdin -v error -y -f concat -safe 0 -i "$TMP/list.txt" -c copy "$TMP/$3" +} +K="keyint=48:min-keyint=48:scenecut=0" +enc late_a.mkv 48 -bf 3 -x264-params "b-pyramid=normal:$K:b-adapt=1:b-bias=-100" +enc late_b.mkv 96 -bf 3 -x264-params "b-pyramid=normal:$K:b-adapt=0" +join late_a.mkv late_b.mkv late.mkv +# Two parts with different parameter sets: joined as MPEG-TS bytes, the second offset by the first's duration (the +# concat demuxer stamps the frames after such a joint alike). +enc undeclared_a.mkv 48 -bf 0 -x264-params "$K" +enc undeclared_b.mkv 96 -bf 3 -x264-params "b-pyramid=normal:$K:b-adapt=0" +ffmpeg -nostdin -v error -y -i "$TMP/undeclared_a.mkv" -c copy -bsf:v h264_mp4toannexb -muxdelay 0 -muxpreload 0 "$TMP/undeclared_a.ts" +ffmpeg -nostdin -v error -y -i "$TMP/undeclared_b.mkv" -c copy -bsf:v h264_mp4toannexb -muxdelay 0 -muxpreload 0 -output_ts_offset 2.002 "$TMP/undeclared_b.ts" +cat "$TMP/undeclared_a.ts" "$TMP/undeclared_b.ts" > "$TMP/undeclared.ts" +ffmpeg -nostdin -v error -y -i "$TMP/undeclared.ts" -c copy "$TMP/undeclared.mkv" + +cat > "$TMP/compare.py" <<'PY' +# compare.py : prints " "; verdict is ok or a reason +import struct, sys +path, want_path, got_path = sys.argv[1:4] +lowest = 0 +if path != '-': + data, pos = open(path, 'rb').read(), 0 + while True: # the lowest composition offset of every trun + pos = data.find(b'trun', pos) + if pos < 0: + break + flags = int.from_bytes(data[pos + 5:pos + 8], 'big') + count = struct.unpack('>I', data[pos + 8:pos + 12])[0] + p = pos + 12 + (4 if flags & 1 else 0) + (4 if flags & 4 else 0) + for _ in range(count): + p += sum(4 for f in (0x100, 0x200, 0x400) if flags & f) + if flags & 0x800: + lowest = min(lowest, struct.unpack('>i', data[p:p + 4])[0]) + p += 4 + pos += 4 +want = sorted(float(l) for l in open(want_path) if l.strip()) +got = sorted(float(l) for l in open(got_path) if l.strip()) +detail = '%d of %d frames, lowest composition offset %d' % (len(got), len(want), lowest) +if len(got) != len(want): + missing = sorted(set(want) - set(got))[:6] + print('count|' + detail + ', source times not read: ' + ' '.join('%.3f' % m for m in missing)) + sys.exit(0) +deltas = sorted(g - w for g, w in zip(got, want)) +detail += ', against the source %+.3f to %+.3f s' % (deltas[0], deltas[-1]) +if deltas[-1] - deltas[0] > 0.0015: + print('moving|' + detail) +elif abs(deltas[len(deltas) // 2]) > 0.0015: + print('shifted|' + detail) +elif len(set(got)) != len(set(want)): + print('duplicates|' + detail) +else: + print('ok|' + detail) +PY + +read_back() { # read_back -> prints the stored and decoded verdicts, sets $verdict + for mode in stored decoded; do + "$TMP/apple-pts" "$2" $mode 2>"$TMP/$1.$mode.err" | cut -d' ' -f1 > "$TMP/$1.$mode" || { cat "$TMP/$1.$mode.err" >&2; } + line=$(python3 "$TMP/compare.py" "$3" "$TMP/$1.want" "$TMP/$1.$mode") + echo " $mode: ${line%%|*} (${line#*|})" + [ "$mode" = decoded ] && verdict=${line%%|*} + done + sort -u "$TMP/$1.decoded.err" | sed 's/^/ /' +} + +failed=0 +check() { # check + name=$1; want=$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; } + 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:" + 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 + if [ "$want" = positive ] && [ "$lowest" -lt 0 ]; then echo " FAIL $name: a negative composition offset ($lowest)"; failed=1; fi + if [ "$verdict" = ok ]; then echo " OK $name: every frame AVFoundation presents is where the source has it" + else echo " FAIL $name: decoded frames are $verdict against the source"; failed=1; fi +} +echo "== AVFoundation against the source" +check late positive +check undeclared negative +[ "$failed" = 0 ] || { echo "apple-check: FAILED" >&2; exit 1; } +echo "apple-check: ALL PASS" diff --git a/scripts/apple-pts.swift b/scripts/apple-pts.swift new file mode 100644 index 00000000..ffb48317 --- /dev/null +++ b/scripts/apple-pts.swift @@ -0,0 +1,49 @@ +// apple-pts - prints the presentation and decode time, in seconds, of the video of a local MP4 as AVFoundation +// reads it (the media stack AVPlayer plays through), one "pts dts" line each. "stored" reads the samples as the file +// stores them, on the media's own clock; "decoded" reads the frames a player presents, on the presentation clock the +// edit list maps to. The track's edit segments go to stderr. Run by scripts/apple-check.sh on macOS. +import AVFoundation +import Foundation + +func fail(_ message: String) -> Never { + FileHandle.standardError.write((message + "\n").data(using: .utf8)!) + exit(1) +} + +guard CommandLine.arguments.count == 3, ["stored", "decoded"].contains(CommandLine.arguments[2]) else { + fail("usage: apple-pts stored|decoded") +} +let decoded = CommandLine.arguments[2] == "decoded" +let asset = AVURLAsset(url: URL(fileURLWithPath: CommandLine.arguments[1])) +guard let track = asset.tracks(withMediaType: .video).first else { fail("no video track read") } + +let reader: AVAssetReader +do { reader = try AVAssetReader(asset: asset) } catch { fail("reader: \(error)") } +for segment in track.segments { + let m = segment.timeMapping + FileHandle.standardError.write(String(format: "edit segment: media %.3f+%.3f -> presentation %.3f+%.3f%@\n", + m.source.start.seconds, m.source.duration.seconds, m.target.start.seconds, m.target.duration.seconds, + segment.isEmpty ? " (empty)" : "").data(using: .utf8)!) +} +let settings: [String: Any]? = decoded + ? [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange] + : nil +let output = AVAssetReaderTrackOutput(track: track, outputSettings: settings) +output.alwaysCopiesSampleData = false +reader.add(output) +guard reader.startReading() else { fail("start reading: \(String(describing: reader.error))") } + +while let buffer = output.copyNextSampleBuffer() { + let count = CMSampleBufferGetNumSamples(buffer) + if count == 0 { continue } + var timings = [CMSampleTimingInfo](repeating: CMSampleTimingInfo(), count: count) + var written: CMItemCount = 0 + guard CMSampleBufferGetSampleTimingInfoArray(buffer, entryCount: count, arrayToFill: &timings, entriesNeededOut: &written) == noErr else { + fail("a sample buffer without timing") + } + for t in timings.prefix(Int(written)) { + let dts = t.decodeTimeStamp.isValid ? t.decodeTimeStamp.seconds : t.presentationTimeStamp.seconds + print(String(format: "%.6f %.6f", t.presentationTimeStamp.seconds, dts)) + } +} +if reader.status != .completed { fail("reading stopped: \(String(describing: reader.error))") } diff --git a/scripts/e2e.sh b/scripts/e2e.sh index ae41c6a1..68acfbb5 100755 --- a/scripts/e2e.sh +++ b/scripts/e2e.sh @@ -275,4 +275,38 @@ done [ "$same" -ge 20 ] || { echo "e2e: only $same codec names could be compared" >&2; exit 1; } echo " codec names OK: $same identical, $unresolved unresolved, $skipped encoder(s) unavailable" +echo "== late reordering: every frame keeps the presentation time the prober reads in the source" +# The opening frames are in presentation order and the B-pyramid starts with the second part, under the same +# parameter sets: what the first frames show is not what the stream reorders by. No frame of the HLS output may +# take another's presentation time, full pass and on demand, from Matroska and from MP4. +LR="b-pyramid=normal:keyint=48:min-keyint=48:scenecut=0" +gen lr_a -f lavfi -i "testsrc2=size=320x180:rate=24000/1001" -frames:v 48 -c:v libx264 -preset medium -pix_fmt yuv420p -bf 3 -x264-params "$LR:b-adapt=1:b-bias=-100" +gen lr_b -f lavfi -i "testsrc2=size=320x180:rate=24000/1001" -frames:v 96 -c:v libx264 -preset medium -pix_fmt yuv420p -bf 3 -x264-params "$LR:b-adapt=0" +printf "file 'lr_a.mkv'\nfile 'lr_b.mkv'\n" > "$TMP/lr.txt" +gen lr -f concat -safe 0 -i "$(stage "$TMP/lr.txt")" -c copy +pts_of() { # pts_of -> the video packets' presentation times, in file order + ffp -select_streams v -show_entries packet=pts_time -of csv=p=0 "$(stage "$1")" | tr -d '\r,' +} +"$MKVGO" -f to-mp4 --faststart "$TMP/lr.mkv" "$TMP/lr.mp4" >/dev/null +for src in lr.mkv lr.mp4; do + pts_of "$TMP/$src" > "$TMP/lr.src" + first=$(awk 'NR>1 && $1+0&2; exit 1; } + sort -n "$TMP/lr.src" > "$TMP/lr.want" + rm -rf "$TMP/lr.full" "$TMP/lr.od"; mkdir "$TMP/lr.od" + "$MKVGO" to-hls "$TMP/$src" -o "$TMP/lr.full" -segment 2 >/dev/null + n=$(ls "$TMP/lr.full" | grep -c '^seg') + "$MKVGO" hls-segment "$TMP/$src" init -o "$TMP/lr.od/init.mp4" -segment 2 >/dev/null + i=1; while [ "$i" -le "$n" ]; do + "$MKVGO" hls-segment "$TMP/$src" "$i" -o "$TMP/lr.od/$(printf 'seg%05d.m4s' "$i")" -segment 2 >/dev/null; i=$((i+1)) + done + for k in full od; do + cat "$TMP/lr.$k/init.mp4" "$TMP/lr.$k"/seg*.m4s > "$TMP/lr_$k.mp4" + pts_of "$TMP/lr_$k.mp4" | sort -n > "$TMP/lr.got" + cmp -s "$TMP/lr.want" "$TMP/lr.got" || { + echo "e2e: $src ($k): $(sort -u "$TMP/lr.got" | wc -l) distinct presentation times for $(wc -l < "$TMP/lr.want") frames, $(diff "$TMP/lr.want" "$TMP/lr.got" | grep -c '^>') differ from the source" >&2; exit 1; } + done + echo " late reordering OK: $src, $(wc -l < "$TMP/lr.want") frames over $n segments, reordering from packet $first" +done + echo "e2e: ALL PASS"