FFmpeg开发教程一、FFmpeg 版 Hello world

本系列根据项目ffmpeg-libav-tutorial翻译而来

Chapter 0 - 万物之源 —— hello world

然而,本节的程序并不会在终端打印“Hello world”,而是会打印原视频文件的一些信息,比如封装格式、视频时长、分辨率、音频通道数。最后,我们将解码每一帧视频,并将它们保存为YUV文件。

FFmpeg libav 架构

在开始coding之前,我们先来了解下FFmpeg的代码结构,并了解它的各个组件之间是怎么通信的。

下图展示了视频解码的大致流程:

首先,我们需要将媒体文件读取出来,并保存至AVFormatContext 组件。(视频封装container,也叫视频格式format).
通常,FFmpeg并不会将整个视频文件加载进来,只是获取了视频的头部。

一旦我们拿到了封装头部,我们便可以访问它所包含的所有媒体流(一般包含视频流、音频流)。
每一路媒体流可以通过 AVStream进行访问。

Stream is a fancy name for a continuous flow of data.

Suppose our video has two streams: an audio encoded with AAC CODEC and a video encoded with H264 (AVC) CODEC. From each stream we can extract pieces (slices) of data called packets that will be loaded into components named AVPacket.

The data inside the packets are still coded (compressed) and in order to decode the packets, we need to pass them to a specific AVCodec.

The AVCodec will decode them into AVFrame and finally, this component gives us the uncompressed frame. Noticed that the same terminology/process is used either by audio and video stream.

Requirements

Since some people were facing issues while compiling or running the examples we‘re going to use Docker as our development/runner environment, we‘ll also use the big buck bunny video so if you don‘t have it locally just run the command make fetch_small_bunny_video.

Chapter 0 - code walkthrough

TLDR; show me the code and execution.

$ make run_hello

We‘ll skip some details, but don‘t worry: the source code is available at github.

We‘re going to allocate memory to the component AVFormatContext that will hold information about the format (container).

AVFormatContext *pFormatContext = avformat_alloc_context();

Now we‘re going to open the file and read its header and fill the AVFormatContext with minimal information about the format (notice that usually the codecs are not opened).
The function used to do this is avformat_open_input. It expects an AVFormatContext, a filename and two optional arguments: the AVInputFormat (if you pass NULL, FFmpeg will guess the format) and the AVDictionary (which are the options to the demuxer).

avformat_open_input(&pFormatContext, filename, NULL, NULL);

We can print the format name and the media duration:

printf("Format %s, duration %lld us", pFormatContext->iformat->long_name, pFormatContext->duration);

To access the streams, we need to read data from the media. The function avformat_find_stream_info does that.
Now, the pFormatContext->nb_streams will hold the amount of streams and the pFormatContext->streams[i] will give us the i stream (an AVStream).

avformat_find_stream_info(pFormatContext,  NULL);

Now we‘ll loop through all the streams.

for (int i = 0; i < pFormatContext->nb_streams; i++)
{
  //
}

For each stream, we‘re going to keep the AVCodecParameters, which describes the properties of a codec used by the stream i.

AVCodecParameters *pLocalCodecParameters = pFormatContext->streams[i]->codecpar;

With the codec properties we can look up the proper CODEC querying the function avcodec_find_decoder and find the registered decoder for the codec id and return an AVCodec, the component that knows how to enCOde and DECode the stream.

AVCodec *pLocalCodec = avcodec_find_decoder(pLocalCodecParameters->codec_id);

Now we can print information about the codecs.

// specific for video and audio
if (pLocalCodecParameters->codec_type == AVMEDIA_TYPE_VIDEO) {
  printf("Video Codec: resolution %d x %d", pLocalCodecParameters->width, pLocalCodecParameters->height);
} else if (pLocalCodecParameters->codec_type == AVMEDIA_TYPE_AUDIO) {
  printf("Audio Codec: %d channels, sample rate %d", pLocalCodecParameters->channels, pLocalCodecParameters->sample_rate);
}
// general
printf("\tCodec %s ID %d bit_rate %lld", pLocalCodec->long_name, pLocalCodec->id, pCodecParameters->bit_rate);

With the codec, we can allocate memory for the AVCodecContext, which will hold the context for our decode/encode process, but then we need to fill this codec context with CODEC parameters; we do that with avcodec_parameters_to_context.

Once we filled the codec context, we need to open the codec. We call the function avcodec_open2 and then we can use it.

AVCodecContext *pCodecContext = avcodec_alloc_context3(pCodec);
avcodec_parameters_to_context(pCodecContext, pCodecParameters);
avcodec_open2(pCodecContext, pCodec, NULL);

Now we‘re going to read the packets from the stream and decode them into frames but first, we need to allocate memory for both components, the AVPacket and AVFrame.

AVPacket *pPacket = av_packet_alloc();
AVFrame *pFrame = av_frame_alloc();

Let‘s feed our packets from the streams with the function av_read_frame while it has packets.

while (av_read_frame(pFormatContext, pPacket) >= 0) {
  //...
}

Let‘s send the raw data packet (compressed frame) to the decoder, through the codec context, using the function avcodec_send_packet.

avcodec_send_packet(pCodecContext, pPacket);

And let‘s receive the raw data frame (uncompressed frame) from the decoder, through the same codec context, using the function avcodec_receive_frame.

avcodec_receive_frame(pCodecContext, pFrame);

We can print the frame number, the PTS, DTS, frame type and etc.

printf(
    "Frame %c (%d) pts %d dts %d key_frame %d [coded_picture_number %d, display_picture_number %d]",
    av_get_picture_type_char(pFrame->pict_type),
    pCodecContext->frame_number,
    pFrame->pts,
    pFrame->pkt_dts,
    pFrame->key_frame,
    pFrame->coded_picture_number,
    pFrame->display_picture_number
);

Finally we can save our decoded frame into a simple gray image. The process is very simple, we‘ll use the pFrame->data where the index is related to the planes Y, Cb and Cr, we just picked 0 (Y) to save our gray image.

save_gray_frame(pFrame->data[0], pFrame->linesize[0], pFrame->width, pFrame->height, frame_filename);

static void save_gray_frame(unsigned char *buf, int wrap, int xsize, int ysize, char *filename)
{
    FILE *f;
    int i;
    f = fopen(filename,"w");
    // writing the minimal required header for a pgm file format
    // portable graymap format -> https://en.wikipedia.org/wiki/Netpbm_format#PGM_example
    fprintf(f, "P5\n%d %d\n%d\n", xsize, ysize, 255);

    // writing line by line
    for (i = 0; i < ysize; i++)
        fwrite(buf + i * wrap, 1, xsize, f);
    fclose(f);
}

And voilà! Now we have a gray scale image with 2MB:

最后贴上完整的代码,本教程所有代码也将存放在Github: FFmpegSimplePlayer项目中:

#include <stdio.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>

static void save_gray_frame(unsigned char *buf, int wrap, int xsize, int ysize, char *filename)
{
    FILE *f = NULL;
    int i = 0;
    f = fopen(filename, "w");
    fprintf(f, "P5\n%d %d\n%d\n", xsize, ysize, 255);

    for (i = 0; i < ysize; i++) {
        fwrite(buf + wrap * i, 1, xsize, f);
    }
    //fwrite(buf, 1, xsize * ysize, f);

    fclose(f);
}

int main(int argc, char *argv[])
{
    AVFormatContext *pFmtCtx = avformat_alloc_context();

    if (avformat_open_input(&pFmtCtx, argv[1], NULL, NULL)) {
        fprintf(stderr, "open input failed\n");
        return -1;
    }

    printf("Format:%s, duration:%ld us\n", pFmtCtx->iformat->long_name, pFmtCtx->duration);

    if (avformat_find_stream_info(pFmtCtx, NULL) < 0) {
        fprintf(stderr, "find stream info failed\n");
        return -2;
    }

    for (int i = 0; i < pFmtCtx->nb_streams; i++) {
        AVCodecParameters *pCodecPar = pFmtCtx->streams[i]->codecpar;
        AVCodec *pCodec = NULL;
        pCodec = avcodec_find_decoder(pCodecPar->codec_id);
        if (NULL == pCodec) {
            fprintf(stderr, "Unsupported codec!\n");
            return -3;
        }
        if (AVMEDIA_TYPE_VIDEO == pCodecPar->codec_type) {
            printf("Video Codec: resolution: %d x %d\n", pCodecPar->width, pCodecPar->height);
        } else if (AVMEDIA_TYPE_AUDIO == pCodecPar->codec_type) {
            printf("Audio Codec: %d channels, sample rate %d\n", pCodecPar->channels, pCodecPar->sample_rate);
        }
        printf("\t Codec %s ID %d bit_rate %ld\n", pCodec->long_name, pCodec->id, pCodecPar->bit_rate);

        AVCodecContext *pCodecCtx = NULL;
        pCodecCtx = avcodec_alloc_context3(pCodec);
        avcodec_parameters_to_context(pCodecCtx, pCodecPar);

        if (avcodec_open2(pCodecCtx, pCodec, NULL)) {
            fprintf(stderr, "Codec open failed!\n");
            return -4;
        }

        AVPacket *pPacket = av_packet_alloc();
        AVFrame *pFrame = av_frame_alloc();

        while (av_read_frame(pFmtCtx, pPacket) >= 0) {
            avcodec_send_packet(pCodecCtx, pPacket);
            avcodec_receive_frame(pCodecCtx, pFrame);
            printf("Frame %c (%d) pts %ld dts %ld key_frame %d [coded_picture_number %d, display_picture_number %d]\n",
                    av_get_picture_type_char(pFrame->pict_type),
                    pCodecCtx->frame_number,
                    pFrame->pts,
                    pFrame->pkt_dts,
                    pFrame->key_frame,
                    pFrame->coded_picture_number,
                    pFrame->display_picture_number
            );
            if (AVMEDIA_TYPE_VIDEO == pCodecPar->codec_type) {
                char frame_filename[30] = {0};
                snprintf(frame_filename, 29, "./frame/Frame%d_%dx%d.yuv", pCodecCtx->frame_number, pFrame->width, pFrame->height);
                save_gray_frame(pFrame->data[0], pFrame->linesize[0], pFrame->width, pFrame->height, frame_filename);
            }
        }
    }

    return 0;
}

原文地址:https://www.cnblogs.com/ichenwin/p/10841667.html

时间: 2024-10-18 12:31:41

FFmpeg开发教程一、FFmpeg 版 Hello world的相关文章

微信应用号(小程序)开发教程一

开发者网址导航:http://www.dev666.com/ 序言 开始开发应用号之前,先看看官方公布的「小程序」教程吧!(以下内容来自微信官方公布的「小程序」开发指南) 本文档将带你一步步创建完成一个微信小程序,并可以在手机上体验该小程序的实际效果.这个小程序的首页将会显示欢迎语以及当前用户的微信头像,点击头像,可以在新开的页面中查看当前小程序的启动日志. 1. 获取微信小程序的 AppID 首先,我们需要拥有一个帐号,如果你能看到该文档,我们应当已经邀请并为你创建好一个帐号.注意不可直接使用

ffmpeg开发指南

FFmpeg是一个集录制.转换.音/视频编码解码功能为一体的完整的开源解决方案.FFmpeg的开发是基于Linux操作系统,但是可以在大多数操作系统中编译和使用.FFmpeg支持MPEG.DivX.MPEG4.AC3.DV.FLV等40多种编码,AVI.MPEG.OGG.Matroska.ASF等90多种解码.TCPMP, VLC, MPlayer等开源播放器都用到了FFmpeg.    一.ffmpeg介绍 ffmpeg软件包经编译过后将生成三个可执行文件,ffmpeg,ffserver,ff

windows环境下搭建ffmpeg开发环境

ffmpeg是一个开源.跨平台的程序库,可以使用在windows.linux等平台下,本文将简单讲解windows环境下ffmpeg开发环境搭建过程,本人使用的操作系统为windows 7,集成开发环境为Visual Studio 2005,ffmpeg版本为2.2.有人可能会说都什么年代了,还VS 2005,现在VS 2010/2012/2013都出了.本人电脑也安装了VS2010,每次打开,伴随着硬盘指示灯的闪烁,以及硬盘的吱吱响声,过了许久才弹出闪屏页面,此时你的思绪可能已经飘到了南极,启

VS配置FFmpeg开发环境

在做视频处理的时候,通常需要对视频数据进行编解码,这时利用开源的FFmpeg视频音频处理方案是大多数程序员的选择,毕竟自己去进行编解码器的编写实在是太太太没效率了,而且大多数情况下还满满的都是写不出来...然决定用FFmpeg只是最开始的一步,因为后面如何去搭建这个环境是个比较麻烦的问题. 通常在VS上搭建FFmpeg开发环境有两种方法,一是从FFmpeg的官网下载源码然后自己进行编译.其复杂度之高实在是令本人望而却步,看了几篇教程之后感觉不会再爱了,当然如果你是立志要在视频上干一番大事业的,还

Visual Studio 开发(二):VS 2017配置FFmpeg开发环境

在上篇文章Visual Studio 开发(一):安装配置Visual Studio Code 中,我们讲了一下如何配置VS CODE,来编写和调试C的代码.如果你已经使用VS Code回顾和复习好C相关的知识了,并且有想深入学习FFmpeg的方法,那么可以看看这篇文章,相信对你会很有帮助. 一.下载安装Visual Studio 下载地址为:https://visualstudio.microsoft.com/zh-hans/downloads/ 然后进行安装,安装时选择C/C++开发的选项进

FFmpeg开发实战(一):FFmpeg 打印日志

在Visual Studio 开发(二):VS 2017配置FFmpeg开发环境一文中,我们配置好了FFmpeg的开发环境,下面我们开始边实战,边学习FFmpeg. 首先,我们要学习的就是FFmpeg的日志输出系统 . 一.FFmpeg 日志输出系统介绍 FFmpeg 日志输出的核心函数方法为: av_log() . 下面是FFmpeg日志输出系统的函数调用结构图: 为什么说av_log()是FFmpeg中输出日志的核心函数函数? 因为我们随便打开一个FFmpeg的源代码文件,就会发现其中遍布着

vs2013+ffmpeg开发环境搭建

http://blog.csdn.net/spaceyqy/article/details/43115391 每当看到配环境,我就泪流满面,好吧,闲话不多说,进入正题. 1.去官方下载ffmpeg  可参见:http://ffmpeg.zeranoe.com/builds/   包含三个版本:Static.Shared以及Dev Static   --- 包含3个应用程序:ffmpeg.exe , ffplay.exe , ffprobe.exe,体积都很大,相关的DLL已经被编译到exe里面去

php教程一,变量

php是一种动态脚本语言,比较适合web开发. php支持8种变量数据类型: 四种标量类型: boolean(布尔型) integer(整型) float(浮点型,也称作 double) string(字符串) 两种复合类型: array(数组) object(对象) 最后是两种特殊类型: resource(资源) NULL(无类型) 变量你可以这样理解,假如php是一个人的话,变量就是各种类型的衣服,设定变量的用途就是在合适的场合穿上合适的衣服 变量的重点就是在于在变字,它不是一个固定的值,我

AppleWatch开发教程之Watch应用对象新增内容介绍以及编写运行代码

AppleWatch开发教程之Watch应用对象新增内容介绍以及编写运行代码 添加Watch应用对象时新增内容介绍 Watch应用对象添加到创建的项目中后,会包含两个部分:Watch App 和 WatchKit Extension,如图2.18所示.其中,Watch App部分位于用户的iWatch上,它目前为止只允许包含Storyboard文件和Resources文件.在我们的项目里,这一部分不包括任何代码.WatchKit Extension部分位于用户的iPhone安装的对应App上,这