iOS/macOS h264VideoToolBox系统硬编码

2020-05-08 12:11:02 浏览数 (1)

之前几篇推文介绍了做直播推流的一些常识和测试环境搭建的基础准备工作,今天就分享一下楼主总结出来的关于h264对视频采集中的总结

1 视频数据采集

视频采集在苹果爸爸的系统平台中是统一的#import <AVFoundation/AVFoundation.h>这个基础库。主要就是使用

AVCaptureDevice进行视频采集

代码语言:javascript复制
 // Do any additional setup after loading the view.
    mCaptureSession = [[AVCaptureSession alloc] init];
    mCaptureSession.sessionPreset = AVCaptureSessionPresetMedium;
    mCaptureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError * aError;

    mCaptureDeviceInput = [AVCaptureDeviceInput
                           deviceInputWithDevice:mCaptureDevice
                           error:&aError];
    if (mCaptureDeviceInput) {
        [mCaptureSession addInput:mCaptureDeviceInput];
    }else{
        NSLog(@"%@",aError);
    }

    mCaptureVideoDataOutput = [[AVCaptureVideoDataOutput alloc] init];

    [mCaptureVideoDataOutput setAlwaysDiscardsLateVideoFrames:YES];

    NSDictionary *settingsDic = [[NSDictionary alloc] initWithObjectsAndKeys:

                                                             [NSNumber numberWithUnsignedInt:kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange],

                                 kCVPixelBufferPixelFormatTypeKey,

                                 nil];// X264_CSP_NV12

    mCaptureVideoDataOutput.videoSettings = settingsDic;

    dispatch_queue_t queue =dispatch_queue_create("myQueue",NULL);



       [mCaptureVideoDataOutput setSampleBufferDelegate:self queue:queue];

        [mCaptureSession addOutput:mCaptureVideoDataOutput];
    mPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:mCaptureSession];

使用苹果设备硬件进行数据采集属于基本操作查查和容易就出来了,通过代理接受到数据。

代码语言:javascript复制
#pragma mark --  AVCaptureVideo(Audio)DataOutputSampleBufferDelegate method

- (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{

}

这里都是基本的操作大家熟悉一下即可,不熟悉这部分的一般看看文档也能顺利完成视频数据采集

2 视频数据格式

我们使用硬件采集到的数据就是CMSampleBufferRef,这个数据很特殊就如上面占比最大的快一样:CMBlockBuffer CVPixelBuffer 其中CMBlockBuffer CVPixelBuffer是编码存储的是b编码前后的视频数据

3 VideoToolBox参数设置

代码语言:javascript复制
- (void)initVideoToolBox {
    dispatch_sync(mEncodeQueue  , ^{
        frameID = 0;
        int width = 480, height = 640;
        OSStatus status = VTCompressionSessionCreate(NULL, width, height, kCMVideoCodecType_H264, NULL, NULL, NULL, didCompressH264, (__bridge void *)(self),  &EncodingSession);
        NSLog(@"H264: VTCompressionSessionCreate %d", (int)status);
        if (status != 0)
        {
            NSLog(@"H264: Unable to create a H264 session");
            return ;
        }

        // 设置实时编码输出(避免延迟)
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_Baseline_AutoLevel);

        // 设置关键帧(GOPsize)间隔
        int frameInterval = 10;
        CFNumberRef  frameIntervalRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &frameInterval);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_MaxKeyFrameInterval, frameIntervalRef);

        // 设置期望帧率
        int fps = 60;
        CFNumberRef  fpsRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &fps);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_ExpectedFrameRate, fpsRef);


        //设置码率,均值,单位是byte
        int bitRate = width * height * 3 * 4 * 8;
        CFNumberRef bitRateRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bitRate);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_AverageBitRate, bitRateRef);

        //设置码率,上限,单位是bps
        int bitRateLimit = width * height * 3 * 4;
        CFNumberRef bitRateLimitRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bitRateLimit);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_DataRateLimits, bitRateLimitRef);

        // Tell the encoder to start encoding
        VTCompressionSessionPrepareToEncodeFrames(EncodingSession);
    });
}

正如上文代码一样VideoToolBox用到很多C层面的函数调用系统底层硬件的资源,因此VideoToolBox做推流也被称为硬解或者硬编码

