04:videoToolbox:硬编码

一:前言:

1:apple develop 来源

2:VideoToolbox(视频工具箱)工作流程

  2.1:创建 一个压缩会话。

  2.2:添加会话属性。

  2.3:编码视频帧、接受视频编码回调。

  2.4:强制完成一些或者全部未处理的视频帧。

  2.5:释放压缩会话、释放内存资源。

3:demo 地址

 

 

二:正文

下面介绍使用VTCompressionSession对接收视频数据的压缩编码;

工作流程:

1:创建 一个compression sessioin

VTCompressionSessionCreate(CFAllocatorRef  _Nullable allocator,      //1: 分配器,如果使用NULL的话,就使用默认的.
                           int32_t width,                   //2: 视频帧的象素宽
                           int32_t height,                   //3: 视频帧的象素高
                           CMVideoCodecType codecType,            //4: 编码器的类型
                           CFDictionaryRef  _Nullable encoderSpecification,  //5:编码器规格: 如果用指定的视频编码器,就要设置这个.使用NULL就是videoToolbox自己选择一个.
                           CFDictionaryRef  _Nullable sourceImageBufferAttributes,  //6:元象素缓存属性,如果你不要videoToolbox给你创建,就传NULL.使用未由VideoToolbox分配的像素缓冲区可能会增加您复制图像数据的机会。
                           CFAllocatorRef  _Nullable compressedDataAllocator,  //7:压缩数据分配器.传NULL可以使用默认的.
                           VTCompressionOutputCallback  _Nullable outputCallback,  //8:回调,这个方法会在另一个线程上被异步的VTCompressionSessionEncodeFrame
                           调用.只有在你要使VTCompressionSessionEncodeFrameWithOutputHandler去编码帧时,才可以设置为NULL.
                           void * _Nullable outputCallbackRefCon,  //9:回调方法所在的实例,回调方法是全局的可以设置为NULL
                           VTCompressionSessionRef  _Nullable * _Nonnull compressionSessionOut)  //10:用来接收新的compression session

示例:

OSStatus status = VTCompressionSessionCreate(NULL, width, height, kCMVideoCodecType_H264, NULL, NULL, NULL, didCompressH264, (__bridge void *)(self),  &EncodingSession);
if (status != 0)
{
    NSLog(@"Error by VTCompressionSessionCreate  ");
    return ;
}
//continue...

2:(可选)配置session的属性(Compression Properties)

2.1:码流配置

  kVTCompressionPropertyKey_Depth:编码视频的像素深度。

  kVTCompressionPropertyKey_ProfileLevel:配置文件和级别. ProfileLevel,h264的协议等级,不同的清晰度使用不同的ProfileLevel。

  kVTCompressionPropertyKey_H264EntropyMode.264压缩的熵编码模式。

2.2:缓冲区

  kVTCompressionPropertyKey_NumberOfPendingFrames:压缩会话中的待处理帧数。

   kVTCompressionPropertyKey_PixelBufferPoolIsShared:一个布尔值,指示公共像素缓冲池是否在视频编码器和会话客户端之间共享。

  kVTCompressionPropertyKey_VideoEncoderPixelBufferAttributes:视频编码器的压缩会话的像素缓冲区属性。

2.3: 清洁光圈和像素宽高比

  kVTCompressionPropertyKey_AspectRatio16x9:一个布尔值,指示DV视频流是否应设置16x9标志。

  kVTCompressionPropertyKey_CleanAperture:用于编码帧的干净光圈。

  kVTCompressionPropertyKey_FieldCount:字段计数指示帧应该是逐行编码(1)还是隔行编码(2)。

  kVTCompressionPropertyKey_FieldDetail:编码隔行扫描帧的场排序。

  kVTCompressionPropertyKey_PixelAspectRatio:编码帧的像素长宽比。

  kVTCompressionPropertyKey_ProgressiveScan:一个布尔值,指示DV视频流是否应设置渐进标志。

