基于 FFMPEG 的视频解码(libavcodec ,致敬雷霄骅)-程序员宅基地

技术标签: 音视频  机器视觉+图像处理+数字信号处理  ffmpeg  

基于 FFMPEG 的视频解码(libavcodec ,致敬雷霄骅)

本文参考了雷博士的博客:

最简单的基于FFMPEG+SDL的视频播放器:拆分-解码器和播放器

基本上雷博士这篇博客已经把这个问题讲的挺清楚了。但是 ffmpeg 新版本的 API 有变化,这篇博客的代码已经无法直接编译运行。所以我写了今天这篇博客,用 新的 API 实现了视频解码的功能。

雷博士的代码除了视频解码还有音频解码,同时还利用 SDL 把视频显示出来了。 我觉得作为初学者还是每次学习的内容不要太多。既然我们的重点是视频解码,那就用最精简的代码来实现视频解码。这样我们的学习曲线才不会太陡峭。

前面几篇博客讲解了 libavformat 和 libswscale 这两个库的使用方法。所以这篇博客里不会再讲解相应的代码功能。如果有同学对我代码里涉及这两个库的用法不明白,可以先读读我的前几篇博客:

最简单的基于FFMPEG的封装格式转换器

基于 FFMPEG 的像素格式变换

libavcodec 的核心是 AVCodec 和 AVCodecContext。AVCodec 是具体的编解码器,AVCodecContext 则是编解码时所需的上下文环境。一个 AVStream 要对应一个AVCodecContext,一个 AVCodecContext 要关联上一个 AVCodec 。实际使用时有可能会有多个 AVCodecContext 关联同一个 AVCodec 的情况。尤其是我们解码音频的时候。比如我们的音频文件时 5.1声道的。通常会对应 3 个 AVStream。左右声道在一个 AVStream 里,环绕声在一个 AVStream,最后低音在另一个AVStream。 3 个AVStream的编码可能是相同的。那么我们要解码这个音频文件时就应该建立 3 个 AVCodecContext ,分别对应三个 AVStream。然后只需要有 1 个 AVCodec 。每个 AVCodecContext 都利用这一个 AVCodec 来解码。

上面是以音频解码为例,实际上视频解码也可能是这样的。比如我们有一个 3D 视频,里面就会有 2 个视频 AVStream,分别对应我们左眼和右眼看到的图像。这两个视频通常编码格式是相同的,所以可以公用一个 AVCodec 。但是一定要用两个 AVCodecContext 。

下面是解码前的准备工作,先要生成 AVCodec 和 AVCodecContext 的实例并打开。

AVCodecParameters * codecpar = pFormatCtx->streams[0]->codecpar;
AVCodec	*pCodec = avcodec_find_decoder(codecpar->codec_id);
if(pCodec == nullptr) qWarning() << "Cannot find_decoder";
AVCodecContext	*pCodecCtx = avcodec_alloc_context3(pCodec);
if(pCodecCtx == nullptr) qWarning() << "Cannot alloc pCodecCtx";
avcodec_parameters_to_context(pCodecCtx, codecpar);
if(avcodec_open2(pCodecCtx, pCodec, nullptr) < 0)
{
    printf("Could not open AVCodec.\n");
    exit(1);
}

到这里Codec 就建好了。所谓解码就是把一个 AVPacket 中的数据解成 AVFrame。简单的说 AVFrame 是原始的,没有编码、没有压缩的数据,编码压缩之后的数据叫做 AVPacket 。

那么,一个 AVPacket 是对应一个 AVFrame 吗?从逻辑上讲是这样的,但是实际上,经常我们有了一个 AVPacket ,却并不能当时就解出 AVFrame 来。因为我们知道视频帧 分为 I帧,P帧和 B 帧。如果 一个 AVPacket 里面的数据是 I帧 那么我们就可以直接解出 AVFrame 。P帧 需要参考前一帧的数据,B 帧还需要有后一帧的数据才能解码。所以我们会遇到前几个 AVPacket 解不出数据。到了某个 AVPacket ,可以连续解出多个 AVFrame 来的情况。这时这 多个 AVFrame 就包括前面积压的 AVPacket 里的数据。

