本人刚开始学习ffmpeg,写此博客作为笔记,也希望能帮助其他刚入门的童鞋!ffmpeg源码下载和编译本文就直接跳过,源码doc/example路径下有很多demo,可以为我们演示ffmpeg的api如何使用,对我们理解ffmpeg的api有很大帮助。本文将介绍decode_video.c如何编译使用。
代码主体框架:
1、根据Codec ID查找编码器(Codec)
2、根据编码器 ID查找解析器(Parse)。注:解析器用于解封装,解封装后的数据放到AVPacket中
3、根据Codec创建AVCodecContext。
4、循环读取输入文件,送入解析器解封装出AVPacket,然后再解码出AVFrame数据,再分别保存每一帧图像。
inputFile ----(解封装)–> AVPacket —(解码)—>AVFrame —(保存图像)–>文件名:FileName-FrameID.
注:针对视频文件,每一个Frame对应一帧图像。对比音频,每一个Frame可能对应多个帧。
decode_video.c代码如下所示,输入的视频像素格式为YUV420P,原始代码仅保存Y图像数据(黑白图像),我修改后的代码保存了YUV数据。
/*
* Copyright (c) 2001 Fabrice Bellard
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* @file
* video decoding with libavcodec API example
*
* @example decode_video.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <libavcodec/avcodec.h>
#define INBUF_SIZE 4096
static void pgm_save(unsigned char *buf[], int wrap[], int xsize, int ysize,
char *filename)
{
FILE *f;
int i;
f = fopen(filename,"w");
/* 这句代码可使得图片可直接被预览 */
fprintf(f, "P5\n%d %d\n%d\n", xsize, ysize, 255);
/* Save Y data */
for (i = 0; (wrap[0]) && (i < ysize); i++)
fwrite(buf[0] + i * wrap[0], 1, xsize, f);
/* Save U(Cb) data */
for (i = 0; (wrap[1]) && (i < ysize/2); i++)
fwrite(buf[1] + i * wrap[1], 1, xsize / 2, f);
/* Save V(Cr) data */
for (i = 0; (wrap[2]) && (i < ysize/2); i++)
fwrite(buf[2] + i * wrap[2], 1, xsize / 2, f);
fclose(f);
}
static void decode(AVCodecContext *dec_ctx, AVFrame *frame, AVPacket *pkt,
const char *filename)
{
char buf[1024];
int ret;
ret = avcodec_send_packet(dec_ctx, pkt);
if (ret < 0) {
fprintf(stderr, "Error sending a packet for decoding\n");
exit(1);
}
while (ret >= 0) {
ret = avcodec_receive_frame(dec_ctx, frame);
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
return;
else if (ret < 0) {
fprintf(stderr, "Error during decoding\n");
exit(1);
}
printf("saving frame %3d\n", dec_ctx->frame_number);
fflush(stdout);
printf("+++++ FLC-DBG: format:%d, linesize[0]:%d, linesize[1]:%d, linesize[2]:%d +++++\n\n",
frame->format, frame->linesize[0], frame->linesize[1], frame->linesize[2]);
/* the picture is allocated by the decoder. no need to
free it */
snprintf(buf, sizeof(buf), "%s-%d", filename, dec_ctx->frame_number);
pgm_save(frame->data, frame->linesize,
frame->width, frame->height, buf);
}
}
int main(int argc, char **argv)
{
const char *filename, *outfilename;
const AVCodec *codec;
AVCodecParserContext *parser;
AVCodecContext *c= NULL;
FILE *f;
AVFrame *frame;
uint8_t inbuf[INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
uint8_t *data;
size_t data_size;
int ret;
AVPacket *pkt;
if (argc <= 2) {
fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
exit(0);
}
filename = argv[1];
outfilename = argv[2];
pkt = av_packet_alloc();
if (!pkt)
exit(1);
/* set end of buffer to 0 (this ensures that no overreading happens for damaged MPEG streams) */
memset(inbuf + INBUF_SIZE, 0, AV_INPUT_BUFFER_PADDING_SIZE);
/* find the MPEG-1 video decoder */
codec = avcodec_find_decoder(AV_CODEC_ID_MPEG1VIDEO);
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
parser = av_parser_init(codec->id);
if (!parser) {
fprintf(stderr, "parser not found\n");
exit(1);
}
c = avcodec_alloc_context3(codec);
if (!c) {
fprintf(stderr, "Could not allocate video codec context\n");
exit(1);
}
/* For some codecs, such as msmpeg4 and mpeg4, width and height
MUST be initialized there because this information is not
available in the bitstream. */
/* open it */
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
f = fopen(filename, "rb");
if (!f) {
fprintf(stderr, "Could not open %s\n", filename);
exit(1);
}
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate video frame\n");
exit(1);
}
while (!feof(f)) {
/* read raw data from the input file */
data_size = fread(inbuf, 1, INBUF_SIZE, f);
if (!data_size)
break;
/* use the parser to split the data into frames */
data = inbuf;
while (data_size > 0) {
ret = av_parser_parse2(parser, c, &pkt->data, &pkt->size,
data, data_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0);
if (ret < 0) {
fprintf(stderr, "Error while parsing\n");
exit(1);
}
data += ret;
data_size -= ret;
printf("+++++ FLC-DBG: pkg->size = %d +++++\n", pkt->size);
if (pkt->size)
decode(c, frame, pkt, outfilename);
}
}
/* flush the decoder */
decode(c, frame, NULL, outfilename);
fclose(f);
av_parser_close(parser);
avcodec_free_context(&c);
av_frame_free(&frame);
av_packet_free(&pkt);
return 0;
}
编译后的bin程序名称为decode_video。使用方法:
./decode_video ~/Videos/MyVideo.mpeg ~/Videos/frame
程序执行完成后,在~/Videos目录下会生成fram-1、frame-2、frame-3…等文件。可直接双击查看图片(注意代码中要有fprintf(f, "P5\n%d %d\n%d\n", xsize, ysize, 255);
这句话)。如果按照上述代码保存了完整的YUV数据,也可以使用ffplay工具查看刚才的图像,比如:
ffplay -f rawvideo -video_size 1280x544 frame-1
工程以及视频资源下载地址如下:
https://download.csdn.net/download/lyy901135/11300573
注:需要修改Makefile中库和头文件的路径,指向你系统中的ffmpeg库和头文件。