2.4:颜色

  kVTCompressionPropertyKey_ColorPrimaries:压缩内容的颜色原色。

  kVTCompressionPropertyKey_TransferFunction:压缩内容的传递函数。

  kVTCompressionPropertyKey_YCbCrMatrix:压缩内容的YCbCr矩阵。

  kVTCompressionPropertyKey_ICCProfile:压缩内容的ICC配置文件。

2.5:预期值

  kVTCompressionPropertyKey_ExpectedDuration:压缩会话的预期总持续时间(如果已知)

  kVTCompressionPropertyKey_ExpectedFrameRate:预期的帧速率,如果已知的话。

  kVTCompressionPropertyKey_SourceFrameCount 源帧的数量(如果已知)。

2.6:帧依赖

  kVTCompressionPropertyKey_AllowFrameReordering:一个布尔值,指示是否启用帧重新排序。

  kVTCompressionPropertyKey_AllowTemporalCompression:一个布尔值,指示是否启用时间压缩。

  kVTCompressionPropertyKey_MaxKeyFrameInterval:关键帧之间的最大间隔,也称为关键帧速率。设置关键帧(GOPsize)间隔; 关键帧最大间隔,关键帧也就是I帧。

  kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration:从一个关键帧到下一个关键帧的最长持续时间(秒)。

2.7:硬件加速

  kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder一个布尔值,指示是否使用硬件加速的视频编码器。

  kVTVideoEncoderSpecification_RequireHardwareAcceleratedVideoEncoder:一个布尔值,指示是否需要硬件加速编码。

  kVTVideoEncoderSpecification_EnableHardwareAcceleratedVideoEncoder:一个布尔值,指示是否允许硬件加速视频编码(如果可用)。

2.8:多通道存储

  kVTCompressionPropertyKey_MultiPassStorage一个属性键,用于启用多通道压缩并为编码器私有数据提供存储。

2.9:每帧配置

  kVTEncodeFrameOptionKey_ForceKeyFrame:布尔值,指示当前帧是否被强制为关键帧。

2.10:预压缩处理

  kVTCompressionPropertyKey_PixelTransferProperties:如有必要,配置VTPixelTransferSession以将源帧从客户端的图像缓冲区传输到视频编码器的图像缓冲区的属性。

2.11:速率控制

  kVTCompressionPropertyKey_AverageBitRate:长期所需的平均比特率,以每秒位数为单位。设置码率,均值,单位是byte

  kVTCompressionPropertyKey_DataRateLimits:数据速率的零,一或两个硬限制。码率上线。

  kVTCompressionPropertyKey_MoreFramesAfterEnd:一个布尔值,指示压缩会话的帧是否以及如何与其他压缩帧连接以形成更长的序列。

  kVTCompressionPropertyKey_MoreFramesBeforeStart:一个布尔值,指示压缩会话的帧是否以及如何与其他压缩帧连接以形成更长的序列。

  kVTCompressionPropertyKey_Quality:所需的压缩质量。

2.12:运行时限制

  kVTCompressionPropertyKey_RealTime:一个布尔值,指示是否建议视频编码器实时执行压缩。设置实时编码

  kVTCompressionPropertyKey_MaxH264SliceBytes:H.264编码的最大切片大小。

  kVTCompressionPropertyKey_MaxFrameDelayCount:压缩器在必须输出压缩帧之前允许保留的最大帧数。

 

 使用VTSessionSetProperty(_:_:_:)VTSessionSetProperties(_:_:)

示例

VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue);//1:实时运行
VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_ProfileLevel, kVTProfileLevel_H264_Baseline_4_1);

SInt32 bitRate = width*height*50;  //2:越高效果越屌  帧数据越大.码率
CFNumberRef ref = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &bitRate);
VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_AverageBitRate, ref);
CFRelease(ref);

int frameInterval = 10; //关键帧间隔 越低效果越屌 帧数据越大
CFNumberRef  frameIntervalRef = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &frameInterval);
VTSessionSetProperty(EncodingSession, kVTCompressionPropertyKey_MaxKeyFrameInterval,frameIntervalRef);
CFRelease(frameIntervalRef);

