文/落影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 = , height = ;
    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 = ;
    CFNumberRef frameIntervalRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &frameInterval);
    VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_MaxKeyFrameInterval, frameIntervalRef);
    // 设置期望帧率
    int fps = ;
    CFNumberRef fpsRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &fps);
    VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_ExpectedFrameRate, fpsRef);
    //设置码率,上限,单位是bps
    int bitRate = width * height * * * ;
    CFNumberRef bitRateRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bitRate);
    VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_AverageBitRate, bitRateRef);
    //设置码率,均值,单位是byte
    int bitRateLimit = width * height * * ;
    CFNumberRef bitRateLimitRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bitRateLimit);
    VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_DataRateLimits, bitRateLimitRef);
  • 传入编码帧

  • CVImageBufferRef imageBuffer = (CVImageBufferRef)CMSampleBufferGetImageBuffer(sampleBuffer);
    // 帧时间,如果不设置会导致时间轴过长。
    CMTime presentationTimeStamp = CMTimeMake(frameID++, );
    VTEncodeInfoFlags flags;
    OSStatus statusCode = VTCompressionSessionEncodeFrame(EncodingSession,
    imageBuffer,
    presentationTimeStamp,
    kCMTimeInvalid,
    NULL, NULL, &flags);
  • 关键帧获取SPS和PPS

  •  bool keyframe = !CFDictionaryContainsKey( (CFArrayGetValueAtIndex(CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, true), )), kCMSampleAttachmentKey_NotSync);
    // 判断当前帧是否为关键帧
    // 获取sps & pps数据
    if (keyframe)
    {
    CMFormatDescriptionRef format = CMSampleBufferGetFormatDescription(sampleBuffer);
    size_t sparameterSetSize, sparameterSetCount;
    const uint8_t *sparameterSet;
    OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, , &sparameterSet, &sparameterSetSize, &sparameterSetCount, );
    if (statusCode == noErr)
    {
    // Found sps and now check for pps
    size_t pparameterSetSize, pparameterSetCount;
    const uint8_t *pparameterSet;
    OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, , &pparameterSet, &pparameterSetSize, &pparameterSetCount, );
    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, , &length, &totalLength, &dataPointer);
    if (statusCodeRet == noErr) {
    size_t bufferOffset = ;
    static const int AVCCHeaderLength = ; // 返回的nalu数据前四个字节不是0001的startcode,而是大端模式的帧长度length // 循环获取nalu数据
    while (bufferOffset < totalLength - AVCCHeaderLength) {
    uint32_t NALUnitLength = ;
    // 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的真正编码与解码过程,故而难度远没有想象中那么大。
    这里有代码地址

使用VideoToolbox硬编码H.264<转>的更多相关文章

  1. 01:***VideoToolbox硬编码H.264

    最近接触了一些视频流H264的编解码知识,之前项目使用的是FFMpeg多媒体库,利用CPU做视频的编码和解码,俗称为软编软解.该方法比较通用,但是占用CPU资源,编解码效率不高.一般系统都会提供GPU ...

  2. iOS VideoToolbox硬编H.265(HEVC)H.264(AVC):2 H264数据写入文件

    本文档为iOS VideoToolbox硬编H.265(HEVC)H.264(AVC):1 概述续篇,主要描述: CMSampleBufferRef读取实际数据 序列参数集(Sequence Para ...

  3. iOS VideoToolbox硬编H.265(HEVC)H.264(AVC):1 概述

    本文档尝试用Video Toolbox进行H.265(HEVC)硬件编码,视频源为iPhone后置摄像头.去年做完硬解H.264,没做编码,技能上感觉有些缺失.正好刚才发现CMFormatDescri ...

  4. 【流媒体】 Android 实时视频编码—H.264硬编码

    [流媒體] Android 实时视频编码—H.264硬编码 SkySeraph Apr 4th 2012 Email:skyseraph00@163.com 1  硬编码 & 软编码 硬编码: ...

  5. iOS硬解H.264:-VideoToolboxDemo源码分析[草稿]

    来源:http://www.cnblogs.com/michaellfx/p/understanding_-VideoToolboxDemo.html iOS硬解H.264:-VideoToolbox ...

  6. How to use VideoToolbox to decompress H.264 video stream

    来源:http://stackoverflow.com/questions/29525000/how-to-use-videotoolbox-to-decompress-h-264-video-str ...

  7. Android 实时视频编码—H.264硬编码

    from://http://www.cnblogs.com/skyseraph/archive/2012/04/04/2431771.html 1  硬编码 & 软编码 硬编码:通过调用And ...

  8. iOS VideoToolbox硬编H.265(HEVC)H.264(AVC):4 同步编码

    本文档描述Video Toolbox实现同步编码的办法. Video Toolbox在头文件描述了编码方式为异步,实际开发中也确实为异步. This function may be called as ...

  9. iOS使用VideoToolbox硬编码录制H264视频

    http://blog.csdn.net/shawnkong/article/details/52045894

随机推荐

  1. 【性能诊断】五、并发场景的性能分析(windbg简介及dump抓取)

    windbg简介 Windbg是在windows平台下,强大的用户态和内核态调试工具.相比较于Visual Studio,它是一个轻量级的调试工具,所谓轻量级指的是它的安装文件大小较小,但是其调试功能 ...

  2. 13、java中的多态

    1,多态的体现 父类的引用指向了自己的子类对象. 父类的引用也可以接收自己的子类对象.2,多态的前提 必须是类与类之间有关系.要么继承,要么实现. 通常还有一个前提:存在覆盖. 3,多态的好处 多态的 ...

  3. ajax请求获取的数据无法赋值给全局变量问题总结

    一.总结: 1.问题描述: 今天做项目遇到在用表单显示详细信息的过程中ajax请求获取的数据无法赋值给全局变量的情况,从列表页面进入详情页,在详情页面被渲染了之后就会调用js文件里的接口向服务器请求数 ...

  4. http load 的使用以及参数解释

    http load 的使用以及参数解释   1.参数含义 参数     全称      含义 -p        -parallel     并发的用户进程数.-f        -fetches   ...

  5. oracle中Update方法

    1.两表(多表)关联update -- 被修改值由另一个表运算而来 update customers a set city_name=(select b.city_name from tmp_cust ...

  6. Error #2044: 未处理的 IOErrorEvent:。 text=Error #2035: 找不到 URL这是flash加载外部资源时有时会遇到的问题,对于此问题解决如下

    导致这个错误的主要原因是未添加IOErrorEvent事件监听,或者添加了监听,但是加载时使用了unload() 参考资料: http://blog.csdn.net/chjh0540237/arti ...

  7. Async Programming - 1 async-await 糖的本质(2)

    上一篇讲了这么多,其实说的就是一个事,return会被编译器重写成SetResult,所以如果我们的异步函数返回的是一个Task<int>,代码就要改成这样: using System; ...

  8. policy

    template <class Apolicy> class Host {   Apolicy direct_policy_use;   Apolicy <SomeInternalT ...

  9. 用Spring+Junit4.4进行测试(使用注解)

    http://nottiansyf.iteye.com/blog/345819 使用Junit4.4测试 在类上的配置Annotation @RunWith(SpringJUnit4ClassRunn ...

  10. 【转】EXCEL不显示科学计数法

    源地址:http://jingyan.baidu.com/article/e4d08ffdcc304e0fd3f60d69.html 2法无效,不知道为何