使用VideoToolbox硬編碼H.264

前言

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

介紹

1、H.264

H.264由視訊編碼層(Video Coding Layer,VCL)與網(wǎng)絡(luò)提取層(Network Abstraction Layer,NAL)組成。
H.264包含一個(gè)內(nèi)建的NAL網(wǎng)絡(luò)協(xié)議適應(yīng)層,藉由NAL來(lái)提供網(wǎng)絡(luò)的狀態(tài),讓VCL有更好的編譯碼彈性與糾錯(cuò)能力。
H.264的介紹看這里
H.264的碼流結(jié)構(gòu)
重點(diǎn)對(duì)象:

  • 序列參數(shù)集SPS:作用于一系列連續(xù)的編碼圖像;
  • 圖像參數(shù)集PPS:作用于編碼視頻序列中一個(gè)或多個(gè)獨(dú)立的圖像;
碼流結(jié)構(gòu)里面的圖

2、VideoToolbox

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

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

效果展示

下圖是解碼出來(lái)的圖像


貼貼代碼

  • 創(chuàng)建session
        int width = 480, height = 640;
        OSStatus status = VTCompressionSessionCreate(NULL, width, height, kCMVideoCodecType_H264, NULL, NULL, NULL, didCompressH264, (__bridge void *)(self),  &EncodingSession);
  • 設(shè)置session屬性
        // 設(shè)置實(shí)時(shí)編碼輸出(避免延遲)
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_Baseline_AutoLevel);
        // 設(shè)置關(guān)鍵幀(GOPsize)間隔
        int frameInterval = 10;
        CFNumberRef  frameIntervalRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &frameInterval);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_MaxKeyFrameInterval, frameIntervalRef);
        // 設(shè)置期望幀率
        int fps = 10;
        CFNumberRef  fpsRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &fps);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_ExpectedFrameRate, fpsRef); 
        //設(shè)置碼率,上限,單位是bps
        int bitRate = width * height * 3 * 4 * 8;
        CFNumberRef bitRateRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bitRate);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_AverageBitRate, bitRateRef);
        //設(shè)置碼率,均值,單位是byte
        int bitRateLimit = width * height * 3 * 4;
        CFNumberRef bitRateLimitRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bitRateLimit);
        VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_DataRateLimits, bitRateLimitRef);       
  • 傳入編碼幀

    CVImageBufferRef imageBuffer = (CVImageBufferRef)CMSampleBufferGetImageBuffer(sampleBuffer);
    // 幀時(shí)間,如果不設(shè)置會(huì)導(dǎo)致時(shí)間軸過(guò)長(zhǎng)。
    CMTime presentationTimeStamp = CMTimeMake(frameID++, 1000);
    VTEncodeInfoFlags flags;
    OSStatus statusCode = VTCompressionSessionEncodeFrame(EncodingSession,
                                                          imageBuffer,
                                                          presentationTimeStamp,
                                                          kCMTimeInvalid,
                                                          NULL, NULL, &flags);
  • 關(guān)鍵幀獲取SPS和PPS
    bool keyframe = !CFDictionaryContainsKey( (CFArrayGetValueAtIndex(CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, true), 0)), kCMSampleAttachmentKey_NotSync);
    // 判斷當(dāng)前幀是否為關(guān)鍵幀
    // 獲取sps & pps數(shù)據(jù)
    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];
                }
            }
        }
    }
  • 寫入數(shù)據(jù)

    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數(shù)據(jù)前四個(gè)字節(jié)不是0001的startcode,而是大端模式的幀長(zhǎng)度length
        
        // 循環(huán)獲取nalu數(shù)據(jù)
        while (bufferOffset < totalLength - AVCCHeaderLength) {
            uint32_t NALUnitLength = 0;
            // Read the NAL unit length
            memcpy(&NALUnitLength, dataPointer + bufferOffset, AVCCHeaderLength);
            
            // 從大端轉(zhuǎn)系統(tǒng)端
            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;
        }
    }

總結(jié)

在網(wǎng)上找到的多個(gè)VideoToolboxDemo代碼大都類似,更重要是自己嘗試實(shí)現(xiàn)。
學(xué)習(xí)硬編碼與硬解碼,目的是對(duì)H264碼流更清晰的了解,實(shí)則我們開發(fā)過(guò)程中并不會(huì)觸碰到H264的真正編碼與解碼過(guò)程,故而難度遠(yuǎn)沒有想象中那么大。
這里有代碼地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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

友情鏈接更多精彩內(nèi)容