iOS直播App(编码篇)

直播技术概况来说分为:采集;前处理;编码;推流;解码;渲染。

1.首先为什么视频要进行编码?

  • 简单来说,未经编码的视频体积庞大,不论在保存还是传输来讲消耗资源过多。

2.为什么能进行编码?

  • 视频存在大量的冗余信息,包括空间冗余,时间冗余,视觉冗余等等。

3.编码标准:

  • 首先你需要知道两个标准化组织:
    International Telecommunications(通讯) Union 简称 ITU
    International Standards Organization 简称 ISO

  • 由ITU主导的编码标准:
    H.261 H.263 H.264 H.265
    目前使用较多的标准是H.264,H.265是目前的编码趋势。

4.接口开放历程

  • 在iOS8之前,苹果并没有开放硬编码的接口,所以我们只能用ffpeng+x264进行软编码。
  • 在iOS8之后,苹果开发了接口,并封装了VideoToolBox&AudioToolBox两个框架,分别对于视频/音频进行硬编码。

5.下面我们重点介绍硬编码,也就是VideoToolBox框架的使用。注解很详细,初学者可仔细看注释去理解。

//准备编码
- (void)prepareEncode{
    //-1.初始化写入文件的对象
    //-1.1.获取沙盒路径
    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true) firstObject] stringByAppendingPathComponent:@"123.h264"];
    
    //-1.2.删除原有文件,创建新文件
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    //-1.3.创建NSFileHandle对象
    self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    
    //0.设置frameIndex为0
    self.frameIndex = 0;
    int width = [UIScreen mainScreen].bounds.size.width;
    int height = [UIScreen mainScreen].bounds.size.height;
    
    //1.创建压缩会话
    // 1> 参数一:NULL CoreFoundation框架分配内存的类型,默认
    // 2> 参数二:视频的宽度
    // 3> 参数三:视频的高度
    // 4> 参数四:编码类型
    // 8> 参数八:成功编码一帧后的回调函数
    // 9> 参数久:对应回调函数里的第一个参数
    VTCompressionSessionCreate(NULL, width, height, kCMVideoCodecType_H264, NULL, NULL, NULL, didCompressionCallBack, (__bridge void * _Nullable)(self), &_compressionSession);
    
    //2.设置VTCompressionSession属性
    //设置视频的实时输出
    VTSessionSetProperty(self.compressionSession, kVTCompressionPropertyKey_RealTime, kCFBooleanTrue);
    //设置比特率(单位时间内保存的数据量)
    VTSessionSetProperty(self.compressionSession, kVTCompressionPropertyKey_AverageBitRate, (__bridge CFTypeRef _Nonnull)(@1500000));
    //设置帧率(每秒钟多少帧)
    VTSessionSetProperty(self.compressionSession, kVTCompressionPropertyKey_ExpectedFrameRate, (__bridge CFTypeRef _Nonnull)(@24));
    VTSessionSetProperty(self.compressionSession, kVTCompressionPropertyKey_DataRateLimits, (__bridge CFTypeRef _Nonnull)@[@(1500000 / 8), @1]);
    //关键帧最大间隔(GOP)
    VTSessionSetProperty(self.compressionSession, kVTCompressionPropertyKey_MaxKeyFrameInterval, (__bridge CFTypeRef _Nonnull)(@24));
    
    //3.准备开始编码
    VTCompressionSessionPrepareToEncodeFrames(_compressionSession);
}

//开始编码
- (void)encodeFrame:(CMSampleBufferRef)sampleBuffer{

    //将CMSampleBufferRef转化为CVImageBufferRef
    CVImageBufferRef imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);
    
    CMTime pts = CMTimeMake(self.frameIndex, 24);
    // 1> 参数一:编码对象
    // 2> 参数二:帧对象
    // 3> 参数三:显示时间戳
    // 4> 参数四:固定
    // 6> 参数六:当前对象
    // 7> 参数七:编码后的信息存放位置
    OSStatus staus = VTCompressionSessionEncodeFrame(self.compressionSession, imageBuffer, pts, kCMTimeInvalid, NULL, (__bridge void * _Nullable)(self), NULL);

    if (staus == noErr){
    
        NSLog(@"编码一帧数据成功");
    }
}