我们从几个主要点说起

1 设置关键帧(GOPsize)间隔

对于视屏同样分辨率大小的视频资源画质的好坏很多城都上由关键帧来决定,看过之前文章的都知道 B/P帧是具有很大压缩比例的在5~20倍之间甚至达到50倍,而I帧是完整不压缩的数据,因此关键帧间隔也就确定了1s内关键帧的个数,很大程度影响了1s内视频数据传输量的大小

2 设置期望帧率

这个不用多说就是一秒内要播放的帧个数,也是影响数据传输量的关键点

3 设置码率,均值(单位是bps)

我们一个画面的数据是 width*height*3*8 宽高不用数 3对应的是RGB色,而每个色使用8个字节(可以表示2^8个阶,因此RGB代表的颜色是:2^8 * 2^8 * 2^8)。因此码率决定单位时间传输数据的吞吐量

4 编码回调 didCompressH264 与 &EncodingSession

代码语言:javascript复制
void didCompressH264(void *outputCallbackRefCon, void *sourceFrameRefCon, OSStatus status, VTEncodeInfoFlags infoFlags, CMSampleBufferRef sampleBuffer) {
    NSLog(@"didCompressH264 called with status %d infoFlags %d", (int)status, (int)infoFlags);
    if (status != 0) {
        return;
    }

    if (!CMSampleBufferDataIsReady(sampleBuffer)) {
        NSLog(@"didCompressH264 data is not ready ");
        return;
    }
    ViewController* encoder = (__bridge ViewController*)outputCallbackRefCon;

    bool keyframe = !CFDictionaryContainsKey( (CFArrayGetValueAtIndex(CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, true), 0)), kCMSampleAttachmentKey_NotSync);
    // 判断当前帧是否为关键帧
    // 获取sps & pps数据
    if (keyframe)
    {
        CMFormatDescriptionRef format = CMSampleBufferGetFormatDescription(sampleBuffer);
        size_t sparameterSetSize, sparameterSetCount;
        const uint8_t *sparameterSet;
        OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, 0, &sparameterSet, &sparameterSetSize, &sparameterSetCount, 0 );
        if (statusCode == noErr)
        {
            // Found sps and now check for pps
            size_t pparameterSetSize, pparameterSetCount;
            const uint8_t *pparameterSet;
            OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, 1, &pparameterSet, &pparameterSetSize, &pparameterSetCount, 0 );
            if (statusCode == noErr)
            {
                // Found pps
                NSData *sps = [NSData dataWithBytes:sparameterSet length:sparameterSetSize];
                NSData *pps = [NSData dataWithBytes:pparameterSet length:pparameterSetSize];
                if (encoder)
                {
                    [encoder gotSpsPps:sps pps:pps];
                }
            }
        }
    }

    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; // 返回的nalu数据前四个字节不是0001的startcode,而是大端模式的帧长度length

        // 循环获取nalu数据
        while (bufferOffset < totalLength - AVCCHeaderLength) {
            uint32_t NALUnitLength = 0;
            // Read the NAL unit length
            memcpy(&NALUnitLength, dataPointer   bufferOffset, AVCCHeaderLength);

            // 从大端转系统端
            NALUnitLength = CFSwapInt32BigToHost(NALUnitLength);

            NSData* data = [[NSData alloc] initWithBytes:(dataPointer   bufferOffset   AVCCHeaderLength) length:NALUnitLength];
            [encoder gotEncodedData:data isKeyFrame:keyframe];

            // Move to the next NAL unit in the block buffer
            bufferOffset  = AVCCHeaderLength   NALUnitLength;
        }
    }
}

OSStatus status = VTCompressionSessionCreate(NULL, width, height, kCMVideoCodecType_H264, NULL, NULL, NULL, didCompressH264, (__bridge void *)(self), &EncodingSession);

didCompressH264这就是典型的C中函数指针作为参数的实例,这个不用太纠结,我们先从一个C来看看

函数指针--格式大致如下 返回类似 (*函数名)(参数列表……)

我们看个例子

代码语言:javascript复制
int sum(int a, int b) {
    return a   b;
};

int multiToNum(int a, int b) {
    return a * b;
}

