Skip to content

Commit ed0e6af

Browse files
Vincent Herbstclaude
andcommitted
fix(dv5): rebuild hvcC with in-band parameter sets for empty-config MP4s
The 2.0.1 colr fix put PQ signaling on the output sample entry but AVPlayer still failed the asset with CoreMediaErrorDomain -4 and `item.tracks[*].fourCC=<no fdesc>` because the source MP4's hvcC carries only the 22-byte configuration header (numOfArrays = 0) with VPS / SPS / PPS in-band on every IRAP packet (issue #19 Wandering Earth 2 WEB-DL). The mp4 muxer stream-copied the empty hvcC through to init.mp4, and CMVideoFormatDescription cannot be built from a dvh1 sample entry whose configuration record has no parameter set arrays. The matroska demuxer doesn't hit this because matroska parameter sets live in the `CodecPrivate` block which FFmpeg lifts into codecpar.extradata as a complete annex-B sequence that the mp4 muxer's `ff_isom_write_hvcc` then rebuilds properly. Scan the first IRAP packet for VPS / SPS / PPS NAL units, build a proper hvcC byte sequence (header + 3 parameter set arrays), and replace the output stream's codecpar.extradata before avformat_write_header. Local repro from issue #19's sample (Dropbox Wandering Earth 2 WEB-DL): aetherctl serve loopback now plays in QuickTime / AVPlayer with current_time advancing past 9 s, init.mp4 has all four boxes (dvh1 + hvcC 125 B with params + colr nclx 9/16/9 + dvcC P5 L6 compat=0). Gated on the precise signal: HEVC codec, extradata >= 23 B with byte 22 = 0, NALU length size 4. Anything else falls through to the existing stream-copy path. Scan budget is 16 packets. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 0b02347 commit ed0e6af

3 files changed

Lines changed: 197 additions & 6 deletions

File tree

‎Sources/AetherEngine/Video/HLSSegmentProducer.swift‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -62,19 +62,25 @@ final class HLSSegmentProducer: @unchecked Sendable {
6262
/// Optional color-signaling override forwarded to the muxer.
6363
/// See `MP4SegmentMuxer.ColorOverride`.
6464
let colorOverride: MP4SegmentMuxer.ColorOverride?
65+
/// Optional replacement for the source's `codecpar.extradata`
66+
/// before `avformat_write_header`. See
67+
/// `MP4SegmentMuxer.VideoConfig.extradataOverride`.
68+
let extradataOverride: [UInt8]?
6569

6670
init(
6771
codecpar: UnsafePointer<AVCodecParameters>,
6872
timeBase: AVRational,
6973
codecTagOverride: String?,
7074
stripDolbyVisionMetadata: Bool = false,
71-
colorOverride: MP4SegmentMuxer.ColorOverride? = nil
75+
colorOverride: MP4SegmentMuxer.ColorOverride? = nil,
76+
extradataOverride: [UInt8]? = nil
7277
) {
7378
self.codecpar = codecpar
7479
self.timeBase = timeBase
7580
self.codecTagOverride = codecTagOverride
7681
self.stripDolbyVisionMetadata = stripDolbyVisionMetadata
7782
self.colorOverride = colorOverride
83+
self.extradataOverride = extradataOverride
7884
}
7985
}
8086

@@ -566,7 +572,8 @@ final class HLSSegmentProducer: @unchecked Sendable {
566572
timeBase: videoConfig.timeBase,
567573
codecTagOverride: videoConfig.codecTagOverride,
568574
stripDolbyVisionMetadata: videoConfig.stripDolbyVisionMetadata,
569-
colorOverride: videoConfig.colorOverride
575+
colorOverride: videoConfig.colorOverride,
576+
extradataOverride: videoConfig.extradataOverride
570577
)
571578
let muxerAudio: MP4SegmentMuxer.AudioConfig? = audioConfig.map { a in
572579
MP4SegmentMuxer.AudioConfig(codecpar: a.codecpar, timeBase: a.inputTimeBase)

‎Sources/AetherEngine/Video/HLSVideoEngine.swift‎

Lines changed: 144 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -562,7 +562,30 @@ public final class HLSVideoEngine: @unchecked Sendable {
562562
// that behavior for DV-routed-as-HDR10 is the right default.
563563
let hdcpLevel: String? = nil
564564

565-
// 5. Position the demuxer at the file's first packet so the
565+
// 5. Scan for in-band HEVC parameter sets when the source's
566+
// hvcC carries only the configuration header (numOfArrays
567+
// = 0). Some DV Profile 5 MP4 encoders ship parameter sets
568+
// in-band on every IRAP instead of in the configuration
569+
// record (issue #19 Wandering Earth 2 WEB-DL). Without
570+
// VPS / SPS / PPS in the output hvcC, AVPlayer cannot
571+
// build a CMVideoFormatDescription for the dvh1 sample
572+
// entry and the item fails with CoreMediaErrorDomain -4.
573+
// Reads consume packets; the seek-to-0 below resets the
574+
// cursor for the producer pump.
575+
let hevcExtradataOverride = rebuildHEVCExtradataWithInBandParameterSets(
576+
demuxer: dem,
577+
videoStreamIndex: videoIndex,
578+
codecpar: codecpar
579+
)
580+
if let rebuilt = hevcExtradataOverride {
581+
EngineLog.emit(
582+
"[HLSVideoEngine] rebuilt hvcC with in-band parameter sets: "
583+
+ "\(codecpar.pointee.extradata_size) B → \(rebuilt.count) B",
584+
category: .session
585+
)
586+
}
587+
588+
// 6. Position the demuxer at the file's first packet so the
566589
// producer's pump starts from byte zero. The cue prewarm
567590
// above moved the cursor mid-file; libavformat's index is
568591
// populated now, this seek-to-0 is cheap.
@@ -605,7 +628,8 @@ public final class HLSVideoEngine: @unchecked Sendable {
605628
timeBase: videoTimeBase,
606629
codecTagOverride: codecTagOverride,
607630
stripDolbyVisionMetadata: stripDolbyVisionMetadata,
608-
colorOverride: p5ColorOverride
631+
colorOverride: p5ColorOverride,
632+
extradataOverride: hevcExtradataOverride
609633
)
610634
self.videoStreamIndex = videoIndex
611635
self.savedVideoConfig = videoConfig
@@ -1351,7 +1375,8 @@ public final class HLSVideoEngine: @unchecked Sendable {
13511375
timeBase: vcfg.timeBase,
13521376
codecTagOverride: vcfg.codecTagOverride,
13531377
stripDolbyVisionMetadata: vcfg.stripDolbyVisionMetadata,
1354-
colorOverride: vcfg.colorOverride
1378+
colorOverride: vcfg.colorOverride,
1379+
extradataOverride: vcfg.extradataOverride
13551380
)
13561381
let probeAudio = MP4SegmentMuxer.AudioConfig(
13571382
codecpar: cfg.codecpar,
@@ -1681,6 +1706,122 @@ public final class HLSVideoEngine: @unchecked Sendable {
16811706
return trc == AVCOL_TRC_SMPTE2084 || trc == AVCOL_TRC_ARIB_STD_B67
16821707
}
16831708

1709+
/// When the source HEVC's `hvcC` (in `codecpar.extradata`) carries
1710+
/// the configuration header but no VPS / SPS / PPS arrays, scan
1711+
/// the first packets for in-band parameter sets and return a
1712+
/// rebuilt `hvcC` byte sequence with those arrays populated.
1713+
/// Returns nil when the source already has parameter set arrays,
1714+
/// when the source uses a non-4-byte NALU length size, or when
1715+
/// the scan exhausts the budget without finding all three NAL
1716+
/// types.
1717+
///
1718+
/// Some DV Profile 5 MP4 encoders write only the 23-byte hvcC
1719+
/// header (`numOfArrays = 0`) and leave VPS / SPS / PPS in-band
1720+
/// in every IRAP packet (issue #19 Wandering Earth 2 WEB-DL).
1721+
/// FFmpeg's mp4 muxer stream-copies that hvcC through, so the
1722+
/// output fMP4 has a `dvh1` sample entry that AVPlayer cannot
1723+
/// build a `CMVideoFormatDescription` from. AVPlayer's symptom is
1724+
/// `item.tracks count=2` but `fourCC=<no fdesc>` and
1725+
/// `item.status .failed` with `CoreMediaErrorDomain -4`. The
1726+
/// matroska demuxer doesn't hit this because matroska parameter
1727+
/// sets are in the `CodecPrivate` block which FFmpeg lifts into
1728+
/// `codecpar.extradata` as a complete annex-B sequence that the
1729+
/// mp4 muxer's `ff_isom_write_hvcc` then rebuilds properly.
1730+
///
1731+
/// Caller is expected to seek the demuxer back to a known
1732+
/// position after this returns, since extracting consumes
1733+
/// packets.
1734+
private func rebuildHEVCExtradataWithInBandParameterSets(
1735+
demuxer: Demuxer,
1736+
videoStreamIndex: Int32,
1737+
codecpar: UnsafePointer<AVCodecParameters>
1738+
) -> [UInt8]? {
1739+
guard codecpar.pointee.codec_id == AV_CODEC_ID_HEVC else { return nil }
1740+
let extradataSize = Int(codecpar.pointee.extradata_size)
1741+
guard extradataSize >= 23, let extradata = codecpar.pointee.extradata else { return nil }
1742+
// hvcC byte 22 is numOfArrays. Non-zero means parameter sets
1743+
// already in the configuration record; nothing to do.
1744+
guard extradata[22] == 0 else { return nil }
1745+
// hvcC byte 21 lower 2 bits + 1 is NALU length size. Anything
1746+
// other than 4 is exotic enough that we bail rather than risk
1747+
// mis-parsing.
1748+
let naluLengthSize = Int(extradata[21] & 0x03) + 1
1749+
guard naluLengthSize == 4 else { return nil }
1750+
1751+
var vps: [UInt8]?
1752+
var sps: [UInt8]?
1753+
var pps: [UInt8]?
1754+
let packetBudget = 16
1755+
var packetsScanned = 0
1756+
1757+
while packetsScanned < packetBudget {
1758+
let readResult: UnsafeMutablePointer<AVPacket>?
1759+
do {
1760+
readResult = try demuxer.readPacket()
1761+
} catch {
1762+
break
1763+
}
1764+
guard let pkt = readResult else { break }
1765+
defer {
1766+
av_packet_unref(pkt)
1767+
var maybePkt: UnsafeMutablePointer<AVPacket>? = pkt
1768+
av_packet_free(&maybePkt)
1769+
}
1770+
packetsScanned += 1
1771+
if pkt.pointee.stream_index != videoStreamIndex { continue }
1772+
guard let pktData = pkt.pointee.data else { continue }
1773+
let pktSize = Int(pkt.pointee.size)
1774+
1775+
var offset = 0
1776+
while offset + naluLengthSize <= pktSize {
1777+
var nalLen = 0
1778+
for i in 0..<naluLengthSize {
1779+
nalLen = (nalLen << 8) | Int(pktData[offset + i])
1780+
}
1781+
offset += naluLengthSize
1782+
if nalLen == 0 || offset + nalLen > pktSize { break }
1783+
// HEVC NAL header: byte 0 = forbidden_zero_bit(1) +
1784+
// nal_unit_type(6) + layer_id high bit(1). NAL unit
1785+
// type is bits 1..6 of byte 0.
1786+
let nalType = (Int(pktData[offset]) >> 1) & 0x3F
1787+
let nalBytes = Array(UnsafeBufferPointer(start: pktData + offset, count: nalLen))
1788+
switch nalType {
1789+
case 32: if vps == nil { vps = nalBytes }
1790+
case 33: if sps == nil { sps = nalBytes }
1791+
case 34: if pps == nil { pps = nalBytes }
1792+
default: break
1793+
}
1794+
offset += nalLen
1795+
}
1796+
1797+
if vps != nil && sps != nil && pps != nil { break }
1798+
}
1799+
1800+
guard let vps, let sps, let pps else { return nil }
1801+
1802+
// Assemble a proper hvcC: keep the source's 22-byte header
1803+
// (configurationVersion + profile / level / chroma / temporal
1804+
// layer fields), set numOfArrays = 3, then append VPS / SPS /
1805+
// PPS arrays. Each array: 1 byte (arrayCompleteness=1 +
1806+
// reserved=0 + nalUnitType), 2 bytes numNalus = 1, 2 bytes
1807+
// nalUnitLength, NAL bytes.
1808+
var hvcC: [UInt8] = []
1809+
hvcC.reserveCapacity(22 + 1 + 5 * 3 + vps.count + sps.count + pps.count)
1810+
for i in 0..<22 { hvcC.append(extradata[i]) }
1811+
hvcC.append(3)
1812+
func appendArray(nalUnitType: UInt8, nal: [UInt8]) {
1813+
hvcC.append(0x80 | (nalUnitType & 0x3F))
1814+
hvcC.append(0); hvcC.append(1)
1815+
let nl = UInt16(nal.count)
1816+
hvcC.append(UInt8(nl >> 8)); hvcC.append(UInt8(nl & 0xFF))
1817+
hvcC.append(contentsOf: nal)
1818+
}
1819+
appendArray(nalUnitType: 32, nal: vps)
1820+
appendArray(nalUnitType: 33, nal: sps)
1821+
appendArray(nalUnitType: 34, nal: pps)
1822+
return hvcC
1823+
}
1824+
16841825
/// Validate that `index` points at an audio stream in the demuxer's
16851826
/// container. Used to gate `audioSourceStreamIndexOverride` so a
16861827
/// stale picker selection (e.g. a stream index from a previous

‎Sources/AetherEngine/Video/MP4SegmentMuxer.swift‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,19 +144,32 @@ final class MP4SegmentMuxer {
144144
let stripDolbyVisionMetadata: Bool
145145
/// Optional color-signaling override. See `ColorOverride`.
146146
let colorOverride: ColorOverride?
147+
/// Optional replacement for the output stream's
148+
/// `codecpar.extradata` after `avcodec_parameters_copy`.
149+
/// Used when the source's hvcC carries only the configuration
150+
/// header (numOfArrays = 0) and parameter sets are in-band,
151+
/// so the engine has rebuilt a proper hvcC with VPS / SPS /
152+
/// PPS arrays for AVPlayer to build a CMVideoFormatDescription
153+
/// from. The mp4 muxer reads `codecpar.extradata` directly
154+
/// into the sample entry's `hvcC` / `avcC` box, so replacing
155+
/// the buffer here is enough to land the rebuilt configuration
156+
/// record in `init.mp4`.
157+
let extradataOverride: [UInt8]?
147158

148159
init(
149160
codecpar: UnsafePointer<AVCodecParameters>,
150161
timeBase: AVRational,
151162
codecTagOverride: String?,
152163
stripDolbyVisionMetadata: Bool = false,
153-
colorOverride: ColorOverride? = nil
164+
colorOverride: ColorOverride? = nil,
165+
extradataOverride: [UInt8]? = nil
154166
) {
155167
self.codecpar = codecpar
156168
self.timeBase = timeBase
157169
self.codecTagOverride = codecTagOverride
158170
self.stripDolbyVisionMetadata = stripDolbyVisionMetadata
159171
self.colorOverride = colorOverride
172+
self.extradataOverride = extradataOverride
160173
}
161174
}
162175

@@ -377,6 +390,9 @@ final class MP4SegmentMuxer {
377390
videoStream.pointee.codecpar.pointee.color_space = co.space
378391
videoStream.pointee.codecpar.pointee.color_range = co.range
379392
}
393+
if let extradata = video.extradataOverride {
394+
Self.replaceExtradata(videoStream.pointee.codecpar, with: extradata)
395+
}
380396

381397
// Audio stream (optional).
382398
if let audio = audio {
@@ -521,6 +537,9 @@ final class MP4SegmentMuxer {
521537
videoStream.pointee.codecpar.pointee.color_space = co.space
522538
videoStream.pointee.codecpar.pointee.color_range = co.range
523539
}
540+
if let extradata = video.extradataOverride {
541+
Self.replaceExtradata(videoStream.pointee.codecpar, with: extradata)
542+
}
524543

525544
// Audio stream (optional).
526545
if let audio = audio {
@@ -850,6 +869,30 @@ final class MP4SegmentMuxer {
850869
AV_PKT_DATA_DOVI_CONF
851870
)
852871
}
872+
873+
/// Replace the output stream's `codecpar.extradata` with the
874+
/// caller-supplied bytes, using FFmpeg's `av_malloc` and the
875+
/// required `AV_INPUT_BUFFER_PADDING_SIZE` trailing pad. Frees
876+
/// the buffer that `avcodec_parameters_copy` placed there.
877+
private static func replaceExtradata(
878+
_ codecpar: UnsafeMutablePointer<AVCodecParameters>,
879+
with bytes: [UInt8]
880+
) {
881+
if codecpar.pointee.extradata != nil {
882+
av_freep(&codecpar.pointee.extradata)
883+
}
884+
codecpar.pointee.extradata_size = 0
885+
let total = bytes.count + Int(AV_INPUT_BUFFER_PADDING_SIZE)
886+
guard let buf = av_malloc(total)?.assumingMemoryBound(to: UInt8.self) else { return }
887+
bytes.withUnsafeBufferPointer { src in
888+
if let base = src.baseAddress {
889+
memcpy(buf, base, bytes.count)
890+
}
891+
}
892+
memset(buf + bytes.count, 0, Int(AV_INPUT_BUFFER_PADDING_SIZE))
893+
codecpar.pointee.extradata = buf
894+
codecpar.pointee.extradata_size = Int32(bytes.count)
895+
}
853896
}
854897

855898
/// Shared mutable state between the FragmentSplitter's

0 commit comments

Comments
 (0)