基于 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

智能推荐

while循环&CPU占用率高问题深入分析与解决方案_main函数使用while(1)循环cpu占用99-程序员宅基地

文章浏览阅读3.8k次,点赞9次,收藏28次。直接上一个工作中碰到的问题,另外一个系统开启多线程调用我这边的接口,然后我这边会开启多线程批量查询第三方接口并且返回给调用方。使用的是两三年前别人遗留下来的方法,放到线上后发现确实是可以正常取到结果,但是一旦调用,CPU占用就直接100%(部署环境是win server服务器)。因此查看了下相关的老代码并使用JProfiler查看发现是在某个while循环的时候有问题。具体项目代码就不贴了,类似于下面这段代码。​​​​​​while(flag) {//your code;}这里的flag._main函数使用while(1)循环cpu占用99

【无标题】jetbrains idea shift f6不生效_idea shift +f6快捷键不生效-程序员宅基地

文章浏览阅读347次。idea shift f6 快捷键无效_idea shift +f6快捷键不生效

node.js学习笔记之Node中的核心模块_node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是-程序员宅基地

文章浏览阅读135次。Ecmacript 中没有DOM 和 BOM核心模块Node为JavaScript提供了很多服务器级别,这些API绝大多数都被包装到了一个具名和核心模块中了,例如文件操作的 fs 核心模块 ,http服务构建的http 模块 path 路径操作模块 os 操作系统信息模块// 用来获取机器信息的var os = require('os')// 用来操作路径的var path = require('path')// 获取当前机器的 CPU 信息console.log(os.cpus._node模块中有很多核心模块,以下不属于核心模块,使用时需下载的是

数学建模【SPSS 下载-安装、方差分析与回归分析的SPSS实现(软件概述、方差分析、回归分析)】_化工数学模型数据回归软件-程序员宅基地

文章浏览阅读10w+次,点赞435次,收藏3.4k次。SPSS 22 下载安装过程7.6 方差分析与回归分析的SPSS实现7.6.1 SPSS软件概述1 SPSS版本与安装2 SPSS界面3 SPSS特点4 SPSS数据7.6.2 SPSS与方差分析1 单因素方差分析2 双因素方差分析7.6.3 SPSS与回归分析SPSS回归分析过程牙膏价格问题的回归分析_化工数学模型数据回归软件

利用hutool实现邮件发送功能_hutool发送邮件-程序员宅基地

文章浏览阅读7.5k次。如何利用hutool工具包实现邮件发送功能呢?1、首先引入hutool依赖<dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.7.19</version></dependency>2、编写邮件发送工具类package com.pc.c..._hutool发送邮件

docker安装elasticsearch,elasticsearch-head,kibana,ik分词器_docker安装kibana连接elasticsearch并且elasticsearch有密码-程序员宅基地

文章浏览阅读867次,点赞2次,收藏2次。docker安装elasticsearch,elasticsearch-head,kibana,ik分词器安装方式基本有两种,一种是pull的方式,一种是Dockerfile的方式,由于pull的方式pull下来后还需配置许多东西且不便于复用,个人比较喜欢使用Dockerfile的方式所有docker支持的镜像基本都在https://hub.docker.com/docker的官网上能找到合..._docker安装kibana连接elasticsearch并且elasticsearch有密码

随便推点

Python 攻克移动开发失败!_beeware-程序员宅基地

文章浏览阅读1.3w次,点赞57次,收藏92次。整理 | 郑丽媛出品 | CSDN(ID:CSDNnews)近年来,随着机器学习的兴起,有一门编程语言逐渐变得火热——Python。得益于其针对机器学习提供了大量开源框架和第三方模块,内置..._beeware

Swift4.0_Timer 的基本使用_swift timer 暂停-程序员宅基地

文章浏览阅读7.9k次。//// ViewController.swift// Day_10_Timer//// Created by dongqiangfei on 2018/10/15.// Copyright 2018年 飞飞. All rights reserved.//import UIKitclass ViewController: UIViewController { ..._swift timer 暂停

元素三大等待-程序员宅基地

文章浏览阅读986次,点赞2次,收藏2次。1.硬性等待让当前线程暂停执行,应用场景:代码执行速度太快了,但是UI元素没有立马加载出来,造成两者不同步,这时候就可以让代码等待一下,再去执行找元素的动作线程休眠,强制等待 Thread.sleep(long mills)package com.example.demo;import org.junit.jupiter.api.Test;import org.openqa.selenium.By;import org.openqa.selenium.firefox.Firefox.._元素三大等待

Java软件工程师职位分析_java岗位分析-程序员宅基地

文章浏览阅读3k次,点赞4次,收藏14次。Java软件工程师职位分析_java岗位分析

Java:Unreachable code的解决方法_java unreachable code-程序员宅基地

文章浏览阅读2k次。Java:Unreachable code的解决方法_java unreachable code

标签data-*自定义属性值和根据data属性值查找对应标签_如何根据data-*属性获取对应的标签对象-程序员宅基地

文章浏览阅读1w次。1、html中设置标签data-*的值 标题 11111 222222、点击获取当前标签的data-url的值$('dd').on('click', function() { var urlVal = $(this).data('ur_如何根据data-*属性获取对应的标签对象

推荐文章

热门文章

相关标签