]> git.sesse.net Git - ffmpeg/blob - doc/examples/transcoding.c
Merge commit '8f144d9e3d5cb2ca92e5bdf7cc9f72effa1bd2ce'
[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/buffersink.h>
34 #include <libavfilter/buffersrc.h>
35 #include <libavutil/opt.h>
36 #include <libavutil/pixdesc.h>
37
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;
44 } FilteringContext;
45 static FilteringContext *filter_ctx;
46
47 typedef struct StreamContext {
48     AVCodecContext *dec_ctx;
49     AVCodecContext *enc_ctx;
50 } StreamContext;
51 static StreamContext *stream_ctx;
52
53 static int open_input_file(const char *filename)
54 {
55     int ret;
56     unsigned int i;
57
58     ifmt_ctx = NULL;
59     if ((ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL)) < 0) {
60         av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
61         return ret;
62     }
63
64     if ((ret = avformat_find_stream_info(ifmt_ctx, NULL)) < 0) {
65         av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
66         return ret;
67     }
68
69     stream_ctx = av_mallocz_array(ifmt_ctx->nb_streams, sizeof(*stream_ctx));
70     if (!stream_ctx)
71         return AVERROR(ENOMEM);
72
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;
77         if (!dec) {
78             av_log(NULL, AV_LOG_ERROR, "Failed to find decoder for stream #%u\n", i);
79             return AVERROR_DECODER_NOT_FOUND;
80         }
81         codec_ctx = avcodec_alloc_context3(dec);
82         if (!codec_ctx) {
83             av_log(NULL, AV_LOG_ERROR, "Failed to allocate the decoder context for stream #%u\n", i);
84             return AVERROR(ENOMEM);
85         }
86         ret = avcodec_parameters_to_context(codec_ctx, stream->codecpar);
87         if (ret < 0) {
88             av_log(NULL, AV_LOG_ERROR, "Failed to copy decoder parameters to input decoder context "
89                    "for stream #%u\n", i);
90             return ret;
91         }
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);
97             /* Open decoder */
98             ret = avcodec_open2(codec_ctx, dec, NULL);
99             if (ret < 0) {
100                 av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i);
101                 return ret;
102             }
103         }
104         stream_ctx[i].dec_ctx = codec_ctx;
105     }
106
107     av_dump_format(ifmt_ctx, 0, filename, 0);
108     return 0;
109 }
110
111 static int open_output_file(const char *filename)
112 {
113     AVStream *out_stream;
114     AVStream *in_stream;
115     AVCodecContext *dec_ctx, *enc_ctx;
116     AVCodec *encoder;
117     int ret;
118     unsigned int i;
119
120     ofmt_ctx = NULL;
121     avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, filename);
122     if (!ofmt_ctx) {
123         av_log(NULL, AV_LOG_ERROR, "Could not create output context\n");
124         return AVERROR_UNKNOWN;
125     }
126
127
128     for (i = 0; i < ifmt_ctx->nb_streams; i++) {
129         out_stream = avformat_new_stream(ofmt_ctx, NULL);
130         if (!out_stream) {
131             av_log(NULL, AV_LOG_ERROR, "Failed allocating output stream\n");
132             return AVERROR_UNKNOWN;
133         }
134
135         in_stream = ifmt_ctx->streams[i];
136         dec_ctx = stream_ctx[i].dec_ctx;
137
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);
142             if (!encoder) {
143                 av_log(NULL, AV_LOG_FATAL, "Necessary encoder not found\n");
144                 return AVERROR_INVALIDDATA;
145             }
146             enc_ctx = avcodec_alloc_context3(encoder);
147             if (!enc_ctx) {
148                 av_log(NULL, AV_LOG_FATAL, "Failed to allocate the encoder context\n");
149                 return AVERROR(ENOMEM);
150             }
151
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];
162                 else
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);
166             } else {
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};
173             }
174
175             /* Third parameter can be used to pass settings to encoder */
176             ret = avcodec_open2(enc_ctx, encoder, NULL);
177             if (ret < 0) {
178                 av_log(NULL, AV_LOG_ERROR, "Cannot open video encoder for stream #%u\n", i);
179                 return ret;
180             }
181             ret = avcodec_parameters_from_context(out_stream->codecpar, enc_ctx);
182             if (ret < 0) {
183                 av_log(NULL, AV_LOG_ERROR, "Failed to copy encoder parameters to output stream #%u\n", i);
184                 return ret;
185             }
186             if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
187                 enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
188
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;
194         } else {
195             /* if this stream must be remuxed */
196             ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);
197             if (ret < 0) {
198                 av_log(NULL, AV_LOG_ERROR, "Copying parameters for stream #%u failed\n", i);
199                 return ret;
200             }
201             out_stream->time_base = in_stream->time_base;
202         }
203
204     }
205     av_dump_format(ofmt_ctx, 0, filename, 1);
206
207     if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
208         ret = avio_open(&ofmt_ctx->pb, filename, AVIO_FLAG_WRITE);
209         if (ret < 0) {
210             av_log(NULL, AV_LOG_ERROR, "Could not open output file '%s'", filename);
211             return ret;
212         }
213     }
214
215     /* init muxer, write output file header */
216     ret = avformat_write_header(ofmt_ctx, NULL);
217     if (ret < 0) {
218         av_log(NULL, AV_LOG_ERROR, "Error occurred when opening output file\n");
219         return ret;
220     }
221
222     return 0;
223 }
224
225 static int init_filter(FilteringContext* fctx, AVCodecContext *dec_ctx,
226         AVCodecContext *enc_ctx, const char *filter_spec)
227 {
228     char args[512];
229     int ret = 0;
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();
237
238     if (!outputs || !inputs || !filter_graph) {
239         ret = AVERROR(ENOMEM);
240         goto end;
241     }
242
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;
249             goto end;
250         }
251
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);
258
259         ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
260                 args, NULL, filter_graph);
261         if (ret < 0) {
262             av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
263             goto end;
264         }
265
266         ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
267                 NULL, NULL, filter_graph);
268         if (ret < 0) {
269             av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
270             goto end;
271         }
272
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);
276         if (ret < 0) {
277             av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\n");
278             goto end;
279         }
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;
286             goto end;
287         }
288
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);
299         if (ret < 0) {
300             av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source\n");
301             goto end;
302         }
303
304         ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
305                 NULL, NULL, filter_graph);
306         if (ret < 0) {
307             av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink\n");
308             goto end;
309         }
310
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);
314         if (ret < 0) {
315             av_log(NULL, AV_LOG_ERROR, "Cannot set output sample format\n");
316             goto end;
317         }
318
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);
322         if (ret < 0) {
323             av_log(NULL, AV_LOG_ERROR, "Cannot set output channel layout\n");
324             goto end;
325         }
326
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);
330         if (ret < 0) {
331             av_log(NULL, AV_LOG_ERROR, "Cannot set output sample rate\n");
332             goto end;
333         }
334     } else {
335         ret = AVERROR_UNKNOWN;
336         goto end;
337     }
338
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;
344
345     inputs->name       = av_strdup("out");
346     inputs->filter_ctx = buffersink_ctx;
347     inputs->pad_idx    = 0;
348     inputs->next       = NULL;
349
350     if (!outputs->name || !inputs->name) {
351         ret = AVERROR(ENOMEM);
352         goto end;
353     }
354
355     if ((ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
356                     &inputs, &outputs, NULL)) < 0)
357         goto end;
358
359     if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
360         goto end;
361
362     /* Fill FilteringContext */
363     fctx->buffersrc_ctx = buffersrc_ctx;
364     fctx->buffersink_ctx = buffersink_ctx;
365     fctx->filter_graph = filter_graph;
366
367 end:
368     avfilter_inout_free(&inputs);
369     avfilter_inout_free(&outputs);
370
371     return ret;
372 }
373
374 static int init_filters(void)
375 {
376     const char *filter_spec;
377     unsigned int i;
378     int ret;
379     filter_ctx = av_malloc_array(ifmt_ctx->nb_streams, sizeof(*filter_ctx));
380     if (!filter_ctx)
381         return AVERROR(ENOMEM);
382
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))
389             continue;
390
391
392         if (ifmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
393             filter_spec = "null"; /* passthrough (dummy) filter for video */
394         else
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);
398         if (ret)
399             return ret;
400     }
401     return 0;
402 }
403
404 static int encode_write_frame(AVFrame *filt_frame, unsigned int stream_index, int *got_frame) {
405     int ret;
406     int got_frame_local;
407     AVPacket enc_pkt;
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;
411
412     if (!got_frame)
413         got_frame = &got_frame_local;
414
415     av_log(NULL, AV_LOG_INFO, "Encoding frame\n");
416     /* encode filtered frame */
417     enc_pkt.data = NULL;
418     enc_pkt.size = 0;
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);
423     if (ret < 0)
424         return ret;
425     if (!(*got_frame))
426         return 0;
427
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);
433
434     av_log(NULL, AV_LOG_DEBUG, "Muxing frame\n");
435     /* mux encoded frame */
436     ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
437     return ret;
438 }
439
440 static int filter_encode_write_frame(AVFrame *frame, unsigned int stream_index)
441 {
442     int ret;
443     AVFrame *filt_frame;
444
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,
448             frame, 0);
449     if (ret < 0) {
450         av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
451         return ret;
452     }
453
454     /* pull filtered frames from the filtergraph */
455     while (1) {
456         filt_frame = av_frame_alloc();
457         if (!filt_frame) {
458             ret = AVERROR(ENOMEM);
459             break;
460         }
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,
463                 filt_frame);
464         if (ret < 0) {
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
468              */
469             if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
470                 ret = 0;
471             av_frame_free(&filt_frame);
472             break;
473         }
474
475         filt_frame->pict_type = AV_PICTURE_TYPE_NONE;
476         ret = encode_write_frame(filt_frame, stream_index, NULL);
477         if (ret < 0)
478             break;
479     }
480
481     return ret;
482 }
483
484 static int flush_encoder(unsigned int stream_index)
485 {
486     int ret;
487     int got_frame;
488
489     if (!(stream_ctx[stream_index].enc_ctx->codec->capabilities &
490                 AV_CODEC_CAP_DELAY))
491         return 0;
492
493     while (1) {
494         av_log(NULL, AV_LOG_INFO, "Flushing stream #%u encoder\n", stream_index);
495         ret = encode_write_frame(NULL, stream_index, &got_frame);
496         if (ret < 0)
497             break;
498         if (!got_frame)
499             return 0;
500     }
501     return ret;
502 }
503
504 int main(int argc, char **argv)
505 {
506     int ret;
507     AVPacket packet = { .data = NULL, .size = 0 };
508     AVFrame *frame = NULL;
509     enum AVMediaType type;
510     unsigned int stream_index;
511     unsigned int i;
512     int got_frame;
513     int (*dec_func)(AVCodecContext *, AVFrame *, int *, const AVPacket *);
514
515     if (argc != 3) {
516         av_log(NULL, AV_LOG_ERROR, "Usage: %s <input file> <output file>\n", argv[0]);
517         return 1;
518     }
519
520     if ((ret = open_input_file(argv[1])) < 0)
521         goto end;
522     if ((ret = open_output_file(argv[2])) < 0)
523         goto end;
524     if ((ret = init_filters()) < 0)
525         goto end;
526
527     /* read all packets */
528     while (1) {
529         if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0)
530             break;
531         stream_index = packet.stream_index;
532         type = ifmt_ctx->streams[packet.stream_index]->codecpar->codec_type;
533         av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n",
534                 stream_index);
535
536         if (filter_ctx[stream_index].filter_graph) {
537             av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
538             frame = av_frame_alloc();
539             if (!frame) {
540                 ret = AVERROR(ENOMEM);
541                 break;
542             }
543             av_packet_rescale_ts(&packet,
544                                  ifmt_ctx->streams[stream_index]->time_base,
545                                  stream_ctx[stream_index].dec_ctx->time_base);
546             dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 :
547                 avcodec_decode_audio4;
548             ret = dec_func(stream_ctx[stream_index].dec_ctx, frame,
549                     &got_frame, &packet);
550             if (ret < 0) {
551                 av_frame_free(&frame);
552                 av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
553                 break;
554             }
555
556             if (got_frame) {
557                 frame->pts = frame->best_effort_timestamp;
558                 ret = filter_encode_write_frame(frame, stream_index);
559                 av_frame_free(&frame);
560                 if (ret < 0)
561                     goto end;
562             } else {
563                 av_frame_free(&frame);
564             }
565         } else {
566             /* remux this frame without reencoding */
567             av_packet_rescale_ts(&packet,
568                                  ifmt_ctx->streams[stream_index]->time_base,
569                                  ofmt_ctx->streams[stream_index]->time_base);
570
571             ret = av_interleaved_write_frame(ofmt_ctx, &packet);
572             if (ret < 0)
573                 goto end;
574         }
575         av_packet_unref(&packet);
576     }
577
578     /* flush filters and encoders */
579     for (i = 0; i < ifmt_ctx->nb_streams; i++) {
580         /* flush filter */
581         if (!filter_ctx[i].filter_graph)
582             continue;
583         ret = filter_encode_write_frame(NULL, i);
584         if (ret < 0) {
585             av_log(NULL, AV_LOG_ERROR, "Flushing filter failed\n");
586             goto end;
587         }
588
589         /* flush encoder */
590         ret = flush_encoder(i);
591         if (ret < 0) {
592             av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n");
593             goto end;
594         }
595     }
596
597     av_write_trailer(ofmt_ctx);
598 end:
599     av_packet_unref(&packet);
600     av_frame_free(&frame);
601     for (i = 0; i < ifmt_ctx->nb_streams; i++) {
602         avcodec_free_context(&stream_ctx[i].dec_ctx);
603         if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && stream_ctx[i].enc_ctx)
604             avcodec_free_context(&stream_ctx[i].enc_ctx);
605         if (filter_ctx && filter_ctx[i].filter_graph)
606             avfilter_graph_free(&filter_ctx[i].filter_graph);
607     }
608     av_free(filter_ctx);
609     av_free(stream_ctx);
610     avformat_close_input(&ifmt_ctx);
611     if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
612         avio_closep(&ofmt_ctx->pb);
613     avformat_free_context(ofmt_ctx);
614
615     if (ret < 0)
616         av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret));
617
618     return ret ? 1 : 0;
619 }