diff --git a/CHANGELOG.md b/CHANGELOG.md index 9a7b5fd..25b1d67 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,19 +9,29 @@ its series' file in [changelog/](changelog/) when a newer one ships. ## [Unreleased] -## [0.71.1] - 2026-11-20 +## [0.71.2] - 2026-11-20 ### Fixed -- Under `WithInBandColourFallback` (`-in-band`, `mp4.Options.InBandColour`), - three video tracks whose header names no colour now get it from their first - sample, where they kept none or the wrong "determined": a VP9 track whose - CodecPrivate holds the Matroska feature records, or whose Colour element - states the range alone (the keyframe header was read only when the profile - was missing); an AV1 track whose `av1C` holds no sequence header (a PQ - video read as having no colour); an HEVC track whose `hvcC` holds arrays - but no SPS. A VP9 Matroska file with no colour anywhere costs one more +- Under `WithInBandColourFallback` (`-in-band`, `mp4.Options.InBandColour`): + an HEVC track declared bt2020-10 is read as HLG (`arib-std-b67`) when an + Alternative Transfer Characteristics SEI of its first sample says so - the + header alone made an HLG video an SDR one; an H.264 record with no SPS + (`avc3`) gets its profile, level, pixel format and colour from the SPS its + samples carry; an MPEG-2 track with no CodecPrivate gets its profile, level + and pixel format from its first sample. Each such track costs one more bounded read under the option. -- A VP9 keyframe header that says its colour is unknown sets - `ColourDetermined`, as an H.264, HEVC or AV1 stream stating "unspecified" - does: the colour was read, there is none to find elsewhere. +- A fragmented MP4 read head-only gets the first-sample fallback too + (`mp4.Options.InBandColour`): its sample tables are empty, so nothing was + read and an `avc3` or `hev1` track kept no profile, level or colour. The + first `moof` is read for where the first samples are. +- An MPEG-2 CodecPrivate gives the profile, level and pixel format head-only, + and a VP8 track its pixel format: they were empty. +- Bitmap subtitles: a DVB block fills and draws a full-size region and one + picture of it, not four planes (254 bytes of block allocated 208 MiB); a + block asking for more is passed over as damaged. +- A keyframe walk (`WithKeyframeIndex`, `keyframes -walk`) cancelled on its + way returns the cancellation: it returned the keyframes met so far with no + error. +- `concat-hls`, `concat-segment` and `PlanConcat` apply `--sub-offset` + (`Options.SubtitleOffsetMs`): the option was accepted and ignored. diff --git a/changelog/0.70-0.79.md b/changelog/0.70-0.79.md index 2df46e8..bf7a81c 100644 --- a/changelog/0.70-0.79.md +++ b/changelog/0.70-0.79.md @@ -2,6 +2,23 @@ Archived entries of mkvgo 0.70.x to 0.79.x, as they were published; a version moves here once a newer one ships. The current versions are in [CHANGELOG.md](../CHANGELOG.md). +## [0.71.1] - 2026-11-20 + +### Fixed + +- Under `WithInBandColourFallback` (`-in-band`, `mp4.Options.InBandColour`), + three video tracks whose header names no colour now get it from their first + sample, where they kept none or the wrong "determined": a VP9 track whose + CodecPrivate holds the Matroska feature records, or whose Colour element + states the range alone (the keyframe header was read only when the profile + was missing); an AV1 track whose `av1C` holds no sequence header (a PQ + video read as having no colour); an HEVC track whose `hvcC` holds arrays + but no SPS. A VP9 Matroska file with no colour anywhere costs one more + bounded read under the option. +- A VP9 keyframe header that says its colour is unknown sets + `ColourDetermined`, as an H.264, HEVC or AV1 stream stating "unspecified" + does: the colour was read, there is none to find elsewhere. + ## [0.71.0] - 2026-11-20 ### Fixed diff --git a/cmd/mkvgo/commands/tell_resynced_test.go b/cmd/mkvgo/commands/tell_resynced_test.go index 8173086..7a593d4 100644 --- a/cmd/mkvgo/commands/tell_resynced_test.go +++ b/cmd/mkvgo/commands/tell_resynced_test.go @@ -8,9 +8,33 @@ import ( "strings" "testing" + "github.com/gravity-zero/mkvgo/ebml" "github.com/gravity-zero/mkvgo/internal/livefixture" ) +// growSegment adds n to the size a sized Segment declares, in place. +func growSegment(t *testing.T, data []byte, n int64) { + t.Helper() + r := bytes.NewReader(data) + h, hdr, err := ebml.ReadElementHeader(r) + if err != nil { + t.Fatal(err) + } + segAt := int64(hdr) + h.Size + if _, err := r.Seek(segAt, io.SeekStart); err != nil { + t.Fatal(err) + } + seg, segHdr, err := ebml.ReadElementHeader(r) + if err != nil || seg.Size < 0 { + t.Fatalf("no sized Segment: %v", err) + } + var size bytes.Buffer + if _, err := ebml.WriteDataSizeWidth(&size, seg.Size+n, segHdr-4); err != nil { + t.Fatal(err) + } + copy(data[segAt+4:], size.Bytes()) +} + // TestWritingCommandsTellWhatTheSourceWasReadPast: a command that wrote from a source read past stray bytes said // nothing, and exited 0 under --exit-damaged. It warns, names the rewrite, and counts as damage; a sound source // stays silent. @@ -18,11 +42,16 @@ func TestWritingCommandsTellWhatTheSourceWasReadPast(t *testing.T) { sound := livefixture.Build(livefixture.Options{}) cluster := bytes.Index(sound, []byte{0x1F, 0x43, 0xB6, 0x75}) junk := append(append(append([]byte(nil), sound[:cluster]...), []byte("0000\x00\x00")...), sound[cluster:]...) + tailed := livefixture.Build(livefixture.Options{SizedClusters: true, TailTags: true}) + tags := bytes.LastIndex(tailed, []byte{0x12, 0x54, 0xC3, 0x67}) + tail := append(append(append([]byte(nil), tailed[:tags]...), []byte("0000\x00\x00")...), tailed[tags:]...) + growSegment(t, tail, 6) for name, tc := range map[string]struct { data []byte want string }{ "stray bytes ahead of the first Cluster": {junk, "6 undecodable byte(s)"}, + "stray bytes ahead of the closing Tags": {tail, "6 undecodable byte(s)"}, "sound": {sound, ""}, } { t.Run(name, func(t *testing.T) { diff --git a/docs/cli.md b/docs/cli.md index e26840b..3c56164 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -9,7 +9,7 @@ mkvgo [options] Global flags: - `-json`, `--json` -- the command's report as JSON on stdout (info, tracks, chapters, attachments, tags, probe, keyframes, validate, compare, analyze, fingerprint, verify, playability, ladder, ingest, track-ends, cue-health, diagnose, salvage, reindex, reindex-inplace, retime; ignored by commands without a report). An empty list is `[]`, an empty map `{}`, never `null`; an optional section is left out. An error goes to stderr as `{"error":"...","exit":N}`. -- `-in-band` -- the inspection commands (`info`, `tracks`, `probe`) complete a video track's description from its first sample where the header leaves it short: colour behind an `hvcC` with no SPS or an `av1C` with no sequence header, a VP9 profile or colour the header does not state, HDR10 static metadata (MaxCLL/MaxFALL, mastering display) kept only in the HEVC SEI / AV1 metadata OBUs. It also reads the channel count each AC-3, E-AC-3 and AAC stream states (`stream_channels` in JSON, `channels_mismatch` when the container's `channels` says otherwise; Matroska). One bounded read, only for such a track; the container wins per field. The library's `WithInBandColourFallback` / `mp4.Options.InBandColour`. Ignored on stdin (`-`) and by the writing commands, which always apply it +- `-in-band` -- the inspection commands (`info`, `tracks`, `probe`) complete a video track's description from its first sample where the header leaves it short: colour behind an `hvcC` with no SPS or an `av1C` with no sequence header, HLG named by a SEI under a `bt2020-10` header, the profile of an `avc3` or MPEG-2 track with none in its header, a VP9 profile or colour the header does not state, HDR10 static metadata (MaxCLL/MaxFALL, mastering display) kept only in the HEVC SEI / AV1 metadata OBUs. It also reads the channel count each AC-3, E-AC-3 and AAC stream states (`stream_channels` in JSON, `channels_mismatch` when the container's `channels` says otherwise; Matroska). One bounded read, only for such a track; the container wins per field. The library's `WithInBandColourFallback` / `mp4.Options.InBandColour`. Ignored on stdin (`-`) and by the writing commands, which always apply it - `-fps-reads` -- the inspection commands (`info`, `tracks`, `probe`) let the frame-rate estimate of a Matroska track without DefaultDuration read the block headers it needs in the first 512 KiB, one exact 32-byte read each; off by default, when the estimate uses only the bytes the head read already holds and the statistics tags. The library's `WithFrameRateReads`. On 63 real files without DefaultDuration (local ext4 disk, page cache dropped per file): 12 estimated by default, 63 with the flag, about 126 more reads per file and a median probe of 7.8 ms instead of 5.0 ms (no difference once cached) - `-f`, `--force` -- overwrite an existing output file. Without it, every command that writes a new file refuses to clobber an existing one (`out.mkv already exists`); with it, an output that is one of the command's inputs is still refused. `edit-inplace` modifies its input file by design, and `split` overwrites existing parts (but never its source). - `--sync` -- a command writing a new Matroska file flushes it to disk before renaming it into place, so a completed output survives a power loss; without it the output is still written to `.mkvgo.tmp` and renamed, so a failure keeps the file already there, but a power loss soon after the command ends can leave an empty file under the output's name, the file it replaced gone (the rename can reach the disk before the data). The replace commands always flush. diff --git a/docs/library.md b/docs/library.md index 37b22c3..bb60230 100644 --- a/docs/library.md +++ b/docs/library.md @@ -1577,7 +1577,7 @@ A few cases are genuinely not readable head-only (the data lives only in the med **HDR10 static metadata.** `Track.HDR` (`*HDRStaticMetadata`) carries the Content Light Level (`MaxCLL`/`MaxFALL`, cd/m²) and the SMPTE ST 2086 Mastering Display colour volume (`MasteringDisplay`: R/G/B + white-point CIE 1931 chromaticities and the luminance range) - the side data probers report for HDR10. Read head-only from the Matroska Colour element (`MaxCLL`/`MaxFALL` + `MasteringMetadata`) or the MP4 `clli`/`mdcv` boxes (whose fixed-point, G,B,R-ordered values are normalised to the Matroska units), nil when absent. Independent of `IsHDR()` (transfer-based detection) and `DolbyVision`. -**In-band fallback (opt-in).** Some streaming-style HEVC muxes keep the SPS in-band (a bare hvcC with no parameter sets) and write no container colour, so a head-only probe sees no colour at all. Passing the in-band option makes the probe - only for such a track - read its first sample, parse the SPS VUI, and apply an Alternative Transfer Characteristics SEI override (HLG's `bt2020-10` → `arib-std-b67` compatibility signal). An hvcC whose arrays hold no SPS is read the same way, and so is an **AV1** track whose container names no colour and whose `av1C` holds no sequence header: the first temporal unit's gives the colour, bit depth and level. The same option covers **VP9 whose container names no colour** - no `vpcC` (how WebM is normally muxed), or the Matroska feature records, which state a profile but no colour: the keyframe's uncompressed header is the only place the stream says them, so the probe reads that one sample and fills `Profile` (`"Profile 0"`..`"Profile 3"`, the prober spelling), `VideoBitDepth`, `PixelFormat`, `ColorRange`, and the colour its `color_space` names where the named standard fixes the code points beyond doubt: BT.709, SMPTE 170M/240M and sRGB fill primaries, transfer and matrix; BT.601 fills matrix and transfer (its primaries differ between the 525- and 625-line variants); **BT.2020 fills primaries and matrix but never the transfer** - a VP9 HDR stream is BT.2020 with PQ or HLG, which the header cannot express and only the container states, so `ColorTransfer` stays nil there unless the container says. `unknown` fills nothing, and counts as read (`ColourDetermined`): the stream has no colour to state. The container Colour element wins per field as always. The same option completes the **HDR10 static metadata** of a PQ or HLG HEVC/AV1 track whose container carries no MasteringMetadata or no MaxCLL/MaxFALL - how most HDR10 muxes write it, keeping only the in-band copy: the first sample's SEI messages (HEVC `mastering_display_colour_volume` 137 / `content_light_level_info` 144) or metadata OBUs (AV1 `HDR_MDCV` / `HDR_CLL`) fill `Track.HDR`, each part only where the container said nothing. It also settles the **scan type of an H.264 track** whose SPS allows field coding (`frame_mbs_only_flag` 0) and whose container states no `FlagInterlaced`, from the first 16 samples of the track - on Matroska whatever the other tracks interleave between them, a track giving up after 128 blocks of other tracks in a row; on MP4 located through the sample table, contiguous samples read in one run, 16 KiB of each and 1 MiB in all. A record with no SPS (`avc3`) is read with the SPS the samples carry, and one that codes frames only makes the track `progressive`, as it would in the header. An **HEVC** track the header leaves open is read the same way: an in-band SPS with `field_seq_flag`, or a picture timing SEI that says a picture is interlaced (`source_scan_type` 0) or a field (`pic_struct` 1, 2, 9-12), makes it `interlaced` - never a picture whose `source_scan_type` says progressive - and `pic_struct` 3-6 and 9-12 give the order. An **MPEG-2** track the container leaves open is read from the sequence header its first sample carries (muxers often write no CodecPrivate): `progressive_sequence` 1 makes it `progressive`; a field picture, or a frame with `progressive_frame` 0, makes it `interlaced`, with the order from `top_field_first` or the first field of a pair; a progressive frame repeating a field (soft telecine) proves nothing. `ScanType` becomes `interlaced` on proof: a field-coded slice (`field_pic_flag` 1); a frame whose two fields have different picture order counts (`delta_pic_order_cnt_bottom`, or `offset_for_top_to_bottom_field` with pic_order_cnt_type 1); a picture timing SEI that shows a field alone (`pic_struct` 1/2) or says `ct_type` interlaced; or `pic_struct` top-bottom/bottom-top (3/4) on an MBAFF stream, unless a sample shows soft telecine (`pic_struct` 5/6) or `ct_type` progressive. `FieldOrder` gets `tt`/`bb` when every sample that states an order agrees: the field picture order counts (the decoding order with pic_order_cnt_type 2), the frame's bottom-field offset, or `pic_struct`. Without proof both stay `""` - a frame whose two fields share an instant proves nothing, MBAFF included. It is off by default on the probe; tracks that already carry the description in the header read no frame. The remux and plan entry points (`RemuxToMP4`, `RemuxToHLS`, `PlanHLS`, `PlanGrowingHLS`, and their MP4-source counterparts) always apply it, so the `colr`/`mdcv`/`clli` they write describe the stream whichever copy the source muxer kept. +**In-band fallback (opt-in).** Some streaming-style HEVC muxes keep the SPS in-band (a bare hvcC with no parameter sets) and write no container colour, so a head-only probe sees no colour at all. Passing the in-band option makes the probe - only for such a track - read its first sample, parse the SPS VUI, and apply an Alternative Transfer Characteristics SEI override (HLG's `bt2020-10` → `arib-std-b67` compatibility signal). An HEVC track the header declares `bt2020-10` is read for that SEI alone, since it is how HLG travels. An hvcC whose arrays hold no SPS is read the same way, and so is an **AV1** track whose container names no colour and whose `av1C` holds no sequence header: the first temporal unit's gives the colour, bit depth and level. The same option covers **VP9 whose container names no colour** - no `vpcC` (how WebM is normally muxed), or the Matroska feature records, which state a profile but no colour: the keyframe's uncompressed header is the only place the stream says them, so the probe reads that one sample and fills `Profile` (`"Profile 0"`..`"Profile 3"`, the prober spelling), `VideoBitDepth`, `PixelFormat`, `ColorRange`, and the colour its `color_space` names where the named standard fixes the code points beyond doubt: BT.709, SMPTE 170M/240M and sRGB fill primaries, transfer and matrix; BT.601 fills matrix and transfer (its primaries differ between the 525- and 625-line variants); **BT.2020 fills primaries and matrix but never the transfer** - a VP9 HDR stream is BT.2020 with PQ or HLG, which the header cannot express and only the container states, so `ColorTransfer` stays nil there unless the container says. `unknown` fills nothing, and counts as read (`ColourDetermined`): the stream has no colour to state. The container Colour element wins per field as always. The same option completes the **HDR10 static metadata** of a PQ or HLG HEVC/AV1 track whose container carries no MasteringMetadata or no MaxCLL/MaxFALL - how most HDR10 muxes write it, keeping only the in-band copy: the first sample's SEI messages (HEVC `mastering_display_colour_volume` 137 / `content_light_level_info` 144) or metadata OBUs (AV1 `HDR_MDCV` / `HDR_CLL`) fill `Track.HDR`, each part only where the container said nothing. It also settles the **scan type of an H.264 track** whose SPS allows field coding (`frame_mbs_only_flag` 0) and whose container states no `FlagInterlaced`, from the first 16 samples of the track - on Matroska whatever the other tracks interleave between them, a track giving up after 128 blocks of other tracks in a row; on MP4 located through the sample table, contiguous samples read in one run, 16 KiB of each and 1 MiB in all. A record with no SPS (`avc3`) is read with the SPS the samples carry, and one that codes frames only makes the track `progressive`, as it would in the header. An **HEVC** track the header leaves open is read the same way: an in-band SPS with `field_seq_flag`, or a picture timing SEI that says a picture is interlaced (`source_scan_type` 0) or a field (`pic_struct` 1, 2, 9-12), makes it `interlaced` - never a picture whose `source_scan_type` says progressive - and `pic_struct` 3-6 and 9-12 give the order. An **MPEG-2** track the container leaves open is read from the sequence header its first sample carries (muxers often write no CodecPrivate): `progressive_sequence` 1 makes it `progressive`; a field picture, or a frame with `progressive_frame` 0, makes it `interlaced`, with the order from `top_field_first` or the first field of a pair; a progressive frame repeating a field (soft telecine) proves nothing. `ScanType` becomes `interlaced` on proof: a field-coded slice (`field_pic_flag` 1); a frame whose two fields have different picture order counts (`delta_pic_order_cnt_bottom`, or `offset_for_top_to_bottom_field` with pic_order_cnt_type 1); a picture timing SEI that shows a field alone (`pic_struct` 1/2) or says `ct_type` interlaced; or `pic_struct` top-bottom/bottom-top (3/4) on an MBAFF stream, unless a sample shows soft telecine (`pic_struct` 5/6) or `ct_type` progressive. `FieldOrder` gets `tt`/`bb` when every sample that states an order agrees: the field picture order counts (the decoding order with pic_order_cnt_type 2), the frame's bottom-field offset, or `pic_struct`. Without proof both stay `""` - a frame whose two fields share an instant proves nothing, MBAFF included. It is off by default on the probe; tracks that already carry the description in the header read no frame. The remux and plan entry points (`RemuxToMP4`, `RemuxToHLS`, `PlanHLS`, `PlanGrowingHLS`, and their MP4-source counterparts) always apply it, so the `colr`/`mdcv`/`clli` they write describe the stream whichever copy the source muxer kept. ```go // MKV (Open and Read take the same options as OpenMeta) diff --git a/mkv/reader/block_overrun_test.go b/mkv/reader/block_overrun_test.go index 3dc38f5..c364998 100644 --- a/mkv/reader/block_overrun_test.go +++ b/mkv/reader/block_overrun_test.go @@ -2,6 +2,7 @@ package reader import ( "bytes" + "context" "errors" "io" "testing" @@ -91,7 +92,7 @@ func TestKeyframeIndexResyncsPastAnOverrunningBlock(t *testing.T) { data, _ := overrunClusters(false) segStart := int64(bytes.Index(data, []byte{0x1F, 0x43, 0xB6, 0x75})) p := &parser{r: bytes.NewReader(data), segStart: segStart, segEnd: -1} - times := p.buildKeyframeIndex(0, 1000000) + times := p.buildKeyframeIndex(context.Background(), 0, 1000000) found := false for _, ms := range times { found = found || ms == 1000 diff --git a/mkv/reader/codec_colour.go b/mkv/reader/codec_colour.go index 6bf28c9..9bf2d03 100644 --- a/mkv/reader/codec_colour.go +++ b/mkv/reader/codec_colour.go @@ -142,6 +142,10 @@ func FillColourFromCodecPrivate(t *mkv.Track) { // left nil from the codec bitstream. Called for video tracks after the TrackEntry // is parsed. Safe on any input. func fillColourFromCodecPrivate(t *mkv.Track) { + if t.Type == mkv.VideoTrack && (t.Codec == "V_VP8" || t.Codec == "vp8") { + mergeBitstreamColour(t, &bitstreamColour{chroma: u16p(1), bitDepth: u16p(8)}) // VP8 codes 8-bit 4:2:0 alone + return + } if t.Type != mkv.VideoTrack || len(t.CodecPrivate) == 0 { return } @@ -241,8 +245,7 @@ func mpeg2Colour(cp []byte) *bitstreamColour { r := &bitReader{data: cp[i+4:]} switch r.bits(4) { // extension_start_code_identifier case 1: // sequence extension: progressive_sequence 1 makes every frame progressive - r.bits(8) // profile_and_level_indication - if r.bit() == 1 && !r.err && bc.scanType == "" { + if mpeg2SequenceExtension(r, bc) && bc.scanType == "" { bc.scanType = "progressive" } case 2: // sequence display extension @@ -256,12 +259,59 @@ func mpeg2Colour(cp []byte) *bitstreamColour { } } } - if !bc.determined && bc.scanType == "" { + if !bc.determined && bc.scanType == "" && bc.profile == "" { return nil } return bc } +// mpeg2SequenceExtension reads the head of a sequence extension past its id: the +// profile and level, then progressive_sequence, which it returns, then the chroma +// format. The first extension read names the stream; MPEG-2 video is 8 bits. +func mpeg2SequenceExtension(r *bitReader, bc *bitstreamColour) (progressive bool) { + pl := r.bits(8) // profile_and_level_indication + progressive = r.bit() == 1 && !r.err + chroma := r.bits(2) + if r.err || bc.profile != "" { + return progressive + } + bc.profile, bc.level = mpeg2ProfileLevel(pl) + if chroma != 0 { + bc.chroma, bc.bitDepth = u16p(uint16(chroma)), u16p(8) + } + return progressive +} + +// mpeg2ProfileLevel names profile_and_level_indication (ISO 13818-2 table 8-2, +// and the escape codes of the 4:2:2 profile): the level is its 4-bit code, 8 for Main. +func mpeg2ProfileLevel(pl uint32) (string, *uint16) { + level := u16p(uint16(pl & 0x0f)) + if pl&0x80 != 0 { + if pl == 0x85 || pl == 0x82 { + return "4:2:2", level + } + return "", nil + } + switch *level { + case 4, 6, 8, 10: + default: + level = nil + } + switch (pl >> 4) & 7 { + case 5: + return "Simple", level + case 4: + return "Main", level + case 3: + return "SNR Scalable", level + case 2: + return "Spatially Scalable", level + case 1: + return "High", level + } + return "", nil +} + // --- bit reader (MSB-first) with Exp-Golomb, over-read tracked in err ---------- type bitReader struct { diff --git a/mkv/reader/inband_colour.go b/mkv/reader/inband_colour.go index 58baee2..a559b24 100644 --- a/mkv/reader/inband_colour.go +++ b/mkv/reader/inband_colour.go @@ -249,7 +249,7 @@ func fillColourFromFirstSample(ctx context.Context, r io.ReadSeeker, c *mkv.Cont scans := make(map[uint64]*scanning) for i := range c.Tracks { t := &c.Tracks[i] - if needsInBandColour(t) || needsInBandHDR(t) { + if NeedsInBandColour(t) { need[t.ID] = t } if needsInBandScan(t) { @@ -343,7 +343,16 @@ func activeTracks[N, S any](need map[uint64]N, scans map[uint64]S) []uint64 { // whose static metadata the container does not carry (see // WithInBandColourFallback). Exposed so the mp4 package can drive the same // fallback off its sample table; the H.264 scan type is NewInBandScan's. -func NeedsInBandColour(t *mkv.Track) bool { return needsInBandColour(t) || needsInBandHDR(t) } +func NeedsInBandColour(t *mkv.Track) bool { + return needsInBandColour(t) || needsInBandHDR(t) || mayBeHLGBySEI(t) +} + +// mayBeHLGBySEI reports an HEVC track the header says bt2020-10 (14): the +// transfer HLG advertises to legacy decoders, the real one travelling in an +// Alternative Transfer Characteristics SEI of the samples. +func mayBeHLGBySEI(t *mkv.Track) bool { + return t.Type == mkv.VideoTrack && isHEVCCodec(t.Codec) && t.ColorTransfer != nil && *t.ColorTransfer == 14 +} // ApplyInBandColour fills t from its first sample: for HEVC, one // length-prefixed access unit - the SPS VUI, an Alternative Transfer @@ -405,6 +414,11 @@ func applyInBandHeader(t *mkv.Track, frame []byte) { default: applyInBandSPSColour(t, frame) } + if mayBeHLGBySEI(t) { + if tc, ok := atcTransferFromFrame(frame, hevcNALLen(t)); ok { + t.ColorTransfer = &tc + } + } if needsInBandHDR(t) { applyInBandHDR(t, frame) } @@ -424,10 +438,7 @@ func isHEVCCodec(codec string) bool { // SPS VUI via the existing SPS parser, then an Alternative Transfer // Characteristics SEI override if present. func applyInBandSPSColour(t *mkv.Track, frame []byte) { - nalLen := 4 - if len(t.CodecPrivate) >= 22 { - nalLen = int(t.CodecPrivate[21]&0x03) + 1 - } + nalLen := hevcNALLen(t) if sps := firstHEVCNAL(frame, nalLen, 33); len(sps) >= 3 { // 33 = SPS_NUT bc := &bitstreamColour{} parseHEVCSPS(unescapeRBSP(sps[2:]), bc) // strip the 2-byte NAL header @@ -442,6 +453,14 @@ func applyInBandSPSColour(t *mkv.Track, frame []byte) { } } +// hevcNALLen is the NAL length prefix size the hvcC states, 4 without one. +func hevcNALLen(t *mkv.Track) int { + if len(t.CodecPrivate) >= 22 { + return int(t.CodecPrivate[21]&0x03) + 1 + } + return 4 +} + // forEachHEVCNAL walks the length-prefixed NAL units of a frame (prefix nalLen // bytes, big-endian), calling fn(nal_unit_type, nal) for each; fn returns true to // stop. Malformed lengths end the walk. diff --git a/mkv/reader/inband_colour_gap_test.go b/mkv/reader/inband_colour_gap_test.go index ba8dd9b..6b4c7ce 100644 --- a/mkv/reader/inband_colour_gap_test.go +++ b/mkv/reader/inband_colour_gap_test.go @@ -60,3 +60,32 @@ func TestInBandColourHEVCRecordWithoutSPS(t *testing.T) { t.Errorf("transfer=%q determined=%v, want smpte2084 true", tr.ColorTransferName(), tr.ColourDetermined) } } + +// TestInBandColourHLGBySEI: an HEVC track the header says bt2020-10 may be HLG, +// named by an Alternative Transfer Characteristics SEI in its samples alone. +func TestInBandColourHLGBySEI(t *testing.T) { + frame := lenPrefixed4(atcSEINAL(18)) + data := hdrTrackMKV("V_MPEGH/ISO/HEVC", mustHex(t, hevcHDRPrivateHex), 14, nil, frame) + base, err := ReadMeta(context.Background(), bytes.NewReader(data), "x.mkv") + if err != nil { + t.Fatal(err) + } + if got := base.Tracks[0].ColorTransferName(); got != "bt2020-10" { + t.Fatalf("head only: transfer=%q, want bt2020-10", got) + } + c, err := ReadMeta(context.Background(), bytes.NewReader(data), "x.mkv", WithInBandColourFallback()) + if err != nil { + t.Fatal(err) + } + if tr := c.Tracks[0]; tr.ColorTransferName() != "arib-std-b67" || !tr.IsHDR() { + t.Errorf("transfer=%q hdr=%v, want arib-std-b67 true", tr.ColorTransferName(), tr.IsHDR()) + } + // No such SEI: the header's word stands. + c, err = ReadMeta(context.Background(), bytes.NewReader(hdrTrackMKV("V_MPEGH/ISO/HEVC", mustHex(t, hevcHDRPrivateHex), 14, nil, lenPrefixed4([]byte{0x26, 0x01, 0xaf}))), "x.mkv", WithInBandColourFallback()) + if err != nil { + t.Fatal(err) + } + if got := c.Tracks[0].ColorTransferName(); got != "bt2020-10" { + t.Errorf("without the SEI: transfer=%q, want bt2020-10", got) + } +} diff --git a/mkv/reader/inband_scan.go b/mkv/reader/inband_scan.go index 5ce374c..30a1a63 100644 --- a/mkv/reader/inband_scan.go +++ b/mkv/reader/inband_scan.go @@ -63,6 +63,8 @@ type avcScan struct { // that codes frames only proves the track progressive, as it would head-only. inBandSPS bool sawSPS, sawFieldCoded bool + firstSPS *bitstreamColour // the first in-band SPS: what the record would have described + descOnly bool // the container states the scan type: the scan is here for that SPS alone interlaced bool // Field orders the samples stated. pic_struct is the display order and wins, @@ -165,7 +167,12 @@ func avcCPPSList(cp []byte) [][]byte { // done reports whether more samples cannot change the verdict: interlaced, and // display orders that already disagree. One order is checked against every sample. -func (s *avcScan) done() bool { return s.interlaced && len(s.structOrders) > 1 } +func (s *avcScan) done() bool { + if s.descOnly { + return s.firstSPS != nil + } + return s.interlaced && len(s.structOrders) > 1 +} // head is whole samples: the walk bounds its NALs and the bytes it parses, and a // frame's second field can sit past its first one's 16 KiB. @@ -204,6 +211,9 @@ func (s *avcScan) walk(frame []byte, truncated bool) { case 7: if bc := parseAVCSPS(unescapeRBSP(nal[1:])); bc != nil { s.addSPS(bc) + if s.firstSPS == nil { + s.firstSPS = bc + } s.sawSPS = true s.sawFieldCoded = s.sawFieldCoded || bc.avc.fieldCoding } @@ -366,6 +376,9 @@ func orderOf(topFirst bool) string { // when every sample that stated one agreed - the pic_struct orders when there // are any, else the picture order counts. Nothing is written otherwise. func (s *avcScan) apply(t *mkv.Track) { + if s.inBandSPS && s.firstSPS != nil { + mergeBitstreamColour(t, s.firstSPS) + } if s.pairStruct && !s.pulldown && !s.progressive { s.interlaced = true } @@ -435,7 +448,21 @@ type scanner interface { // settle: a scan type already stated, a codec without one, or a record that // already rules interlacing out. func newScanner(t *mkv.Track) scanner { - if t.Type != mkv.VideoTrack || t.ScanType != "" { + if t.Type != mkv.VideoTrack { + return nil + } + if t.Codec == "V_MPEG2" || t.Codec == "mpeg2" { + if t.ScanType != "" && t.Profile != "" { + return nil + } + return &mpeg2Scan{orders: map[string]bool{}, scanKnown: t.ScanType != ""} + } + if t.ScanType != "" { + // An H.264 record with no SPS still leaves the profile to the samples. + if s := newAVCScan(t.CodecPrivate); isAVCCodec(t.Codec) && t.Profile == "" && s != nil && s.inBandSPS { + s.descOnly = true + return s + } return nil } switch { @@ -447,8 +474,6 @@ func newScanner(t *mkv.Track) scanner { if s := newHEVCScan(t.CodecPrivate); s != nil { return s } - case t.Codec == "V_MPEG2" || t.Codec == "mpeg2": - return &mpeg2Scan{orders: map[string]bool{}} } return nil } @@ -463,6 +488,10 @@ type mpeg2Scan struct { interlaced, progressiveSeq bool orders map[string]bool firstField bool // the last picture was the first field of a frame + // The sequence extension also names the stream: profile, level, chroma format. + // scanKnown: the container states the scan type, the scan is here for those alone. + desc bitstreamColour + scanKnown bool } func (s *mpeg2Scan) feed(frame []byte, _ bool) { @@ -473,9 +502,8 @@ func (s *mpeg2Scan) feed(frame []byte, _ bool) { r := &bitReader{data: frame[i+4:]} switch r.bits(4) { case 1: // sequence extension - r.bits(8) - if p := r.bit(); !r.err { - s.progressiveSeq = s.progressiveSeq || p == 1 + if mpeg2SequenceExtension(r, &s.desc) { + s.progressiveSeq = true } case 8: // picture coding extension r.bits(16) // f_codes @@ -510,12 +538,16 @@ func (s *mpeg2Scan) picture(structure uint32, tff, progressiveFrame bool) { } func (s *mpeg2Scan) done() bool { + if s.scanKnown { + return s.desc.profile != "" + } return (s.interlaced && len(s.orders) > 1) || (s.progressiveSeq && !s.interlaced) } func (s *mpeg2Scan) head() int { return inBandScanHead } func (s *mpeg2Scan) apply(t *mkv.Track) { + mergeBitstreamColour(t, &s.desc) if t.ScanType != "" { return } @@ -538,7 +570,7 @@ func (s *mpeg2Scan) apply(t *mkv.Track) { type InBandScan struct{ s scanner } // NewInBandScan returns the scan for t, nil when t needs none: not H.264, HEVC or MPEG-2, -// a scan type already stated, or an H.264 SPS that codes frames only. +// a scan type already stated (and, for MPEG-2, a profile), or an H.264 SPS that codes frames only. func NewInBandScan(t *mkv.Track) *InBandScan { if s := newScanner(t); s != nil { return &InBandScan{s} diff --git a/mkv/reader/inband_scan_test.go b/mkv/reader/inband_scan_test.go index 8cf5aa5..ff86f8d 100644 --- a/mkv/reader/inband_scan_test.go +++ b/mkv/reader/inband_scan_test.go @@ -617,3 +617,81 @@ func TestMPEG2ScanPictures(t *testing.T) { t.Error("a CodecPrivate sequence extension with progressive_sequence 1 gave no progressive scan type") } } + +// TestInBandAVC3Description: a record with no SPS leaves the profile, the pixel +// format and the colour signalling to the SPS the samples carry. +func TestInBandAVC3Description(t *testing.T) { + sps := scanSPS{frameOnly: true} + frame := au(sps.nal(), scanPPS(0, 0, true), frameOnlySlice(true, scanSlice{idr: true})) + want, err := ReadMeta(context.Background(), bytes.NewReader(avcScanMKV(scanAvcC([][]byte{sps.nal()}, nil), nil, frame)), "") + if err != nil { + t.Fatal(err) + } + w := want.Tracks[0] + if w.Profile == "" || w.PixelFormat == "" || !w.ColourDetermined { + t.Fatalf("fixture: the record with its SPS gives profile=%q pix=%q determined=%v", w.Profile, w.PixelFormat, w.ColourDetermined) + } + // With or without a scan type from the container: a muxer that states it keeps the SPS in the samples all the same. + progressive := masterElem(mkv.IDVideo, uintElem(mkv.IDFlagInterlaced, 2, 1)) + for name, video := range map[string][]byte{"no scan type": nil, "container says progressive": progressive} { + meta, err := ReadMeta(context.Background(), bytes.NewReader(avcScanMKV(scanAvcC(nil, nil), video, frame)), "", WithInBandColourFallback()) + if err != nil { + t.Fatal(err) + } + if g := meta.Tracks[0]; g.Profile != w.Profile || g.PixelFormat != w.PixelFormat || g.ColourDetermined != w.ColourDetermined { + t.Errorf("%s: profile=%q pix=%q determined=%v, want %q %q %v", name, g.Profile, g.PixelFormat, g.ColourDetermined, w.Profile, w.PixelFormat, w.ColourDetermined) + } + } +} + +// TestMPEG2DescriptionFFmpegFiles: the sequence extension of the first block +// gives the profile, the level and the pixel format of an MPEG-2 track with no +// CodecPrivate, whether or not the container states the scan type. +func TestMPEG2DescriptionFFmpegFiles(t *testing.T) { + for _, file := range []string{"mpeg2_tff.mkv", "mpeg2_progressive.mkv"} { + raw, err := os.ReadFile("../../internal/testdata/" + file) + if err != nil { + t.Fatal(err) + } + for name, data := range map[string][]byte{"as written": raw, "scan elements cleared": stripScanElements(t, raw)} { + c, err := ReadMeta(context.Background(), bytes.NewReader(data), "", WithInBandColourFallback()) + if err != nil { + t.Fatalf("%s: %v", file, err) + } + if g := c.Tracks[0]; g.Profile != "Main" || u16v(g.Level) != 8 || g.PixelFormat != "yuv420p" { + t.Errorf("%s (%s): profile=%q level=%d pix=%q, want Main 8 yuv420p", file, name, g.Profile, u16v(g.Level), g.PixelFormat) + } + } + } +} + +// TestMPEG2DescriptionFromCodecPrivate: the same fields head-only when the +// record holds the sequence extension, 4:2:2 profile included. +func TestMPEG2DescriptionFromCodecPrivate(t *testing.T) { + ext := func(pl byte, chroma uint32) []byte { + b := &tbw{} + b.u(1, 4) + b.u(uint32(pl), 8) + b.u(1, 1) + b.u(chroma, 2) + b.u(0, 1) + return append([]byte{0, 0, 1, 0xb5}, b.bytes()...) + } + for _, c := range []struct { + pl byte + chroma uint32 + profile string + level int + pix string + }{{0x48, 1, "Main", 8, "yuv420p"}, {0x44, 1, "Main", 4, "yuv420p"}, {0x85, 2, "4:2:2", 5, "yuv422p"}, {0x14, 3, "High", 4, "yuv444p"}} { + bc := mpeg2Colour(ext(c.pl, c.chroma)) + if bc == nil { + t.Fatalf("0x%02X: nil", c.pl) + } + tr := &mkv.Track{Type: mkv.VideoTrack} + mergeBitstreamColour(tr, bc) + if tr.Profile != c.profile || u16v(tr.Level) != c.level || tr.PixelFormat != c.pix { + t.Errorf("0x%02X: profile=%q level=%d pix=%q, want %q %d %q", c.pl, tr.Profile, u16v(tr.Level), tr.PixelFormat, c.profile, c.level, c.pix) + } + } +} diff --git a/mkv/reader/keyframe_index.go b/mkv/reader/keyframe_index.go index d02d0f9..ea20374 100644 --- a/mkv/reader/keyframe_index.go +++ b/mkv/reader/keyframe_index.go @@ -2,6 +2,7 @@ package reader import ( "bufio" + "context" "fmt" "io" "sort" @@ -28,7 +29,7 @@ import ( // end, and continues - so a damaged region costs at most the keyframes in it. // Matroska carries no edit list, so block times need no shift; this matches the // Cues-derived index (keyframeTimesMs), the other Matroska keyframe path. -func (p *parser) buildKeyframeIndex(videoTrack uint64, scale int64) []int64 { +func (p *parser) buildKeyframeIndex(ctx context.Context, videoTrack uint64, scale int64) []int64 { segStart, segEnd := p.segStart, p.segEnd if segEnd < 0 { // unknown-size Segment: walk to the file end if end, err := p.r.Seek(0, io.SeekEnd); err == nil { @@ -88,6 +89,9 @@ walk: if !inCluster { if h.ID == mkv.IDCluster { + if ctx.Err() != nil { + return nil // cancelled: the caller reports it, a partial index is not the file's + } inCluster, haveTS, clusterTS = true, false, 0 if h.Size >= 0 { clusterEnd = p.pos() + h.Size diff --git a/mkv/reader/keyframe_index_cancel_test.go b/mkv/reader/keyframe_index_cancel_test.go new file mode 100644 index 0000000..780a273 --- /dev/null +++ b/mkv/reader/keyframe_index_cancel_test.go @@ -0,0 +1,46 @@ +package reader + +import ( + "bytes" + "context" + "errors" + "io" + "testing" + + "github.com/gravity-zero/mkvgo/internal/livefixture" +) + +// cancelAfter cancels its context once the source was read past a given offset, and reads 32 bytes at a time. +type cancelAfter struct { + *bytes.Reader + past int64 + cancel context.CancelFunc +} + +func (c *cancelAfter) Read(p []byte) (int, error) { + if pos, _ := c.Seek(0, io.SeekCurrent); pos >= c.past { + c.cancel() + } + return c.Reader.Read(p[:min(len(p), 32)]) // short reads, so the walk meets the cancellation on its way +} + +// TestKeyframeWalkStopsOnCancel: the keyframe walk reads the whole file; a context cancelled on the way ended in a +// read that returned no error and the keyframes met so far, as if they were the file's. +func TestKeyframeWalkStopsOnCancel(t *testing.T) { + data := livefixture.Build(livefixture.Options{SizedClusters: true}) + whole, err := ReadMeta(context.Background(), bytes.NewReader(data), "", WithKeyframeIndex()) + if err != nil || len(whole.Keyframes) < 2 { + t.Fatalf("fixture: %d keyframes, err %v", len(whole.Keyframes), err) + } + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + first := int64(bytes.Index(data, []byte{0x1F, 0x43, 0xB6, 0x75})) + c, err := ReadMeta(ctx, &cancelAfter{Reader: bytes.NewReader(data), past: first + 8, cancel: cancel}, "", WithKeyframeIndex()) + if !errors.Is(err, context.Canceled) { + n := -1 + if c != nil { + n = len(c.Keyframes) + } + t.Fatalf("err = %v with %d keyframes of %d; want context.Canceled", err, n, len(whole.Keyframes)) + } +} diff --git a/mkv/reader/reader_meta.go b/mkv/reader/reader_meta.go index bfbe4a2..1ff9d4f 100644 --- a/mkv/reader/reader_meta.go +++ b/mkv/reader/reader_meta.go @@ -92,18 +92,21 @@ func ReadMeta(ctx context.Context, r io.ReadSeeker, path string, opts ...ReadOpt // Keyframes head-only above and win). The complete index is preferred over the // sample when both are requested. if o.keyframeWalk && len(c.Keyframes) > 0 { - if ks := p.buildKeyframeIndex(videoTrackID(c), c.Info.TimecodeScale); len(ks) > 0 { + if ks := p.buildKeyframeIndex(ctx, videoTrackID(c), c.Info.TimecodeScale); len(ks) > 0 { c.Keyframes = ks } } if len(c.Keyframes) == 0 { switch { case o.keyframeIndex: - c.Keyframes = p.buildKeyframeIndex(videoTrackID(c), c.Info.TimecodeScale) + c.Keyframes = p.buildKeyframeIndex(ctx, videoTrackID(c), c.Info.TimecodeScale) case o.sampledKeyframes > 0: c.Keyframes = p.sampleClusterKeyframes(o.sampledKeyframes, c.Info.TimecodeScale, videoTrackID(c)) } } + if err := ctx.Err(); err != nil && (o.keyframeWalk || o.keyframeIndex) { + return nil, err // the walk reads the whole file: cancelled on the way, its keyframes are not the file's + } if o.inBandChannels { fillStreamChannels(ctx, r, c) } diff --git a/mkv/reader/vp9_test.go b/mkv/reader/vp9_test.go index f874404..b7824cb 100644 --- a/mkv/reader/vp9_test.go +++ b/mkv/reader/vp9_test.go @@ -331,3 +331,15 @@ func TestVP9FeatureMetadataInBandColour(t *testing.T) { t.Errorf("with a Colour element: space=%v transfer=%d, want the element alone", tr.ColorSpace, u16v(tr.ColorTransfer)) } } + +// TestVP8PixelFormat: VP8 has one pixel format, stated head-only. +func TestVP8PixelFormat(t *testing.T) { + data := bytes.Replace(vp9MKV(nil, nil, 320, 240, []byte{0x10, 0x02, 0x00, 0x9d, 0x01, 0x2a}), []byte("V_VP9"), []byte("V_VP8"), 1) + c, err := ReadMeta(context.Background(), bytes.NewReader(data), "x.webm") + if err != nil { + t.Fatal(err) + } + if tr := c.Tracks[0]; tr.Codec != "V_VP8" && tr.Codec != "vp8" || tr.PixelFormat != "yuv420p" || u16v(tr.VideoBitDepth) != 8 { + t.Errorf("codec=%q pix=%q depth=%d, want vp8 yuv420p 8", tr.Codec, tr.PixelFormat, u16v(tr.VideoBitDepth)) + } +} diff --git a/mkv/subtitle/dvbsub.go b/mkv/subtitle/dvbsub.go index 206ca2a..530f7a0 100644 --- a/mkv/subtitle/dvbsub.go +++ b/mkv/subtitle/dvbsub.go @@ -46,8 +46,9 @@ const ( dvbMaxDim = 4096 // dvbMaxEpochBytes bounds what an epoch's regions hold together: they live until the next mode change. dvbMaxEpochBytes = 16 << 20 - // dvbMaxBlockPixels bounds the work of one block, counted in pixels filled, drawn and handed back. - dvbMaxBlockPixels = 4 * dvbMaxDim * dvbMaxDim + // dvbMaxBlockPixels bounds the work of one block, counted in pixels filled, drawn and handed back: a + // full-size region and one picture of it, and the small change of placements and object references. + dvbMaxBlockPixels = 2*dvbMaxDim*dvbMaxDim + 1<<20 // dvbObjectRefBytes is what one object reference of a region counts for in dvbMaxEpochBytes. dvbObjectRefBytes = 24 ) diff --git a/mkv/subtitle/dvbsub_block_pictures_test.go b/mkv/subtitle/dvbsub_block_pictures_test.go new file mode 100644 index 0000000..f5a783a --- /dev/null +++ b/mkv/subtitle/dvbsub_block_pictures_test.go @@ -0,0 +1,30 @@ +package subtitle + +import ( + "runtime" + "strings" + "testing" +) + +// A full-size region shown again under a CLUT that changes each time made a picture of 64 MiB per display set: +// 254 bytes of block allocated 208 MiB. The block's budget is the region and one picture of it. +func TestDVBSubBlockPicturesBounded(t *testing.T) { + entry := func(y byte) [6]byte { return [6]byte{1, 0xe1, y, 0x80, 0x80, 0x00} } + block := concat(dvbPCS(2, dvbPlacement{}), dvbRCS(0, true, dvbMaxDim, dvbMaxDim, 3, 0, 1), dvbCDS(0, entry(0x40)), dvbEDS()) + for i := 0; i < 6; i++ { + again := dvbCDS(0, entry(byte(0x50+i))) + again[7] = byte(i+1) << 4 // CLUT version + block = concat(block, dvbPCS(0, dvbPlacement{}), again, dvbEDS()) + } + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + _, err := newDVBSub(t).Decode(block) + runtime.ReadMemStats(&after) + if err == nil || !strings.Contains(err.Error(), "fills and draws more than") { + t.Fatalf("err = %v, want the block's pixel bound", err) + } + if alloc := after.TotalAlloc - before.TotalAlloc; alloc > 100<<20 { + t.Errorf("a %d-byte block allocated %d MiB, want the region and one picture, 80 MiB", len(block), alloc>>20) + } +} diff --git a/mkv/subtitle/dvbsub_test.go b/mkv/subtitle/dvbsub_test.go index 724579e..ef4c49a 100644 --- a/mkv/subtitle/dvbsub_test.go +++ b/mkv/subtitle/dvbsub_test.go @@ -480,10 +480,10 @@ func TestDVBSubDecoder_NonPixelObjectsIgnored(t *testing.T) { func TestDVBSubBlockPixelsBounded(t *testing.T) { fill := dvbRCS(0, true, dvbMaxDim, dvbMaxDim, 3, 0, 1) d := newDVBSub(t) - if _, err := d.Decode(concat(fill, fill, fill, fill)); err != nil { - t.Fatalf("four fills of a full-size region: %v", err) + if _, err := d.Decode(concat(fill, fill)); err != nil { + t.Fatalf("two fills of a full-size region: %v", err) } - _, err := d.Decode(concat(fill, fill, fill, fill, fill)) + _, err := d.Decode(concat(fill, fill, fill)) if err == nil || !strings.Contains(err.Error(), "fills and draws more than") { t.Fatalf("err = %v, want the block's pixel bound", err) } diff --git a/mp4/concat.go b/mp4/concat.go index 9d19fa1..1a1135b 100644 --- a/mp4/concat.go +++ b/mp4/concat.go @@ -435,7 +435,7 @@ func writeConcatSubtitles(o *Options, fs *mkv.FS, outDir string, results []*hlsR var whole []subtitle.Cue for k, res := range results { bounds := res.bounds - cuesLocal := res.subs[j].cues + cuesLocal := subtitle.ShiftCues(res.subs[j].cues, o.SubtitleOffsetMs) for n := range res.durs { segStart := bounds[n] var segEnd int64 = math.MaxInt64 diff --git a/mp4/concat_suboffset_test.go b/mp4/concat_suboffset_test.go new file mode 100644 index 0000000..063295d --- /dev/null +++ b/mp4/concat_suboffset_test.go @@ -0,0 +1,69 @@ +package mp4 + +import ( + "bytes" + "context" + "os" + "path/filepath" + "sort" + "testing" +) + +func concatVTT(t *testing.T, offset int64) []byte { + t.Helper() + srcs := []string{buildConcatSource(t, 2000, "eng", "a", 100), buildConcatSource(t, 2000, "eng", "b", 100)} + o := Options{SegmentMs: 500, SubtitleOffsetMs: offset} + var all bytes.Buffer + dir := t.TempDir() + if err := RemuxConcatToHLS(context.Background(), srcs, dir, o); err != nil { + t.Fatal(err) + } + names, _ := filepath.Glob(filepath.Join(dir, "*.vtt")) + sort.Strings(names) + for _, n := range names { + b, _ := os.ReadFile(n) + all.Write(b) + } + return all.Bytes() +} + +// TestConcatAppliesSubtitleOffset: concat-hls lists --sub-offset; the cues it writes must move with it. +func TestConcatAppliesSubtitleOffset(t *testing.T) { + base, shifted := concatVTT(t, 0), concatVTT(t, 300) + if len(base) == 0 { + t.Fatal("fixture: no WebVTT written") + } + if bytes.Equal(base, shifted) { + t.Errorf("a 300 ms subtitle offset changed nothing in the WebVTT of a full-pass concat:\n%s", base) + } +} + +// The on-demand concat serves the same cues as the full pass, offset included. +func TestConcatPlanAppliesSubtitleOffset(t *testing.T) { + srcs := []string{buildConcatSource(t, 2000, "eng", "a", 100), buildConcatSource(t, 2000, "eng", "b", 100)} + o := Options{SegmentMs: 500, SubtitleOffsetMs: 300} + dir := t.TempDir() + if err := RemuxConcatToHLS(context.Background(), srcs, dir, o); err != nil { + t.Fatal(err) + } + cp, err := PlanConcat(context.Background(), srcs, o) + if err != nil { + t.Fatal(err) + } + names, _ := filepath.Glob(filepath.Join(dir, "*.vtt")) + more, _ := filepath.Glob(filepath.Join(dir, "p*", "*.vtt")) + if len(names) == 0 || len(more) == 0 { + t.Fatal("fixture: no WebVTT written") + } + for _, n := range append(names, more...) { + want, _ := os.ReadFile(n) + rel, _ := filepath.Rel(dir, n) + got, _, err := cp.Resource(context.Background(), filepath.ToSlash(rel)) + if err != nil { + t.Fatalf("%s: %v", rel, err) + } + if !bytes.Equal(got, want) { + t.Errorf("%s: the plan serves\n%s\nthe full pass wrote\n%s", rel, got, want) + } + } +} diff --git a/mp4/concatplan.go b/mp4/concatplan.go index 5450b7c..bf8812c 100644 --- a/mp4/concatplan.go +++ b/mp4/concatplan.go @@ -262,16 +262,15 @@ func (cp *ConcatPlan) windowedSubtitle(ctx context.Context, k, j, n int) ([]byte if n < 0 || n >= p.segCount { return nil, noResource("subtitle segment %d out of range for part %d (0..%d)", n, k, p.segCount-1) } - segStart := p.bounds[n] - var segEnd int64 = math.MaxInt64 - if n+1 < p.segCount { - segEnd = p.bounds[n+1] - } - cues, err := p.subCuesForWindow(ctx, j, segStart, segEnd) + window, err := p.subtitleWindow(ctx, j, n) if err != nil { return nil, err } - return shiftWindowVTT(cues, segStart, segEnd, cp.cumMs[k]) + var buf strings.Builder + if err := subtitle.WriteWebVTT(&buf, shiftCues(window, cp.cumMs[k])); err != nil { + return nil, err + } + return []byte(buf.String()), nil } // wholeSubtitle builds the j-th subtitle rendition's whole-presentation @@ -287,7 +286,7 @@ func (cp *ConcatPlan) wholeSubtitle(ctx context.Context, j int) ([]byte, error) if err != nil { return nil, err } - all = append(all, shiftCues(cues, cp.cumMs[k])...) + all = append(all, shiftCues(subtitle.ShiftCues(cues, p.opts.SubtitleOffsetMs), cp.cumMs[k])...) } var buf strings.Builder if err := subtitle.WriteWebVTT(&buf, all); err != nil { diff --git a/mp4/hlsplan_subtitle.go b/mp4/hlsplan_subtitle.go index aa87641..5af914d 100644 --- a/mp4/hlsplan_subtitle.go +++ b/mp4/hlsplan_subtitle.go @@ -554,6 +554,19 @@ func (p *HLSPlan) subtitleSegment(ctx context.Context, i, n int) ([]byte, error) if err := p.checkSource(); err != nil { return nil, err } + window, err := p.subtitleWindow(ctx, i, n) + if err != nil { + return nil, err + } + var buf strings.Builder + if err := subtitle.WriteWebVTT(&buf, window); err != nil { + return nil, err + } + return []byte(buf.String()), nil +} + +// subtitleWindow is the cues of rendition i that segment n shows, Options.SubtitleOffsetMs applied. +func (p *HLSPlan) subtitleWindow(ctx context.Context, i, n int) ([]subtitle.Cue, error) { segStart := p.bounds[n] var segEnd int64 = math.MaxInt64 if n+1 < p.segCount { @@ -581,9 +594,5 @@ func (p *HLSPlan) subtitleSegment(ctx context.Context, i, n int) ([]byte, error) window = append(window, cue) } } - var buf strings.Builder - if err := subtitle.WriteWebVTT(&buf, window); err != nil { - return nil, err - } - return []byte(buf.String()), nil + return window, nil } diff --git a/mp4/inband_colour.go b/mp4/inband_colour.go index 9175cf2..22c8484 100644 --- a/mp4/inband_colour.go +++ b/mp4/inband_colour.go @@ -177,6 +177,9 @@ func prefixLen(l sampleLoc) int64 { return min(int64(l.size), inbandScanCap) } // HEVC SPS VUI (and ATC SEI), reusing the reader package's logic. Best-effort: // any failure leaves the colour unset, exactly as without the option. func fillInBandColour(r io.ReadSeeker, mv *movie, c *mkv.Container) { + if mv.fragmented { + fragHeadSamples(r, mv) + } for i := range mv.tracks { if i >= len(c.Tracks) { break @@ -200,3 +203,101 @@ func fillInBandColour(r io.ReadSeeker, mv *movie, c *mkv.Container) { reader.ApplyInBandColour(mt, buf) } } + +// maxBoxesToFirstMoof bounds the top-level boxes fragHeadSamples steps over looking for the first moof. +const maxBoxesToFirstMoof = 32 + +// fragHeadSamples gives the tracks of a fragmented movie the place of their first samples, which the first moof +// states: their sample tables are empty, so the in-band fallback had nothing to read. Best-effort, and the movie +// keeps no sample of it. +func fragHeadSamples(r io.ReadSeeker, mv *movie) { + missing := false + for i := range mv.tracks { + t := &mv.tracks[i] + if t.firstSampleSize != 0 { + continue + } + if len(t.samples) == 0 { + missing = true + continue + } + // A full parse already walked the fragments: the samples are here. + t.firstSampleOffset, t.firstSampleSize = t.samples[0].offset, t.samples[0].size + for _, s := range t.samples[:min(len(t.samples), headSampleCount)] { + t.headSamples = append(t.headSamples, sampleLoc{off: s.offset, size: s.size}) + } + } + if !missing { + return + } + size, err := r.Seek(0, io.SeekEnd) + if err != nil { + return + } + var hdr [16]byte + off := int64(0) + for n := 0; n < maxBoxesToFirstMoof && off+8 <= size; n++ { + if _, err := r.Seek(off, io.SeekStart); err != nil { + return + } + if _, err := io.ReadFull(r, hdr[:8]); err != nil { + return + } + boxSize, headerLen := int64(binary.BigEndian.Uint32(hdr[:4])), int64(8) + switch boxSize { + case 1: + if _, err := io.ReadFull(r, hdr[8:16]); err != nil { + return + } + boxSize, headerLen = int64(binary.BigEndian.Uint64(hdr[8:16])), 16 + case 0: + boxSize = size - off + } + if boxSize < headerLen || boxSize > size-off { + return + } + if string(hdr[4:8]) != "moof" { + off += boxSize + continue + } + if boxSize-headerLen > maxFragMoofBytes { + return + } + payload, err := readExact(r, boxSize-headerLen) + if err != nil { + return + } + firstMoofSamples(payload, off, mdatEnd(r, off+boxSize, size), mv) + return + } +} + +// firstMoofSamples parses one moof for the first samples of each track that has none, and puts the movie back as it was. +func firstMoofSamples(moof []byte, moofStart, limit int64, mv *movie) { + type saved struct { + n int + end int64 + } + before, held := make([]saved, len(mv.tracks)), mv.fragHeld + mv.trackIdx = make(map[uint32]int, len(mv.tracks)) + for i := range mv.tracks { + before[i] = saved{len(mv.tracks[i].samples), mv.tracks[i].fragDecodeEnd} + if _, dup := mv.trackIdx[mv.tracks[i].trackID]; !dup { + mv.trackIdx[mv.tracks[i].trackID] = i + } + } + err := parseMoofSamples(moof, moofStart, mv.trex, mv, limit) + mv.trackIdx, mv.fragHeld = nil, held + for i := range mv.tracks { + t := &mv.tracks[i] + fresh := t.samples[before[i].n:] + if err == nil && t.firstSampleSize == 0 && before[i].n == 0 && len(fresh) > 0 { + t.firstSampleOffset, t.firstSampleSize = fresh[0].offset, fresh[0].size + t.headSamples = t.headSamples[:0] + for _, s := range fresh[:min(len(fresh), headSampleCount)] { + t.headSamples = append(t.headSamples, sampleLoc{off: s.offset, size: s.size}) + } + } + t.samples, t.fragDecodeEnd = t.samples[:before[i].n], before[i].end + } +} diff --git a/mp4/inband_frag_test.go b/mp4/inband_frag_test.go new file mode 100644 index 0000000..8da64d0 --- /dev/null +++ b/mp4/inband_frag_test.go @@ -0,0 +1,52 @@ +package mp4 + +import ( + "bytes" + "testing" +) + +// TestFragmentedHeadSamples: a fragmented movie read head-only has empty sample tables, so the first-sample +// fallback had nothing to read (an avc3 or hev1 track kept no profile). The first moof gives each track the place +// of its first samples, the same a full parse finds, and the movie keeps no sample of it. +func TestFragmentedHeadSamples(t *testing.T) { + data, _ := makeFragmentedMP4(t) + full, err := parseMP4(bytes.NewReader(data), int64(len(data)), sampleFull) + if err != nil { + t.Fatal(err) + } + mv, err := parseMP4(bytes.NewReader(data), int64(len(data)), sampleNone) + if err != nil { + t.Fatal(err) + } + vt, want := videoTrack(mv), videoTrack(full) + if vt == nil || want == nil || len(want.samples) < 2 { + t.Fatal("fixture: no video samples") + } + if vt.firstSampleSize != 0 || len(vt.samples) != 0 { + t.Fatalf("head-only: first sample size %d, %d samples; want none", vt.firstSampleSize, len(vt.samples)) + } + endBefore := vt.fragDecodeEnd + fragHeadSamples(bytes.NewReader(data), mv) + if vt.firstSampleOffset != want.samples[0].offset || vt.firstSampleSize != want.samples[0].size { + t.Errorf("first sample at %d (%d bytes), want %d (%d)", vt.firstSampleOffset, vt.firstSampleSize, want.samples[0].offset, want.samples[0].size) + } + if len(vt.headSamples) < 2 || len(vt.headSamples) > headSampleCount { + t.Fatalf("%d head samples, want 2..%d", len(vt.headSamples), headSampleCount) + } + for i, l := range vt.headSamples { + if l.off != want.samples[i].offset || l.size != want.samples[i].size { + t.Errorf("head sample %d at %d (%d bytes), want %d (%d)", i, l.off, l.size, want.samples[i].offset, want.samples[i].size) + } + } + if len(vt.samples) != 0 || vt.fragDecodeEnd != endBefore || mv.trackIdx != nil { + t.Errorf("the movie kept %d samples, decode end %d (was %d): the head-only read must stay as it was", len(vt.samples), vt.fragDecodeEnd, endBefore) + } + + // After a full parse the samples are already here: no fragment is read again. + fv := videoTrack(full) + fv.firstSampleSize, fv.headSamples = 0, nil + fragHeadSamples(bytes.NewReader(nil), full) + if fv.firstSampleSize != want.samples[0].size || len(fv.headSamples) == 0 { + t.Errorf("after a full parse: first sample size %d, %d head samples", fv.firstSampleSize, len(fv.headSamples)) + } +} diff --git a/mp4/parse.go b/mp4/parse.go index e26fa2d..01d394d 100644 --- a/mp4/parse.go +++ b/mp4/parse.go @@ -131,16 +131,17 @@ type movie struct { tracks []inTrack chapters []mkv.Chapter dropped []DroppedTrack - durationMs int64 // from mvhd, used when the sample table was not built - tags []mkv.SimpleTag // file-level metadata from udta/meta/ilst - title string // ©nam, for Info.Title - cover *mkv.Attachment // covr cover art, carried as an MKV attachment - hashes map[uint32]string // freeform CONTENT_SHA256_ atoms, for VerifyContentHashes - fragmented bool // an mvex box is present → sample data is in moof fragments - mehdKnown bool // the mvex's mehd stated the fragments' total duration - chapterTrak []byte // the trak of a QuickTime chapter track (tref/chap), read when there is no chpl - fragHeld int64 // the samples every track holds, kept by readFragmentSamples for each traf's room - trackIdx map[uint32]int // tracks by track_ID (the first of an ID), for trackByID while fragments are read + durationMs int64 // from mvhd, used when the sample table was not built + tags []mkv.SimpleTag // file-level metadata from udta/meta/ilst + title string // ©nam, for Info.Title + cover *mkv.Attachment // covr cover art, carried as an MKV attachment + hashes map[uint32]string // freeform CONTENT_SHA256_ atoms, for VerifyContentHashes + fragmented bool // an mvex box is present → sample data is in moof fragments + mehdKnown bool // the mvex's mehd stated the fragments' total duration + chapterTrak []byte // the trak of a QuickTime chapter track (tref/chap), read when there is no chpl + fragHeld int64 // the samples every track holds, kept by readFragmentSamples for each traf's room + trackIdx map[uint32]int // tracks by track_ID (the first of an ID), for trackByID while fragments are read + trex map[uint32]trexDefault // the mvex defaults, kept for the first fragment's samples (in-band fallback) } // memBox is a box parsed from an in-memory buffer. @@ -330,6 +331,9 @@ func parseMoov(moovPayload []byte, size int64, mode sampleMode) (*movie, error) // real per-sample data (frame rate, keyframes) lives in the moof fragments, // which a head-only probe does not read. Record it so the caller can fall back. mv.fragmented = hasMemBox(moovBoxes, "mvex") + if mv.fragmented { + mv.trex = parseTrexDefaults(moovBoxes) + } // mvhd carries the movie timescale (needed to convert empty-edit durations, // which are in the movie timebase) and the movie duration (used as the metadata