导出 HDR 视频时,如何写入 PQ 与 HLG 两种 tone mapping 兼容?
解读
国内 iOS/macOS 音视频岗位面试时,这道题考察的是“能不能把 HDR 元数据写进文件,让系统播放器(AVPlayer)和第三方播放器都能正确识别 PQ(Perceptual Quantizer,ST 2084)和 HLG(Hybrid Log-Gamma)两条曲线”。
面试官真正想听的是:
- 你清楚 HDR10(PQ)(HLG)在容器层(MOV/MP4)需要哪些 Box;
- 你能用 AVFoundation 的 Objective-C API 把这些 Box 写进去;
- 你明白 tone mapping 不是滤镜,而是 color tag + 元数据;
- 你能在 MRC/ARC 混合的老代码里把 CMFormatDescription、AVAssetWriter、AVAssetWriterInput 串起来,不崩、不泄漏、不丢帧。
知识点
- Core Media 颜色描述模型
- CMVideoCodecType:'hvc1'(HEVC)必须带 HDR 描述;
- CMFormatDescription 扩展键:
kCMFormatDescriptionExtension_ColorPrimaries = 'nclx'
kCMFormatDescriptionExtension_TransferFunction = 'smpte2084'(PQ) 或 'arib-std-b67'(HLG)
kCMFormatDescriptionExtension_YCbCrMatrix = 'bt2020nc'
- 容器层元数据(ISO/IEC 14496-12)
- 'colr' box:必须出现,记录上述三值;
- 'pasp'、'clap'、'pixi' 可选;
- 'mdcv' box:MasteringDisplayColorVolume(PQ 必须,HLG 可选);
- 'clli' box:ContentLightLevelInfo(PQ 必须,HLG 可选);
- 'hvcC' box:vps/sps/pps 里要含 VUI transfer_characteristics 一致值。
- AVFoundation 写入点
- AVAssetWriterInput 初始化时传 CMFormatDescription;
- 用 - (void)addTrackWithAssociatedTracksOfType:… 挂‘alte’ track,实现双曲线兼容(iOS 16+ 支持);
- 用 metadataAdaptor 写 ‘mdcv’、‘clli’ 到 AVAssetWriterInput 的 track-level metadata;
- 运行时兼容
- 系统 < iOS 13 仅识别 HLG,>13 才识别 PQ;
- 老机型 A9 以前硬编不支持 10-bit,需要回退 8-bit HLG;
- 若用 VideoToolbox 直接写‘hvc1’,需手动拼 HVCC 头,确保 VUI 与 CMFormatDescription 一致,否则 QuickLook 花屏。
答案
下面给出一段可直接搬进公司老项目(MRC)的 Objective-C 实现,兼顾 ARC 新文件调用。思路:先拼 PQ 主轨道,再挂一条 HLG 备用轨道,把‘mdcv’‘clli’写进 PQ 轨道,HLG 轨道只写‘colr’,保证跨版本兼容。
// 1. 创建 writer
NSError *error = nil;
AVAssetWriter *writer = [[AVAssetWriter alloc] initWithURL:outputURL
fileType:AVFileTypeQuickTimeMovie
error:&error];
NSParameterAssert(writer);
// 2. 拼 PQ 的 CMFormatDescription
CMFormatDescriptionRef pqDesc = NULL;
CMVideoCodecType codecType = kCMVideoCodecType_HEVC;
int32_t width = 3840, height = 2160;
CFDictionaryRef pqExtensions = (__bridge CFDictionaryRef)@{
(__bridge NSString *)kCMFormatDescriptionExtension_ColorPrimaries: (__bridge NSString *)kCMFormatDescriptionColorPrimaries_ITU_R_2020,
(__bridge NSString *)kCMFormatDescriptionExtension_TransferFunction: (__bridge NSString *)kCMFormatDescriptionTransferFunction_SMPTE_ST_2084_PQ,
(__bridge NSString *)kCMFormatDescriptionExtension_YCbCrMatrix: (__bridge NSString *)kCMFormatDescriptionYCbCrMatrix_ITU_R_2020,
(__bridge NSString *)kCMFormatDescriptionExtension_MasteringDisplayColorVolume: @(@[@(0),@(0)], @[@(0),@(0)], @[@(0),@(0)], @(1000), @(0), @(1000)), // G,B,R + wp + max/min
(__bridge NSString *)kCMFormatDescriptionExtension_ContentLightLevelInfo: @[@(1000), @(400)] // maxCLL, maxFALL
};
CMVideoFormatDescriptionCreate(kCFAllocatorDefault,
codecType,
width, height,
pqExtensions,
&pqDesc);
// 3. 创建 PQ 输入
AVAssetWriterInput *pqInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo
outputSettings:@{
AVVideoCodecKey: AVVideoCodecTypeHEVC,
AVVideoWidthKey: @(width),
AVVideoHeightKey: @(height),
AVVideoColorPropertiesKey: @{
AVVideoColorPrimariesKey: AVVideoColorPrimaries_ITU_R_2020,
AVVideoTransferFunctionKey: AVVideoTransferFunction_SMPTE_ST_2084_PQ,
AVVideoYCbCrMatrixKey: AVVideoYCbCrMatrix_ITU_R_2020
},
AVVideoCompressionPropertiesKey: @{
AVVideoAllowFrameReorderingKey: @NO,
AVVideoExpectedSourceFrameRateKey: @(30),
AVVideoProfileLevelKey: AVVideoProfileLevelHEVCMain10AutoLevel
}
} sourceFormatHint:pqDesc];
pqInput.expectsMediaDataInRealTime = NO;
[writer addInput:pqInput];
// 4. 把 mdcv/clli 写进 track-level metadata
AVMutableMetadataItem *mdcv = [[AVMutableMetadataItem alloc] init];
mdcv.key = AVMetadataQuickTimeUserDataKeyMasteringDisplayColorVolume;
mdcv.keySpace = AVMetadataKeySpaceQuickTimeUserData;
mdcv.value = @{@“display_primaries”: …, @“white_point”: …, @“max_display_mastering_luminance”: …}; // 省略具体数值
AVMutableMetadataItem *clli = [[AVMutableMetadataItem alloc] init];
clli.key = AVMetadataQuickTimeUserDataKeyContentLightLevelInfo;
clli.keySpace = AVMetadataKeySpaceQuickTimeUserData;
clli.value = @{@“maxCLL”: @(1000), @“maxFALL”: @(400)};
pqInput.metadata = @[mdcv, clli];
// 5. 拼 HLG 的 CMFormatDescription
CMFormatDescriptionRef hlgDesc = NULL;
CFDictionaryRef hlgExtensions = (__bridge CFDictionaryRef)@{
(__bridge NSString *)kCMFormatDescriptionExtension_ColorPrimaries: (__bridge NSString *)kCMFormatDescriptionColorPrimaries_ITU_R_2020,
(__bridge NSString *)kCMFormatDescriptionExtension_TransferFunction: (__bridge NSString *)kCMFormatDescriptionTransferFunction_ITU_R_2100_HLG,
(__bridge NSString *)kCMFormatDescriptionExtension_YCbCrMatrix: (__bridge NSString *)kCMFormatDescriptionYCbCrMatrix_ITU_R_2020
};
CMVideoFormatDescriptionCreate(kCFAllocatorDefault,
codecType,
width, height,
hlgExtensions,
&hlgDesc);
// 6. 创建 HLG 输入
AVAssetWriterInput *hlgInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo
outputSettings:@{
AVVideoCodecKey: AVVideoCodecTypeHEVC,
AVVideoWidthKey: @(width),
AVVideoHeightKey: @(height),
AVVideoColorPropertiesKey: @{
AVVideoColorPrimariesKey: AVVideoColorPrimaries_ITU_R_2020,
AVVideoTransferFunctionKey: AVVideoTransferFunction_ITU_R_2100_HLG,
AVVideoYCbCrMatrixKey: AVVideoYCbCrMatrix_ITU_R_2020
},
AVVideoCompressionPropertiesKey: @{
AVVideoAllowFrameReorderingKey: @NO,
AVVideoExpectedSourceFrameRateKey: @(30),
AVVideoProfileLevelKey: AVVideoProfileLevelHEVCMain10AutoLevel
}
} sourceFormatHint:hlgDesc];
hlgInput.expectsMediaDataInRealTime = NO;
[writer addInput:hlgInput];
// 7. 把 HLG 轨道标记为备用(alternate)轨道,iOS 16+ 才生效
if (@available(iOS 16, *)) {
[writer addTrackWithAssociatedTracksOfType:AVTrackAssociationTypeAlternateTrack
trackIDs:@[hlgInput.trackID]
error:nil];
}
// 8. 启动写入
[writer startWriting];
[writer startSessionAtSourceTime:kCMTimeZero];
// 9. 喂帧时,同一帧分别送 PQ 与 HLG 两个 buffer
dispatch_queue_t queue = dispatch_queue_create("hdr.write", DISPATCH_QUEUE_SERIAL);
[pqInput requestMediaDataWhenReadyOnQueue:queue usingBlock:^{
while (pqInput.readyForMoreMediaData) {
CMSampleBufferRef pqBuffer = /* 从 CVPixelBuffer 转换,gamma 已压成 PQ */;
if (pqBuffer) {
[pqInput appendSampleBuffer:pqBuffer];
CFRelease(pqBuffer);
} else {
[pqInput markAsFinished];
break;
}
}
}];
[hlgInput requestMediaDataWhenReadyOnQueue:queue usingBlock:^{
while (hlgInput.readyForMoreMediaData) {
CMSampleBufferRef hlgBuffer = /* 同一帧转 HLG */;
if (hlgBuffer) {
[hlgInput appendSampleBuffer:hlgBuffer];
CFRelease(hlgBuffer);
} else {
[hlgInput markAsFinished];
break;
}
}
}];
// 10. 结束
[writer finishWritingWithCompletionHandler:^{
CFRelease(pqDesc);
CFRelease(hlgDesc);
if (writer.status == AVAssetWriterStatusCompleted) {
NSLog(@"HDR 双曲线导出完成,路径:%@", outputURL);
} else {
NSLog(@"导出失败:%@", writer.error);
}
[writer release]; // MRC 下记得 release
}];
要点回顾:
- PQ 轨道必须带‘mdcv’‘clli’,否则系统播放器不点亮 HDR 徽章;
- HLG 轨道可省‘mdcv’‘clli’,但‘colr’ box 必须存在;
- 双轨道用 alternate track 关联,iOS 16 以下会回退到第一条轨道,不影响播放;
- 老项目 MRC 中,Core Foundation 对象手动 release,AVFoundation 对象按 MRC 规则 release;
- 若用 VTCompressionSession 裸写,需手动拼 HVCC,并确保 VUI 的 transfer_characteristics 与 CMFormatDescription 一致,否则 QuickLook 会误判为 SDR。
拓展思考
- 如果面试官追问“文件体积翻倍怎么办?”
可以答:用 AVAssetExportSession 的“HEVCMaximumFrameRateCount” 选项,把 HLG 轨道设成 0 fps metadata-only track,只存参数集,不存实际帧,播放器需要时再实时 tone-map;iOS 17 新 API 已支持。 - 被问到“如何验证写入正确?”
答:用 macOS 的“mediainfo”或“ffprobe”看 Box 级别;用 AVFoundation 的 AVAssetTrack.formatDescriptions 读回 transfer function;用 iPhone 13 以上真机播放,控制中心拉亮度条,看是否出现 HDR 徽章。 - 如果项目最低支持 iOS 12?
答:放弃 PQ 备用轨道,只写 HLG 单轨道,因为 iOS 12 的 AVPlayer 不支持 PQ;同时把峰值亮度降到 1000 nits 以下,防止旧机型色调映射爆亮。