iOS 硬编码

iOS 硬编码

iOS 硬编码简单的总结来说就是将采集到的CMSampleBufferRef编码成H264或者是H265,对编码完成后的数据最后进行合成等工作用以实现自己不同的需求。
编码的主要步骤可分为以下几个步骤:

  1. 创建编码用的session,并设置编码的参数
  2. 等待数据进行正式编码工作
  3. 处理编码完成的数据

总结的步骤是比较简单的,但是在各个步骤中有几个比较重要的点需要注意,下面在代码中逐步进行指出

编码session 的创建

在进行session创建的时候需要设置回调函数,数据编码之后将通过该函数方法输出,另配置session的几个关键属性。

  • 配置是否实时编码
  • 配置编码等级(baseline/main/high)
  • 配置帧率(1秒多少帧画面)
  • 配置GOP(两个I帧的间隔多少帧)
  • 配置编码类型(CABAC/CAVLC)

具体的操作代码如下:

- (void)createSessionWithConfig:(VideoEncodeConfig *)config {
    needSetVideoParam = YES;
    // 创建session,指定回调方法
    VTCompressionSessionCreate(NULL, config.size.width, config.size.height, kCMVideoCodecType_H264, NULL, NULL, NULL, outputCallback, (__bridge void *)self, &pCompressionSession);
    // 配置session 属性
    // 是否实时
    VTSessionSetProperty(pCompressionSession, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue);
    // gop数值
    VTSessionSetProperty(pCompressionSession, kVTCompressionPropertyKey_MaxKeyFrameInterval, (__bridge CFTypeRef)@(config.videoMaxKeyframeInterval));
    // 期望帧率
    VTSessionSetProperty(pCompressionSession, kVTCompressionPropertyKey_ExpectedFrameRate, (__bridge CFTypeRef)@(config.videoFrameRate));
    // 关键帧采样间隔时间
    VTSessionSetProperty(pCompressionSession, kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration,( __bridge CFTypeRef)@(config.videoMaxKeyframeInterval / config.videoFrameRate));
    // 比特率
    VTSessionSetProperty(pCompressionSession, kVTCompressionPropertyKey_AverageBitRate, ( __bridge CFTypeRef)@(config.videoBitRate));
    NSArray *limit = @[@(config.videoBitRate * 1.5/8), @(1)];
    VTSessionSetProperty(pCompressionSession, kVTCompressionPropertyKey_DataRateLimits, (__bridge CFArrayRef)limit);
    // 编码登记
    VTSessionSetProperty(pCompressionSession, kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_High_AutoLevel);
    // 编码类型
    VTSessionSetProperty(pCompressionSession, kVTCompressionPropertyKey_H264EntropyMode, kVTH264EntropyMode_CABAC);
    VTCompressionSessionPrepareToEncodeFrames(pCompressionSession);
    
}
编码数据

在编码过程中,主要调用的方法为VTCompressionSessionEncodeFrame该方法的参数解析如下:

/*!
	@function	VTCompressionSessionEncodeFrame
	@param	session
		解码session
	@param	imageBuffer 
		从CMSampleBufferRef 中获取的CVImageBuffer 
	@param	presentationTimeStamp
		该帧的显示时间戳,CMTime 类型的,后面的一帧一定要比前面的大
	@param	duration
		一帧显示多久,不知道可传递kCMTimeInvalid
	@param	frameProperties
		此帧的其他属性。很关键
	@param	sourceFrameRefcon
		Your reference value for the frame, which will be passed to the output callback functio
	@param	infoFlagsOut
		可为NULL
*/

知道了上述方法的关键阐述,就只是往里面添加参数了。
需要注意的点:

  1. 我们可以通过对编码帧数的累加来赋值presentation。 CMTime 参数的构建一般有CMTimeMakeCMTimeMakeWithSeconds,两者之间的区别就是第一个参数,CMTimeMake第一个入参是第几帧,而CMTimeMakeWithSeconds入参为具体的时间点,在编码时不需关注解码时间点,所以使用CMTimeMake比较贴合场景。
  2. 配置frameProperties。在进行视频数据编码时生成的H264 默认只会在首帧的时候为I帧,但如果这样的数据在进行封装为其他文件时会出现很多问题,如:无法进行中间数据拉取播放等(因为解码都需要SPS/PPS数据,且一般从I帧开始),所以需要根据当前编码的framerate 设置kVTEncodeFrameOptionKey_ForceKeyFrame为YES达到编码I帧的目的.
    下面是编码相关的代码:
