音视频

ffmpeg_sample解读_demuxing_decoing

2020-10-22  本文已影响0人  刘佳阔

title: ffmpeg_sample解读_demuxing_decoing
date: 2020-10-21 10:15:02
tags: [读书笔记]
typora-copy-images-to: ./imgs
typora-root-url: ./imgs


整体流程是把数据的mp4 文件分配解码出音频流和视频流.然后通过格式上下文里的信息构建各自的解码器上下文.

然后从输入文件中读出一个一个的packet. 在根据packet 的流索引分别进行音频流和视频流的解码.通过解码器上下文解码成frame帧. 送入各自的缓存中.最后分别写入原生视频文件.和原生音频文件.

流程图如下代码

graph TB
 A[avformat_open_input]
    -->B(avformat_find_stream_info)
    -->C{视频?}
    C--> |yes|openV["open_codec_context(video)"]
    C--> |no|openA["open_codec_context(audio)"]
    
    openA--> steam[av_find_best_stream]
    -->decoderA[avcodec_find_decoder]
    -->contextA[avcodec_alloc_context3]
    -->paramsA[avcodec_parameters_to_context]
    -->opendecodeA[avcodec_open2]
    openV-->steamV[av_find_best_stream]
    -->decoderV[avcodec_find_decoder]
    -->contextV[avcodec_alloc_context3]
    -->paramsV[avcodec_parameters_to_context]
    -->opendecodeV[avcodec_open2]
    -->image[av_image_alloc]
    image--> frame[av_frame_alloc]
    opendecodeA -->frame
    -->readframe{av_read_frame>=0?}
    readframe -->|yes|decodePacket[decode_packet]
    readframe -->|no|freeSource
    decodePacket --> sendPacket[avcodec_send_packet]
    -->receiveframe{avcodec_receive_frame>=0?}
    receiveframe-->|no| no[no]
    receiveframe-->|yes|outframe{isVideo?}
    no --> readframe
    outframe -->|yes|copy[av_image_copy]
    -->fwrite
    outframe -->|no|fwriteA[fwrite]
    fwrite -->unref[av_frame_unref]
    fwriteA -->unref[av_frame_unref]
    unref-->receiveframe
    

流程图截图

lct

源码如下



/**
 * @file
 * Demuxing and decoding example.
 *
 * Show how to use the libavformat and libavcodec API to demux and
 * decode audio and video data.
 * @example demuxing_decoding.c
 */

#include <libavutil/imgutils.h>
#include <libavutil/samplefmt.h>
#include <libavutil/timestamp.h>
#include <libavformat/avformat.h>
#include "../macro.h"

//输入文件的格式上下文
static AVFormatContext *fmt_ctx = NULL;
//输出文件的编解码器上下文
static AVCodecContext *video_dec_ctx = NULL, *audio_dec_ctx;
static int width, height;
static enum AVPixelFormat pix_fmt;
static AVStream *video_stream = NULL, *audio_stream = NULL;
static const char *src_filename = NULL;
static const char *video_dst_filename = NULL;
static const char *audio_dst_filename = NULL;
static FILE *video_dst_file = NULL;
static FILE *audio_dst_file = NULL;

static uint8_t *video_dst_data[4] = {NULL};
static int video_dst_linesize[4];
static int video_dst_bufsize;

static int video_stream_idx = -1, audio_stream_idx = -1;
static AVFrame *frame = NULL;
static AVPacket pkt;
static int video_frame_count = 0;
static int audio_frame_count = 0;

/**
 * 输出 视频帧.
 * @param frame
 * @return
 */
static int output_video_frame(AVFrame *frame) {
    if (frame->width != width || frame->height != height ||
        frame->format != pix_fmt) {
        /* To handle this change, one could call av_image_alloc again and
         * decode the following frames into another rawvideo file. */
        LOGE("Error: Width, height and pixel format have to be "
             "constant in a rawvideo file, but the width, height or "
             "pixel format of the input video changed:\n"
             "old: width = %d, height = %d, format = %s\n"
             "new: width = %d, height = %d, format = %s\n",
             width, height, av_get_pix_fmt_name(pix_fmt),
             frame->width, frame->height,
             av_get_pix_fmt_name(frame->format));
        return -1;
    }

    printf("video_frame n:%d coded_n:%d\n",
           video_frame_count++, frame->coded_picture_number);

    /* copy decoded frame to destination buffer:
     * this is required since rawvideo expects non aligned data *///原始书序不需要对齐
    //吧数据从 frame->data 到 video_dst_data中. 二者的宽高,帧的格式应该是一样的
    //frame->data, frame->linesize 是入参,      video_dst_data, video_dst_linesize,是出餐,一个指向部分,一个是行数
    av_image_copy(video_dst_data, video_dst_linesize,
                  (const uint8_t **) (frame->data), frame->linesize,
                  pix_fmt, width, height);

    /* write to rawvideo file */
    //把video_dst_data中的数据.全部写到视频输出文件中, 数量是 video_dst_bufsize.
    // 这是之前根据video的宽高,pix_format 生成的image的大小.
    fwrite(video_dst_data[0], 1, video_dst_bufsize, video_dst_file);
    return 0;
}

