FFmpeg C++ Video || Audio 解码

---------- FFmepg官网 ----------
---------- FFmepg简介 ----------
本文主要用于FFmpeg for C++入门介绍和学习,若您发现文章中错误或者对文章内容有疑问,请在留言区留言。谢谢!

下载编译FFmpeg-lib

环境:CentOS 7 FFmpeg 版本:3.3

#!/bin/bash
set -o errexit

# Download ffmpeg-3.3
mkdir ffmpeg -p
wget http://ffmpeg.org/releases/ffmpeg-3.3.tar.bz2 -O ffmpeg/ffmpeg-3.3.tar.bz2

# Untar ffmpeg-3.3
cd ffmpeg
tar xvf ffmpeg-3.3.tar.bz2
cd ffmpeg-3.3

# Build ffmpeg
./configure --enable-pic --enable-shared
make

# Prepare the output package
mkdir ffmpeg-lib -p
mkdir ffmpeg-lib/lib -p
mkdir ffmpeg-lib/inc -p
libarr=("avcodec" "avdevice" "avfilter" "avformat" "avutil" "swresample" "swscale")
for lib in ${libarr[@]}; do
    echo "Copy lib and header for $lib"
    cp lib${lib}/lib${lib}.so* ffmpeg-lib/lib/ -av
    mkdir -p ffmpeg-lib/inc/lib${lib}
    cp lib${lib}/*.h ffmpeg-lib/inc/lib${lib}/
done
# Create ffmpeg artifact
tar -cpzvf ffmpeg-lib.tar.gz ffmpeg-lib

将代码copy到bash脚本,执行就可以得到ffmpeg-lib。

Audio || Video decode

解压编译得到的ffmpeg-lib.tar.gz
新建文件 decode.cpp

#include 
#include 
#include 
#include 
#include 

extern "C" {
#include 
}

#define AUDIO_INBUF_SIZE 20480
#define AUDIO_REFILL_THRESH 4096

static void decode(AVCodecContext *dec_ctx, AVPacket *pkt, AVFrame *frame,
                   FILE *outfile)
{
    int i, ch;
    int ret, data_size;

    /* send the packet with the compressed data to the decoder */
    ret = avcodec_send_packet(dec_ctx, pkt);
    if (ret < 0) {
        fprintf(stderr, "Error submitting the packet to the decoder\n");
        exit(1);
    }

    /* read all the output frames (in general there may be any number of them */
    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);
        }
        data_size = av_get_bytes_per_sample(dec_ctx->sample_fmt);
        if (data_size < 0) {
            /* This should not occur, checking just for paranoia */
            fprintf(stderr, "Failed to calculate data size\n");
            exit(1);
        }
        for (i = 0; i < frame->nb_samples; i++)
            for (ch = 0; ch < dec_ctx->channels; ch++)
                fwrite(frame->data[ch] + data_size*i, 1, data_size, outfile);
    }
}

int main(int argc, char* argv[])
{
    const char *outfilename, *filename;
    const AVCodec *codec;
    AVCodecContext *c= NULL;
    AVCodecParserContext *parser = NULL;
    int len, ret;
    FILE *f, *outfile;
    uint8_t inbuf[AUDIO_INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
    uint8_t *data;
    size_t   data_size;
    AVPacket *pkt;
    AVFrame *decoded_frame = NULL;

    if (argc <= 2) {
        fprintf(stderr, "Usage: %s  \n", argv[0]);
        exit(0);
    }
    filename    = argv[1];
    outfilename = argv[2];
    
    avcodec_register_all();
    pkt = av_packet_alloc();

    /* find the MPEG audio decoder */
    codec = avcodec_find_decoder(AV_CODEC_ID_AAC);
    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 audio codec context\n");
        exit(1);
    }

    /* 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);
    }
    outfile = fopen(outfilename, "wb");
    if (!outfile) {
        av_free(c);
        exit(1);
    }

    /* decode until eof */
    data      = inbuf;
    data_size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);

    while (data_size > 0) {
        if (!decoded_frame) {
            if (!(decoded_frame = av_frame_alloc())) {
                fprintf(stderr, "Could not allocate audio frame\n");
                exit(1);
            }
        }

        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;

        if (pkt->size)
            decode(c, pkt, decoded_frame, outfile);

        if (data_size < AUDIO_REFILL_THRESH) {
            memmove(inbuf, data, data_size);
            data = inbuf;
            len = fread(data + data_size, 1,
                        AUDIO_INBUF_SIZE - data_size, f);
            if (len > 0)
                data_size += len;
        }
    }

    /* flush the decoder */
    pkt->data = NULL;
    pkt->size = 0;
    decode(c, pkt, decoded_frame, outfile);

    fclose(outfile);
    fclose(f);

    avcodec_free_context(&c);
    av_parser_close(parser);
    av_frame_free(&decoded_frame);
    av_packet_free(&pkt);

    return 0;
}

注意:
avcodec_register_all(); 注册编解码器
codec = avcodec_find_decoder(AV_CODEC_ID_AAC); 查找音视频解码器,可替换成AV_CODEC_ID_MP3,AV_CODEC_ID_H264等等
编译并执行.out

[root@Jelly-Test-119 ~]# g++ -std=c++11 -I ffmpeg-lib/inc decode.cpp -L ffmpeg-lib/lib -lavdevice -lavfilter -lavformat -lavcodec -lswresample -lswscale -lavutil -o decode.out
[root@Jelly-Test-119 ~]# export LD_LIBRARY_PATH=ffmpeg-lib/lib
[root@Jelly-Test-119 ~]# ./decode.out test.mp3 jelly.mp3

到这里我们就完成了一个简单的ffmpeg decode demo了。


欢迎提出和纠正问题!

你可能感兴趣的:(FFmpeg C++ Video || Audio 解码)