]> git.sesse.net Git - ffmpeg/blob - doc/examples/transcoding.c
Merge commit 'c33c1fa8af2b2e82418a06901b6ad17b3d61b73e'
[ffmpeg] / doc / examples / transcoding.c
1 /*
2  * Copyright (c) 2010 Nicolas George
3  * Copyright (c) 2011 Stefano Sabatini
4  * Copyright (c) 2014 Andrey Utkin
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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
22  * THE SOFTWARE.
23  */
24
25 /**
26  * @file
27  * API example for demuxing, decoding, filtering, encoding and muxing
28  * @example transcoding.c
29  */
30
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>
38
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;
45 } FilteringContext;
46 static FilteringContext *filter_ctx;
47
48 static int open_input_file(const char *filename)
49 {
50     int ret;
51     unsigned int i;
52
53     ifmt_ctx = NULL;
54     if ((ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL)) < 0) {
55         av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
56         return ret;
57     }
58
59     if ((ret = avformat_find_stream_info(ifmt_ctx, NULL)) < 0) {
60         av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
61         return ret;
62     }
63
64     for (i = 0; i < ifmt_ctx->nb_streams; i++) {
65         AVStream *stream;
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) {
72             /* Open decoder */
73             ret = avcodec_open2(codec_ctx,
74                     avcodec_find_decoder(codec_ctx->codec_id), NULL);
75             if (ret < 0) {
76                 av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i);
77                 return ret;
78             }
79         }
80     }
81
82     av_dump_format(ifmt_ctx, 0, filename, 0);
83     return 0;
84 }
85
86 static int open_output_file(const char *filename)
87 {
88     AVStream *out_stream;
89     AVStream *in_stream;
90     AVCodecContext *dec_ctx, *enc_ctx;
91     AVCodec *encoder;
92     int ret;
93     unsigned int i;
94
95     ofmt_ctx = NULL;
96     avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, filename);
97     if (!ofmt_ctx) {
98         av_log(NULL, AV_LOG_ERROR, "Could not create output context\n");
99         return AVERROR_UNKNOWN;
100     }
101
102
103     for (i = 0; i < ifmt_ctx->nb_streams; i++) {
104         out_stream = avformat_new_stream(ofmt_ctx, NULL);
105         if (!out_stream) {
106             av_log(NULL, AV_LOG_ERROR, "Failed allocating output stream\n");
107             return AVERROR_UNKNOWN;
108         }
109
110         in_stream = ifmt_ctx->streams[i];
111         dec_ctx = in_stream->codec;
112         enc_ctx = out_stream->codec;
113
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);
118             if (!encoder) {
119                 av_log(NULL, AV_LOG_FATAL, "Necessary encoder not found\n");
120                 return AVERROR_INVALIDDATA;
121             }
122
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                 enc_ctx->pix_fmt = encoder->pix_fmts[0];
132                 /* video time_base can be set to whatever is handy and supported by encoder */
133                 enc_ctx->time_base = dec_ctx->time_base;
134             } else {
135                 enc_ctx->sample_rate = dec_ctx->sample_rate;
136                 enc_ctx->channel_layout = dec_ctx->channel_layout;
137                 enc_ctx->channels = av_get_channel_layout_nb_channels(enc_ctx->channel_layout);
138                 /* take first format from list of supported formats */
139                 enc_ctx->sample_fmt = encoder->sample_fmts[0];
140                 enc_ctx->time_base = (AVRational){1, enc_ctx->sample_rate};
141             }
142
143             /* Third parameter can be used to pass settings to encoder */
144             ret = avcodec_open2(enc_ctx, encoder, NULL);
145             if (ret < 0) {
146                 av_log(NULL, AV_LOG_ERROR, "Cannot open video encoder for stream #%u\n", i);
147                 return ret;
148             }
149         } else if (dec_ctx->codec_type == AVMEDIA_TYPE_UNKNOWN) {
150             av_log(NULL, AV_LOG_FATAL, "Elementary stream #%d is of unknown type, cannot proceed\n", i);
151             return AVERROR_INVALIDDATA;
152         } else {
153             /* if this stream must be remuxed */
154             ret = avcodec_copy_context(ofmt_ctx->streams[i]->codec,
155                     ifmt_ctx->streams[i]->codec);
156             if (ret < 0) {
157                 av_log(NULL, AV_LOG_ERROR, "Copying stream context failed\n");
158                 return ret;
159             }
160         }
161
162         if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
163             enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
164
165     }
166     av_dump_format(ofmt_ctx, 0, filename, 1);
167
168     if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
169         ret = avio_open(&ofmt_ctx->pb, filename, AVIO_FLAG_WRITE);
170         if (ret < 0) {
171             av_log(NULL, AV_LOG_ERROR, "Could not open output file '%s'", filename);
172             return ret;
173         }
174     }
175
176     /* init muxer, write output file header */
177     ret = avformat_write_header(ofmt_ctx, NULL);
178     if (ret < 0) {
179         av_log(NULL, AV_LOG_ERROR, "Error occurred when opening output file\n");
180         return ret;
181     }
182
183     return 0;
184 }
185
186 static int init_filter(FilteringContext* fctx, AVCodecContext *dec_ctx,
187         AVCodecContext *enc_ctx, const char *filter_spec)
188 {
189     char args[512];
190     int ret = 0;
191     AVFilter *buffersrc = NULL;
192     AVFilter *buffersink = NULL;
193     AVFilterContext *buffersrc_ctx = NULL;
194     AVFilterContext *buffersink_ctx = NULL;
195     AVFilterInOut *outputs = avfilter_inout_alloc();
196     AVFilterInOut *inputs  = avfilter_inout_alloc();
197     AVFilterGraph *filter_graph = avfilter_graph_alloc();
198
199     if (!outputs || !inputs || !filter_graph) {
200         ret = AVERROR(ENOMEM);
201         goto end;
202     }
203
204     if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
205         buffersrc = avfilter_get_by_name("buffer");
206         buffersink = avfilter_get_by_name("buffersink");
207         if (!buffersrc || !buffersink) {
208             av_log(NULL, AV_LOG_ERROR, "filtering source or sink element not found\n");
209             ret = AVERROR_UNKNOWN;
210             goto end;
211         }
212
213         snprintf(args, sizeof(args),
214                 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
215                 dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,
216                 dec_ctx->time_base.num, dec_ctx->time_base.den,
217                 dec_ctx->sample_aspect_ratio.num,
218                 dec_ctx->sample_aspect_ratio.den);
219
220         ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
221                 args, NULL, filter_graph);
222         if (ret < 0) {
223             av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
224             goto end;
225         }
226
227         ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
228                 NULL, NULL, filter_graph);
229         if (ret < 0) {
230             av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
231             goto end;
232         }
233
234         ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
235                 (uint8_t*)&enc_ctx->pix_fmt, sizeof(enc_ctx->pix_fmt),
236                 AV_OPT_SEARCH_CHILDREN);
237         if (ret < 0) {
238             av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\n");
239             goto end;
240         }
241     } else if (dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
242         buffersrc = avfilter_get_by_name("abuffer");
243         buffersink = avfilter_get_by_name("abuffersink");
244         if (!buffersrc || !buffersink) {
245             av_log(NULL, AV_LOG_ERROR, "filtering source or sink element not found\n");
246             ret = AVERROR_UNKNOWN;
247             goto end;
248         }
249
250         if (!dec_ctx->channel_layout)
251             dec_ctx->channel_layout =
252                 av_get_default_channel_layout(dec_ctx->channels);
253         snprintf(args, sizeof(args),
254                 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%"PRIx64,
255                 dec_ctx->time_base.num, dec_ctx->time_base.den, dec_ctx->sample_rate,
256                 av_get_sample_fmt_name(dec_ctx->sample_fmt),
257                 dec_ctx->channel_layout);
258         ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
259                 args, NULL, filter_graph);
260         if (ret < 0) {
261             av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source\n");
262             goto end;
263         }
264
265         ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
266                 NULL, NULL, filter_graph);
267         if (ret < 0) {
268             av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink\n");
269             goto end;
270         }
271
272         ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
273                 (uint8_t*)&enc_ctx->sample_fmt, sizeof(enc_ctx->sample_fmt),
274                 AV_OPT_SEARCH_CHILDREN);
275         if (ret < 0) {
276             av_log(NULL, AV_LOG_ERROR, "Cannot set output sample format\n");
277             goto end;
278         }
279
280         ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
281                 (uint8_t*)&enc_ctx->channel_layout,
282                 sizeof(enc_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
283         if (ret < 0) {
284             av_log(NULL, AV_LOG_ERROR, "Cannot set output channel layout\n");
285             goto end;
286         }
287
288         ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
289                 (uint8_t*)&enc_ctx->sample_rate, sizeof(enc_ctx->sample_rate),
290                 AV_OPT_SEARCH_CHILDREN);
291         if (ret < 0) {
292             av_log(NULL, AV_LOG_ERROR, "Cannot set output sample rate\n");
293             goto end;
294         }
295     } else {
296         ret = AVERROR_UNKNOWN;
297         goto end;
298     }
299
300     /* Endpoints for the filter graph. */
301     outputs->name       = av_strdup("in");
302     outputs->filter_ctx = buffersrc_ctx;
303     outputs->pad_idx    = 0;
304     outputs->next       = NULL;
305
306     inputs->name       = av_strdup("out");
307     inputs->filter_ctx = buffersink_ctx;
308     inputs->pad_idx    = 0;
309     inputs->next       = NULL;
310
311     if (!outputs->name || !inputs->name) {
312         ret = AVERROR(ENOMEM);
313         goto end;
314     }
315
316     if ((ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
317                     &inputs, &outputs, NULL)) < 0)
318         goto end;
319
320     if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
321         goto end;
322
323     /* Fill FilteringContext */
324     fctx->buffersrc_ctx = buffersrc_ctx;
325     fctx->buffersink_ctx = buffersink_ctx;
326     fctx->filter_graph = filter_graph;
327
328 end:
329     avfilter_inout_free(&inputs);
330     avfilter_inout_free(&outputs);
331
332     return ret;
333 }
334
335 static int init_filters(void)
336 {
337     const char *filter_spec;
338     unsigned int i;
339     int ret;
340     filter_ctx = av_malloc_array(ifmt_ctx->nb_streams, sizeof(*filter_ctx));
341     if (!filter_ctx)
342         return AVERROR(ENOMEM);
343
344     for (i = 0; i < ifmt_ctx->nb_streams; i++) {
345         filter_ctx[i].buffersrc_ctx  = NULL;
346         filter_ctx[i].buffersink_ctx = NULL;
347         filter_ctx[i].filter_graph   = NULL;
348         if (!(ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO
349                 || ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO))
350             continue;
351
352
353         if (ifmt_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
354             filter_spec = "null"; /* passthrough (dummy) filter for video */
355         else
356             filter_spec = "anull"; /* passthrough (dummy) filter for audio */
357         ret = init_filter(&filter_ctx[i], ifmt_ctx->streams[i]->codec,
358                 ofmt_ctx->streams[i]->codec, filter_spec);
359         if (ret)
360             return ret;
361     }
362     return 0;
363 }
364
365 static int encode_write_frame(AVFrame *filt_frame, unsigned int stream_index, int *got_frame) {
366     int ret;
367     int got_frame_local;
368     AVPacket enc_pkt;
369     int (*enc_func)(AVCodecContext *, AVPacket *, const AVFrame *, int *) =
370         (ifmt_ctx->streams[stream_index]->codec->codec_type ==
371          AVMEDIA_TYPE_VIDEO) ? avcodec_encode_video2 : avcodec_encode_audio2;
372
373     if (!got_frame)
374         got_frame = &got_frame_local;
375
376     av_log(NULL, AV_LOG_INFO, "Encoding frame\n");
377     /* encode filtered frame */
378     enc_pkt.data = NULL;
379     enc_pkt.size = 0;
380     av_init_packet(&enc_pkt);
381     ret = enc_func(ofmt_ctx->streams[stream_index]->codec, &enc_pkt,
382             filt_frame, got_frame);
383     av_frame_free(&filt_frame);
384     if (ret < 0)
385         return ret;
386     if (!(*got_frame))
387         return 0;
388
389     /* prepare packet for muxing */
390     enc_pkt.stream_index = stream_index;
391     av_packet_rescale_ts(&enc_pkt,
392                          ofmt_ctx->streams[stream_index]->codec->time_base,
393                          ofmt_ctx->streams[stream_index]->time_base);
394
395     av_log(NULL, AV_LOG_DEBUG, "Muxing frame\n");
396     /* mux encoded frame */
397     ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
398     return ret;
399 }
400
401 static int filter_encode_write_frame(AVFrame *frame, unsigned int stream_index)
402 {
403     int ret;
404     AVFrame *filt_frame;
405
406     av_log(NULL, AV_LOG_INFO, "Pushing decoded frame to filters\n");
407     /* push the decoded frame into the filtergraph */
408     ret = av_buffersrc_add_frame_flags(filter_ctx[stream_index].buffersrc_ctx,
409             frame, 0);
410     if (ret < 0) {
411         av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
412         return ret;
413     }
414
415     /* pull filtered frames from the filtergraph */
416     while (1) {
417         filt_frame = av_frame_alloc();
418         if (!filt_frame) {
419             ret = AVERROR(ENOMEM);
420             break;
421         }
422         av_log(NULL, AV_LOG_INFO, "Pulling filtered frame from filters\n");
423         ret = av_buffersink_get_frame(filter_ctx[stream_index].buffersink_ctx,
424                 filt_frame);
425         if (ret < 0) {
426             /* if no more frames for output - returns AVERROR(EAGAIN)
427              * if flushed and no more frames for output - returns AVERROR_EOF
428              * rewrite retcode to 0 to show it as normal procedure completion
429              */
430             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
431                 ret = 0;
432             av_frame_free(&filt_frame);
433             break;
434         }
435
436         filt_frame->pict_type = AV_PICTURE_TYPE_NONE;
437         ret = encode_write_frame(filt_frame, stream_index, NULL);
438         if (ret < 0)
439             break;
440     }
441
442     return ret;
443 }
444
445 static int flush_encoder(unsigned int stream_index)
446 {
447     int ret;
448     int got_frame;
449
450     if (!(ofmt_ctx->streams[stream_index]->codec->codec->capabilities &
451                 AV_CODEC_CAP_DELAY))
452         return 0;
453
454     while (1) {
455         av_log(NULL, AV_LOG_INFO, "Flushing stream #%u encoder\n", stream_index);
456         ret = encode_write_frame(NULL, stream_index, &got_frame);
457         if (ret < 0)
458             break;
459         if (!got_frame)
460             return 0;
461     }
462     return ret;
463 }
464
465 int main(int argc, char **argv)
466 {
467     int ret;
468     AVPacket packet = { .data = NULL, .size = 0 };
469     AVFrame *frame = NULL;
470     enum AVMediaType type;
471     unsigned int stream_index;
472     unsigned int i;
473     int got_frame;
474     int (*dec_func)(AVCodecContext *, AVFrame *, int *, const AVPacket *);
475
476     if (argc != 3) {
477         av_log(NULL, AV_LOG_ERROR, "Usage: %s <input file> <output file>\n", argv[0]);
478         return 1;
479     }
480
481     av_register_all();
482     avfilter_register_all();
483
484     if ((ret = open_input_file(argv[1])) < 0)
485         goto end;
486     if ((ret = open_output_file(argv[2])) < 0)
487         goto end;
488     if ((ret = init_filters()) < 0)
489         goto end;
490
491     /* read all packets */
492     while (1) {
493         if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0)
494             break;
495         stream_index = packet.stream_index;
496         type = ifmt_ctx->streams[packet.stream_index]->codec->codec_type;
497         av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n",
498                 stream_index);
499
500         if (filter_ctx[stream_index].filter_graph) {
501             av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
502             frame = av_frame_alloc();
503             if (!frame) {
504                 ret = AVERROR(ENOMEM);
505                 break;
506             }
507             av_packet_rescale_ts(&packet,
508                                  ifmt_ctx->streams[stream_index]->time_base,
509                                  ifmt_ctx->streams[stream_index]->codec->time_base);
510             dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 :
511                 avcodec_decode_audio4;
512             ret = dec_func(ifmt_ctx->streams[stream_index]->codec, frame,
513                     &got_frame, &packet);
514             if (ret < 0) {
515                 av_frame_free(&frame);
516                 av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
517                 break;
518             }
519
520             if (got_frame) {
521                 frame->pts = av_frame_get_best_effort_timestamp(frame);
522                 ret = filter_encode_write_frame(frame, stream_index);
523                 av_frame_free(&frame);
524                 if (ret < 0)
525                     goto end;
526             } else {
527                 av_frame_free(&frame);
528             }
529         } else {
530             /* remux this frame without reencoding */
531             av_packet_rescale_ts(&packet,
532                                  ifmt_ctx->streams[stream_index]->time_base,
533                                  ofmt_ctx->streams[stream_index]->time_base);
534
535             ret = av_interleaved_write_frame(ofmt_ctx, &packet);
536             if (ret < 0)
537                 goto end;
538         }
539         av_packet_unref(&packet);
540     }
541
542     /* flush filters and encoders */
543     for (i = 0; i < ifmt_ctx->nb_streams; i++) {
544         /* flush filter */
545         if (!filter_ctx[i].filter_graph)
546             continue;
547         ret = filter_encode_write_frame(NULL, i);
548         if (ret < 0) {
549             av_log(NULL, AV_LOG_ERROR, "Flushing filter failed\n");
550             goto end;
551         }
552
553         /* flush encoder */
554         ret = flush_encoder(i);
555         if (ret < 0) {
556             av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n");
557             goto end;
558         }
559     }
560
561     av_write_trailer(ofmt_ctx);
562 end:
563     av_packet_unref(&packet);
564     av_frame_free(&frame);
565     for (i = 0; i < ifmt_ctx->nb_streams; i++) {
566         avcodec_close(ifmt_ctx->streams[i]->codec);
567         if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && ofmt_ctx->streams[i]->codec)
568             avcodec_close(ofmt_ctx->streams[i]->codec);
569         if (filter_ctx && filter_ctx[i].filter_graph)
570             avfilter_graph_free(&filter_ctx[i].filter_graph);
571     }
572     av_free(filter_ctx);
573     avformat_close_input(&ifmt_ctx);
574     if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
575         avio_closep(&ofmt_ctx->pb);
576     avformat_free_context(ofmt_ctx);
577
578     if (ret < 0)
579         av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret));
580
581     return ret ? 1 : 0;
582 }