/**
 * 输出音频真到文件总
 * @param frame
 * @return
 */
static int output_audio_frame(AVFrame *frame) {
    //输出音频帧,音频真大小是i 采样数* 每个采样的字节数 (疑问 这里没有涉及通道了)
    size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format);
    printf("audio_frame n:%d nb_samples:%d pts:%s\n",
           audio_frame_count++, frame->nb_samples,
           av_ts2timestr(frame->pts, &audio_dec_ctx->time_base));

    /* Write the raw audio data samples of the first plane. This works
     * fine for packed formats (e.g. AV_SAMPLE_FMT_S16). However,
     * most audio decoders output planar audio, which uses a separate
     * plane of audio samples for each channel (e.g. AV_SAMPLE_FMT_S16P).
     * In other words, this code will write only the first audio channel
     * in these cases.
     * You should use libswresample or libavfilter to convert the frame
     * to packed data. */
    //这里解释了这里只输出了单通道的声音. 说明如果有多通道.不能用这种方式输出
    fwrite(frame->extended_data[0], 1, unpadded_linesize, audio_dst_file);

    return 0;
}

/**
 * 解码packet 中的内容,看了几个sample后.这里的代码基本是常规写法了
 * @param dec
 * @param pkt
 * @return
 */
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) {
        LOGE("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);//从解码器中读取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;

            LOGE("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);
        //释放帧.以便继续while循环使用. 因为一个packet里可能有多个frame.所以多次取.
        av_frame_unref(frame);
        if (ret < 0)
            return ret;
    }

    return 0;
}

/**
 * 根据格式上下文fmt_ctx ,找到数据流并生产解码器,最终生成解码流的索引和解码上下文,
 * @param stream_idx 数据流索引,这是结果
 * @param dec_ctx 解码上下文,这是产生的结果
 * @param fmt_ctx  输入文件的格式上下文
 * @param type 音频还是视频
 * @return
 */
static int open_codec_context(int *stream_idx,
                              AVCodecContext **dec_ctx, AVFormatContext *fmt_ctx,
                              enum AVMediaType type) {
    int ret, stream_index;
    AVStream *st;
    AVCodec *dec = NULL;
    AVDictionary *opts = NULL;

    //根据type类型找到最合适的流. 视频就找视频流.音频找音频流 返回结果就是留的索引
    ret = av_find_best_stream(fmt_ctx, type, -1, -1, NULL, 0);
    if (ret < 0) {
        LOGE("Could not find %s stream in input file '%s'\n",
             av_get_media_type_string(type), src_filename);
        return ret;
    } else {
        stream_index = ret;
        st = fmt_ctx->streams[stream_index];//找到的数据流

        /* find decoder for the stream */ //通过流的编码参数的id 找到解码器
        dec = avcodec_find_decoder(st->codecpar->codec_id);
        if (!dec) {
            LOGE("Failed to find %s codec\n",
                 av_get_media_type_string(type));
            return AVERROR(EINVAL);
        }

        /* Allocate a codec context for the decoder *///初始化编解码上下文,这是输出文件的编解码上下文
        *dec_ctx = avcodec_alloc_context3(dec);
        if (!*dec_ctx) {
            LOGE("Failed to allocate the %s codec context\n",
                 av_get_media_type_string(type));
            return AVERROR(ENOMEM);
        }
        //把输入流中的编解码参数拷贝到输出文件的编解码上下文中
        /* Copy codec parameters from input stream to output codec context */
        if ((ret = avcodec_parameters_to_context(*dec_ctx, st->codecpar)) < 0) {
            LOGE("Failed to copy %s codec parameters to decoder context\n",
                 av_get_media_type_string(type));
            return ret;
        }

        /* Init the decoders *///使用解码器来初始化 解码器上下文参数
        //这里看到.解码器上下文由解码器和上文的数据流的解码参数共同进行了初始化
        if ((ret = avcodec_open2(*dec_ctx, dec, &opts)) < 0) {
            LOGE("Failed to open %s codec\n",
                 av_get_media_type_string(type));
            return ret;
        }

        *stream_idx = stream_index;
    }

    return 0;
}

static int get_format_from_sample_fmt(const char **fmt,
                                      enum AVSampleFormat sample_fmt) {
    int i;
    struct sample_fmt_entry {
        enum AVSampleFormat sample_fmt;
        const char *fmt_be, *fmt_le;
    } sample_fmt_entries[] = {
            {AV_SAMPLE_FMT_U8,  "u8",    "u8"},
            {AV_SAMPLE_FMT_S16, "s16be", "s16le"},
            {AV_SAMPLE_FMT_S32, "s32be", "s32le"},
            {AV_SAMPLE_FMT_FLT, "f32be", "f32le"},
            {AV_SAMPLE_FMT_DBL, "f64be", "f64le"},
    };
    *fmt = NULL;

    for (i = 0; i < FF_ARRAY_ELEMS(sample_fmt_entries); i++) {
        struct sample_fmt_entry *entry = &sample_fmt_entries[i];
        if (sample_fmt == entry->sample_fmt) {
            *fmt = AV_NE(entry->fmt_be, entry->fmt_le);
            return 0;
        }
    }

    LOGE(
            "sample format %s is not supported as output format\n",
            av_get_sample_fmt_name(sample_fmt));
    return -1;
}

/**
 * avformat_open_input():打开输入文件,初始化输入的AVFormatContext。
avformat_find_stream_info() : 读取视音频数据来获取一些相关的信息。
av_find_best_stream:获取音视频对应的stream_index。
avcodec_alloc_context3:为AVCodecContext分配内存。
avcodec_parameters_to_context() : 使用AVCodecParameters来填充AVCodecContext。
avcodec_open2:打开解码器。
av_image_alloc():按照指定的宽、高、像素格式来分配图像内存,分配的图像内存必须使用av_freep(&pointers[0])来释放。
av_frame_alloc:创建一个AVFrame,并将其字段设置为默认值。
av_init_packet():用默认值初始化可选字段,不包括必须单独初始化的Packet的data和size成员。
av_read_frame:把文件中存储的内容分割成帧,并为每个调用返回一个帧。
avcodec_send_packet:将AVPacket压缩数据给解码器。
avcodec_receive_frame:获取到解码后的AVFrame数据。
读取一个输入文件.然后通过format_context 格式上下文分别找出对应的音频视频的流索引,
 然后分别构建音频解码上下文和视频解码上下文
 然后在通过av_read_frame 读取数据包.针对音频包和视频包送入各自的解码器解码
 然后视频把解码后的视频帧.放入通过av_image_alloc 分配的图片缓冲中,在写入文件
 音频则是只写入的单通道的数据. 双通道则需要别的函数支持
 * @param argc
 * @param argv
 * @return
 */
int demuxing_decoding_main(int argc, char **argv) {
    int ret = 0;

    if (argc != 4) {
        LOGE("usage: %s  input_file video_output_file audio_output_file\n"
             "API example program to show how to read frames from an input file.\n"
             "This program reads frames from a file, decodes them, and writes decoded\n"
             "video frames to a rawvideo file named video_output_file, and decoded\n"
             "audio frames to a rawaudio file named audio_output_file.\n",
             argv[0]);
        exit(1);
    }
    //源文件
    src_filename = argv[1];
    //输出视频文件
    video_dst_filename = argv[2];
    //输出音频文件
    audio_dst_filename = argv[3];

    /* open input file, and allocate format context */
    //读取文件,创建format上下文,格式上下文
    if (avformat_open_input(&fmt_ctx, src_filename, NULL, NULL) < 0) {
        LOGE("Could not open source file %s\n", src_filename);
        exit(1);
    }

    /* retrieve stream information */
    //从文件中提取流信息到fmt上下文中
    if (avformat_find_stream_info(fmt_ctx, NULL) < 0) {
        LOGE("Could not find stream information\n");
        exit(1);
    }
    //获得视频流索引,视频解码上下文
    if (open_codec_context(&video_stream_idx, &video_dec_ctx, fmt_ctx, AVMEDIA_TYPE_VIDEO) >= 0) {
        video_stream = fmt_ctx->streams[video_stream_idx];
        //拿到视频流.打开输出流
        video_dst_file = fopen(video_dst_filename, "wb");
        if (!video_dst_file) {
            LOGE("Could not open destination file %s\n", video_dst_filename);
            ret = 1;
            goto end;
        }

        /* allocate image where the decoded image will be put */
        width = video_dec_ctx->width;//960
        height = video_dec_ctx->height; //400
        pix_fmt = video_dec_ctx->pix_fmt; //AV_PIX_FMT_YUV420P
        //用给定的宽,高, 图片格式,来分配一个图片内存,ret表示图片内存大小,我理解这里是存一帧解码后的压缩画面的
        //新分配的空间在video_dat_data中, 大小就是ret
        ret = av_image_alloc(video_dst_data, video_dst_linesize,
                             width, height, pix_fmt, 1);
        if (ret < 0) {
            LOGE("Could not allocate raw video buffer\n");
            goto end;
        }
        video_dst_bufsize = ret;
    }
    //活了音频流索引.初始化音频解码上下文
    if (open_codec_context(&audio_stream_idx, &audio_dec_ctx, fmt_ctx, AVMEDIA_TYPE_AUDIO) >= 0) {
        //找到音频流.打开音频输出文件
        audio_stream = fmt_ctx->streams[audio_stream_idx];
        audio_dst_file = fopen(audio_dst_filename, "wb");
        if (!audio_dst_file) {
            LOGE("Could not open destination file %s\n", audio_dst_filename);
            ret = 1;
            goto end;
        }
    }

    /* dump input information to stderr *///获取输入文件的流的相关信息
    av_dump_format(fmt_ctx, 0, src_filename, 0);

    if (!audio_stream && !video_stream) {
        LOGE("Could not find audio or video stream in the input, aborting\n");
        ret = 1;
        goto end;
    }
//分配解码后的接受帧
    frame = av_frame_alloc();
    if (!frame) {
        LOGE("Could not allocate frame\n");
        ret = AVERROR(ENOMEM);
        goto end;
    }

    //初始化一个packet  常规最烦了
    /* initialize packet, set data to NULL, let the demuxer fill it */
    av_init_packet(&pkt);
    pkt.data = NULL;
    pkt.size = 0;

    if (video_stream)
        printf("Demuxing video from file '%s' into '%s'\n", src_filename, video_dst_filename);
    if (audio_stream)
        printf("Demuxing audio from file '%s' into '%s'\n", src_filename, audio_dst_filename);

    /* read frames from the file */
    //从格式上下文中读取一帧 (packet),这是未解码的数据.可能是音频,可能是视频.需要再从packet中通过解码器解码出frame来
    while (av_read_frame(fmt_ctx, &pkt) >= 0) {
        // check if the packet belongs to a stream we are interested in, otherwise
        // skip it
        //分别对视频packet 和音频packet进行处理. 根据就是我们之前得到的音视频流的索引.
        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);
        //处理完后释放这个packet .以便于下次再进行av_read_frame.
        av_packet_unref(&pkt);
        if (ret < 0)
            break;
    }

    //刷新音视频解码器中的packet. 这个操作在几个sample里都有.
    /* flush the decoders */
    if (video_dec_ctx)
        decode_packet(video_dec_ctx, NULL);
    if (audio_dec_ctx)
        decode_packet(audio_dec_ctx, NULL);

    printf("Demuxing succeeded.\n");

    if (video_stream) {//打印视频数据和视频的播放格式 这时的视频已经是没有编码过的原生数据
        printf("Play the output video file with the command:\n"
               "ffplay -f rawvideo -pix_fmt %s -video_size %dx%d %s\n",
               av_get_pix_fmt_name(pix_fmt), width, height,
               video_dst_filename);
    }

    if (audio_stream) {
        enum AVSampleFormat sfmt = audio_dec_ctx->sample_fmt;
        int n_channels = audio_dec_ctx->channels;
        const char *fmt;

        //打印音频的相关格式.这里也是解码后的原始数据
        if (av_sample_fmt_is_planar(sfmt)) {
            const char *packed = av_get_sample_fmt_name(sfmt);
            printf("Warning: the sample format the decoder produced is planar "//音频是平面的,只播放第一个通道
                   "(%s). This example will output the first channel only.\n",
                   packed ? packed : "?");
            sfmt = av_get_packed_sample_fmt(sfmt);
            n_channels = 1;
        }

        //通过 sfmt 格式确定 fmt 的内容
        if ((ret = get_format_from_sample_fmt(&fmt, sfmt)) < 0)
            goto end;

        printf("Play the output audio file with the command:\n"
               "ffplay -f %s -ac %d -ar %d %s\n",
               fmt, n_channels, audio_dec_ctx->sample_rate,
               audio_dst_filename);
    }

    end:
    avcodec_free_context(&video_dec_ctx);
    avcodec_free_context(&audio_dec_ctx);
    avformat_close_input(&fmt_ctx);
    if (video_dst_file)
        fclose(video_dst_file);
    if (audio_dst_file)
        fclose(audio_dst_file);
    av_frame_free(&frame);
    av_free(video_dst_data[0]);

    return ret < 0;
}

上一篇下一篇

猜你喜欢

热点阅读