2 * Copyright (c) 2010 Nicolas George
3 * Copyright (c) 2011 Stefano Sabatini
4 * Copyright (c) 2014 Andrey Utkin
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
27 * API example for demuxing, decoding, filtering, encoding and muxing
28 * @example transcoding.c
31 #include <libavcodec/avcodec.h>
32 #include <libavformat/avformat.h>
33 #include <libavfilter/avfiltergraph.h>
34 #include <libavfilter/buffersink.h>
35 #include <libavfilter/buffersrc.h>
36 #include <libavutil/opt.h>
37 #include <libavutil/pixdesc.h>
39 static AVFormatContext *ifmt_ctx;
40 static AVFormatContext *ofmt_ctx;
41 typedef struct FilteringContext {
42 AVFilterContext *buffersink_ctx;
43 AVFilterContext *buffersrc_ctx;
44 AVFilterGraph *filter_graph;
46 static FilteringContext *filter_ctx;
48 static int open_input_file(const char *filename)
54 if ((ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL)) < 0) {
55 av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
59 if ((ret = avformat_find_stream_info(ifmt_ctx, NULL)) < 0) {
60 av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
64 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
66 AVCodecContext *codec_ctx;
67 stream = ifmt_ctx->streams[i];
68 codec_ctx = stream->codec;
69 /* Reencode video & audio and remux subtitles etc. */
70 if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
71 || codec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
73 ret = avcodec_open2(codec_ctx,
74 avcodec_find_decoder(codec_ctx->codec_id), NULL);
76 av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i);
82 av_dump_format(ifmt_ctx, 0, filename, 0);
86 static int open_output_file(const char *filename)
90 AVCodecContext *dec_ctx, *enc_ctx;
96 avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, filename);
98 av_log(NULL, AV_LOG_ERROR, "Could not create output context\n");
99 return AVERROR_UNKNOWN;
103 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
104 out_stream = avformat_new_stream(ofmt_ctx, NULL);
106 av_log(NULL, AV_LOG_ERROR, "Failed allocating output stream\n");
107 return AVERROR_UNKNOWN;
110 in_stream = ifmt_ctx->streams[i];
111 dec_ctx = in_stream->codec;
112 enc_ctx = out_stream->codec;
114 if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
115 || dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
116 /* in this example, we choose transcoding to same codec */
117 encoder = avcodec_find_encoder(dec_ctx->codec_id);
119 av_log(NULL, AV_LOG_FATAL, "Necessary encoder not found\n");
120 return AVERROR_INVALIDDATA;
123 /* In this example, we transcode to same properties (picture size,
124 * sample rate etc.). These properties can be changed for output
125 * streams easily using filters */
126 if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
127 enc_ctx->height = dec_ctx->height;
128 enc_ctx->width = dec_ctx->width;
129 enc_ctx->sample_aspect_ratio = dec_ctx->sample_aspect_ratio;
130 /* take first format from list of supported formats */
131 if (encoder->pix_fmts)
132 enc_ctx->pix_fmt = encoder->pix_fmts[0];
134 enc_ctx->pix_fmt = dec_ctx->pix_fmt;
135 /* video time_base can be set to whatever is handy and supported by encoder */
136 enc_ctx->time_base = dec_ctx->time_base;
138 enc_ctx->sample_rate = dec_ctx->sample_rate;
139 enc_ctx->channel_layout = dec_ctx->channel_layout;
140 enc_ctx->channels = av_get_channel_layout_nb_channels(enc_ctx->channel_layout);
141 /* take first format from list of supported formats */
142 enc_ctx->sample_fmt = encoder->sample_fmts[0];
143 enc_ctx->time_base = (AVRational){1, enc_ctx->sample_rate};
146 /* Third parameter can be used to pass settings to encoder */
147 ret = avcodec_open2(enc_ctx, encoder, NULL);
149 av_log(NULL, AV_LOG_ERROR, "Cannot open video encoder for stream #%u\n", i);
152 } else if (dec_ctx->codec_type == AVMEDIA_TYPE_UNKNOWN) {
153 av_log(NULL, AV_LOG_FATAL, "Elementary stream #%d is of unknown type, cannot proceed\n", i);
154 return AVERROR_INVALIDDATA;
156 /* if this stream must be remuxed */
157 ret = avcodec_copy_context(ofmt_ctx->streams[i]->codec,
158 ifmt_ctx->streams[i]->codec);
160 av_log(NULL, AV_LOG_ERROR, "Copying stream context failed\n");
165 if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
166 enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
169 av_dump_format(ofmt_ctx, 0, filename, 1);
171 if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
172 ret = avio_open(&ofmt_ctx->pb, filename, AVIO_FLAG_WRITE);
174 av_log(NULL, AV_LOG_ERROR, "Could not open output file '%s'", filename);
179 /* init muxer, write output file header */
180 ret = avformat_write_header(ofmt_ctx, NULL);
182 av_log(NULL, AV_LOG_ERROR, "Error occurred when opening output file\n");
189 static int init_filter(FilteringContext* fctx, AVCodecContext *dec_ctx,
190 AVCodecContext *enc_ctx, const char *filter_spec)
194 AVFilter *buffersrc = NULL;
195 AVFilter *buffersink = NULL;
196 AVFilterContext *buffersrc_ctx = NULL;
197 AVFilterContext *buffersink_ctx = NULL;
198 AVFilterInOut *outputs = avfilter_inout_alloc();
199 AVFilterInOut *inputs = avfilter_inout_alloc();
200 AVFilterGraph *filter_graph = avfilter_graph_alloc();
202 if (!outputs || !inputs || !filter_graph) {
203 ret = AVERROR(ENOMEM);
207 if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
208 buffersrc = avfilter_get_by_name("buffer");
209 buffersink = avfilter_get_by_name("buffersink");
210 if (!buffersrc || !buffersink) {
211 av_log(NULL, AV_LOG_ERROR, "filtering source or sink element not found\n");
212 ret = AVERROR_UNKNOWN;
216 snprintf(args, sizeof(args),
217 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
218 dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,
219 dec_ctx->time_base.num, dec_ctx->time_base.den,
220 dec_ctx->sample_aspect_ratio.num,
221 dec_ctx->sample_aspect_ratio.den);
223 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
224 args, NULL, filter_graph);
226 av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
230 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
231 NULL, NULL, filter_graph);
233 av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
237 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
238 (uint8_t*)&enc_ctx->pix_fmt, sizeof(enc_ctx->pix_fmt),
239 AV_OPT_SEARCH_CHILDREN);
241 av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\n");
244 } else if (dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
245 buffersrc = avfilter_get_by_name("abuffer");
246 buffersink = avfilter_get_by_name("abuffersink");
247 if (!buffersrc || !buffersink) {
248 av_log(NULL, AV_LOG_ERROR, "filtering source or sink element not found\n");
249 ret = AVERROR_UNKNOWN;
253 if (!dec_ctx->channel_layout)
254 dec_ctx->channel_layout =
255 av_get_default_channel_layout(dec_ctx->channels);
256 snprintf(args, sizeof(args),
257 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%"PRIx64,
258 dec_ctx->time_base.num, dec_ctx->time_base.den, dec_ctx->sample_rate,
259 av_get_sample_fmt_name(dec_ctx->sample_fmt),
260 dec_ctx->channel_layout);
261 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
262 args, NULL, filter_graph);
264 av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source\n");
268 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
269 NULL, NULL, filter_graph);
271 av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink\n");
275 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
276 (uint8_t*)&enc_ctx->sample_fmt, sizeof(enc_ctx->sample_fmt),
277 AV_OPT_SEARCH_CHILDREN);
279 av_log(NULL, AV_LOG_ERROR, "Cannot set output sample format\n");
283 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
284 (uint8_t*)&enc_ctx->channel_layout,
285 sizeof(enc_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
287 av_log(NULL, AV_LOG_ERROR, "Cannot set output channel layout\n");
291 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
292 (uint8_t*)&enc_ctx->sample_rate, sizeof(enc_ctx->sample_rate),
293 AV_OPT_SEARCH_CHILDREN);
295 av_log(NULL, AV_LOG_ERROR, "Cannot set output sample rate\n");
299 ret = AVERROR_UNKNOWN;
303 /* Endpoints for the filter graph. */
304 outputs->name = av_strdup("in");
305 outputs->filter_ctx = buffersrc_ctx;
306 outputs->pad_idx = 0;
307 outputs->next = NULL;
309 inputs->name = av_strdup("out");
310 inputs->filter_ctx = buffersink_ctx;
314 if (!outputs->name || !inputs->name) {
315 ret = AVERROR(ENOMEM);
319 if ((ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
320 &inputs, &outputs, NULL)) < 0)
323 if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
326 /* Fill FilteringContext */
327 fctx->buffersrc_ctx = buffersrc_ctx;
328 fctx->buffersink_ctx = buffersink_ctx;
329 fctx->filter_graph = filter_graph;
332 avfilter_inout_free(&inputs);
333 avfilter_inout_free(&outputs);
338 static int init_filters(void)
340 const char *filter_spec;
343 filter_ctx = av_malloc_array(ifmt_ctx->nb_streams, sizeof(*filter_ctx));
345 return AVERROR(ENOMEM);
347 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
348 filter_ctx[i].buffersrc_ctx = NULL;
349 filter_ctx[i].buffersink_ctx = NULL;
350 filter_ctx[i].filter_graph = NULL;
351 if (!(ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO
352 || ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO))
356 if (ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
357 filter_spec = "null"; /* passthrough (dummy) filter for video */
359 filter_spec = "anull"; /* passthrough (dummy) filter for audio */
360 ret = init_filter(&filter_ctx[i], ifmt_ctx->streams[i]->codec,
361 ofmt_ctx->streams[i]->codec, filter_spec);
368 static int encode_write_frame(AVFrame *filt_frame, unsigned int stream_index, int *got_frame) {
372 int (*enc_func)(AVCodecContext *, AVPacket *, const AVFrame *, int *) =
373 (ifmt_ctx->streams[stream_index]->codec->codec_type ==
374 AVMEDIA_TYPE_VIDEO) ? avcodec_encode_video2 : avcodec_encode_audio2;
377 got_frame = &got_frame_local;
379 av_log(NULL, AV_LOG_INFO, "Encoding frame\n");
380 /* encode filtered frame */
383 av_init_packet(&enc_pkt);
384 ret = enc_func(ofmt_ctx->streams[stream_index]->codec, &enc_pkt,
385 filt_frame, got_frame);
386 av_frame_free(&filt_frame);
392 /* prepare packet for muxing */
393 enc_pkt.stream_index = stream_index;
394 av_packet_rescale_ts(&enc_pkt,
395 ofmt_ctx->streams[stream_index]->codec->time_base,
396 ofmt_ctx->streams[stream_index]->time_base);
398 av_log(NULL, AV_LOG_DEBUG, "Muxing frame\n");
399 /* mux encoded frame */
400 ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
404 static int filter_encode_write_frame(AVFrame *frame, unsigned int stream_index)
409 av_log(NULL, AV_LOG_INFO, "Pushing decoded frame to filters\n");
410 /* push the decoded frame into the filtergraph */
411 ret = av_buffersrc_add_frame_flags(filter_ctx[stream_index].buffersrc_ctx,
414 av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
418 /* pull filtered frames from the filtergraph */
420 filt_frame = av_frame_alloc();
422 ret = AVERROR(ENOMEM);
425 av_log(NULL, AV_LOG_INFO, "Pulling filtered frame from filters\n");
426 ret = av_buffersink_get_frame(filter_ctx[stream_index].buffersink_ctx,
429 /* if no more frames for output - returns AVERROR(EAGAIN)
430 * if flushed and no more frames for output - returns AVERROR_EOF
431 * rewrite retcode to 0 to show it as normal procedure completion
433 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
435 av_frame_free(&filt_frame);
439 filt_frame->pict_type = AV_PICTURE_TYPE_NONE;
440 ret = encode_write_frame(filt_frame, stream_index, NULL);
448 static int flush_encoder(unsigned int stream_index)
453 if (!(ofmt_ctx->streams[stream_index]->codec->codec->capabilities &
458 av_log(NULL, AV_LOG_INFO, "Flushing stream #%u encoder\n", stream_index);
459 ret = encode_write_frame(NULL, stream_index, &got_frame);
468 int main(int argc, char **argv)
471 AVPacket packet = { .data = NULL, .size = 0 };
472 AVFrame *frame = NULL;
473 enum AVMediaType type;
474 unsigned int stream_index;
477 int (*dec_func)(AVCodecContext *, AVFrame *, int *, const AVPacket *);
480 av_log(NULL, AV_LOG_ERROR, "Usage: %s <input file> <output file>\n", argv[0]);
485 avfilter_register_all();
487 if ((ret = open_input_file(argv[1])) < 0)
489 if ((ret = open_output_file(argv[2])) < 0)
491 if ((ret = init_filters()) < 0)
494 /* read all packets */
496 if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0)
498 stream_index = packet.stream_index;
499 type = ifmt_ctx->streams[packet.stream_index]->codec->codec_type;
500 av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n",
503 if (filter_ctx[stream_index].filter_graph) {
504 av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
505 frame = av_frame_alloc();
507 ret = AVERROR(ENOMEM);
510 av_packet_rescale_ts(&packet,
511 ifmt_ctx->streams[stream_index]->time_base,
512 ifmt_ctx->streams[stream_index]->codec->time_base);
513 dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 :
514 avcodec_decode_audio4;
515 ret = dec_func(ifmt_ctx->streams[stream_index]->codec, frame,
516 &got_frame, &packet);
518 av_frame_free(&frame);
519 av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
524 frame->pts = av_frame_get_best_effort_timestamp(frame);
525 ret = filter_encode_write_frame(frame, stream_index);
526 av_frame_free(&frame);
530 av_frame_free(&frame);
533 /* remux this frame without reencoding */
534 av_packet_rescale_ts(&packet,
535 ifmt_ctx->streams[stream_index]->time_base,
536 ofmt_ctx->streams[stream_index]->time_base);
538 ret = av_interleaved_write_frame(ofmt_ctx, &packet);
542 av_packet_unref(&packet);
545 /* flush filters and encoders */
546 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
548 if (!filter_ctx[i].filter_graph)
550 ret = filter_encode_write_frame(NULL, i);
552 av_log(NULL, AV_LOG_ERROR, "Flushing filter failed\n");
557 ret = flush_encoder(i);
559 av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n");
564 av_write_trailer(ofmt_ctx);
566 av_packet_unref(&packet);
567 av_frame_free(&frame);
568 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
569 avcodec_close(ifmt_ctx->streams[i]->codec);
570 if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && ofmt_ctx->streams[i]->codec)
571 avcodec_close(ofmt_ctx->streams[i]->codec);
572 if (filter_ctx && filter_ctx[i].filter_graph)
573 avfilter_graph_free(&filter_ctx[i].filter_graph);
576 avformat_close_input(&ifmt_ctx);
577 if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
578 avio_closep(&ofmt_ctx->pb);
579 avformat_free_context(ofmt_ctx);
582 av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret));