使用VideoToolBox进行硬编码

2,011 阅读2分钟
原文链接: www.maxiaoma.top

视频硬编码

硬编码流程图

VideoToolBox(硬编码部分)

VideoToolBox是一个直接通过硬件来提升视频编码和解码能力的框架。也就是我们俗称的硬解码和硬编码

VTCompressionSession (object)

一个管理视频数据压缩的会话

VTCompressionSessionCreate (method)

创建VTCompressionSession

//OSStatus 返回创建的状态
OSStatus VTCompressionSessionCreate(
//1. 一个分配器 默认为Null
CFAllocatorRef allocator, 
//2. 视频帧的像素宽度
int32_t width, 
//3. 视频帧的像素高度
int32_t height, 
//4. 编码类型 常用H264编码 kCMVideoCodecType_H264
CMVideoCodecType codecType, 
//5. 编码方式Null由videoToolBox选择
CFDictionaryRef encoderSpecification, 
//6. 创建一个像素缓冲池的属性 Null为由videoToolBox创建
CFDictionaryRef sourceImageBufferAttributes, 
//7. 数据压缩分配器  默认为Null
CFAllocatorRef compressedDataAllocator, 
//8. 输出回调   VTCompressionSessionEncodeFrame
VTCompressionOutputCallback outputCallback, 
//9. 回调对象 
void *outputCallbackRefCon,
//10. VTCompressionSession 要创建的对象 
VTCompressionSessionRef  _Nullable *compressionSessionOut);

VTSessionSetProperty && VTSessionSetProperties (method)

设置 VideoToolbox session 属性

//返回状态
OSStatus VTSessionSetProperty(
//VTCompressionSession 设置的session对象
VTSessionRef session, 
//key值
CFStringRef propertyKey, 
//value值
CFTypeRef propertyValue);

批量设置 VideoToolbox session 属性


//返回状态
OSStatus VTSessionSetProperties(
//VTCompressionSession 设置的session对象
VTSessionRef session, 
//CFDictionaryRef 字典存储
CFDictionaryRef propertyDictionary);

VTCompressionSessionPrepareToEncodeFrames (method)

允许编码器编码开始之前执行任何必要的资源分配框架(可选)。该方法需要在VTCompressionSessionEncodeFrame之前调用

OSStatus VTCompressionSessionPrepareToEncodeFrames(VTCompressionSessionRef session);

VTCompressionSessionEncodeFrame (method)

把会话中的每一帧进行压缩

OSStatus VTCompressionSessionEncodeFrame(
//数据压缩会话
VTCompressionSessionRef session, 
//一个核心的视频图像缓冲区包含一个视频帧
CVImageBufferRef imageBuffer, 
//帧的时间戳,时间戳后一个必须大于前一个
CMTime presentationTimeStamp, 
//这一帧展示的时间 默认kCMTimeInvalid
CMTime duration, 
//每一帧的属性
CFDictionaryRef frameProperties, 
//一个回调,可以对每一帧进行处理 不需要处理传Null
void *sourceFrameRefCon, 
//VTEncodeInfoFlags 设置同步异步处理 0为异步
VTEncodeInfoFlags *infoFlagsOut);

VTCompressionSessionInvalidate (method)

废弃VTCompressionSession

//废弃值
void VTCompressionSessionInvalidate(VTCompressionSessionRef session);
//完成后需要进行release
void CFRelease(CFTypeRef cf);
//最后将对象置空Null
session = Null

代码参考简书作者:落影loyinglin