在旧版 FFMPEG 中,是用下面这个函数来解码。

int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
                         int *got_picture_ptr,
                         const AVPacket *avpkt);

这里 got_picture_ptr 就是标明是否可以从当前帧解出 AVFrame。

下面的代码片段来自雷博士的博客:https://blog.csdn.net/leixiaohua1020/article/details/46889389

这个代码给出了一个解码的框架。

while(av_read_frame(pFormatCtx, packet) >=0 )
{
	if(packet->stream_index == videoindex)
	{
		ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
		if(ret < 0)
		{
			printf("Decode Error.\n");
			return -1;
		}
		if(got_picture)
		{
			// 到这里表示成功解出一个 Frame,可以用这个 Frame 中的数据做我们正式的工作了
			printf("Flush Decoder: Succeed to decode 1 frame!\n");

		}
	}
	av_free_packet(packet);
}
//flush decoder
//FIX: Flush Frames remained in Codec
while (1) 
{
	ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
	if (ret < 0)
		break;
	if (!got_picture)
		break;
	// 到这里表示成功解出一个 Frame,可以用这个 Frame 中的数据做我们正式的工作了
	printf("Flush Decoder: Succeed to decode 1 frame!\n");
}

这个代码里后面多了一个 while() 循环,就是解决 Codec 中积存的 Frame 问题。

我个人猜测,可能就是由于解码代码中必须要多这一段,让人总感觉这代码不那么清爽。所以 ffmpeg 的作者才把 avcodec_decode_video2() 函数给废弃了的。我们的新代码中应该使用如下两个函数:

int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt);
int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame);

简单的说这两个函数就是解决了 avcodec_decode_video2() 函数强制要求 Packet 和 Frame 一对一的问题。让我们可以往Codec 推一个 Packet ,然后读出多个 frame 来。当然,这多个 frame 并不是真的是从这个 packet 里解出来的,还可能包括以前推到 Codec 里的其他 packet 的的数据。

新版的这两个函数的用法可以参考 ffmpeg 自带的例子代码 demuxing_decoding.c。 代码片段如下:

while (av_read_frame(fmt_ctx, pkt) >= 0) {
    // check if the packet belongs to a stream we are interested in, otherwise
    // skip it
    if (pkt->stream_index == video_stream_idx)
        ret = decode_packet(video_dec_ctx, pkt);
    else if (pkt->stream_index == audio_stream_idx)
        ret = decode_packet(audio_dec_ctx, pkt);
    av_packet_unref(pkt);
    if (ret < 0)
        break;
}

解码操作集中在 decode_packet() 函数中了,调用一次 avcodec_send_packet() 将一个 packet 推给Codec,然后 调用一次或多次 avcodec_receive_frame() 来获得 frame:

static int decode_packet(AVCodecContext *dec, const AVPacket *pkt)
{
    int ret = 0;

    // submit the packet to the decoder
    ret = avcodec_send_packet(dec, pkt);
    if (ret < 0) {
        fprintf(stderr, "Error submitting a packet for decoding (%s)\n", av_err2str(ret));
        return ret;
    }

    // get all the available frames from the decoder
    while (ret >= 0) {
        ret = avcodec_receive_frame(dec, frame);
        if (ret < 0) {
            // those two return values are special and mean there is no output
            // frame available, but there were no errors during decoding
            if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
                return 0;

            fprintf(stderr, "Error during decoding (%s)\n", av_err2str(ret));
            return ret;
        }

        // write the frame data to output file
        if (dec->codec->type == AVMEDIA_TYPE_VIDEO)
            ret = output_video_frame(frame);
        else
            ret = output_audio_frame(frame);

        av_frame_unref(frame);
        if (ret < 0)
            return ret;
    }

    return 0;
}

仿照这个代码,我做了一个小例子,这个小例子中,我将视频帧存到图像文件中。当然,一个视频文件的帧数很多,全都存文件太占硬盘空间了。所以我是每隔 10 帧存一幅图像。并且也不是从视频的开始就存,而是 seek 到了一个比较靠后的地方。存图像这个操作我用到了 Qt 的 QImage 类。没有用过 Qt 的同学可以忽略那一两行代码。不过Qt 真的很好用,建议有点 C++ 基础的同学都可以学学。