还有其它很多,可以去属性查看

 

3:编码视频一帧、接受视频回调

VTCompressionSessionEncodeFrame(VTCompressionSessionRef  _Nonnull session,  //1:已经被定义的compress session
                                CVImageBufferRef  _Nonnull imageBuffer,    //2:包含了一帧要被压缩的视频帧,这个buffer必须要有值.
                                CMTime presentationTimeStamp,          //3:这一帧要显示的时间,这个会关联到采样缓存.每一个显示时间都必须要大于前一次的时间.
                                CMTime duration ,                 //4:这一帧要显示的持续时间,会关联到采样缓存,如果你没有持续时间,传kCMTimeInvalid.
                                CFDictionaryRef  _Nullable frameProperties,   //5:帧属性
                                void * _Nullable sourceFrameRefCon,      //6:帧的引用值,这个会被传给输出回调方法.
                                VTEncodeInfoFlags * _Nullable infoFlagsOut)  //7:接受编码操作的信息,可以传NULL

示例:

3.1:压缩帧数据

- (void) encode:(CMSampleBufferRef )sampleBuffer
{
    if (EncodingSession==nil||EncodingSession==NULL)
    {
        return;
    }
    dispatch_sync(aQueue, ^{
        frameCount++;
        CVImageBufferRef imageBuffer = (CVImageBufferRef)CMSampleBufferGetImageBuffer(sampleBuffer);
        CMTime presentationTimeStamp = CMTimeMake(frameCount, 1000);
        VTEncodeInfoFlags flags;
        OSStatus statusCode = VTCompressionSessionEncodeFrame(EncodingSession,
                                                              imageBuffer,
                                                              presentationTimeStamp,
                                                              kCMTimeInvalid,
                                                              NULL, NULL, &flags);
        if (statusCode != noErr)
        {
            if (EncodingSession!=nil||EncodingSession!=NULL)
            {
                VTCompressionSessionInvalidate(EncodingSession);
                CFRelease(EncodingSession);
                EncodingSession = NULL;
                return;
            }
        }
    });
}

3.2:帧压缩完成时调用的回调原型。

创建压缩会话时,传入一个回调函数以调用压缩帧。以解码顺序调用此函数(不一定与显示顺序相同)。

typedef void (*VTCompressionOutputCallback)(
void *outputCallbackRefCon, // 1: 回调的参考值。
void *sourceFrameRefCon, // 2:框架的引用值,从sourceFrameRefCon参数复制到VTCompressionSessionEncodeFrame
OSStatus status,        // 3:noErr如果压缩成功;压缩不成功时的错误代码。
VTEncodeInfoFlags infoFlags, // 4:
包含有关编码操作的信息。如果编码异步运行,则可以设置kVTEncodeInfo_Asynchronous位。如果帧被丢弃,则可以设置kVTEncodeInfo_FrameDropped位.
 CMSampleBufferRef sampleBuffer  // 5:如果压缩成功并且帧未被丢弃,则包含压缩帧;否则,为NULL。
);

 

4.强制完成一些或全部未处理的视频帧.

调用VTCompressionSessionCompleteFrames(_:_:)

VTCompressionSessionCompleteFrames(VTCompressionSessionRef  _Nonnull session,//compression session
                                   CMTime completeUntilPresentationTimeStamp) // 视频帧关联的时间

如果completeUntilPresentationTimeStamp是数字的话,包括当前时间和之前时间的帧都会在方法返回前发出(处理完)?.
如果completeUntilPresentationTimeStamp是不是数字的话,全部的未处理的帧都会在方法返回前发出(处理完?).

示例

VTCompressionSessionCompleteFrames(EncodingSession, kCMTimeInvalid); 
5.当你要结果编码时.

调用VTCompressionSessionInvalidate(_:)使session无效,并用CFRelease去释放内存.

示例

VTCompressionSessionInvalidate(EncodingSession);
CFRelease(EncodingSession);
EncodingSession = NULL;

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

在编码完成时会在

