![50f233eb054aef2a95b52372fc033aa6.png](https://i-blog.csdnimg.cn/blog_migrate/57b34a7d2cc1bd017151d5f55330b9ec.jpeg)
ffmpeg视频解码的使用。
一、ffmpeg初始化
- (void)videoDecoder_init {
avcodec_register_all();
// _videoFrame = av_frame_alloc();
AVCodec *codec = avcodec_find_decoder(AV_CODEC_ID_H264);
_videoCodecCtx = avcodec_alloc_context3(codec);
int ret = avcodec_open2(_videoCodecCtx, codec, nil);
if (ret != 0){
NSLog(@"open codec failed :%d",ret);
}
_videoFrame = av_frame_alloc();
av_init_packet(&_packet);
}
其中,
_videoCodecCtx是ffmpeg编解码对象;
_videoFrame是解码后的图像帧,可从中生成image图像;
_packet是解码前的数据帧,包括I帧、P帧等
二、解码操作
- (CGSize)videoDecoder_decodeToImage:(uint8_t *)nalBuffer size:(int)inSize {
_packet.size = inSize;
_packet.data = nalBuffer;
CGSize frameSize = {0, 0};
while (inSize > 0) {
int gotframe = 0;
int len = avcodec_decode_video2(_videoCodecCtx,
_videoFrame,
&gotframe,
&_packet);
if (len < 0) {
NSLog(@"decode video error, skip packet");
return frameSize;
}
inSize -= len;
}
frameSize.width = _videoCodecCtx->width;
frameSize.height = _videoCodecCtx->height;
_outputWidth = _videoCodecCtx->width;
self.outputHeight = _videoCodecCtx->height;
return frameSize;
}
三、获取解码后的图像
- (UIImage *)currentImage {
if (!_videoFrame->data[0]) {
return nil;
}
[self convertFrameToRGB];
return [self imageFromAVPicture:_picture width:_outputWidth height:_outputHeight];
}
- (void)convertFrameToRGB {
sws_scale(_img_convert_ctx, (const uint8_t * const*)_videoFrame->data, _videoFrame->linesize, 0, _videoCodecCtx->height, _picture.data, _picture.linesize);
}
- (UIImage *)imageFromAVPicture:(AVPicture)pict width:(int)width height:(int)height {
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
CFDataRef data = CFDataCreateWithBytesNoCopy(kCFAllocatorDefault, pict.data[0], pict.linesize[0] * height,kCFAllocatorNull);
CGDataProviderRef provider = CGDataProviderCreateWithCFData(data);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGImageRef cgImage = CGImageCreate(width,
height,
8,
24,
pict.linesize[0],
colorSpace,
bitmapInfo,
provider,
NULL,
YES,
kCGRenderingIntentDefault);
CGColorSpaceRelease(colorSpace);
UIImage *image = [[UIImage alloc]initWithCGImage:cgImage];
CGImageRelease(cgImage);
CGDataProviderRelease(provider);
CFRelease(data);
return image;
}
对解码后的图像传入UIImageView,即可进行视频播放。
首先恭喜您,能够认真的阅读到这里,如果对部分理解不太明白,建议先将文章收藏起来,然后对不清楚的知识点进行查阅,然后在进行阅读,相应你会有更深的认知。如果您喜欢这篇文章,就点个赞或者【关注我】吧!!