前言
H.264是目前很流行的編碼層視頻壓縮格式苟弛,目前項目中的協(xié)議層有rtmp與http速警,但是視頻的編碼層都是使用的H.264专筷。
在熟悉H.264的過程中,為更好的了解H.264忿墅,嘗試用VideoToolbox硬編碼與硬解碼H.264的原始碼流。
介紹
1沮峡、H.264
H.264由視訊編碼層(Video Coding Layer疚脐,VCL)與網(wǎng)絡(luò)提取層(Network Abstraction Layer,NAL)組成邢疙。
H.264包含一個內(nèi)建的NAL網(wǎng)絡(luò)協(xié)議適應(yīng)層棍弄,藉由NAL來提供網(wǎng)絡(luò)的狀態(tài),讓VCL有更好的編譯碼彈性與糾錯能力疟游。
H.264的介紹看這里
H.264的碼流結(jié)構(gòu)
重點對象:
- 序列參數(shù)集SPS:作用于一系列連續(xù)的編碼圖像呼畸;
- 圖像參數(shù)集PPS:作用于編碼視頻序列中一個或多個獨立的圖像;
2颁虐、VideoToolbox
VideoToolbox是iOS8以后開放的硬編碼與硬解碼的API蛮原,一組用C語言寫的函數(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竭贩、每一幀視頻編碼完成后會調(diào)用預先設(shè)置的編碼函數(shù)
didCompressH264
,如果是關(guān)鍵幀需要用CMSampleBufferGetFormatDescription獲取CMFormatDescriptionRef莺禁,然后用
CMVideoFormatDescriptionGetH264ParameterSetAtIndex取得PPS和SPS留量;
最后把每一幀的所有NALU數(shù)據(jù)前四個字節(jié)變成0x00 00 00 01之后再寫入文件; - 4哟冬、調(diào)用VTCompressionSessionCompleteFrames完成編碼楼熄,然后銷毀session:VTCompressionSessionInvalidate,釋放session浩峡。
效果展示
下圖是解碼出來的圖像
貼貼代碼
- 創(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è)置實時編碼輸出(避免延遲)
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è)置會導致時間軸過長。
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);
// 判斷當前幀是否為關(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ù)前四個字節(jié)不是0001的startcode致开,而是大端模式的幀長度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)上找到的多個VideoToolboxDemo代碼大都類似峰锁,更重要是自己嘗試實現(xiàn)。
學習硬編碼與硬解碼双戳,目的是對H264碼流更清晰的了解虹蒋,實則我們開發(fā)過程中并不會觸碰到H264的真正編碼與解碼過程,故而難度遠沒有想象中那么大飒货。
這里有代碼地址