diff --git a/CHANGELOG.md b/CHANGELOG.md index c67d168..9a7b5fd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,72 +9,19 @@ its series' file in [changelog/](changelog/) when a newer one ships. ## [Unreleased] -## [0.71.0] - 2026-11-20 +## [0.71.1] - 2026-11-20 ### Fixed -- Stray bytes ahead of the first Cluster that happen to decode as an element - header (the tail of an old tag an in-place edit before 0.56.0 could leave) - no longer make `analyze`, `ingest -analyze` and `validate` report a complete - file as cut short, or lose its first Clusters without a word: the block walk - resynchronizes past them as the head reads do. -- A Void or CRC-32 ahead of the first Cluster declaring a few bytes too many - no longer swallows the head of the element behind it: the readers - resynchronize on that element instead of losing it without a word. -- `reindex --resync` and `salvage` keep the Info and Tracks that sit behind - such bytes (the output had no track, exit 0), and `keyframes -walk` no longer - loses the keyframes of the Clusters a stray size led it past. -- A few stray bytes between the last Cluster and the Cues or Tags closing a - finished file (up to 64) end the block walk as the end of the media: such a - file is no longer reported as cut short by `analyze`, nor refused by - `demux`, `split`, `remove-track` and `fingerprint`. A longer run is still - refused: it may hide a Cluster. -- `diagnose` no longer answers healthy when stray bytes sit between the head - elements it reads and the first Cluster: it walks the head to the first - Cluster. -- The strict `reindex`, `reindex-inplace` and `retime` refuse bytes that read - as an element running past the end with the offset and the command that - works (`mkvgo reindex --resync`), not `copy unknown 0x8C body: EOF` nor a - "truncated file" pointing back at the command that refused. -- Bytes that read as a Cluster header too small to hold a block (8 bytes at - most, opening with no element of a Cluster) are passed over as the stray - bytes they are instead of refused as a damaged region, and `diagnose` counts - them. -- `analyze` warns when the file it measured was read past undecodable bytes. -- What a strict block walk now reads past without an error, where it failed - or lost media before: bytes ahead of the first Cluster that decode as an - element whose size leads nowhere or that declare no size, the excess of a - Void or CRC-32 that declares too much, 8 bytes at most read as a Cluster, - 64 at most before the closing elements. `Container.ResyncedBytes`, - `validate`, `diagnose` and `analyze` say so for the head; a tolerant walk - counts them all (`SkippedBytes`). `ReadStream` cannot look past an element - and keeps skipping a header that decodes by its size. -- Bitmap subtitles: a block whose display sets together composite more than - two subtitle planes is passed over as damaged (each composition had its own - picture, 64 MiB for 30 bytes of block); a PGS object's buffer grows with - its data instead of taking the 4 MiB its first segment may declare; a nil - `SubtitleIndex` refuses `MarshalBinary` instead of panicking. -- Bitmap subtitles, again: a PGS block hands back two planes of pictures at - most, not four (256 MiB for 115 bytes of block); a VobSub control sequence - with no end command stops where the next one starts instead of running its - header as commands (a picture forced on, at the wrong time); `extract-subtitle - -format png` encodes a picture shown again once, each cue keeping its file. -- `to-mp4`, `to-webm`, `to-hls`, `demux`, `split` and `remove-track` warn when - the Matroska source was read past undecodable bytes between its elements, - and exit 3 under `--exit-damaged`: they said nothing. - -### Changed - -- A VobSub header with no `palette:` line (an old `.idx`, whose palette is in - the `.ifo` beside it, or a track muxed from one) is read instead of refused: - each picture is drawn in greys from black to white in the order of the pixel - values it shows. A header with no `size:` line is still refused, and the - refusal no longer speaks of a CodecPrivate for a `.idx` file. - -### Added - -- `Diagnosis.ResyncedBytes` (`resynced_bytes` in JSON): the bytes the head - read passed over ahead of the first Cluster, so a caller needs no second - read to count them. `WithWholeHead` (`reader` and `matroska`) gives the - same count to a head read of its own. A Void declaring too much counts for - its excess. +- 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. diff --git a/changelog/0.70-0.79.md b/changelog/0.70-0.79.md index 1c9df84..2df46e8 100644 --- a/changelog/0.70-0.79.md +++ b/changelog/0.70-0.79.md @@ -2,6 +2,76 @@ 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.0] - 2026-11-20 + +### Fixed + +- Stray bytes ahead of the first Cluster that happen to decode as an element + header (the tail of an old tag an in-place edit before 0.56.0 could leave) + no longer make `analyze`, `ingest -analyze` and `validate` report a complete + file as cut short, or lose its first Clusters without a word: the block walk + resynchronizes past them as the head reads do. +- A Void or CRC-32 ahead of the first Cluster declaring a few bytes too many + no longer swallows the head of the element behind it: the readers + resynchronize on that element instead of losing it without a word. +- `reindex --resync` and `salvage` keep the Info and Tracks that sit behind + such bytes (the output had no track, exit 0), and `keyframes -walk` no longer + loses the keyframes of the Clusters a stray size led it past. +- A few stray bytes between the last Cluster and the Cues or Tags closing a + finished file (up to 64) end the block walk as the end of the media: such a + file is no longer reported as cut short by `analyze`, nor refused by + `demux`, `split`, `remove-track` and `fingerprint`. A longer run is still + refused: it may hide a Cluster. +- `diagnose` no longer answers healthy when stray bytes sit between the head + elements it reads and the first Cluster: it walks the head to the first + Cluster. +- The strict `reindex`, `reindex-inplace` and `retime` refuse bytes that read + as an element running past the end with the offset and the command that + works (`mkvgo reindex --resync`), not `copy unknown 0x8C body: EOF` nor a + "truncated file" pointing back at the command that refused. +- Bytes that read as a Cluster header too small to hold a block (8 bytes at + most, opening with no element of a Cluster) are passed over as the stray + bytes they are instead of refused as a damaged region, and `diagnose` counts + them. +- `analyze` warns when the file it measured was read past undecodable bytes. +- What a strict block walk now reads past without an error, where it failed + or lost media before: bytes ahead of the first Cluster that decode as an + element whose size leads nowhere or that declare no size, the excess of a + Void or CRC-32 that declares too much, 8 bytes at most read as a Cluster, + 64 at most before the closing elements. `Container.ResyncedBytes`, + `validate`, `diagnose` and `analyze` say so for the head; a tolerant walk + counts them all (`SkippedBytes`). `ReadStream` cannot look past an element + and keeps skipping a header that decodes by its size. +- Bitmap subtitles: a block whose display sets together composite more than + two subtitle planes is passed over as damaged (each composition had its own + picture, 64 MiB for 30 bytes of block); a PGS object's buffer grows with + its data instead of taking the 4 MiB its first segment may declare; a nil + `SubtitleIndex` refuses `MarshalBinary` instead of panicking. +- Bitmap subtitles, again: a PGS block hands back two planes of pictures at + most, not four (256 MiB for 115 bytes of block); a VobSub control sequence + with no end command stops where the next one starts instead of running its + header as commands (a picture forced on, at the wrong time); `extract-subtitle + -format png` encodes a picture shown again once, each cue keeping its file. +- `to-mp4`, `to-webm`, `to-hls`, `demux`, `split` and `remove-track` warn when + the Matroska source was read past undecodable bytes between its elements, + and exit 3 under `--exit-damaged`: they said nothing. + +### Changed + +- A VobSub header with no `palette:` line (an old `.idx`, whose palette is in + the `.ifo` beside it, or a track muxed from one) is read instead of refused: + each picture is drawn in greys from black to white in the order of the pixel + values it shows. A header with no `size:` line is still refused, and the + refusal no longer speaks of a CodecPrivate for a `.idx` file. + +### Added + +- `Diagnosis.ResyncedBytes` (`resynced_bytes` in JSON): the bytes the head + read passed over ahead of the first Cluster, so a caller needs no second + read to count them. `WithWholeHead` (`reader` and `matroska`) gives the + same count to a head read of its own. A Void declaring too much counts for + its excess. + ## [0.70.0] - 2026-11-19 ### Changed diff --git a/cmd/mkvgo/main.go b/cmd/mkvgo/main.go index aac84b9..5a053da 100644 --- a/cmd/mkvgo/main.go +++ b/cmd/mkvgo/main.go @@ -254,8 +254,9 @@ Global flags: retime, salvage...; ignored by commands without a report); an error goes to stderr as {"error":"...","exit":N} -in-band Complete a video track's description from its first sample - when the header leaves it short: colour behind a bare hvcC, - VP9 profile with no vpcC, HDR10 static metadata kept in-band + when the header leaves it short: colour behind a bare hvcC + or av1C, VP9 profile or colour the header does not state, + HDR10 static metadata kept in-band (info, tracks, probe; one bounded read; ignored elsewhere) -fps-reads Let the frame-rate estimate of a Matroska track without DefaultDuration read the block headers it needs in the first diff --git a/docs/cli.md b/docs/cli.md index 64e64f8..e26840b 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 a bare `hvcC`, a VP9 profile with no `vpcC`, 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, 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 f78b069..37b22c3 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). The same option covers **VP9 without a `vpcC`** - how WebM is normally muxed: the keyframe's uncompressed header is the only place the stream says its profile, 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. 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 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/model.go b/mkv/model.go index 2b573c5..e691e1e 100644 --- a/mkv/model.go +++ b/mkv/model.go @@ -323,7 +323,7 @@ type Track struct { Unmodeled []RawElement `json:"-"` // ColourDetermined reports that the colour was actually read from a source - the // container Colour element, an MP4 colr box, or the codec bitstream's colour - // signalling (H.264/HEVC VUI, AV1 color_config, VP9 vpcC) - even when it resolves + // signalling (H.264/HEVC VUI, AV1 color_config, VP9 vpcC or keyframe header) - even when it resolves // to "unspecified" (all Color* nil). It distinguishes a confirmed-SDR/unspecified // stream (true, Color* nil) from one whose colour could not be read at all // (false): a caller should treat the latter, not the former, as "fall back". diff --git a/mkv/reader/inband_colour.go b/mkv/reader/inband_colour.go index cfcd88f..58baee2 100644 --- a/mkv/reader/inband_colour.go +++ b/mkv/reader/inband_colour.go @@ -186,12 +186,15 @@ func WithSampledKeyframes(n int) ReadOption { // sample triggers a read of that sample: // // - HEVC whose colour is absent from BOTH the container and the codec-private -// SPS - a bare hvcC with no NAL arrays, as streaming-style muxes write when +// SPS - an hvcC that holds no SPS, as streaming-style muxes write when // they keep the parameter sets in-band: the SPS is recovered and its colour // VUI parsed; -// - VP9 with no vpcC in CodecPrivate - how WebM is normally muxed - whose -// profile, bit depth and chroma subsampling (Profile, VideoBitDepth, -// PixelFormat, ColorRange) exist only in the keyframe's uncompressed header; +// - AV1 whose container names no colour and whose av1C holds no sequence +// header: the first temporal unit's is read; +// - VP9 whose container names no colour, or with no vpcC in CodecPrivate - +// how WebM is normally muxed: profile, bit depth, chroma subsampling and +// colour (Profile, VideoBitDepth, PixelFormat, ColorRange, the colour +// code points) come from the keyframe's uncompressed header; // - an HDR (PQ or HLG) HEVC or AV1 track whose static metadata is incomplete // in the container - no MasteringMetadata, or no MaxCLL/MaxFALL - as most // HDR10 muxes write it, keeping only the in-band copy (HEVC SEI 137/144, AV1 @@ -336,7 +339,7 @@ func activeTracks[N, S any](need map[uint64]N, scans map[uint64]S) []uint64 { // NeedsInBandColour reports whether t is a video track whose stream // description can only be completed from its first sample: an HEVC track with a -// bare hvcC and no colour, a VP9 track with no vpcC, or an HDR HEVC/AV1 track +// hvcC that holds no SPS, an av1C that holds no sequence header, a VP9 track with no colour, or an HDR HEVC/AV1 track // 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. @@ -352,25 +355,34 @@ func NeedsInBandColour(t *mkv.Track) bool { return needsInBandColour(t) || needs func ApplyInBandColour(t *mkv.Track, frame []byte) { applyInBandHeader(t, frame) } // needsInBandColour reports whether t is a video track whose description can -// only come from its first sample: HEVC with no container/SPS colour yet and a -// hvcC that holds no NAL arrays (numOfArrays == 0, byte 22 of the configuration -// record); or VP9 with no profile yet - no vpcC in CodecPrivate, the profile -// then exists only in the keyframe header. +// only come from its first sample: no colour from the container, and a codec +// record that states none - a VP9 track (the keyframe header has it, and the +// profile no vpcC gave), an AV1 av1C with no sequence header, an hvcC with no SPS. func needsInBandColour(t *mkv.Track) bool { if t.Type != mkv.VideoTrack { return false } - if isVP9Codec(t.Codec) { - return t.Profile == "" + if isVP9Codec(t.Codec) && t.Profile == "" { + return true } if t.ColorTransfer != nil || t.ColorPrimaries != nil || t.ColorSpace != nil { return false } - if !isHEVCCodec(t.Codec) { - return false + switch { + case isVP9Codec(t.Codec): + return true + case isAV1Codec(t.Codec): + return len(t.CodecPrivate) >= 4 && !privateStatesColour(t) + case isHEVCCodec(t.Codec): + return len(t.CodecPrivate) >= 23 && t.CodecPrivate[0] == 1 && !privateStatesColour(t) } - cp := t.CodecPrivate - return len(cp) >= 23 && cp[0] == 1 && cp[22] == 0 + return false +} + +// privateStatesColour reports that the CodecPrivate holds the colour signalling itself, unspecified or not. +func privateStatesColour(t *mkv.Track) bool { + bc := parseCodecColour(t.Codec, t.CodecPrivate) + return bc != nil && bc.determined } // applyInBandHeader dispatches the first-sample parse on the codec: the colour @@ -385,7 +397,12 @@ func applyInBandHeader(t *mkv.Track, frame []byte) { mergeBitstreamColour(t, vp9HeaderColour(h)) } return - case needsInBandColour(t): + case !needsInBandColour(t): + case isAV1Codec(t.Codec): + bc := &bitstreamColour{} + parseAV1OBUs(frame, uint32(t.CodecPrivate[1]>>5), bc) + mergeBitstreamColour(t, bc) + default: applyInBandSPSColour(t, frame) } if needsInBandHDR(t) { diff --git a/mkv/reader/inband_colour_gap_test.go b/mkv/reader/inband_colour_gap_test.go new file mode 100644 index 0000000..ba8dd9b --- /dev/null +++ b/mkv/reader/inband_colour_gap_test.go @@ -0,0 +1,62 @@ +package reader + +import ( + "bytes" + "context" + "testing" +) + +// TestInBandColourAV1BareRecord: an av1C with no sequence header and no +// container colour leaves the colour to the first temporal unit. +func TestInBandColourAV1BareRecord(t *testing.T) { + full := mustHex(t, av1HDRPrivateHex) + tu := append([]byte{0x12, 0x00}, full[4:]...) // temporal delimiter, then the sequence header OBU + data := inBandColourMKV(full[:4], tu) + data = bytes.Replace(data, []byte("V_MPEGH/ISO/HEVC"), []byte("V_AV1\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), 1) + + want, err := ReadMeta(context.Background(), bytes.NewReader(bytes.Replace(inBandColourMKV(full, nil), + []byte("V_MPEGH/ISO/HEVC"), []byte("V_AV1\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"), 1)), "x.mkv") + if err != nil { + t.Fatal(err) + } + w := want.Tracks[0] + if !w.ColourDetermined || w.ColorTransferName() != "smpte2084" { + t.Fatalf("fixture: the full av1C must state PQ, got determined=%v transfer=%q", w.ColourDetermined, w.ColorTransferName()) + } + + base, err := ReadMeta(context.Background(), bytes.NewReader(data), "x.mkv") + if err != nil { + t.Fatal(err) + } + if tr := base.Tracks[0]; tr.ColourDetermined || tr.ColorTransfer != nil { + t.Fatalf("head only: determined=%v transfer=%v, want none", tr.ColourDetermined, tr.ColorTransfer) + } + c, err := ReadMeta(context.Background(), bytes.NewReader(data), "x.mkv", WithInBandColourFallback()) + if err != nil { + t.Fatal(err) + } + tr := c.Tracks[0] + if !tr.ColourDetermined || tr.ColorTransferName() != w.ColorTransferName() || + tr.ColorPrimariesName() != w.ColorPrimariesName() || tr.ColorSpaceName() != w.ColorSpaceName() { + t.Errorf("determined=%v transfer=%q primaries=%q space=%q, want true %q %q %q", tr.ColourDetermined, + tr.ColorTransferName(), tr.ColorPrimariesName(), tr.ColorSpaceName(), + w.ColorTransferName(), w.ColorPrimariesName(), w.ColorSpaceName()) + } +} + +// TestInBandColourHEVCRecordWithoutSPS: an hvcC whose arrays hold no SPS (a VPS +// alone here) states no colour either, so the first sample's SPS is read. +func TestInBandColourHEVCRecordWithoutSPS(t *testing.T) { + sps := extractHEVCSPSNAL(t, mustHex(t, hevcHDRPrivateHex)) + cp := bareHvcC() + cp[22] = 1 + cp = append(cp, 0x20, 0x00, 0x01, 0x00, 0x04, 0x40, 0x01, 0x0c, 0x01) // one array: a 4-byte VPS + data := inBandColourMKV(cp, lenPrefixed4(sps)) + c, err := ReadMeta(context.Background(), bytes.NewReader(data), "x.mkv", WithInBandColourFallback()) + if err != nil { + t.Fatal(err) + } + if tr := c.Tracks[0]; tr.ColorTransferName() != "smpte2084" || !tr.ColourDetermined { + t.Errorf("transfer=%q determined=%v, want smpte2084 true", tr.ColorTransferName(), tr.ColourDetermined) + } +} diff --git a/mkv/reader/vp9.go b/mkv/reader/vp9.go index 9829553..4bdc9d9 100644 --- a/mkv/reader/vp9.go +++ b/mkv/reader/vp9.go @@ -144,7 +144,7 @@ func vp9HeaderColour(h *VP9KeyframeHeader) *bitstreamColour { case 7: // CS_RGB = sRGB (IEC 61966-2-1): identity matrix bc.primaries, bc.transfer, bc.matrix = u16p(1), u16p(13), u16p(0) } - bc.determined = h.ColorSpace != 0 && h.ColorSpace != 6 + bc.determined = h.ColorSpace != 6 // unknown (0) is the stream saying so; 6 is reserved return bc } diff --git a/mkv/reader/vp9_test.go b/mkv/reader/vp9_test.go index 7e005be..f874404 100644 --- a/mkv/reader/vp9_test.go +++ b/mkv/reader/vp9_test.go @@ -147,7 +147,7 @@ func TestVP9InBandHeader(t *testing.T) { {"profile 2 bt2020 leaves transfer open", 2, 5, false, nil, "Profile 2", "yuv420p10le", 10, 9, -1, 9, 1, true}, {"bt601 fixes matrix and transfer only", 0, 1, false, nil, "Profile 0", "yuv420p", 8, -1, 6, 5, 1, true}, {"srgb", 0, 7, true, nil, "Profile 0", "yuv444p", 8, 1, 13, 0, 2, true}, - {"unknown fills nothing", 0, 0, true, nil, "Profile 0", "yuv420p", 8, -1, -1, -1, 2, false}, + {"unknown fills nothing, read all the same", 0, 0, true, nil, "Profile 0", "yuv420p", 8, -1, -1, -1, 2, true}, {"container transfer wins", 2, 5, false, masterElem(mkv.IDColour, uintElem(mkv.IDColourTransfer, 16, 1)), "Profile 2", "yuv420p10le", 10, 9, 16, 9, 1, true}, @@ -288,3 +288,46 @@ func TestParseVP9FeatureMetadataStrict(t *testing.T) { } } } + +// TestVP9FeatureMetadataInBandColour: a Codec Feature Metadata CodecPrivate +// states a profile but no colour, so the keyframe header is still read for it. +func TestVP9FeatureMetadataInBandColour(t *testing.T) { + ctx := context.Background() + cp := []byte{1, 1, 0, 3, 1, 8, 4, 1, 1} // profile 0, 8 bits, 4:2:0, no level + data := vp9MKV(cp, nil, 1920, 1080, vp9KeyframeHeaderBytes(0, 2, false)) + base, err := ReadMeta(ctx, bytes.NewReader(data), "x.mkv") + if err != nil { + t.Fatal(err) + } + if tr := base.Tracks[0]; tr.Profile != "Profile 0" || tr.ColourDetermined || tr.ColorSpace != nil { + t.Fatalf("head only: profile=%q determined=%v space=%v, want Profile 0, no colour", tr.Profile, tr.ColourDetermined, tr.ColorSpace) + } + c, err := ReadMeta(ctx, bytes.NewReader(data), "x.mkv", WithInBandColourFallback()) + if err != nil { + t.Fatal(err) + } + tr := c.Tracks[0] + if !tr.ColourDetermined || tr.ColorSpaceName() != "bt709" || u16v(tr.ColorRange) != 1 { + t.Errorf("determined=%v space=%q range=%d, want true bt709 1", tr.ColourDetermined, tr.ColorSpaceName(), u16v(tr.ColorRange)) + } + + // A Colour element that states the range alone leaves the colour to the keyframe. + rangeOnly := masterElem(mkv.IDColour, uintElem(mkv.IDColourRange, 1, 1)) + c, err = ReadMeta(ctx, bytes.NewReader(vp9MKV(cp, rangeOnly, 1920, 1080, vp9KeyframeHeaderBytes(0, 2, false))), "x.mkv", WithInBandColourFallback()) + if err != nil { + t.Fatal(err) + } + if tr := c.Tracks[0]; tr.ColorSpaceName() != "bt709" { + t.Errorf("with a range-only Colour element: space=%q, want bt709", tr.ColorSpaceName()) + } + + // A container Colour element that names a colour settles it: the first sample is not read. + colour := masterElem(mkv.IDColour, uintElem(mkv.IDColourTransfer, 16, 1)) + c, err = ReadMeta(ctx, bytes.NewReader(vp9MKV(cp, colour, 1920, 1080, vp9KeyframeHeaderBytes(0, 2, false))), "x.mkv", WithInBandColourFallback()) + if err != nil { + t.Fatal(err) + } + if tr := c.Tracks[0]; tr.ColorSpace != nil || u16v(tr.ColorTransfer) != 16 { + t.Errorf("with a Colour element: space=%v transfer=%d, want the element alone", tr.ColorSpace, u16v(tr.ColorTransfer)) + } +}