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/buffersink.h>
34 #include <libavfilter/buffersrc.h>
35 #include <libavutil/opt.h>
36 #include <libavutil/pixdesc.h>
38 static AVFormatContext *ifmt_ctx;
39 static AVFormatContext *ofmt_ctx;
40 typedef struct FilteringContext {
41 AVFilterContext *buffersink_ctx;
42 AVFilterContext *buffersrc_ctx;
43 AVFilterGraph *filter_graph;
45 static FilteringContext *filter_ctx;
47 typedef struct StreamContext {
48 AVCodecContext *dec_ctx;
49 AVCodecContext *enc_ctx;
51 static StreamContext *stream_ctx;
53 static int open_input_file(const char *filename)
59 if ((ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL)) < 0) {
60 av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
64 if ((ret = avformat_find_stream_info(ifmt_ctx, NULL)) < 0) {
65 av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
69 stream_ctx = av_mallocz_array(ifmt_ctx->nb_streams, sizeof(*stream_ctx));
71 return AVERROR(ENOMEM);
73 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
74 AVStream *stream = ifmt_ctx->streams[i];
75 AVCodec *dec = avcodec_find_decoder(stream->codecpar->codec_id);
76 AVCodecContext *codec_ctx;
78 av_log(NULL, AV_LOG_ERROR, "Failed to find decoder for stream #%u\n", i);
79 return AVERROR_DECODER_NOT_FOUND;
81 codec_ctx = avcodec_alloc_context3(dec);
83 av_log(NULL, AV_LOG_ERROR, "Failed to allocate the decoder context for stream #%u\n", i);
84 return AVERROR(ENOMEM);
86 ret = avcodec_parameters_to_context(codec_ctx, stream->codecpar);
88 av_log(NULL, AV_LOG_ERROR, "Failed to copy decoder parameters to input decoder context "
89 "for stream #%u\n", i);
92 /* Reencode video & audio and remux subtitles etc. */
93 if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
94 || codec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
95 if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
96 codec_ctx->framerate = av_guess_frame_rate(ifmt_ctx, stream, NULL);
98 ret = avcodec_open2(codec_ctx, dec, NULL);
100 av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i);
104 stream_ctx[i].dec_ctx = codec_ctx;
107 av_dump_format(ifmt_ctx, 0, filename, 0);
111 static int open_output_file(const char *filename)
113 AVStream *out_stream;
115 AVCodecContext *dec_ctx, *enc_ctx;
121 avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, filename);
123 av_log(NULL, AV_LOG_ERROR, "Could not create output context\n");
124 return AVERROR_UNKNOWN;
128 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
129 out_stream = avformat_new_stream(ofmt_ctx, NULL);
131 av_log(NULL, AV_LOG_ERROR, "Failed allocating output stream\n");
132 return AVERROR_UNKNOWN;
135 in_stream = ifmt_ctx->streams[i];
136 dec_ctx = stream_ctx[i].dec_ctx;
138 if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
139 || dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
140 /* in this example, we choose transcoding to same codec */
141 encoder = avcodec_find_encoder(dec_ctx->codec_id);
143 av_log(NULL, AV_LOG_FATAL, "Necessary encoder not found\n");
144 return AVERROR_INVALIDDATA;
146 enc_ctx = avcodec_alloc_context3(encoder);
148 av_log(NULL, AV_LOG_FATAL, "Failed to allocate the encoder context\n");
149 return AVERROR(ENOMEM);
152 /* In this example, we transcode to same properties (picture size,
153 * sample rate etc.). These properties can be changed for output
154 * streams easily using filters */
155 if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
156 enc_ctx->height = dec_ctx->height;
157 enc_ctx->width = dec_ctx->width;
158 enc_ctx->sample_aspect_ratio = dec_ctx->sample_aspect_ratio;
159 /* take first format from list of supported formats */
160 if (encoder->pix_fmts)
161 enc_ctx->pix_fmt = encoder->pix_fmts[0];
163 enc_ctx->pix_fmt = dec_ctx->pix_fmt;
164 /* video time_base can be set to whatever is handy and supported by encoder */
165 enc_ctx->time_base = av_inv_q(dec_ctx->framerate);
167 enc_ctx->sample_rate = dec_ctx->sample_rate;
168 enc_ctx->channel_layout = dec_ctx->channel_layout;
169 enc_ctx->channels = av_get_channel_layout_nb_channels(enc_ctx->channel_layout);
170 /* take first format from list of supported formats */
171 enc_ctx->sample_fmt = encoder->sample_fmts[0];
172 enc_ctx->time_base = (AVRational){1, enc_ctx->sample_rate};
175 /* Third parameter can be used to pass settings to encoder */
176 ret = avcodec_open2(enc_ctx, encoder, NULL);
178 av_log(NULL, AV_LOG_ERROR, "Cannot open video encoder for stream #%u\n", i);
181 ret = avcodec_parameters_from_context(out_stream->codecpar, enc_ctx);
183 av_log(NULL, AV_LOG_ERROR, "Failed to copy encoder parameters to output stream #%u\n", i);
186 if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
187 enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
189 out_stream->time_base = enc_ctx->time_base;
190 stream_ctx[i].enc_ctx = enc_ctx;
191 } else if (dec_ctx->codec_type == AVMEDIA_TYPE_UNKNOWN) {
192 av_log(NULL, AV_LOG_FATAL, "Elementary stream #%d is of unknown type, cannot proceed\n", i);
193 return AVERROR_INVALIDDATA;
195 /* if this stream must be remuxed */
196 ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);
198 av_log(NULL, AV_LOG_ERROR, "Copying parameters for stream #%u failed\n", i);
201 out_stream->time_base = in_stream->time_base;
205 av_dump_format(ofmt_ctx, 0, filename, 1);
207 if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
208 ret = avio_open(&ofmt_ctx->pb, filename, AVIO_FLAG_WRITE);
210 av_log(NULL, AV_LOG_ERROR, "Could not open output file '%s'", filename);
215 /* init muxer, write output file header */
216 ret = avformat_write_header(ofmt_ctx, NULL);
218 av_log(NULL, AV_LOG_ERROR, "Error occurred when opening output file\n");
225 static int init_filter(FilteringContext* fctx, AVCodecContext *dec_ctx,
226 AVCodecContext *enc_ctx, const char *filter_spec)
230 const AVFilter *buffersrc = NULL;
231 const AVFilter *buffersink = NULL;
232 AVFilterContext *buffersrc_ctx = NULL;
233 AVFilterContext *buffersink_ctx = NULL;
234 AVFilterInOut *outputs = avfilter_inout_alloc();
235 AVFilterInOut *inputs = avfilter_inout_alloc();
236 AVFilterGraph *filter_graph = avfilter_graph_alloc();
238 if (!outputs || !inputs || !filter_graph) {
239 ret = AVERROR(ENOMEM);
243 if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
244 buffersrc = avfilter_get_by_name("buffer");
245 buffersink = avfilter_get_by_name("buffersink");
246 if (!buffersrc || !buffersink) {
247 av_log(NULL, AV_LOG_ERROR, "filtering source or sink element not found\n");
248 ret = AVERROR_UNKNOWN;
252 snprintf(args, sizeof(args),
253 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
254 dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,
255 dec_ctx->time_base.num, dec_ctx->time_base.den,
256 dec_ctx->sample_aspect_ratio.num,
257 dec_ctx->sample_aspect_ratio.den);
259 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
260 args, NULL, filter_graph);
262 av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
266 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
267 NULL, NULL, filter_graph);
269 av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
273 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
274 (uint8_t*)&enc_ctx->pix_fmt, sizeof(enc_ctx->pix_fmt),
275 AV_OPT_SEARCH_CHILDREN);
277 av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\n");
280 } else if (dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
281 buffersrc = avfilter_get_by_name("abuffer");
282 buffersink = avfilter_get_by_name("abuffersink");
283 if (!buffersrc || !buffersink) {
284 av_log(NULL, AV_LOG_ERROR, "filtering source or sink element not found\n");
285 ret = AVERROR_UNKNOWN;
289 if (!dec_ctx->channel_layout)
290 dec_ctx->channel_layout =
291 av_get_default_channel_layout(dec_ctx->channels);
292 snprintf(args, sizeof(args),
293 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%"PRIx64,
294 dec_ctx->time_base.num, dec_ctx->time_base.den, dec_ctx->sample_rate,
295 av_get_sample_fmt_name(dec_ctx->sample_fmt),
296 dec_ctx->channel_layout);
297 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
298 args, NULL, filter_graph);
300 av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source\n");
304 ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
305 NULL, NULL, filter_graph);
307 av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink\n");
311 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
312 (uint8_t*)&enc_ctx->sample_fmt, sizeof(enc_ctx->sample_fmt),
313 AV_OPT_SEARCH_CHILDREN);
315 av_log(NULL, AV_LOG_ERROR, "Cannot set output sample format\n");
319 ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
320 (uint8_t*)&enc_ctx->channel_layout,
321 sizeof(enc_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
323 av_log(NULL, AV_LOG_ERROR, "Cannot set output channel layout\n");
327 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
328 (uint8_t*)&enc_ctx->sample_rate, sizeof(enc_ctx->sample_rate),
329 AV_OPT_SEARCH_CHILDREN);
331 av_log(NULL, AV_LOG_ERROR, "Cannot set output sample rate\n");
335 ret = AVERROR_UNKNOWN;
339 /* Endpoints for the filter graph. */
340 outputs->name = av_strdup("in");
341 outputs->filter_ctx = buffersrc_ctx;
342 outputs->pad_idx = 0;
343 outputs->next = NULL;
345 inputs->name = av_strdup("out");
346 inputs->filter_ctx = buffersink_ctx;
350 if (!outputs->name || !inputs->name) {
351 ret = AVERROR(ENOMEM);
355 if ((ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
356 &inputs, &outputs, NULL)) < 0)
359 if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
362 /* Fill FilteringContext */
363 fctx->buffersrc_ctx = buffersrc_ctx;
364 fctx->buffersink_ctx = buffersink_ctx;
365 fctx->filter_graph = filter_graph;
368 avfilter_inout_free(&inputs);
369 avfilter_inout_free(&outputs);
374 static int init_filters(void)
376 const char *filter_spec;
379 filter_ctx = av_malloc_array(ifmt_ctx->nb_streams, sizeof(*filter_ctx));
381 return AVERROR(ENOMEM);
383 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
384 filter_ctx[i].buffersrc_ctx = NULL;
385 filter_ctx[i].buffersink_ctx = NULL;
386 filter_ctx[i].filter_graph = NULL;
387 if (!(ifmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO
388 || ifmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO))
392 if (ifmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
393 filter_spec = "null"; /* passthrough (dummy) filter for video */
395 filter_spec = "anull"; /* passthrough (dummy) filter for audio */
396 ret = init_filter(&filter_ctx[i], stream_ctx[i].dec_ctx,
397 stream_ctx[i].enc_ctx, filter_spec);
404 static int encode_write_frame(AVFrame *filt_frame, unsigned int stream_index, int *got_frame) {
408 int (*enc_func)(AVCodecContext *, AVPacket *, const AVFrame *, int *) =
409 (ifmt_ctx->streams[stream_index]->codecpar->codec_type ==
410 AVMEDIA_TYPE_VIDEO) ? avcodec_encode_video2 : avcodec_encode_audio2;
413 got_frame = &got_frame_local;
415 av_log(NULL, AV_LOG_INFO, "Encoding frame\n");
416 /* encode filtered frame */
419 av_init_packet(&enc_pkt);
420 ret = enc_func(stream_ctx[stream_index].enc_ctx, &enc_pkt,
421 filt_frame, got_frame);
422 av_frame_free(&filt_frame);
428 /* prepare packet for muxing */
429 enc_pkt.stream_index = stream_index;
430 av_packet_rescale_ts(&enc_pkt,
431 stream_ctx[stream_index].enc_ctx->time_base,
432 ofmt_ctx->streams[stream_index]->time_base);
434 av_log(NULL, AV_LOG_DEBUG, "Muxing frame\n");
435 /* mux encoded frame */
436 ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
440 static int filter_encode_write_frame(AVFrame *frame, unsigned int stream_index)
445 av_log(NULL, AV_LOG_INFO, "Pushing decoded frame to filters\n");
446 /* push the decoded frame into the filtergraph */
447 ret = av_buffersrc_add_frame_flags(filter_ctx[stream_index].buffersrc_ctx,
450 av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
454 /* pull filtered frames from the filtergraph */
456 filt_frame = av_frame_alloc();
458 ret = AVERROR(ENOMEM);
461 av_log(NULL, AV_LOG_INFO, "Pulling filtered frame from filters\n");
462 ret = av_buffersink_get_frame(filter_ctx[stream_index].buffersink_ctx,
465 /* if no more frames for output - returns AVERROR(EAGAIN)
466 * if flushed and no more frames for output - returns AVERROR_EOF
467 * rewrite retcode to 0 to show it as normal procedure completion
469 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
471 av_frame_free(&filt_frame);
475 filt_frame->pict_type = AV_PICTURE_TYPE_NONE;
476 ret = encode_write_frame(filt_frame, stream_index, NULL);
484 static int flush_encoder(unsigned int stream_index)
489 if (!(stream_ctx[stream_index].enc_ctx->codec->capabilities &
494 av_log(NULL, AV_LOG_INFO, "Flushing stream #%u encoder\n", stream_index);
495 ret = encode_write_frame(NULL, stream_index, &got_frame);
504 int main(int argc, char **argv)
507 AVPacket packet = { .data = NULL, .size = 0 };
508 AVFrame *frame = NULL;
509 enum AVMediaType type;
510 unsigned int stream_index;
513 int (*dec_func)(AVCodecContext *, AVFrame *, int *, const AVPacket *);
516 av_log(NULL, AV_LOG_ERROR, "Usage: %s <input file> <output file>\n", argv[0]);
521 avfilter_register_all();
523 if ((ret = open_input_file(argv[1])) < 0)
525 if ((ret = open_output_file(argv[2])) < 0)
527 if ((ret = init_filters()) < 0)
530 /* read all packets */
532 if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0)
534 stream_index = packet.stream_index;
535 type = ifmt_ctx->streams[packet.stream_index]->codecpar->codec_type;
536 av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n",
539 if (filter_ctx[stream_index].filter_graph) {
540 av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
541 frame = av_frame_alloc();
543 ret = AVERROR(ENOMEM);
546 av_packet_rescale_ts(&packet,
547 ifmt_ctx->streams[stream_index]->time_base,
548 stream_ctx[stream_index].dec_ctx->time_base);
549 dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 :
550 avcodec_decode_audio4;
551 ret = dec_func(stream_ctx[stream_index].dec_ctx, frame,
552 &got_frame, &packet);
554 av_frame_free(&frame);
555 av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
560 frame->pts = frame->best_effort_timestamp;
561 ret = filter_encode_write_frame(frame, stream_index);
562 av_frame_free(&frame);
566 av_frame_free(&frame);
569 /* remux this frame without reencoding */
570 av_packet_rescale_ts(&packet,
571 ifmt_ctx->streams[stream_index]->time_base,
572 ofmt_ctx->streams[stream_index]->time_base);
574 ret = av_interleaved_write_frame(ofmt_ctx, &packet);
578 av_packet_unref(&packet);
581 /* flush filters and encoders */
582 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
584 if (!filter_ctx[i].filter_graph)
586 ret = filter_encode_write_frame(NULL, i);
588 av_log(NULL, AV_LOG_ERROR, "Flushing filter failed\n");
593 ret = flush_encoder(i);
595 av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n");
600 av_write_trailer(ofmt_ctx);
602 av_packet_unref(&packet);
603 av_frame_free(&frame);
604 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
605 avcodec_free_context(&stream_ctx[i].dec_ctx);
606 if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && stream_ctx[i].enc_ctx)
607 avcodec_free_context(&stream_ctx[i].enc_ctx);
608 if (filter_ctx && filter_ctx[i].filter_graph)
609 avfilter_graph_free(&filter_ctx[i].filter_graph);
613 avformat_close_input(&ifmt_ctx);
614 if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
615 avio_closep(&ofmt_ctx->pb);
616 avformat_free_context(ofmt_ctx);
619 av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret));