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 "http://音頻是平面的,只播放第一個通道
"(%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;
}