- (void)startEncodeWithCMSampleBufferRef:(CMSampleBufferRef)samplerBuffer {
    if (pCompressionSession == NULL) {
        return;
    }
    pFrameIndex++;
    CMTime presentationTimeStamp = CMTimeMake(pFrameIndex,(int32_t)pvideoConfig.videoFrameRate);
    VTEncodeInfoFlags flags;
    CMTime duration = CMTimeMake(1, (int32_t)pvideoConfig.videoFrameRate);
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(samplerBuffer);
    NSDictionary *properties = nil;
    // 将指定帧作为i帧
    if (pFrameIndex % (int32_t)pvideoConfig.videoMaxKeyframeInterval == 0) {
        properties = @{(__bridge NSString *)kVTEncodeFrameOptionKey_ForceKeyFrame: @YES};
    }
    // 编码操作
    OSStatus status = VTCompressionSessionEncodeFrame(pCompressionSession, imageBuffer, presentationTimeStamp, duration, (__bridge CFDictionaryRef)properties, NULL, &flags);
    if(status != noErr){
        
    }
}
数据处理

数据处理及将得到的数据字节组装成H264文件,H264的格式解析可见我的H264格式解析
关键的步骤就是在首个I帧时,获取SPS/PPS并将其组装到所需要的文件上。如果你的码流需要动态刷新,也可以在每个I帧时都插入SPS/PPS/SEI等信。
组装的代码如下:

static void outputCallback(
                                    void * CM_NULLABLE outputCallbackRefCon,
                                    void * CM_NULLABLE sourceFrameRefCon,
                                    OSStatus status,
                                    VTEncodeInfoFlags infoFlags,
                                    CM_NULLABLE CMSampleBufferRef sampleBuffer ) {
    if (status != noErr) {
        NSLog(@"编码出错");
        return;
    }
    CFArrayRef array = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, true);
    if (!array) return;
    CFDictionaryRef dic = (CFDictionaryRef)CFArrayGetValueAtIndex(array, 0);
    if (!dic) return;
    
    BOOL keyframe = !CFDictionaryContainsKey(dic, kCMSampleAttachmentKey_NotSync);
    HardEncode *encode = (__bridge HardEncode *)outputCallbackRefCon;
    if (keyframe) {
        static size_t  keyParameterSetBufferSize = 0;
        if (keyParameterSetBufferSize == 0 && encode->needSetVideoParam == YES) {
            CMFormatDescriptionRef format = CMSampleBufferGetFormatDescription(sampleBuffer);
            size_t sparameterSetSize, sparameterSetCount;
            const uint8_t *sparameterSet;
            OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, 0, &sparameterSet, &sparameterSetSize, &sparameterSetCount, 0);
            if (statusCode == noErr) {
                size_t pparameterSetSize, pparameterSetCount;
                const uint8_t *pparameterSet;
                OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, 1, &pparameterSet, &pparameterSetSize, &pparameterSetCount, 0);
                if (statusCode == noErr) {
                    NSData *sps = [NSData dataWithBytes:sparameterSet length:sparameterSetSize];
                    NSData *pps = [NSData dataWithBytes:pparameterSet length:pparameterSetSize];
                    NSMutableData *data = [[NSMutableData alloc] init];
                    uint8_t header[] = {0x00, 0x00, 0x00, 0x01};
                    [data appendBytes:header length:4];
                    [data appendData:sps];
                    [data appendBytes:header length:4];
                    [data appendData:pps];
                    // 写入文件
                    fwrite(data.bytes, 1, data.length, encode->fp);
                    NSLog(@"首次写入,配置SPS/PPS 信息");
                    
                    encode->needSetVideoParam = NO;
                }
            }
        }
    }
    
    CMBlockBufferRef dataBuffer = CMSampleBufferGetDataBuffer(sampleBuffer);
    size_t length, totalLength;
    char *dataPointer;
    OSStatus statusCodeRet = CMBlockBufferGetDataPointer(dataBuffer, 0, &length, &totalLength, &dataPointer);
    if (statusCodeRet == noErr) {
        size_t bufferOffset = 0;
        static const int AVCCHeaderLength = 4;
        while (bufferOffset < totalLength - AVCCHeaderLength) {
            uint32_t NALUnitLength = 0;
            memcpy(&NALUnitLength, dataPointer + bufferOffset, AVCCHeaderLength);
            NALUnitLength = CFSwapInt32BigToHost(NALUnitLength);
            NSData *data = [[NSData alloc] initWithBytes:(dataPointer + bufferOffset + AVCCHeaderLength) length:NALUnitLength];
            NSMutableData *tempData = [[NSMutableData alloc] init];
            uint8_t header[] = {0x00, 0x00, 0x00, 0x01};
            [tempData appendBytes:header length:4];
            [tempData appendData:data];
            
            fwrite(tempData.bytes, 1, tempData.length, encode->fp);
            bufferOffset += AVCCHeaderLength + NALUnitLength;
        }
    }
}

上述的代码和基本逻辑就组成了iOS 的基本编码功能,iOS硬编码还有很多比较复杂的操作,暂时还没有研究。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值