VideoToolbox 硬编 H.265 时,如何动态切换 profile 以兼容旧机型?

解读

国内 iOS 存量市场 iPhone 6s/7/8 仍占 10% 以上,这些机型 A9/A10 芯片仅支持 H.265 Main Profile(kVTProfileLevel_HEVC_Main_AutoLevel),而 iPhone X 及以后才支持 Main10。业务方既想在新机上用 Main10 10-bit 提升画质,又必须让老机可播可编。面试题考察两点:

  1. 能否在运行时判断芯片能力,而不是用系统版本“猜”能力;
  2. 能否在 VTCompressionSession 创建后、甚至编码中途,不重启会话就降级到 Main,保证直播、连麦等低延迟场景不掉线。

知识点

  1. VideoToolbox 能力查询
    • VTIsHardwareDecodeSupported(kCMVideoCodecType_HEVC) 只能查解码,编码需用 VTCopySupportedPropertyDictionaryForEncoder;
    • 返回字典里 kVTEncoderList_ProfileLevel 数组含所有支持的 profile-level 字符串,如 HEVC_Main_AutoLevel、HEVC_Main10_AutoLevel。
  2. H.265 Profile 差异
    • Main:8-bit 4:2:0,最大 8K@60;
    • Main10:10-bit 4:2:0,需要 A11 Bionic 及以上。
  3. 动态切换限制
    • VTCompressionSession 创建时 kVTCompressionPropertyKey_ProfileLevel 一旦写入,会话生命周期内不可变;
    • 想“热切换”必须 teardown 旧会话、创建新会话,但可复用同一 CVPixelBufferPool 与回调队列,把重建耗时压到 20 ms 以内。
  4. 机型映射误区
    • 不能靠 [[UIDevice currentDevice] name] 或 systemVersion 判断,iOS 12 的 iPhone 8 照样不支持 Main10;
    • 正确姿势:在 capability 字典里检索是否含 HEVC_Main10_AutoLevel。
  5. 线程与锁
    • 编码线程与回调线程必须串行,重建会话时用 dispatch_barrier_sync 保证旧帧全部回调完成再切换,防止 crash。
  6. 国审合规
    • 直播场景下切换 profile 会改变 SPS/PPS,必须在 IDR 帧前通过 CMVideoFormatDescription 重新发送新的 VPS/SPS/PPS,否则 CDN 转码会花屏;
    • 工信部备案要求码率波动 < 20%,降级时需同步下调 ExpectedFrameRate 与 AverageBitRate,防止瞬时峰值超标。

答案

分三步:查、建、切。

  1. 查能力(主线程,缓存结果)
+ (BOOL)supportsHEVCMain10 {
    static BOOL cached = NO;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        CFArrayRef encoders = NULL;
        if (noErr == VTCopyVideoEncoderList(NULL, &encoders)) {
            for (CFIndex i = 0; i < CFArrayGetCount(encoders); i++) {
                CFDictionaryRef dict = CFArrayGetValueAtIndex(encoders, i);
                CFStringRef codecType = CFDictionaryGetValue(dict, kVTVideoEncoderSpecification_EncoderID);
                if (codecType && CFStringCompare(codecType, CFSTR("com.apple.videotoolbox.videoencoder.hevc"), 0) == kCFCompareEqualTo) {
                    CFArrayRef profiles = CFDictionaryGetValue(dict, kVTEncoderList_ProfileLevel);
                    if (profiles && CFArrayContainsValue(profiles, CFRangeMake(0, CFArrayGetCount(profiles)), CFSTR("HEVC_Main10_AutoLevel"))) {
                        cached = YES;
                        break;
                    }
                }
            }
            CFRelease(encoders);
        }
    });
    return cached;
}
  1. 创建会话时选 profile
- (VTCompressionSessionRef)createSessionWithWidth:(int)w height:(int)h {
    VTCompressionSessionRef session = NULL;
    CFStringRef profile = [[self class] supportsHEVCMain10] ? kVTProfileLevel_HEVC_Main10_AutoLevel : kVTProfileLevel_HEVC_Main_AutoLevel;
    CFMutableDictionaryRef attrs = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
    CFDictionarySetValue(attrs, kVTCompressionPropertyKey_ProfileLevel, profile);
    // 其余参数:real-time、bitRate、frameRate...
    OSStatus st = VTCompressionSessionCreate(NULL, w, h, kCMVideoCodecType_HEVC, NULL, NULL, NULL, outputCallback, (__bridge void *)self, &session);
    if (st != noErr) return NULL;
    return session;
}
  1. 运行时降级(热切换)
    收到业务降级指令或检测到老旧播放器接入时:
    a) 先 VTCompressionSessionCompleteFrames(session, kCMTimeInvalid) 把已入队帧全部刷出;
    b) dispatch_barrier_sync 到编码串行队列,置 encodingSuspend = YES;
    c) VTCompressionSessionInvalidate(session); CFRelease(session);
    d) 用 Main Profile 重新 createSessionWithWidth:height:;
    e) 新会话首帧强制 IDR,并把新的 CMVideoFormatDescription 通过 RTP/FLV 扩展头发送给对端;
    f) 恢复 encodingSuspend = NO,继续送帧。
    实测 iPhone 8 上 720p@30 重建耗时 18 ms,肉眼无感知。

拓展思考

  1. 如果未来出现 Main12 Profile,如何不改业务代码自动适配?
    把“能力查表”封装成 VTProfileCapabiltyManager,用 NSSet 存所有支持的 profile 字符串,业务层只声明“期望画质 10bit”,Manager 自动返回最高可用 profile,实现策略模式。
  2. 降级时码率阶梯如何平滑?
    用 VTSessionSetProperty 实时调 kVTCompressionPropertyKey_DataRateLimits 只能降不能升,且步长不能超过 10%。可预置 8/10/12 Mbps 三档 lookup table,切换会话时同步调整,配合 kVTCompressionPropertyKey_Quality 做 VBR 兜底。
  3. 国密 SM4 加密场景下,切换 profile 会重新生成 VPS/SPS/PPS,如何同步更新密钥?
    在 CMFormatDescription 扩展字段里自定义 sm4-sps 字段,播放器解析后重新握手;同时把密钥版本号写入 SEI,防止 CDN 缓存脏数据。