ffmpeg实战教程(一)Mp4,mkv等格式解码为h264和yuv数据

FFmpeg有非常强大的功能包括视频采集功能、视频格式转换、视频抓图、给视频加水印等。而网上对这些功能的使用大多是基于命令行的。这不利于我们深入学习定制化ffmpeg,今后我将写一系列的用代码实现这些功能的教程供大家学习。这系列的前部分我打算写在windows上的实现,后部分写移植到Android系统上实现。
代码实现的前提是对ffmpeg源码有一定的了解,如果你不了解可以看这里
ffmpeg源码简析(一)结构总览

下面进入正题,用FFmpeg实现Mp4,mkv等格式的解码。解码为h264和YUV数据并存在文件中。

先上运行结果图,可见生成了两个文件即是解码之后的数据:
h264比YUV文件小了这么多。h264压缩技术真是杠杠的。新一代压缩技术H265更是杠杠的以后给大家介绍这块。


先介绍整个流程,然后给出源代码。
1.把名称为ws.mp4的视频拷贝进项目跟目录
然后创建两个解码后的输出文件 代码如下:

char filepath[]="ws.mp4";

FILE *fp_yuv=fopen("output.yuv","wb+");  
FILE *fp_h264=fopen("output.h264","wb+");

2.然后就是初始化一些组件

av_register_all();//注册所有组件
avformat_network_init();//初始化网络
pFormatCtx = avformat_alloc_context();//初始化一个AVFormatContext

3.打开视频文件,并获取视频信息,选择解码器

avformat_open_input(&pFormatCtx,filepath,NULL,NULL)

avformat_find_stream_info(pFormatCtx,NULL)

avcodec_find_decoder(pCodecCtx->codec_id)

4.打开解码器,开始解码

avcodec_open2(pCodecCtx, pCodec,NULL)

avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet)

注意:当av_read_frame()循环退出的时候,实际上解码器中可能还包含剩余的几帧数据。
因此需要通过“flush_decoder”将这几帧数据输出。“flush_decoder”功能简而言之即直接调用avcodec_decode_video2()获得AVFrame,而不再向解码器传递AVPacket。代码如下:
 

while (1) {
        ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
        if (ret < 0)
            break;
        if (!got_picture)
            break;
        sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, 
            pFrameYUV->data, pFrameYUV->linesize);

        int y_size=pCodecCtx->width*pCodecCtx->height;  
        fwrite(pFrameYUV->data[0],1,y_size,fp_yuv);    //Y 
        fwrite(pFrameYUV->data[1],1,y_size/4,fp_yuv);  //U
        fwrite(pFrameYUV->data[2],1,y_size/4,fp_yuv);  //V

        printf("Flush Decoder: Succeed to decode 1 frame!\n");
}

工程运行之后,可见生成了两个文件即是解码之后的数据:
这里写图片描述

源代码如下:


#include <stdio.h>

#define __STDC_CONSTANT_MACROS

#ifdef _WIN32
//Windows
extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
};
#else
//Linux...
#ifdef __cplusplus
extern "C"
{
#endif
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
#ifdef __cplusplus
};
#endif
#endif


int main(int argc, char* argv[])
{
    AVFormatContext *pFormatCtx;
    int             i, videoindex;
    AVCodecContext  *pCodecCtx;
    AVCodec         *pCodec;
    AVFrame *pFrame,*pFrameYUV;
    uint8_t *out_buffer;
    AVPacket *packet;
    int y_size;
    int ret, got_picture;
    struct SwsContext *img_convert_ctx;

    char filepath[]="ws.mp4";

    FILE *fp_yuv=fopen("output.yuv","wb+");  
    FILE *fp_h264=fopen("output.h264","wb+");

    av_register_all();//注册所有组件
    avformat_network_init();//初始化网络
    pFormatCtx = avformat_alloc_context();//初始化一个AVFormatContext

    if(avformat_open_input(&pFormatCtx,filepath,NULL,NULL)!=0){//打开输入的视频文件
        printf("Couldn't open input stream.\n");
        return -1;
    }
    if(avformat_find_stream_info(pFormatCtx,NULL)<0){//获取视频文件信息
        printf("Couldn't find stream information.\n");
        return -1;
    }
    videoindex=-1;
    for(i=0; i<pFormatCtx->nb_streams; i++) 
        if(pFormatCtx->streams[i]->codec->codec_type==AVMEDIA_TYPE_VIDEO){
            videoindex=i;
            break;
        }

    if(videoindex==-1){
        printf("Didn't find a video stream.\n");
        return -1;
    }

    pCodecCtx=pFormatCtx->streams[videoindex]->codec;
    pCodec=avcodec_find_decoder(pCodecCtx->codec_id);//查找解码器
    if(pCodec==NULL){
        printf("Codec not found.\n");
        return -1;
    }
    if(avcodec_open2(pCodecCtx, pCodec,NULL)<0){//打开解码器
        printf("Could not open codec.\n");
        return -1;
    }

    pFrame=av_frame_alloc();
    pFrameYUV=av_frame_alloc();
    out_buffer=(uint8_t *)av_malloc(avpicture_get_size(PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height));
    avpicture_fill((AVPicture *)pFrameYUV, out_buffer, PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height);
    packet=(AVPacket *)av_malloc(sizeof(AVPacket));
    //Output Info-----------------------------
    printf("--------------- File Information ----------------\n");
    av_dump_format(pFormatCtx,0,filepath,0);
    printf("-------------------------------------------------\n");
    img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt, 
        pCodecCtx->width, pCodecCtx->height, PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL); 

    while(av_read_frame(pFormatCtx, packet)>=0){//读取一帧压缩数据
        if(packet->stream_index==videoindex){

            fwrite(packet->data,1,packet->size,fp_h264); //把H264数据写入fp_h264文件

            ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);//解码一帧压缩数据
            if(ret < 0){
                printf("Decode Error.\n");
                return -1;
            }
            if(got_picture){
                sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, 
                    pFrameYUV->data, pFrameYUV->linesize);

                y_size=pCodecCtx->width*pCodecCtx->height;  
                fwrite(pFrameYUV->data[0],1,y_size,fp_yuv);    //Y 
                fwrite(pFrameYUV->data[1],1,y_size/4,fp_yuv);  //U
                fwrite(pFrameYUV->data[2],1,y_size/4,fp_yuv);  //V
                printf("Succeed to decode 1 frame!\n");

            }
        }
        av_free_packet(packet);
    }
    //flush decoder
    /*当av_read_frame()循环退出的时候,实际上解码器中可能还包含剩余的几帧数据。
    因此需要通过“flush_decoder”将这几帧数据输出。
   “flush_decoder”功能简而言之即直接调用avcodec_decode_video2()获得AVFrame,而不再向解码器传递AVPacket。*/
    while (1) {
        ret = avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, packet);
        if (ret < 0)
            break;
        if (!got_picture)
            break;
        sws_scale(img_convert_ctx, (const uint8_t* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height, 
            pFrameYUV->data, pFrameYUV->linesize);

        int y_size=pCodecCtx->width*pCodecCtx->height;  
        fwrite(pFrameYUV->data[0],1,y_size,fp_yuv);    //Y 
        fwrite(pFrameYUV->data[1],1,y_size/4,fp_yuv);  //U
        fwrite(pFrameYUV->data[2],1,y_size/4,fp_yuv);  //V

        printf("Flush Decoder: Succeed to decode 1 frame!\n");
    }

    sws_freeContext(img_convert_ctx);

    //关闭文件以及释放内存
    fclose(fp_yuv);
    fclose(fp_h264);

    av_frame_free(&pFrameYUV);
    av_frame_free(&pFrame);
    avcodec_close(pCodecCtx);
    avformat_close_input(&pFormatCtx);

    return 0;
}

编译运行
1.VC++ 下配置好ffmpeg环境之后将代码拷贝进源文件目录即可。自行百度配置。

2.对于Android开发的客官们可能木有VC++,所以再介绍一种编译方式MinGW下,
以前我们用MinGW编译过ffmpeg:http://blog.csdn.net/king1425/article/details/70338674
MinGW下执行命令

    g++ ffmpeg_decoder.cpp -g -o ffmpeg_decoder.exe \  
    -I /usr/local/include -L /usr/local/lib \  
    -lmingw32 -lSDL2main -lSDL2 -lavformat -lavcodec -lavutil -lswscale  

注意:MinGW执行命令之前要配置一下。
(1)从FFmpeg Windows Build (http://ffmpeg.zeranoe.com/) 网站下载最新的shared 和dev版本的FFmpeg。

(2)在Msys安装目录下创建“local”文件夹,“local”文件夹下创建“include”和“lib”文件夹。

(3)将FFmpeg的dev版本下的include拷贝至{msys}/local/include;lib拷贝至{msys}/local/lib。

(4)将FFmpeg的shared版本下的Dll拷贝至{mingw}/bin。

3.GCC:Linux或者MacOS命令行下运行命令
 

gcc ffmpeg_decoder.cpp -g -o ffmpeg_decoder.out \  
-I /usr/local/include -L /usr/local/lib -lSDL2main -lSDL2 -lavformat -lavcodec -lavutil -lswscale  

 

 

 

 

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值