typedef void (*VTCompressionOutputCallback)(
        void * CM_NULLABLE outputCallbackRefCon,
        void * CM_NULLABLE sourceFrameRefCon, 
        OSStatus status, 
        VTEncodeInfoFlags infoFlags,
        CM_NULLABLE CMSampleBufferRef sampleBuffer );

里返回,详见上面的第一条.

void didCompressH264(void *outputCallbackRefCon, void *sourceFrameRefCon, OSStatus status, VTEncodeInfoFlags infoFlags,
                     CMSampleBufferRef sampleBuffer )
{
   
  // 1:判断编码是否完成  if (status != 0) return; // 2:判断数据是否完整。 if (!CMSampleBufferDataIsReady(sampleBuffer)) { NSLog(@"didCompressH264 data is not ready "); return; }
  
// 3:通过outputCallbackRefCon获取AWHEncoder的对象指针,将编码好的h264数据传出去。
H264HwEncoderImpl* encoder = (__bridge H264HwEncoderImpl*)outputCallbackRefCon; CFArrayRef array = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, true); const void * value = CFArrayGetValueAtIndex(array, 0); bool keyframe = !CFDictionaryContainsKey(value, kCMSampleAttachmentKey_NotSync);
  // 4:判断是否是关键帧 if (keyframe) {
      CMFormatDescriptionRef format = CMSampleBufferGetFormatDescription(sampleBuffer); size_t sparameterSetSize, sparameterSetCount; const uint8_t *sparameterSet; //提取SPS<<<<< OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, 0, &sparameterSet, &sparameterSetSize, &sparameterSetCount, NULL ); if (statusCode == noErr) { size_t pparameterSetSize, pparameterSetCount; const uint8_t *pparameterSet; //提取PPS<<<<<<< OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, 1, &pparameterSet, &pparameterSetSize, &pparameterSetCount, 0 ); if (statusCode == noErr) { encoder->sps = [NSData dataWithBytes:sparameterSet length:sparameterSetSize]; encoder->pps = [NSData dataWithBytes:pparameterSet length:pparameterSetSize]; if (encoder->_delegate) { [encoder->_delegate gotSpsPps:encoder->sps pps:encoder->pps]; } } } } //提取IDR<<<<<<< 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; while (bufferOffset < totalLength - AVCCHeaderLength) { uint32_t NALUnitLength = 0; memcpy(&NALUnitLength, dataPointer + bufferOffset, AVCCHeaderLength); NALUnitLength = CFSwapInt32BigToHost(NALUnitLength); NSData* data = [[NSData alloc] initWithBytes:(dataPointer + bufferOffset + AVCCHeaderLength) length:NALUnitLength]; [encoder->_delegate gotEncodedData:data isKeyFrame:keyframe]; bufferOffset += AVCCHeaderLength + NALUnitLength; } } }

分解:
用以下方法,可以把SPS.PPS提取出来.

OSStatus statusCode = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format,
                                                                         0,
                                                                         &sparameterSet,
                                                                         &sparameterSetSize,
                                                                         &sparameterSetCount,
                                                                         NULL );

用以下方法,可以把IDR提取出来,

    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;
        while (bufferOffset < totalLength - AVCCHeaderLength)
        {
            uint32_t NALUnitLength = 0;
            memcpy(&NALUnitLength, dataPointer + bufferOffset, AVCCHeaderLength);//取出头4个字节存到NALUintLength,
            NALUnitLength = CFSwapInt32BigToHost(NALUnitLength);//把字节顺序反转一下,得到数据长度.
            NSData* data = [[NSData alloc] initWithBytes:(dataPointer + bufferOffset + AVCCHeaderLength) length:NALUnitLength];
            [encoder->_delegate gotEncodedData:data isKeyFrame:keyframe];
            bufferOffset += AVCCHeaderLength + NALUnitLength;
        }
    }



链接:https://www.jianshu.com/p/7a355a1dbfb9

posted on 2018-07-26 16:01  风zk  阅读(2620)  评论(0编辑  收藏  举报

导航