void save(AVFrame *pFrame, int frameCount)
{
    int srcWidth = pFrame->width;
    int srcHeight = pFrame->height;
    AVPixelFormat srcFormat = (AVPixelFormat)pFrame->format;

    struct SwsContext *imageConvertContex = sws_getContext(srcWidth, srcHeight, srcFormat,
                                                        srcWidth, srcHeight, AV_PIX_FMT_RGB24,
                                                        SWS_BICUBIC, nullptr, nullptr, nullptr);

    QImage image(srcWidth, srcHeight, QImage::Format_RGB888);
    uint8_t *out_data[1];
    int out_linesize[1];
    av_image_fill_arrays(out_data, out_linesize, image.bits(), AV_PIX_FMT_RGB24, srcWidth, srcHeight, 1);


    //转格式
    sws_scale(imageConvertContex,
        pFrame->data, pFrame->linesize, 0, srcHeight,
        out_data, out_linesize);

    if(imageConvertContex) sws_freeContext(imageConvertContex);
    QString fileName = QString("d:/AV_%1.jpg").arg(frameCount);
    image.save(fileName);
}
int decode_packet(AVCodecContext *dec, const AVPacket *pkt, AVFrame	*pFrame)
{
    static int frameCount = 0;
    int ret = 0;

    //avcodec_decode_video2();
    // submit the packet to the decoder
    ret = avcodec_send_packet(dec, pkt);
    if (ret < 0) {
        //fprintf(stderr, "Error submitting a packet for decoding (%s)\n", av_err2str(ret));
        return ret;
    }

    // get all the available frames from the decoder
    while (ret >= 0) {
        ret = avcodec_receive_frame(dec, pFrame);
        if (ret < 0) {
            // those two return values are special and mean there is no output
            // frame available, but there were no errors during decoding
            if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
                return 0;

            //fprintf(stderr, "Error during decoding (%s)\n", av_err2str(ret));
            return ret;
        }
        frameCount ++;

        // write the frame data to output file
        if(frameCount % 10 == 1)
        {
            qDebug() <<(AVPixelFormat) pFrame->format << ", packetCount = " << packetCount << ", frameCount = " << frameCount;
            save(pFrame, frameCount);
        }

        av_frame_unref(pFrame);
    }

    return 0;
}


void test03()
{
    const char * filename = "D:\\AV36_1.avi";
    AVFormatContext *pFormatCtx = avformat_alloc_context();
    msg("avformat_open_input",
        avformat_open_input(&pFormatCtx, filename, nullptr, nullptr));
    msg("avformat_find_stream_info",
        avformat_find_stream_info(pFormatCtx, nullptr));
    av_dump_format(pFormatCtx, 0, filename, 0);

    AVCodecParameters * codecpar = pFormatCtx->streams[0]->codecpar;
    AVCodec	*pCodec = avcodec_find_decoder(codecpar->codec_id);
    if(pCodec == nullptr) qWarning() << "Cannot find_decoder";
    AVCodecContext	*pCodecCtx = avcodec_alloc_context3(pCodec);
    if(pCodecCtx == nullptr) qWarning() << "Cannot alloc pCodecCtx";
    avcodec_parameters_to_context(pCodecCtx, codecpar);
    if(avcodec_open2(pCodecCtx, pCodec, nullptr) < 0)
    {
        printf("Could not open AVCodec.\n");
        exit(1);
    }
    av_seek_frame(pFormatCtx, -1, 30 * AV_TIME_BASE, AVSEEK_FLAG_BACKWARD);
    AVPacket pkt;
    while (1)
    {
        int ret = av_read_frame(pFormatCtx, &pkt);
        if (ret < 0)  break;

        if (pkt.stream_index != 0)
        {
            av_packet_unref(&pkt);
            continue;
        }
        AVFrame	*pFrame = av_frame_alloc();
        AVFrame *pFrameRGB32 = av_frame_alloc();

        packetCount++;
        decode_packet(pCodecCtx, &pkt, pFrame);

        av_frame_free(&pFrameRGB32);
        av_frame_free(&pFrame);
        av_packet_unref(&pkt);
    }
    avformat_close_input(&pFormatCtx);
}

