使用VideoToolbox硬編碼H.264<轉>


文/落影loyinglin(簡書作者)
原文鏈接:http://www.jianshu.com/p/37784e363b8a
著作權歸作者所有,轉載請聯系作者獲得授權,並標注“簡書作者”。

===========================================

使用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的真正編碼與解碼過程,故而難度遠沒有想象中那么大。
    這里有代碼地址


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM