使用VideoToolbox硬編碼H.264

前言

H.264是目前很流行的編碼層視頻壓縮格式,目前項目中的協議層有rtmp與http,但是視頻的編碼層都是使用的H.264。
在熟悉H.264的過程中,為更好的了解H.264,嘗試用VideoToolbox硬編碼與硬解碼H.264的原始碼流。

介紹

1、H.264

H.264由視訊編碼層(Video Coding Layer,VCL)與網絡提取層(Network Abstraction Layer,NAL)組成。
H.264包含一個內建的NAL網絡協議適應層,藉由NAL來提供網絡的狀態,讓VCL有更好的編譯碼彈性與糾錯能力。
H.264的介紹看這里
H.264的碼流結構
重點對象:

  • 序列參數集SPS:作用于一系列連續的編碼圖像;
  • 圖像參數集PPS:作用于編碼視頻序列中一個或多個獨立的圖像;
碼流結構里面的圖

2、VideoToolbox

VideoToolbox是iOS8以后開放的硬編碼與硬解碼的API,一組用C語言寫的函數。使用流程如下:

  • 1、-initVideoToolBox中調用VTCompressionSessionCreate創建編碼session,然后調用VTSessionSetProperty設置參數,最后調用VTCompressionSessionPrepareToEncodeFrames開始編碼;
  • 2、開始視頻錄制,獲取到攝像頭的視頻幀,傳入-encode:,調用VTCompressionSessionEncodeFrame傳入需要編碼的視頻幀,如果返回失敗,調用VTCompressionSessionInvalidate銷毀session,然后釋放session;
  • 3、每一幀視頻編碼完成后會調用預先設置的編碼函數didCompressH264,如果是關鍵幀需要用CMSampleBufferGetFormatDescription獲取CMFormatDescriptionRef,然后用
    CMVideoFormatDescriptionGetH264ParameterSetAtIndex取得PPS和SPS;
    最后把每一幀的所有NALU數據前四個字節變成0x00 00 00 01之后再寫入文件;
  • 4、調用VTCompressionSessionCompleteFrames完成編碼,然后銷毀session:VTCompressionSessionInvalidate,釋放session。

效果展示

下圖是解碼出來的圖像


貼貼代碼

  • 創建session
        int width = 480, height = 640;
        OSStatus status = VTCompressionSessionCreate(NULL, width, height, kCMVideoCodecType_H264, NULL, NULL, NULL, didCompressH264, (__bridge void *)(self),  &EncodingSession);
  • 設置session屬性
        // 設置實時編碼輸出(避免延遲)
        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 = 10;
        CFNumberRef  fpsRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &fps);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_ExpectedFrameRate, fpsRef); 
        //設置碼率,上限,單位是bps
        int bitRate = width * height * 3 * 4 * 8;
        CFNumberRef bitRateRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bitRate);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_AverageBitRate, bitRateRef);
        //設置碼率,均值,單位是byte
        int bitRateLimit = width * height * 3 * 4;
        CFNumberRef bitRateLimitRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bitRateLimit);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_DataRateLimits, bitRateLimitRef);       
  • 傳入編碼幀

    CVImageBufferRef imageBuffer = (CVImageBufferRef)CMSampleBufferGetImageBuffer(sampleBuffer);
    // 幀時間,如果不設置會導致時間軸過長。
    CMTime presentationTimeStamp = CMTimeMake(frameID++, 1000);
    VTEncodeInfoFlags flags;
    OSStatus statusCode = VTCompressionSessionEncodeFrame(EncodingSession,
                                                          imageBuffer,
                                                          presentationTimeStamp,
                                                          kCMTimeInvalid,
                                                          NULL, NULL, &flags);
  • 關鍵幀獲取SPS和PPS
    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;
        }
    }

總結

在網上找到的多個VideoToolboxDemo代碼大都類似,更重要是自己嘗試實現。
學習硬編碼與硬解碼,目的是對H264碼流更清晰的了解,實則我們開發過程中并不會觸碰到H264的真正編碼與解碼過程,故而難度遠沒有想象中那么大。
這里有代碼地址

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 引言 從iOS8開始,蘋果將VideoToolbox.framework開放了出來,使開發者可以使用iOS設備內置...
    sxyxsp123閱讀 2,216評論 1 6
  • 硬件編碼相關知識(H264,H265) 閱讀人群:研究硬件編碼器應用于iOS開發中,從0研究關于硬件編解碼,碼流中...
    小東邪啊閱讀 12,839評論 0 18
  • 在保證視頻圖像質量的前提下,HEVC通過增加一定的計算復雜度,可以實現碼流在H.264/AVC的基礎上降低50%。...
    加劉景長閱讀 7,994評論 0 6
  • 斷夜奶已經第三天了,婆婆說寶貝睡得很好,只醒了一次,而且稍微哄哄就睡了。這也是我睡整覺的第三天,從第一天的小興奮,...
    快快媽媽育兒說閱讀 117評論 3 0
  • 帕金森定律是一個自私的現象,我們應該提升自己,雇傭比自己更優秀的人幫助自己,這樣團隊才能有所進步,集體的利益才能有所提升
    耿婷婷GTT閱讀 216評論 0 0