int action(int (*op)(int, int), int a, int b) {
    return op(a, b);
};

上栗是简单的做action操作,参数是:一个函数指针,两个变量参数

我们看怎么使用

代码语言:javascript复制
int result = action(&sum, 1, 2);
int multi = action(&multiToNum, 1, 2);

&EncodingSession 是个什么?

其实很好理解这个是指针,通过传递指针,在函数内部进行数据赋值初始化,有效的隐藏内部细节和防止人为外部定义的赋值的参数设置错误问题

例如

代码语言:javascript复制
struct Person{
    int id;
    int age;
};
void  InnerSetValue(Person * p){
    p->id = 1;
    p->age = 31;
}

//赋值使用

 Person p;
InnerSetValue(&p);

Person的变量经过指针的传递在函数内部很好的被数据赋值

4视频硬编码

上面几步我们我了视频采集 VideoToolBox初始,那么采集的数据需要进行encode编码,编码完成之后VideoToolBox会将数据回调发送个初始换设定好的C函数中

1 数据编码

代码语言:javascript复制
- (void) encode:(CMSampleBufferRef )sampleBuffer
{
    CVImageBufferRef imageBuffer = (CVImageBufferRef)CMSampleBufferGetImageBuffer(sampleBuffer);
    // 帧时间,如果不设置会导致时间轴过长。
    CMTime presentationTimeStamp = CMTimeMake(frameID  , 1000);
    VTEncodeInfoFlags flags;
    OSStatus statusCode = VTCompressionSessionEncodeFrame(EncodingSession,
                                                          imageBuffer,
                                                          presentationTimeStamp,
                                                          kCMTimeInvalid,
                                                          NULL, NULL, &flags);
    if (statusCode != noErr) {
        NSLog(@"H264: VTCompressionSessionEncodeFrame failed with %d", (int)statusCode);
        
        VTCompressionSessionInvalidate(EncodingSession);
        CFRelease(EncodingSession);
        EncodingSession = NULL;
        return;
    }
    NSLog(@"H264: VTCompressionSessionEncodeFrame Success");
}

这一步骤很简单就是使用初始好的Session和对按时间顺序采集到的Buffer进行按接收时间先后排序后扔给系统编码,然后系统吧结果数据回调给设定好的C,最终我们拿到系统加工后的数据查找PPS SPS进行处理加工

代码语言:javascript复制
- (void)gotSpsPps:(NSData*)sps pps:(NSData*)pps
{
    NSLog(@"gotSpsPps %d %d", (int)[sps length], (int)[pps length]);
    const char bytes[] = "x00x00x00x01";
    size_t length = (sizeof bytes) - 1; //string literals have implicit trailing ''
    NSData *ByteHeader = [NSData dataWithBytes:bytes length:length];
    [fileHandle writeData:ByteHeader];
    [fileHandle writeData:sps];
    [fileHandle writeData:ByteHeader];
    [fileHandle writeData:pps];
    
}
- (void)gotEncodedData:(NSData*)data isKeyFrame:(BOOL)isKeyFrame
{
    NSLog(@"gotEncodedData %d", (int)[data length]);
    if (fileHandle != NULL)
    {
        const char bytes[] = "x00x00x00x01";
        size_t length = (sizeof bytes) - 1; //string literals have implicit trailing ''
        NSData *ByteHeader = [NSData dataWithBytes:bytes length:length];
        
        [fileHandle writeData:ByteHeader];
        [fileHandle writeData:data];
    }
}

可能这部分代码很多,但是最多的是套路和对编码流程的认知过程,也许你会和lz一样感觉VideoToolBox设置参数有点多,但是这些都是套路,是根据视频行业的一些常识走的,配合着整理的视频知识常识就好理解。

总结一句就是:

1 视频的处理中的一些常识概念要搞熟悉:码率 PPS SPS 关键帧等

2 C语言的一些基础常识要有,别看到C调用就怕,其实系统分出来的C调用真的很少

3 理清顺序 视频采集~VideoToolBox初始化=》采集数据=》VideoToolBox编码=》数据回调给初始化是VideoToolBox指定的C函数 =》拿到回调数据进行h264编码(SPS PPS)

0 人点赞