输出结果如下,总共保存了 5 张图片:

avformat_open_input : success.
avformat_find_stream_info : success.
Input #0, avi, from 'D:\AV36_1.avi':
  Duration: 00:00:32.93, start: 0.000000, bitrate: 2372 kb/s
  Stream #0:0: Video: indeo5 (IV50 / 0x30355649), yuv410p, 320x240, 2058 kb/s, 15 fps, 15 tbr, 15 tbn, 15 tbc
    Metadata:
      title           : Steyr.avi ���#1
  Stream #0:1: Audio: adpcm_ms ([2][0][0][0] / 0x0002), 22050 Hz, 2 channels, s16, 176 kb/s
    Metadata:
      title           : Sound Forge 4.0 Audio
AV_PIX_FMT_YUV410P, packetCount = 1, frameCount = 1
AV_PIX_FMT_YUV410P, packetCount = 11, frameCount = 11
AV_PIX_FMT_YUV410P, packetCount = 21, frameCount = 21
AV_PIX_FMT_YUV410P, packetCount = 31, frameCount = 31
AV_PIX_FMT_YUV410P, packetCount = 41, frameCount = 41

好了,这一讲就讲这么多。下一篇博客准备将这篇博客的内容用 C++ 来封装一下。封装之后的代码会极度的清爽。请大家拭目以待。

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/liyuanbhu/article/details/121885984

智能推荐

874计算机科学基础综合,2018年四川大学874计算机科学专业基础综合之计算机操作系统考研仿真模拟五套题...-程序员宅基地

文章浏览阅读1.1k次。一、选择题1. 串行接口是指( )。A. 接口与系统总线之间串行传送,接口与I/0设备之间串行传送B. 接口与系统总线之间串行传送,接口与1/0设备之间并行传送C. 接口与系统总线之间并行传送,接口与I/0设备之间串行传送D. 接口与系统总线之间并行传送,接口与I/0设备之间并行传送【答案】C2. 最容易造成很多小碎片的可变分区分配算法是( )。A. 首次适应算法B. 最佳适应算法..._874 计算机科学专业基础综合题型

XShell连接失败:Could not connect to '192.168.191.128' (port 22): Connection failed._could not connect to '192.168.17.128' (port 22): c-程序员宅基地

文章浏览阅读9.7k次,点赞5次,收藏15次。连接xshell失败,报错如下图,怎么解决呢。1、通过ps -e|grep ssh命令判断是否安装ssh服务2、如果只有客户端安装了,服务器没有安装,则需要安装ssh服务器,命令:apt-get install openssh-server3、安装成功之后,启动ssh服务,命令:/etc/init.d/ssh start4、通过ps -e|grep ssh命令再次判断是否正确启动..._could not connect to '192.168.17.128' (port 22): connection failed.

杰理之KeyPage【篇】_杰理 空白芯片 烧入key文件-程序员宅基地

文章浏览阅读209次。00000000_杰理 空白芯片 烧入key文件

一文读懂ChatGPT,满足你对chatGPT的好奇心_引发对chatgpt兴趣的表述-程序员宅基地

文章浏览阅读475次。2023年初,“ChatGPT”一词在社交媒体上引起了热议,人们纷纷探讨它的本质和对社会的影响。就连央视新闻也对此进行了报道。作为新传专业的前沿人士,我们当然不能忽视这一热点。本文将全面解析ChatGPT,打开“技术黑箱”,探讨它对新闻与传播领域的影响。_引发对chatgpt兴趣的表述

中文字符频率统计python_用Python数据分析方法进行汉字声调频率统计分析-程序员宅基地

文章浏览阅读259次。用Python数据分析方法进行汉字声调频率统计分析木合塔尔·沙地克;布合力齐姑丽·瓦斯力【期刊名称】《电脑知识与技术》【年(卷),期】2017(013)035【摘要】该文首先用Python程序,自动获取基本汉字字符集中的所有汉字,然后用汉字拼音转换工具pypinyin把所有汉字转换成拼音,最后根据所有汉字的拼音声调,统计并可视化拼音声调的占比.【总页数】2页(13-14)【关键词】数据分析;数据可..._汉字声调频率统计

linux输出信息调试信息重定向-程序员宅基地

文章浏览阅读64次。最近在做一个android系统移植的项目,所使用的开发板com1是调试串口,就是说会有uboot和kernel的调试信息打印在com1上(ttySAC0)。因为后期要使用ttySAC0作为上层应用通信串口,所以要把所有的调试信息都给去掉。参考网上的几篇文章,自己做了如下修改,终于把调试信息重定向到ttySAC1上了,在这做下记录。参考文章有:http://blog.csdn.net/longt..._嵌入式rootfs 输出重定向到/dev/console

随便推点

uniapp 引入iconfont图标库彩色symbol教程_uniapp symbol图标-程序员宅基地

文章浏览阅读1.2k次,点赞4次,收藏12次。1,先去iconfont登录,然后选择图标加入购物车 2,点击又上角车车添加进入项目我的项目中就会出现选择的图标 3,点击下载至本地,然后解压文件夹,然后切换到uniapp打开终端运行注:要保证自己电脑有安装node(没有安装node可以去官网下载Node.js 中文网)npm i -g iconfont-tools(mac用户失败的话在前面加个sudo,password就是自己的开机密码吧)4,终端切换到上面解压的文件夹里面,运行iconfont-tools 这些可以默认也可以自己命名(我是自己命名的_uniapp symbol图标

C、C++ 对于char*和char[]的理解_c++ char*-程序员宅基地

文章浏览阅读1.2w次,点赞25次,收藏192次。char*和char[]都是指针,指向第一个字符所在的地址,但char*是常量的指针,char[]是指针的常量_c++ char*

Sublime Text2 使用教程-程序员宅基地

文章浏览阅读930次。代码编辑器或者文本编辑器,对于程序员来说,就像剑与战士一样,谁都想拥有一把可以随心驾驭且锋利无比的宝剑,而每一位程序员,同样会去追求最适合自己的强大、灵活的编辑器,相信你和我一样,都不会例外。我用过的编辑器不少,真不少~ 但却没有哪款让我特别心仪的,直到我遇到了 Sublime Text 2 !如果说“神器”是我能给予一款软件最高的评价,那么我很乐意为它封上这么一个称号。它小巧绿色且速度非

对10个整数进行按照从小到大的顺序排序用选择法和冒泡排序_对十个数进行大小排序java-程序员宅基地

文章浏览阅读4.1k次。一、选择法这是每一个数出来跟后面所有的进行比较。2.冒泡排序法,是两个相邻的进行对比。_对十个数进行大小排序java

物联网开发笔记——使用网络调试助手连接阿里云物联网平台(基于MQTT协议)_网络调试助手连接阿里云连不上-程序员宅基地

文章浏览阅读2.9k次。物联网开发笔记——使用网络调试助手连接阿里云物联网平台(基于MQTT协议)其实作者本意是使用4G模块来实现与阿里云物联网平台的连接过程,但是由于自己用的4G模块自身的限制,使得阿里云连接总是无法建立,已经联系客服返厂检修了,于是我在此使用网络调试助手来演示如何与阿里云物联网平台建立连接。一.准备工作1.MQTT协议说明文档(3.1.1版本)2.网络调试助手(可使用域名与服务器建立连接)PS:与阿里云建立连解释,最好使用域名来完成连接过程,而不是使用IP号。这里我跟阿里云的售后工程师咨询过,表示对应_网络调试助手连接阿里云连不上

<<<零基础C++速成>>>_无c语言基础c++期末速成-程序员宅基地

文章浏览阅读544次,点赞5次,收藏6次。运算符与表达式任何高级程序设计语言中,表达式都是最基本的组成部分,可以说C++中的大部分语句都是由表达式构成的。_无c语言基础c++期末速成