void didCompressionCallBack(
                                     void * CM_NULLABLE outputCallbackRefCon,
                                     void * CM_NULLABLE sourceFrameRefCon,
                                     OSStatus status,
                                     VTEncodeInfoFlags infoFlags,
                                                          CM_NULLABLE CMSampleBufferRef sampleBuffer ){
    
    //outputCallbackRefCon转化为H264Encoder
    H264Ecoder *encoder = (__bridge H264Ecoder *)(outputCallbackRefCon);
    
    //1.判断编码的该帧是否是关键帧
    CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(sampleBuffer, true);
    CFDictionaryRef attachmentDict = CFArrayGetValueAtIndex(attachments, 0);
    BOOL iskeyFrame = !CFDictionaryContainsKey(attachmentDict, kCMSampleAttachmentKey_NotSync);
    
    //2.是关键帧要获取sps/pps数据,然后写入文件
    if (iskeyFrame){
    
        //2.1获取编码后的信息
        CMFormatDescriptionRef format = CMSampleBufferGetFormatDescription(sampleBuffer);
        //2.2获取SPS信息
        // 1> 参数一: 编码后的信息
        // 2> 参数二: 0: sps, 1: pps
        const uint8_t *spsOut;
        size_t spsSize, spsCount;
        CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, 0, &spsOut, &spsSize, &spsCount, NULL);
        
        //2.3获取PPS信息
        const uint8_t *ppsOut;
        size_t ppsSize, ppsCount;
        CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format, 1, &ppsOut, &ppsSize, &ppsCount, NULL);

        //2.4.将sps/pps转化为NSData类型
        NSData *spsData = [NSData dataWithBytes:spsOut length:spsSize];
        NSData *ppsData = [NSData dataWithBytes:ppsOut length:ppsSize];
        
        //2.5.写入文件
        [encoder writeSps:spsData ppsData:ppsData];
    }
    
    //3.获取编码后的数据写入文件
    //3.1.获取CMBlockBufferRef
    CMBlockBufferRef blockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer);
    //3.2.从CMBlockBufferRef中获得起始位置的内存地址
    size_t totalLength = 0;
    char *dataPointer;
    CMBlockBufferGetDataPointer(blockBuffer, 0, NULL, &totalLength, &dataPointer);
    
    //3.3.一帧图像可能需要多个NALU单元 --> Slice切换
    static const int H264HeaderLength = 4;
    size_t bufferOffset = 0;
    while (bufferOffset < totalLength - H264HeaderLength) {
        //3.4.从起始位置开始拷贝长度为H264HeaderLength的地址,计算NALULength一个NALU单元有多长
        int NALULength = 0;
        memcpy(&NALULength, dataPointer + bufferOffset, H264HeaderLength);
        
        //大端模式/小端模式 --> 系统模式
        NALULength = CFSwapInt32BigToHost(NALULength);
        
        //3.5.从dataPointer开始,根据长度获取NSData
        NSData *data = [NSData dataWithBytes:dataPointer + bufferOffset + H264HeaderLength length:NALULength];
        //3.6.写入文件
        [encoder writeEncodedData:data];
        
        //3.7.重新赋值bufferOffset
        bufferOffset += H264HeaderLength + NALULength;
    }
    
}
//关键帧之前写入sps,pps
- (void)writeSps:(NSData *)spsData ppsData:(NSData *)ppsData{

    //1.定义NALU单元的Header,都是以0x00 00 00 01
    const char bytes[] = "\x00\x00\x00\x01";
    size_t length = (sizeof(bytes)) - 1;
    NSData *ByteHeaderData = [NSData dataWithBytes:bytes length:length];
    [self.fileHandle writeData:ByteHeaderData];
    [self.fileHandle writeData:spsData];
    [self.fileHandle writeData:ByteHeaderData];
    [self.fileHandle writeData:ppsData];
}
//写入帧数据
- (void)writeEncodedData:(NSData *)data{
    if (self.fileHandle != NULL){
        //1.定义NALU单元的Header,都是以0x00 00 00 01
        const char bytes[] = "\x00\x00\x00\x01";
        size_t length = (sizeof(bytes)) - 1;
        NSData *ByteHeader = [NSData dataWithBytes:bytes length:length];
        //2.写入数据
        [self.fileHandle writeData:ByteHeader];
        [self.fileHandle writeData:data];
    }
}

编码关键点整理,提供给各位参考:

1.创建压缩会话
VTCompressionSessionCreate()

2.设置压缩会话属性(比特率,帧率,关键帧最大间隔)
VTSessionSetProperty()

3.开始编码
VTCompressionSessionEncodeFrame()

4.编码成功后的回调函数中写入文件
void didCompressionCallBack()
4.1.判断是否是关键帧,如果是要取得sps,pps写入文件。
4.2.如果不是关键帧,获取CMBlockBufferRef分解成多个NALU单元,写入文件。

你可能感兴趣的:(iOS直播App(编码篇))