avconv: decouple configuring filtergraphs and setting input parameters
[libav.git] / avconv.c
CommitLineData
6291d7e4
AK
1/*
2 * avconv main
41ed7ab4 3 * Copyright (c) 2000-2011 The Libav developers
6291d7e4
AK
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include "config.h"
23#include <ctype.h>
24#include <string.h>
25#include <math.h>
26#include <stdlib.h>
27#include <errno.h>
28#include <signal.h>
29#include <limits.h>
8f8bc923
DB
30#include <stdint.h>
31
6291d7e4
AK
32#include "libavformat/avformat.h"
33#include "libavdevice/avdevice.h"
34#include "libswscale/swscale.h"
bcb82fe1 35#include "libavresample/avresample.h"
6291d7e4 36#include "libavutil/opt.h"
a903f8f0 37#include "libavutil/channel_layout.h"
6291d7e4
AK
38#include "libavutil/parseutils.h"
39#include "libavutil/samplefmt.h"
6291d7e4 40#include "libavutil/fifo.h"
40cf1bba 41#include "libavutil/internal.h"
6291d7e4
AK
42#include "libavutil/intreadwrite.h"
43#include "libavutil/dict.h"
44#include "libavutil/mathematics.h"
45#include "libavutil/pixdesc.h"
46#include "libavutil/avstring.h"
47#include "libavutil/libm.h"
64dca32c 48#include "libavutil/imgutils.h"
896bb0d7 49#include "libavutil/time.h"
6291d7e4
AK
50#include "libavformat/os_support.h"
51
6291d7e4 52# include "libavfilter/avfilter.h"
04a14d4d 53# include "libavfilter/buffersrc.h"
ac712309 54# include "libavfilter/buffersink.h"
6291d7e4
AK
55
56#if HAVE_SYS_RESOURCE_H
3f65eff4 57#include <sys/time.h>
6291d7e4 58#include <sys/types.h>
6291d7e4
AK
59#include <sys/resource.h>
60#elif HAVE_GETPROCESSTIMES
61#include <windows.h>
62#endif
63#if HAVE_GETPROCESSMEMORYINFO
64#include <windows.h>
65#include <psapi.h>
66#endif
67
68#if HAVE_SYS_SELECT_H
69#include <sys/select.h>
70#endif
71
5db5169e
AK
72#if HAVE_PTHREADS
73#include <pthread.h>
5db5169e
AK
74#endif
75
6291d7e4
AK
76#include <time.h>
77
f5e66827 78#include "avconv.h"
6291d7e4
AK
79#include "cmdutils.h"
80
81#include "libavutil/avassert.h"
82
83const char program_name[] = "avconv";
84const int program_birth_year = 2000;
85
6291d7e4 86static FILE *vstats_file;
6291d7e4 87
6291d7e4 88static int nb_frames_drop = 0;
6291d7e4 89
1c169782 90static int want_sdp = 1;
3460dd8a 91
47b812e9 92#if HAVE_PTHREADS
5db5169e
AK
93/* signal to input threads that they should exit; set by the main thread */
94static int transcoding_finished;
95#endif
96
f5e66827
AK
97InputStream **input_streams = NULL;
98int nb_input_streams = 0;
99InputFile **input_files = NULL;
100int nb_input_files = 0;
6b779ccc 101
f5e66827
AK
102OutputStream **output_streams = NULL;
103int nb_output_streams = 0;
104OutputFile **output_files = NULL;
105int nb_output_files = 0;
6b779ccc 106
f5e66827
AK
107FilterGraph **filtergraphs;
108int nb_filtergraphs;
575ec4e1 109
6291d7e4
AK
110static void term_exit(void)
111{
112 av_log(NULL, AV_LOG_QUIET, "");
113}
114
115static volatile int received_sigterm = 0;
116static volatile int received_nb_signals = 0;
117
118static void
119sigterm_handler(int sig)
120{
121 received_sigterm = sig;
122 received_nb_signals++;
123 term_exit();
124}
125
126static void term_init(void)
127{
7636c8c6 128 signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
6291d7e4
AK
129 signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
130#ifdef SIGXCPU
131 signal(SIGXCPU, sigterm_handler);
132#endif
133}
134
2abe947a 135static int decode_interrupt_cb(void *ctx)
6291d7e4
AK
136{
137 return received_nb_signals > 1;
138}
139
f5e66827 140const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
2abe947a 141
636ced8e 142static void avconv_cleanup(int ret)
6291d7e4 143{
560f7774
AK
144 int i, j;
145
146 for (i = 0; i < nb_filtergraphs; i++) {
73ed8558
AK
147 FilterGraph *fg = filtergraphs[i];
148 avfilter_graph_free(&fg->graph);
149 for (j = 0; j < fg->nb_inputs; j++) {
722ec3eb 150 av_buffer_unref(&fg->inputs[j]->hw_frames_ctx);
73ed8558
AK
151 av_freep(&fg->inputs[j]->name);
152 av_freep(&fg->inputs[j]);
cf6c38c6 153 }
73ed8558
AK
154 av_freep(&fg->inputs);
155 for (j = 0; j < fg->nb_outputs; j++) {
156 av_freep(&fg->outputs[j]->name);
157 av_freep(&fg->outputs[j]);
cf6c38c6 158 }
73ed8558
AK
159 av_freep(&fg->outputs);
160 av_freep(&fg->graph_desc);
161
560f7774
AK
162 av_freep(&filtergraphs[i]);
163 }
164 av_freep(&filtergraphs);
6291d7e4
AK
165
166 /* close files */
7636c8c6 167 for (i = 0; i < nb_output_files; i++) {
73ed8558
AK
168 OutputFile *of = output_files[i];
169 AVFormatContext *s = of->ctx;
274e134e 170 if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE) && s->pb)
6291d7e4
AK
171 avio_close(s->pb);
172 avformat_free_context(s);
73ed8558
AK
173 av_dict_free(&of->opts);
174
2e215267 175 av_freep(&output_files[i]);
6291d7e4 176 }
1135a071 177 for (i = 0; i < nb_output_streams; i++) {
73ed8558 178 OutputStream *ost = output_streams[i];
4426540f
AK
179
180 for (j = 0; j < ost->nb_bitstream_filters; j++)
181 av_bsf_free(&ost->bsf_ctx[j]);
182 av_freep(&ost->bsf_ctx);
183 av_freep(&ost->bitstream_filters);
184
73ed8558
AK
185 av_frame_free(&ost->filtered_frame);
186
187 av_parser_close(ost->parser);
35c85806 188 avcodec_free_context(&ost->parser_avctx);
ac646076 189
73ed8558
AK
190 av_freep(&ost->forced_keyframes);
191 av_freep(&ost->avfilter);
192 av_freep(&ost->logfile_prefix);
c872d310 193
38313626
AK
194 avcodec_free_context(&ost->enc_ctx);
195
398f015f
AK
196 while (av_fifo_size(ost->muxing_queue)) {
197 AVPacket pkt;
198 av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
199 av_packet_unref(&pkt);
200 }
201 av_fifo_free(ost->muxing_queue);
202
2e215267 203 av_freep(&output_streams[i]);
1135a071 204 }
7636c8c6 205 for (i = 0; i < nb_input_files; i++) {
2e215267
AK
206 avformat_close_input(&input_files[i]->ctx);
207 av_freep(&input_files[i]);
6291d7e4 208 }
9179f27c 209 for (i = 0; i < nb_input_streams; i++) {
73ed8558
AK
210 InputStream *ist = input_streams[i];
211
212 av_frame_free(&ist->decoded_frame);
213 av_frame_free(&ist->filter_frame);
f3a6ad22 214 av_dict_free(&ist->decoder_opts);
73ed8558
AK
215 av_freep(&ist->filters);
216 av_freep(&ist->hwaccel_device);
217
41776ba9
AK
218 avcodec_free_context(&ist->dec_ctx);
219
2e215267 220 av_freep(&input_streams[i]);
9179f27c 221 }
6291d7e4 222
6291d7e4
AK
223 if (vstats_file)
224 fclose(vstats_file);
225 av_free(vstats_filename);
226
6291d7e4
AK
227 av_freep(&input_streams);
228 av_freep(&input_files);
4288e031 229 av_freep(&output_streams);
af70aa45 230 av_freep(&output_files);
6291d7e4 231
6291d7e4 232 uninit_opts();
6291d7e4 233
776f2bb9 234 avformat_network_deinit();
6291d7e4
AK
235
236 if (received_sigterm) {
e3245b26
AK
237 av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
238 (int) received_sigterm);
6291d7e4
AK
239 exit (255);
240 }
6291d7e4
AK
241}
242
f5e66827 243void assert_avoptions(AVDictionary *m)
6291d7e4
AK
244{
245 AVDictionaryEntry *t;
246 if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
f24facd3 247 av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
636ced8e 248 exit_program(1);
6291d7e4
AK
249 }
250}
251
c854102d 252static void abort_codec_experimental(AVCodec *c, int encoder)
6291d7e4
AK
253{
254 const char *codec_string = encoder ? "encoder" : "decoder";
255 AVCodec *codec;
c854102d
NC
256 av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
257 "results.\nAdd '-strict experimental' if you want to use it.\n",
258 codec_string, c->name);
259 codec = encoder ? avcodec_find_encoder(c->id) : avcodec_find_decoder(c->id);
def97856 260 if (!(codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL))
c854102d
NC
261 av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
262 codec_string, codec->name);
636ced8e 263 exit_program(1);
6291d7e4
AK
264}
265
398f015f 266static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)
7636c8c6 267{
398f015f 268 AVFormatContext *s = of->ctx;
15e84ed3 269 AVStream *st = ost->st;
6291d7e4
AK
270 int ret;
271
398f015f
AK
272 if (!of->header_written) {
273 AVPacket tmp_pkt;
274 /* the muxer is not initialized yet, buffer the packet */
275 if (!av_fifo_space(ost->muxing_queue)) {
276 int new_size = FFMIN(2 * av_fifo_size(ost->muxing_queue),
277 ost->max_muxing_queue_size);
278 if (new_size <= av_fifo_size(ost->muxing_queue)) {
279 av_log(NULL, AV_LOG_ERROR,
280 "Too many packets buffered for output stream %d:%d.\n",
281 ost->file_index, ost->st->index);
282 exit_program(1);
283 }
284 ret = av_fifo_realloc2(ost->muxing_queue, new_size);
285 if (ret < 0)
286 exit_program(1);
287 }
288 av_packet_move_ref(&tmp_pkt, pkt);
289 av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);
290 return;
291 }
292
99932847
AK
293 /*
294 * Audio encoders may split the packets -- #frames in != #packets out.
295 * But there is no reordering, so we can limit the number of output packets
296 * by simply dropping them here.
297 * Counting encoded video frames needs to be done separately because of
298 * reordering, see do_video_out()
299 */
15e84ed3 300 if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed)) {
c9594fe0 301 if (ost->frame_number >= ost->max_frames) {
ce70f28a 302 av_packet_unref(pkt);
99932847 303 return;
c9594fe0 304 }
99932847
AK
305 ost->frame_number++;
306 }
15e84ed3 307 if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
5d3addb9
VG
308 uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_FACTOR,
309 NULL);
310 ost->quality = sd ? *(int *)sd : -1;
3efd71b4
AK
311
312 if (ost->frame_rate.num) {
313 pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
314 ost->st->time_base);
315 }
5d3addb9 316 }
99932847 317
76d23f40
AK
318 if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
319 ost->last_mux_dts != AV_NOPTS_VALUE &&
320 pkt->dts < ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT)) {
321 av_log(NULL, AV_LOG_WARNING, "Non-monotonous DTS in output stream "
322 "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
323 ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
324 if (exit_on_error) {
325 av_log(NULL, AV_LOG_FATAL, "aborting.\n");
636ced8e 326 exit_program(1);
76d23f40
AK
327 }
328 av_log(NULL, AV_LOG_WARNING, "changing to %"PRId64". This may result "
329 "in incorrect timestamps in the output file.\n",
330 ost->last_mux_dts + 1);
331 pkt->dts = ost->last_mux_dts + 1;
332 if (pkt->pts != AV_NOPTS_VALUE)
333 pkt->pts = FFMAX(pkt->pts, pkt->dts);
334 }
335 ost->last_mux_dts = pkt->dts;
336
baeb59d8 337 ost->data_size += pkt->size;
47543450 338 ost->packets_written++;
baeb59d8 339
61a09968 340 pkt->stream_index = ost->index;
7636c8c6
AD
341 ret = av_interleaved_write_frame(s, pkt);
342 if (ret < 0) {
6291d7e4 343 print_error("av_interleaved_write_frame()", ret);
636ced8e 344 exit_program(1);
6291d7e4
AK
345 }
346}
347
398f015f 348static void output_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost)
4426540f
AK
349{
350 int ret = 0;
351
352 /* apply the output bitstream filters, if any */
353 if (ost->nb_bitstream_filters) {
354 int idx;
355
356 ret = av_bsf_send_packet(ost->bsf_ctx[0], pkt);
357 if (ret < 0)
358 goto finish;
359
360 idx = 1;
361 while (idx) {
362 /* get a packet from the previous filter up the chain */
363 ret = av_bsf_receive_packet(ost->bsf_ctx[idx - 1], pkt);
364 if (ret == AVERROR(EAGAIN)) {
365 ret = 0;
366 idx--;
367 continue;
368 } else if (ret < 0)
369 goto finish;
370
371 /* send it to the next filter down the chain or to the muxer */
372 if (idx < ost->nb_bitstream_filters) {
373 ret = av_bsf_send_packet(ost->bsf_ctx[idx], pkt);
374 if (ret < 0)
375 goto finish;
376 idx++;
377 } else
398f015f 378 write_packet(of, pkt, ost);
4426540f
AK
379 }
380 } else
398f015f 381 write_packet(of, pkt, ost);
4426540f
AK
382
383finish:
384 if (ret < 0 && ret != AVERROR_EOF) {
385 av_log(NULL, AV_LOG_FATAL, "Error applying bitstream filters to an output "
386 "packet for stream #%d:%d.\n", ost->file_index, ost->index);
387 exit_program(1);
388 }
389}
390
1270e12e
AK
391static int check_recording_time(OutputStream *ost)
392{
2e215267 393 OutputFile *of = output_files[ost->file_index];
1270e12e
AK
394
395 if (of->recording_time != INT64_MAX &&
38313626 396 av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
1270e12e 397 AV_TIME_BASE_Q) >= 0) {
57d24225 398 ost->finished = 1;
1270e12e
AK
399 return 0;
400 }
401 return 1;
402}
403
398f015f 404static void do_audio_out(OutputFile *of, OutputStream *ost,
369cb092 405 AVFrame *frame)
ee458cb1 406{
38313626 407 AVCodecContext *enc = ost->enc_ctx;
ee458cb1 408 AVPacket pkt;
35846d93 409 int ret;
ee458cb1
JR
410
411 av_init_packet(&pkt);
412 pkt.data = NULL;
413 pkt.size = 0;
414
369cb092 415 if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
9b9fc9ba 416 frame->pts = ost->sync_opts;
369cb092 417 ost->sync_opts = frame->pts + frame->nb_samples;
ee458cb1 418
47543450
AK
419 ost->samples_encoded += frame->nb_samples;
420 ost->frames_encoded++;
421
35846d93 422 ret = avcodec_send_frame(enc, frame);
423 if (ret < 0)
424 goto error;
425
426 while (1) {
427 ret = avcodec_receive_packet(enc, &pkt);
428 if (ret == AVERROR(EAGAIN))
429 break;
430 if (ret < 0)
431 goto error;
ee458cb1 432
452860d7 433 av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
398f015f 434 output_packet(of, &pkt, ost);
ee458cb1 435 }
35846d93 436
437 return;
438error:
439 av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
440 exit_program(1);
6291d7e4
AK
441}
442
398f015f 443static void do_subtitle_out(OutputFile *of,
6291d7e4
AK
444 OutputStream *ost,
445 InputStream *ist,
446 AVSubtitle *sub,
447 int64_t pts)
448{
449 static uint8_t *subtitle_out = NULL;
450 int subtitle_out_max_size = 1024 * 1024;
451 int subtitle_out_size, nb, i;
452 AVCodecContext *enc;
453 AVPacket pkt;
454
455 if (pts == AV_NOPTS_VALUE) {
e3245b26 456 av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
6291d7e4 457 if (exit_on_error)
636ced8e 458 exit_program(1);
6291d7e4
AK
459 return;
460 }
461
38313626 462 enc = ost->enc_ctx;
6291d7e4
AK
463
464 if (!subtitle_out) {
465 subtitle_out = av_malloc(subtitle_out_max_size);
466 }
467
468 /* Note: DVB subtitle need one packet to draw them and one other
469 packet to clear them */
470 /* XXX: signal it in the codec context ? */
36ef5369 471 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
6291d7e4
AK
472 nb = 2;
473 else
474 nb = 1;
475
7636c8c6 476 for (i = 0; i < nb; i++) {
1270e12e
AK
477 ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
478 if (!check_recording_time(ost))
479 return;
480
6291d7e4
AK
481 sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
482 // start_display_time is required to be 0
7636c8c6
AD
483 sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
484 sub->end_display_time -= sub->start_display_time;
6291d7e4 485 sub->start_display_time = 0;
47543450
AK
486
487 ost->frames_encoded++;
488
6291d7e4
AK
489 subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
490 subtitle_out_max_size, sub);
491 if (subtitle_out_size < 0) {
e3245b26 492 av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
636ced8e 493 exit_program(1);
6291d7e4
AK
494 }
495
496 av_init_packet(&pkt);
6291d7e4
AK
497 pkt.data = subtitle_out;
498 pkt.size = subtitle_out_size;
7636c8c6 499 pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
36ef5369 500 if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
6291d7e4
AK
501 /* XXX: the pts correction is handled here. Maybe handling
502 it in the codec would be better */
503 if (i == 0)
504 pkt.pts += 90 * sub->start_display_time;
505 else
506 pkt.pts += 90 * sub->end_display_time;
507 }
398f015f 508 output_packet(of, &pkt, ost);
6291d7e4
AK
509 }
510}
511
398f015f 512static void do_video_out(OutputFile *of,
87ef060c 513 OutputStream *ost,
87ef060c 514 AVFrame *in_picture,
fb722a90 515 int *frame_size)
87ef060c 516{
35846d93 517 int ret, format_video_sync;
74b961db 518 AVPacket pkt;
38313626 519 AVCodecContext *enc = ost->enc_ctx;
87ef060c
AC
520
521 *frame_size = 0;
522
553735f5 523 format_video_sync = video_sync_method;
e8c04f62 524 if (format_video_sync == VSYNC_AUTO)
398f015f
AK
525 format_video_sync = (of->ctx->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
526 (of->ctx->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
74b961db
AK
527 if (format_video_sync != VSYNC_PASSTHROUGH &&
528 ost->frame_number &&
529 in_picture->pts != AV_NOPTS_VALUE &&
530 in_picture->pts < ost->sync_opts) {
d43040e2 531 nb_frames_drop++;
aa499568
VG
532 av_log(NULL, AV_LOG_WARNING,
533 "*** dropping frame %d from stream %d at ts %"PRId64"\n",
534 ost->frame_number, ost->st->index, in_picture->pts);
87ef060c 535 return;
d43040e2 536 }
87ef060c 537
74b961db
AK
538 if (in_picture->pts == AV_NOPTS_VALUE)
539 in_picture->pts = ost->sync_opts;
540 ost->sync_opts = in_picture->pts;
541
542
1270e12e 543 if (!ost->frame_number)
74b961db 544 ost->first_pts = in_picture->pts;
1270e12e 545
39885a4b
AK
546 av_init_packet(&pkt);
547 pkt.data = NULL;
548 pkt.size = 0;
6291d7e4 549
a83c0da5 550 if (ost->frame_number >= ost->max_frames)
39885a4b 551 return;
1270e12e 552
34ed5c2e
LB
553 if (enc->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
554 ost->top_field_first >= 0)
555 in_picture->top_field_first = !!ost->top_field_first;
6291d7e4 556
34ed5c2e
LB
557 in_picture->quality = enc->global_quality;
558 in_picture->pict_type = 0;
559 if (ost->forced_kf_index < ost->forced_kf_count &&
560 in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
561 in_picture->pict_type = AV_PICTURE_TYPE_I;
562 ost->forced_kf_index++;
563 }
47543450 564
34ed5c2e 565 ost->frames_encoded++;
47543450 566
35846d93 567 ret = avcodec_send_frame(enc, in_picture);
568 if (ret < 0)
569 goto error;
570
69a63801
AK
571 /*
572 * For video, there may be reordering, so we can't throw away frames on
573 * encoder flush, we need to limit them here, before they go into encoder.
574 */
575 ost->frame_number++;
576
35846d93 577 while (1) {
578 ret = avcodec_receive_packet(enc, &pkt);
579 if (ret == AVERROR(EAGAIN))
580 break;
581 if (ret < 0)
582 goto error;
6291d7e4 583
34ed5c2e 584 av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
398f015f 585 output_packet(of, &pkt, ost);
34ed5c2e 586 *frame_size = pkt.size;
324fbadf 587
34ed5c2e
LB
588 /* if two pass, output log */
589 if (ost->logfile && enc->stats_out) {
590 fprintf(ost->logfile, "%s", enc->stats_out);
6291d7e4 591 }
35846d93 592
593 ost->sync_opts++;
39885a4b 594 }
34ed5c2e 595
35846d93 596 return;
597error:
598 av_assert0(ret != AVERROR(EAGAIN) && ret != AVERROR_EOF);
599 av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
600 exit_program(1);
6291d7e4
AK
601}
602
e2a3df1a 603#if FF_API_CODED_FRAME && FF_API_ERROR_FRAME
7636c8c6
AD
604static double psnr(double d)
605{
606 return -10.0 * log(d) / log(10.0);
6291d7e4 607}
763d69bf 608#endif
6291d7e4 609
70478746 610static void do_video_stats(OutputStream *ost, int frame_size)
6291d7e4
AK
611{
612 AVCodecContext *enc;
613 int frame_number;
614 double ti1, bitrate, avg_bitrate;
615
616 /* this is executed just the first time do_video_stats is called */
617 if (!vstats_file) {
618 vstats_file = fopen(vstats_filename, "w");
619 if (!vstats_file) {
620 perror("fopen");
636ced8e 621 exit_program(1);
6291d7e4
AK
622 }
623 }
624
38313626 625 enc = ost->enc_ctx;
6291d7e4
AK
626 if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
627 frame_number = ost->frame_number;
5d3addb9
VG
628 fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
629 ost->quality / (float)FF_QP2LAMBDA);
40cf1bba 630
e2a3df1a 631#if FF_API_CODED_FRAME && FF_API_ERROR_FRAME
40cf1bba 632FF_DISABLE_DEPRECATION_WARNINGS
7c6eb0a1 633 if (enc->flags & AV_CODEC_FLAG_PSNR)
7636c8c6 634 fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
40cf1bba
VG
635FF_ENABLE_DEPRECATION_WARNINGS
636#endif
6291d7e4
AK
637
638 fprintf(vstats_file,"f_size= %6d ", frame_size);
639 /* compute pts value */
640 ti1 = ost->sync_opts * av_q2d(enc->time_base);
641 if (ti1 < 0.01)
642 ti1 = 0.01;
643
7636c8c6 644 bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
baeb59d8 645 avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
6291d7e4 646 fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
baeb59d8 647 (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
40cf1bba
VG
648#if FF_API_CODED_FRAME
649FF_DISABLE_DEPRECATION_WARNINGS
6291d7e4 650 fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
40cf1bba
VG
651FF_ENABLE_DEPRECATION_WARNINGS
652#endif
6291d7e4
AK
653 }
654}
655
c1ef30a6 656/*
a4f50110
AK
657 * Read one frame for lavfi output for ost and encode it.
658 */
659static int poll_filter(OutputStream *ost)
560f7774 660{
a4f50110 661 OutputFile *of = output_files[ost->file_index];
560f7774 662 AVFrame *filtered_frame = NULL;
a4f50110
AK
663 int frame_size, ret;
664
5b9c3b45 665 if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
a4f50110 666 return AVERROR(ENOMEM);
674fa491 667 }
a4f50110
AK
668 filtered_frame = ost->filtered_frame;
669
670 if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
def97856 671 !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
9b2dc295 672 ret = av_buffersink_get_samples(ost->filter->filter, filtered_frame,
38313626 673 ost->enc_ctx->frame_size);
a4f50110 674 else
9b2dc295 675 ret = av_buffersink_get_frame(ost->filter->filter, filtered_frame);
369cb092 676
a4f50110
AK
677 if (ret < 0)
678 return ret;
560f7774 679
9b2dc295 680 if (filtered_frame->pts != AV_NOPTS_VALUE) {
56ee3f9d 681 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
9b2dc295 682 filtered_frame->pts = av_rescale_q(filtered_frame->pts,
a4f50110 683 ost->filter->filter->inputs[0]->time_base,
38313626 684 ost->enc_ctx->time_base) -
56ee3f9d 685 av_rescale_q(start_time,
a4f50110 686 AV_TIME_BASE_Q,
38313626 687 ost->enc_ctx->time_base);
560f7774 688 }
a4f50110
AK
689
690 switch (ost->filter->filter->inputs[0]->type) {
691 case AVMEDIA_TYPE_VIDEO:
692 if (!ost->frame_aspect_ratio)
38313626 693 ost->enc_ctx->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
a4f50110 694
398f015f 695 do_video_out(of, ost, filtered_frame, &frame_size);
a4f50110 696 if (vstats_filename && frame_size)
70478746 697 do_video_stats(ost, frame_size);
a4f50110
AK
698 break;
699 case AVMEDIA_TYPE_AUDIO:
398f015f 700 do_audio_out(of, ost, filtered_frame);
a4f50110
AK
701 break;
702 default:
703 // TODO support subtitle filters
704 av_assert0(0);
705 }
706
9b2dc295 707 av_frame_unref(filtered_frame);
a4f50110 708
560f7774
AK
709 return 0;
710}
711
48e50921
AK
712static void finish_output_stream(OutputStream *ost)
713{
714 OutputFile *of = output_files[ost->file_index];
715 int i;
716
717 ost->finished = 1;
718
719 if (of->shortest) {
720 for (i = 0; i < of->ctx->nb_streams; i++)
721 output_streams[of->ost_index + i]->finished = 1;
722 }
723}
724
c1ef30a6 725/*
a4f50110
AK
726 * Read as many frames from possible from lavfi and encode them.
727 *
728 * Always read from the active stream with the lowest timestamp. If no frames
729 * are available for it then return EAGAIN and wait for more input. This way we
730 * can use lavfi sources that generate unlimited amount of frames without memory
731 * usage exploding.
732 */
733static int poll_filters(void)
734{
48e50921 735 int i, ret = 0;
a4f50110
AK
736
737 while (ret >= 0 && !received_sigterm) {
738 OutputStream *ost = NULL;
739 int64_t min_pts = INT64_MAX;
740
741 /* choose output stream with the lowest timestamp */
742 for (i = 0; i < nb_output_streams; i++) {
743 int64_t pts = output_streams[i]->sync_opts;
744
57d24225 745 if (!output_streams[i]->filter || output_streams[i]->finished)
a4f50110
AK
746 continue;
747
38313626 748 pts = av_rescale_q(pts, output_streams[i]->enc_ctx->time_base,
a4f50110
AK
749 AV_TIME_BASE_Q);
750 if (pts < min_pts) {
751 min_pts = pts;
752 ost = output_streams[i];
753 }
754 }
755
756 if (!ost)
757 break;
758
759 ret = poll_filter(ost);
760
761 if (ret == AVERROR_EOF) {
48e50921 762 finish_output_stream(ost);
a4f50110
AK
763 ret = 0;
764 } else if (ret == AVERROR(EAGAIN))
765 return 0;
766 }
767
768 return ret;
769}
770
a220b07b
AK
771static void print_final_stats(int64_t total_size)
772{
773 uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
774 uint64_t data_size = 0;
775 float percent = -1.0;
47543450 776 int i, j;
a220b07b
AK
777
778 for (i = 0; i < nb_output_streams; i++) {
779 OutputStream *ost = output_streams[i];
38313626 780 switch (ost->enc_ctx->codec_type) {
a220b07b
AK
781 case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
782 case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
783 default: other_size += ost->data_size; break;
784 }
38313626 785 extra_size += ost->enc_ctx->extradata_size;
a220b07b
AK
786 data_size += ost->data_size;
787 }
788
789 if (data_size && total_size >= data_size)
790 percent = 100.0 * (total_size - data_size) / data_size;
791
792 av_log(NULL, AV_LOG_INFO, "\n");
793 av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB other streams:%1.0fkB global headers:%1.0fkB muxing overhead: ",
794 video_size / 1024.0,
795 audio_size / 1024.0,
796 other_size / 1024.0,
797 extra_size / 1024.0);
798 if (percent >= 0.0)
799 av_log(NULL, AV_LOG_INFO, "%f%%", percent);
800 else
801 av_log(NULL, AV_LOG_INFO, "unknown");
802 av_log(NULL, AV_LOG_INFO, "\n");
47543450
AK
803
804 /* print verbose per-stream stats */
805 for (i = 0; i < nb_input_files; i++) {
806 InputFile *f = input_files[i];
807 uint64_t total_packets = 0, total_size = 0;
808
809 av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
810 i, f->ctx->filename);
811
812 for (j = 0; j < f->nb_streams; j++) {
813 InputStream *ist = input_streams[f->ist_index + j];
41776ba9 814 enum AVMediaType type = ist->dec_ctx->codec_type;
47543450
AK
815
816 total_size += ist->data_size;
817 total_packets += ist->nb_packets;
818
819 av_log(NULL, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
820 i, j, media_type_string(type));
821 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
822 ist->nb_packets, ist->data_size);
823
824 if (ist->decoding_needed) {
825 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
826 ist->frames_decoded);
827 if (type == AVMEDIA_TYPE_AUDIO)
828 av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
829 av_log(NULL, AV_LOG_VERBOSE, "; ");
830 }
831
832 av_log(NULL, AV_LOG_VERBOSE, "\n");
833 }
834
835 av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
836 total_packets, total_size);
837 }
838
839 for (i = 0; i < nb_output_files; i++) {
840 OutputFile *of = output_files[i];
841 uint64_t total_packets = 0, total_size = 0;
842
843 av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
844 i, of->ctx->filename);
845
846 for (j = 0; j < of->ctx->nb_streams; j++) {
847 OutputStream *ost = output_streams[of->ost_index + j];
38313626 848 enum AVMediaType type = ost->enc_ctx->codec_type;
47543450
AK
849
850 total_size += ost->data_size;
851 total_packets += ost->packets_written;
852
853 av_log(NULL, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
854 i, j, media_type_string(type));
855 if (ost->encoding_needed) {
856 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
857 ost->frames_encoded);
858 if (type == AVMEDIA_TYPE_AUDIO)
859 av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
860 av_log(NULL, AV_LOG_VERBOSE, "; ");
861 }
862
863 av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
864 ost->packets_written, ost->data_size);
865
866 av_log(NULL, AV_LOG_VERBOSE, "\n");
867 }
868
869 av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
870 total_packets, total_size);
871 }
a220b07b
AK
872}
873
ea9367e9 874static void print_report(int is_last_report, int64_t timer_start)
6291d7e4
AK
875{
876 char buf[1024];
877 OutputStream *ost;
878 AVFormatContext *oc;
879 int64_t total_size;
880 AVCodecContext *enc;
881 int frame_number, vid, i;
882 double bitrate, ti1, pts;
883 static int64_t last_time = -1;
884 static int qp_histogram[52];
885
3460dd8a
AK
886 if (!print_stats && !is_last_report)
887 return;
888
6291d7e4
AK
889 if (!is_last_report) {
890 int64_t cur_time;
891 /* display the report every 0.5 seconds */
d0c09302 892 cur_time = av_gettime_relative();
6291d7e4
AK
893 if (last_time == -1) {
894 last_time = cur_time;
895 return;
896 }
897 if ((cur_time - last_time) < 500000)
898 return;
899 last_time = cur_time;
900 }
901
902
2e215267 903 oc = output_files[0]->ctx;
6291d7e4
AK
904
905 total_size = avio_size(oc->pb);
1b891d17 906 if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
7636c8c6 907 total_size = avio_tell(oc->pb);
1b891d17
JG
908 if (total_size < 0) {
909 char errbuf[128];
910 av_strerror(total_size, errbuf, sizeof(errbuf));
911 av_log(NULL, AV_LOG_VERBOSE, "Bitrate not available, "
912 "avio_tell() failed: %s\n", errbuf);
913 total_size = 0;
914 }
6291d7e4
AK
915
916 buf[0] = '\0';
917 ti1 = 1e10;
918 vid = 0;
ea9367e9 919 for (i = 0; i < nb_output_streams; i++) {
6291d7e4 920 float q = -1;
2e215267 921 ost = output_streams[i];
38313626 922 enc = ost->enc_ctx;
5d3addb9
VG
923 if (!ost->stream_copy)
924 q = ost->quality / (float) FF_QP2LAMBDA;
925
6291d7e4
AK
926 if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
927 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
928 }
929 if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
d0c09302 930 float t = (av_gettime_relative() - timer_start) / 1000000.0;
6291d7e4
AK
931
932 frame_number = ost->frame_number;
933 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
7636c8c6
AD
934 frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
935 if (is_last_report)
6291d7e4 936 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
7636c8c6 937 if (qp_hist) {
6291d7e4
AK
938 int j;
939 int qp = lrintf(q);
7636c8c6 940 if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
6291d7e4 941 qp_histogram[qp]++;
7636c8c6 942 for (j = 0; j < 32; j++)
d752509b 943 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
6291d7e4 944 }
40cf1bba 945
e2a3df1a 946#if FF_API_CODED_FRAME && FF_API_ERROR_FRAME
40cf1bba 947FF_DISABLE_DEPRECATION_WARNINGS
7c6eb0a1 948 if (enc->flags & AV_CODEC_FLAG_PSNR) {
6291d7e4 949 int j;
7636c8c6
AD
950 double error, error_sum = 0;
951 double scale, scale_sum = 0;
952 char type[3] = { 'Y','U','V' };
6291d7e4 953 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
7636c8c6
AD
954 for (j = 0; j < 3; j++) {
955 if (is_last_report) {
956 error = enc->error[j];
957 scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
958 } else {
959 error = enc->coded_frame->error[j];
960 scale = enc->width * enc->height * 255.0 * 255.0;
6291d7e4 961 }
7636c8c6
AD
962 if (j)
963 scale /= 4;
6291d7e4
AK
964 error_sum += error;
965 scale_sum += scale;
7636c8c6 966 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
6291d7e4 967 }
7636c8c6 968 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
6291d7e4 969 }
40cf1bba
VG
970FF_ENABLE_DEPRECATION_WARNINGS
971#endif
6291d7e4
AK
972 vid = 1;
973 }
974 /* compute min output value */
dc40d886 975 pts = (double)ost->last_mux_dts * av_q2d(ost->st->time_base);
6291d7e4
AK
976 if ((pts < ti1) && (pts > 0))
977 ti1 = pts;
978 }
979 if (ti1 < 0.01)
980 ti1 = 0.01;
981
e3245b26 982 bitrate = (double)(total_size * 8) / ti1 / 1000.0;
6291d7e4 983
e3245b26 984 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
6291d7e4
AK
985 "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
986 (double)total_size / 1024, ti1, bitrate);
987
781d97fd
AK
988 if (nb_frames_drop)
989 snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " drop=%d",
990 nb_frames_drop);
6291d7e4 991
f5646a32 992 av_log(NULL, AV_LOG_INFO, "%s \r", buf);
6291d7e4 993
e3245b26 994 fflush(stderr);
6291d7e4 995
a220b07b
AK
996 if (is_last_report)
997 print_final_stats(total_size);
baeb59d8 998
6291d7e4
AK
999}
1000
ea9367e9 1001static void flush_encoders(void)
4a4ce2e7
AK
1002{
1003 int i, ret;
1004
ea9367e9 1005 for (i = 0; i < nb_output_streams; i++) {
2e215267 1006 OutputStream *ost = output_streams[i];
38313626 1007 AVCodecContext *enc = ost->enc_ctx;
398f015f 1008 OutputFile *of = output_files[ost->file_index];
ee458cb1 1009 int stop_encoding = 0;
6f1c66d5 1010
b62b5cb6 1011 if (!ost->encoding_needed)
6f1c66d5
AK
1012 continue;
1013
38313626 1014 if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
6f1c66d5 1015 continue;
6f1c66d5 1016
35846d93 1017 if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
1018 continue;
1019
1020 avcodec_send_frame(enc, NULL);
1021
7636c8c6 1022 for (;;) {
35846d93 1023 const char *desc = NULL;
6f1c66d5 1024
38313626 1025 switch (enc->codec_type) {
6f1c66d5 1026 case AVMEDIA_TYPE_AUDIO:
369cb092 1027 desc = "Audio";
6f1c66d5
AK
1028 break;
1029 case AVMEDIA_TYPE_VIDEO:
369cb092 1030 desc = "Video";
369cb092
AK
1031 break;
1032 default:
35846d93 1033 av_assert0(0);
369cb092
AK
1034 }
1035
35846d93 1036 if (1) {
369cb092 1037 AVPacket pkt;
369cb092
AK
1038 av_init_packet(&pkt);
1039 pkt.data = NULL;
1040 pkt.size = 0;
1041
35846d93 1042 ret = avcodec_receive_packet(enc, &pkt);
1043 if (ret < 0 && ret != AVERROR_EOF) {
369cb092 1044 av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
636ced8e 1045 exit_program(1);
6f1c66d5 1046 }
6f1c66d5
AK
1047 if (ost->logfile && enc->stats_out) {
1048 fprintf(ost->logfile, "%s", enc->stats_out);
1049 }
35846d93 1050 if (ret == AVERROR_EOF) {
ee458cb1
JR
1051 stop_encoding = 1;
1052 break;
1053 }
452860d7 1054 av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
398f015f 1055 output_packet(of, &pkt, ost);
4a4ce2e7 1056 }
369cb092 1057
ee458cb1 1058 if (stop_encoding)
6f1c66d5 1059 break;
4a4ce2e7
AK
1060 }
1061 }
1062}
1063
7204ec1a
AK
1064/*
1065 * Check whether a packet from ist should be written into ost at this time
1066 */
1067static int check_output_constraints(InputStream *ist, OutputStream *ost)
1068{
2e215267
AK
1069 OutputFile *of = output_files[ost->file_index];
1070 int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
7204ec1a
AK
1071
1072 if (ost->source_index != ist_index)
1073 return 0;
1074
56ee3f9d 1075 if (of->start_time != AV_NOPTS_VALUE && ist->last_dts < of->start_time)
7204ec1a
AK
1076 return 0;
1077
7204ec1a
AK
1078 return 1;
1079}
1080
1081static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1082{
2e215267 1083 OutputFile *of = output_files[ost->file_index];
488a0fa6 1084 InputFile *f = input_files [ist->file_index];
56ee3f9d
AK
1085 int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1086 int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
7204ec1a
AK
1087 AVPacket opkt;
1088
1089 av_init_packet(&opkt);
1090
1091 if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1092 !ost->copy_initial_nonkeyframes)
1093 return;
1094
1270e12e 1095 if (of->recording_time != INT64_MAX &&
56ee3f9d 1096 ist->last_dts >= of->recording_time + start_time) {
57d24225 1097 ost->finished = 1;
1270e12e
AK
1098 return;
1099 }
1100
488a0fa6
AK
1101 if (f->recording_time != INT64_MAX) {
1102 start_time = f->ctx->start_time;
1103 if (f->start_time != AV_NOPTS_VALUE)
1104 start_time += f->start_time;
1105 if (ist->last_dts >= f->recording_time + start_time) {
1106 ost->finished = 1;
1107 return;
1108 }
1109 }
1110
7204ec1a 1111 /* force the input stream PTS */
38313626 1112 if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
7204ec1a 1113 ost->sync_opts++;
7204ec1a 1114
7204ec1a
AK
1115 if (pkt->pts != AV_NOPTS_VALUE)
1116 opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1117 else
1118 opkt.pts = AV_NOPTS_VALUE;
1119
1120 if (pkt->dts == AV_NOPTS_VALUE)
23576b3f 1121 opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);
7204ec1a
AK
1122 else
1123 opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1124 opkt.dts -= ost_tb_start_time;
1125
1126 opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1127 opkt.flags = pkt->flags;
1128
7636c8c6 1129 // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
38313626
AK
1130 if ( ost->enc_ctx->codec_id != AV_CODEC_ID_H264
1131 && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG1VIDEO
1132 && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG2VIDEO
1133 && ost->enc_ctx->codec_id != AV_CODEC_ID_VC1
7204ec1a 1134 ) {
35c85806 1135 if (av_parser_change(ost->parser, ost->parser_avctx,
c872d310
AK
1136 &opkt.data, &opkt.size,
1137 pkt->data, pkt->size,
1138 pkt->flags & AV_PKT_FLAG_KEY)) {
9b2dc295
AK
1139 opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
1140 if (!opkt.buf)
636ced8e 1141 exit_program(1);
9b2dc295 1142 }
7204ec1a
AK
1143 } else {
1144 opkt.data = pkt->data;
1145 opkt.size = pkt->size;
1146 }
1147
398f015f 1148 output_packet(of, &opkt, ost);
7204ec1a
AK
1149}
1150
84aea95e 1151// This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
1152// There is the following difference: if you got a frame, you must call
1153// it again with pkt=NULL. pkt==NULL is treated differently from pkt.size==0
1154// (pkt==NULL means get more output, pkt.size==0 is a flush/drain packet)
1155static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
1156{
1157 int ret;
1158
1159 *got_frame = 0;
1160
1161 if (pkt) {
1162 ret = avcodec_send_packet(avctx, pkt);
1163 // In particular, we don't expect AVERROR(EAGAIN), because we read all
1164 // decoded frames with avcodec_receive_frame() until done.
1165 if (ret < 0)
1166 return ret == AVERROR_EOF ? 0 : ret;
1167 }
1168
1169 ret = avcodec_receive_frame(avctx, frame);
1170 if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
1171 return ret;
1172 if (ret >= 0)
1173 *got_frame = 1;
1174
1175 return 0;
1176}
1177
f5e66827 1178int guess_input_channel_layout(InputStream *ist)
369cb092 1179{
41776ba9 1180 AVCodecContext *dec = ist->dec_ctx;
369cb092
AK
1181
1182 if (!dec->channel_layout) {
1183 char layout_name[256];
1184
1185 dec->channel_layout = av_get_default_channel_layout(dec->channels);
1186 if (!dec->channel_layout)
1187 return 0;
1188 av_get_channel_layout_string(layout_name, sizeof(layout_name),
1189 dec->channels, dec->channel_layout);
41ed7ab4 1190 av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
369cb092
AK
1191 "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1192 }
1193 return 1;
1194}
1195
0629f612 1196static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
ded28ba3 1197{
9b2dc295 1198 AVFrame *decoded_frame, *f;
41776ba9 1199 AVCodecContext *avctx = ist->dec_ctx;
9b2dc295 1200 int i, ret, err = 0, resample_changed;
ded28ba3 1201
5b9c3b45 1202 if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
d1241ff3 1203 return AVERROR(ENOMEM);
9b2dc295
AK
1204 if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1205 return AVERROR(ENOMEM);
9179f27c 1206 decoded_frame = ist->decoded_frame;
ded28ba3 1207
84aea95e 1208 ret = decode(avctx, decoded_frame, got_output, pkt);
b114f6d4 1209 if (!*got_output || ret < 0)
af8ad892 1210 return ret;
ded28ba3 1211
47543450
AK
1212 ist->samples_decoded += decoded_frame->nb_samples;
1213 ist->frames_decoded++;
1214
d1241ff3
JR
1215 /* if the decoder provides a pts, use it instead of the last packet pts.
1216 the decoder could be delaying output by a packet or more. */
1217 if (decoded_frame->pts != AV_NOPTS_VALUE)
3101bb66 1218 ist->next_dts = decoded_frame->pts;
84aea95e 1219 else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
369cb092 1220 decoded_frame->pts = pkt->pts;
84aea95e 1221 }
ded28ba3 1222
369cb092
AK
1223 resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
1224 ist->resample_channels != avctx->channels ||
1225 ist->resample_channel_layout != decoded_frame->channel_layout ||
1226 ist->resample_sample_rate != decoded_frame->sample_rate;
1227 if (resample_changed) {
1228 char layout1[64], layout2[64];
ded28ba3 1229
369cb092
AK
1230 if (!guess_input_channel_layout(ist)) {
1231 av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1232 "layout for Input Stream #%d.%d\n", ist->file_index,
1233 ist->st->index);
636ced8e 1234 exit_program(1);
369cb092
AK
1235 }
1236 decoded_frame->channel_layout = avctx->channel_layout;
1237
1238 av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
1239 ist->resample_channel_layout);
1240 av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
1241 decoded_frame->channel_layout);
1242
1243 av_log(NULL, AV_LOG_INFO,
1244 "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",
1245 ist->file_index, ist->st->index,
1246 ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
1247 ist->resample_channels, layout1,
1248 decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
1249 avctx->channels, layout2);
1250
1251 ist->resample_sample_fmt = decoded_frame->format;
1252 ist->resample_sample_rate = decoded_frame->sample_rate;
1253 ist->resample_channel_layout = decoded_frame->channel_layout;
1254 ist->resample_channels = avctx->channels;
1255
722ec3eb
AK
1256 for (i = 0; i < ist->nb_filters; i++) {
1257 err = ifilter_parameters_from_frame(ist->filters[i], decoded_frame);
1258 if (err < 0) {
1259 av_log(NULL, AV_LOG_ERROR,
1260 "Error reconfiguring input stream %d:%d filter %d\n",
1261 ist->file_index, ist->st->index, i);
1262 goto fail;
1263 }
1264 }
1265
369cb092
AK
1266 for (i = 0; i < nb_filtergraphs; i++)
1267 if (ist_in_filtergraph(filtergraphs[i], ist) &&
1268 configure_filtergraph(filtergraphs[i]) < 0) {
1269 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
636ced8e 1270 exit_program(1);
369cb092 1271 }
ded28ba3 1272 }
110d2af2 1273
715129cd
MS
1274 if (decoded_frame->pts != AV_NOPTS_VALUE)
1275 decoded_frame->pts = av_rescale_q(decoded_frame->pts,
1276 ist->st->time_base,
41776ba9 1277 (AVRational){1, avctx->sample_rate});
16b0c929 1278 ist->nb_samples = decoded_frame->nb_samples;
9b2dc295
AK
1279 for (i = 0; i < ist->nb_filters; i++) {
1280 if (i < ist->nb_filters - 1) {
1281 f = ist->filter_frame;
1282 err = av_frame_ref(f, decoded_frame);
1283 if (err < 0)
1284 break;
1285 } else
1286 f = decoded_frame;
369cb092 1287
9b2dc295
AK
1288 err = av_buffersrc_add_frame(ist->filters[i]->filter, f);
1289 if (err < 0)
1290 break;
1291 }
1292
722ec3eb 1293fail:
9b2dc295
AK
1294 av_frame_unref(ist->filter_frame);
1295 av_frame_unref(decoded_frame);
1296 return err < 0 ? err : ret;
ded28ba3
AK
1297}
1298
0629f612 1299static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
45d4b66f 1300{
9b2dc295 1301 AVFrame *decoded_frame, *f;
9b2dc295 1302 int i, ret = 0, err = 0, resample_changed;
45d4b66f 1303
9b2dc295
AK
1304 if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1305 return AVERROR(ENOMEM);
1306 if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
45d4b66f 1307 return AVERROR(ENOMEM);
9179f27c 1308 decoded_frame = ist->decoded_frame;
45d4b66f 1309
84aea95e 1310 ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt);
b114f6d4 1311 if (!*got_output || ret < 0)
af8ad892 1312 return ret;
f154ef1a 1313
47543450
AK
1314 ist->frames_decoded++;
1315
07fd0a22 1316 if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
41776ba9 1317 err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
07fd0a22
AK
1318 if (err < 0)
1319 goto fail;
1320 }
1321 ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
1322
beb62dac 1323 decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pts,
b34856a1 1324 decoded_frame->pkt_dts);
45d4b66f 1325
695ec04e
AK
1326 if (ist->st->sample_aspect_ratio.num)
1327 decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1328
e77c8662
AK
1329 resample_changed = ist->resample_width != decoded_frame->width ||
1330 ist->resample_height != decoded_frame->height ||
1331 ist->resample_pix_fmt != decoded_frame->format;
1332 if (resample_changed) {
1333 av_log(NULL, AV_LOG_INFO,
1334 "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1335 ist->file_index, ist->st->index,
1336 ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
1337 decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
1338
2f34021d 1339 ret = poll_filters();
63f7f8d1 1340 if (ret < 0 && ret != AVERROR_EOF) {
22a6d48b
LB
1341 char errbuf[128];
1342 av_strerror(ret, errbuf, sizeof(errbuf));
1343
1344 av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
1345 }
2f34021d 1346
e77c8662
AK
1347 ist->resample_width = decoded_frame->width;
1348 ist->resample_height = decoded_frame->height;
1349 ist->resample_pix_fmt = decoded_frame->format;
e77c8662 1350
722ec3eb
AK
1351 for (i = 0; i < ist->nb_filters; i++) {
1352 err = ifilter_parameters_from_frame(ist->filters[i], decoded_frame);
1353 if (err < 0) {
1354 av_log(NULL, AV_LOG_ERROR,
1355 "Error reconfiguring input stream %d:%d filter %d\n",
1356 ist->file_index, ist->st->index, i);
1357 goto fail;
1358 }
1359 }
1360
3b266da3
AK
1361 for (i = 0; i < nb_filtergraphs; i++)
1362 if (ist_in_filtergraph(filtergraphs[i], ist) &&
1363 configure_filtergraph(filtergraphs[i]) < 0) {
ac646076 1364 av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
636ced8e 1365 exit_program(1);
3b266da3
AK
1366 }
1367 }
ac646076 1368
3b266da3 1369 for (i = 0; i < ist->nb_filters; i++) {
9b2dc295
AK
1370 if (i < ist->nb_filters - 1) {
1371 f = ist->filter_frame;
1372 err = av_frame_ref(f, decoded_frame);
1373 if (err < 0)
1374 break;
04a14d4d 1375 } else
9b2dc295
AK
1376 f = decoded_frame;
1377
1378 err = av_buffersrc_add_frame(ist->filters[i]->filter, f);
1379 if (err < 0)
1380 break;
45d4b66f
AK
1381 }
1382
07fd0a22 1383fail:
9b2dc295
AK
1384 av_frame_unref(ist->filter_frame);
1385 av_frame_unref(decoded_frame);
9b2dc295 1386 return err < 0 ? err : ret;
45d4b66f
AK
1387}
1388
9595234c
AK
1389static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1390{
1391 AVSubtitle subtitle;
41776ba9 1392 int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
9595234c
AK
1393 &subtitle, got_output, pkt);
1394 if (ret < 0)
1395 return ret;
1396 if (!*got_output)
af8ad892 1397 return ret;
9595234c 1398
47543450
AK
1399 ist->frames_decoded++;
1400
9595234c 1401 for (i = 0; i < nb_output_streams; i++) {
2e215267 1402 OutputStream *ost = output_streams[i];
9595234c
AK
1403
1404 if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1405 continue;
1406
398f015f 1407 do_subtitle_out(output_files[ost->file_index], ost, ist, &subtitle, pkt->pts);
9595234c
AK
1408 }
1409
1410 avsubtitle_free(&subtitle);
af8ad892 1411 return ret;
9595234c
AK
1412}
1413
b114f6d4
AK
1414static int send_filter_eof(InputStream *ist)
1415{
1416 int i, ret;
1417 for (i = 0; i < ist->nb_filters; i++) {
1418 ret = av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
1419 if (ret < 0)
1420 return ret;
1421 }
1422 return 0;
1423}
1424
6291d7e4 1425/* pkt = NULL means EOF (needed to flush decoder buffers) */
16b0c929 1426static void process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
6291d7e4 1427{
ffa0674e 1428 int i;
84aea95e 1429 int repeating = 0;
6291d7e4 1430 AVPacket avpkt;
6291d7e4 1431
3101bb66 1432 if (ist->next_dts == AV_NOPTS_VALUE)
23576b3f 1433 ist->next_dts = ist->last_dts;
6291d7e4 1434
f929ab05 1435 if (!pkt) {
6291d7e4
AK
1436 /* EOF handling */
1437 av_init_packet(&avpkt);
1438 avpkt.data = NULL;
1439 avpkt.size = 0;
6291d7e4
AK
1440 } else {
1441 avpkt = *pkt;
1442 }
1443
84aea95e 1444 if (pkt && pkt->dts != AV_NOPTS_VALUE)
23576b3f 1445 ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
6291d7e4 1446
7636c8c6 1447 // while we have more to decode or while the decoder did output something on EOF
84aea95e 1448 while (ist->decoding_needed && (!pkt || avpkt.size > 0)) {
ffa0674e 1449 int ret = 0;
84aea95e 1450 int got_output = 0;
6291d7e4 1451
84aea95e 1452 if (!repeating)
1453 ist->last_dts = ist->next_dts;
8b0268a8 1454
41776ba9 1455 switch (ist->dec_ctx->codec_type) {
82963f8f 1456 case AVMEDIA_TYPE_AUDIO:
84aea95e 1457 ret = decode_audio (ist, repeating ? NULL : &avpkt, &got_output);
82963f8f
AK
1458 break;
1459 case AVMEDIA_TYPE_VIDEO:
84aea95e 1460 ret = decode_video (ist, repeating ? NULL : &avpkt, &got_output);
1461 if (repeating && !got_output)
1462 ;
1463 else if (pkt && pkt->duration)
1464 ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
aba232cf 1465 else if (ist->st->avg_frame_rate.num)
82494835 1466 ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
722410ad 1467 AV_TIME_BASE_Q);
557d4c4e 1468 else if (ist->dec_ctx->framerate.num != 0) {
b34856a1 1469 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
41776ba9 1470 ist->dec_ctx->ticks_per_frame;
557d4c4e 1471 ist->next_dts += av_rescale_q(ticks, ist->dec_ctx->framerate, AV_TIME_BASE_Q);
b34856a1 1472 }
82963f8f
AK
1473 break;
1474 case AVMEDIA_TYPE_SUBTITLE:
84aea95e 1475 if (repeating)
1476 break;
82963f8f
AK
1477 ret = transcode_subtitles(ist, &avpkt, &got_output);
1478 break;
78162b4e 1479 default:
9a5e4fbe
AK
1480 return;
1481 }
1482
1483 if (ret < 0) {
1484 av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
1485 ist->file_index, ist->st->index);
1486 if (exit_on_error)
1487 exit_program(1);
1488 break;
78162b4e 1489 }
6291d7e4 1490
84aea95e 1491 if (!got_output)
1492 break;
1493
1494 repeating = 1;
6291d7e4 1495 }
6291d7e4 1496
b114f6d4 1497 /* after flushing, send an EOF on all the filter inputs attached to the stream */
16b0c929
AH
1498 /* except when looping we need to flush but not to send an EOF */
1499 if (!pkt && ist->decoding_needed && !no_eof) {
b114f6d4
AK
1500 int ret = send_filter_eof(ist);
1501 if (ret < 0) {
1502 av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
1503 exit_program(1);
1504 }
1505 }
1506
7204ec1a 1507 /* handle stream copy */
2a651b71 1508 if (!ist->decoding_needed) {
23576b3f 1509 ist->last_dts = ist->next_dts;
41776ba9 1510 switch (ist->dec_ctx->codec_type) {
2a651b71 1511 case AVMEDIA_TYPE_AUDIO:
41776ba9
AK
1512 ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
1513 ist->dec_ctx->sample_rate;
2a651b71
AK
1514 break;
1515 case AVMEDIA_TYPE_VIDEO:
557d4c4e 1516 if (ist->dec_ctx->framerate.num != 0) {
41776ba9 1517 int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
3101bb66 1518 ist->next_dts += ((int64_t)AV_TIME_BASE *
557d4c4e
AK
1519 ist->dec_ctx->framerate.den * ticks) /
1520 ist->dec_ctx->framerate.num;
2a651b71
AK
1521 }
1522 break;
1523 }
1524 }
ea9367e9 1525 for (i = 0; pkt && i < nb_output_streams; i++) {
2e215267 1526 OutputStream *ost = output_streams[i];
7204ec1a
AK
1527
1528 if (!check_output_constraints(ist, ost) || ost->encoding_needed)
1529 continue;
1530
1531 do_streamcopy(ist, ost, pkt);
1532 }
1533
9a5e4fbe 1534 return;
6291d7e4
AK
1535}
1536
ea9367e9 1537static void print_sdp(void)
6291d7e4 1538{
a23abaf3 1539 char sdp[16384];
af70aa45 1540 int i;
1c169782 1541 AVFormatContext **avc;
af70aa45 1542
1c169782
AK
1543 for (i = 0; i < nb_output_files; i++) {
1544 if (!output_files[i]->header_written)
1545 return;
1546 }
1547
1548 avc = av_malloc(sizeof(*avc) * nb_output_files);
af70aa45 1549 if (!avc)
636ced8e 1550 exit_program(1);
ea9367e9 1551 for (i = 0; i < nb_output_files; i++)
2e215267 1552 avc[i] = output_files[i]->ctx;
6291d7e4 1553
ea9367e9 1554 av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
6291d7e4
AK
1555 printf("SDP:\n%s\n", sdp);
1556 fflush(stdout);
af70aa45 1557 av_freep(&avc);
6291d7e4
AK
1558}
1559
07fd0a22
AK
1560static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
1561{
1562 int i;
1563 for (i = 0; hwaccels[i].name; i++)
1564 if (hwaccels[i].pix_fmt == pix_fmt)
1565 return &hwaccels[i];
1566 return NULL;
1567}
1568
1569static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
1570{
1571 InputStream *ist = s->opaque;
1572 const enum AVPixelFormat *p;
1573 int ret;
1574
1575 for (p = pix_fmts; *p != -1; p++) {
1576 const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
1577 const HWAccel *hwaccel;
1578
1579 if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
1580 break;
1581
1582 hwaccel = get_hwaccel(*p);
1583 if (!hwaccel ||
1584 (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
1585 (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
1586 continue;
1587
1588 ret = hwaccel->init(s);
1589 if (ret < 0) {
1590 if (ist->hwaccel_id == hwaccel->id) {
1591 av_log(NULL, AV_LOG_FATAL,
1592 "%s hwaccel requested for input stream #%d:%d, "
1593 "but cannot be initialized.\n", hwaccel->name,
1594 ist->file_index, ist->st->index);
dc7536ca 1595 return AV_PIX_FMT_NONE;
07fd0a22
AK
1596 }
1597 continue;
1598 }
1599 ist->active_hwaccel_id = hwaccel->id;
1600 ist->hwaccel_pix_fmt = *p;
1601 break;
1602 }
1603
1604 return *p;
1605}
1606
1607static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
1608{
1609 InputStream *ist = s->opaque;
1610
1611 if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
1612 return ist->hwaccel_get_buffer(s, frame, flags);
1613
1614 return avcodec_default_get_buffer2(s, frame, flags);
1615}
1616
ea9367e9 1617static int init_input_stream(int ist_index, char *error, int error_len)
630902a1 1618{
56c2f377 1619 int ret;
2e215267 1620 InputStream *ist = input_streams[ist_index];
630902a1
AK
1621 if (ist->decoding_needed) {
1622 AVCodec *codec = ist->dec;
630902a1 1623 if (!codec) {
9a414d89 1624 snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
41776ba9 1625 ist->dec_ctx->codec_id, ist->file_index, ist->st->index);
630902a1
AK
1626 return AVERROR(EINVAL);
1627 }
1628
41776ba9
AK
1629 ist->dec_ctx->opaque = ist;
1630 ist->dec_ctx->get_format = get_format;
1631 ist->dec_ctx->get_buffer2 = get_buffer;
1632 ist->dec_ctx->thread_safe_callbacks = 1;
07fd0a22 1633
41776ba9 1634 av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
64dca32c 1635
f3a6ad22
AK
1636 if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
1637 av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
41776ba9 1638 if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
42cc6cef 1639 char errbuf[128];
c854102d
NC
1640 if (ret == AVERROR_EXPERIMENTAL)
1641 abort_codec_experimental(codec, 0);
42cc6cef
LB
1642
1643 av_strerror(ret, errbuf, sizeof(errbuf));
1644
1645 snprintf(error, error_len,
1646 "Error while opening decoder for input stream "
1647 "#%d:%d : %s",
1648 ist->file_index, ist->st->index, errbuf);
c854102d 1649 return ret;
630902a1 1650 }
f3a6ad22 1651 assert_avoptions(ist->decoder_opts);
630902a1
AK
1652 }
1653
41776ba9 1654 ist->last_dts = ist->st->avg_frame_rate.num ? - ist->dec_ctx->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
3101bb66 1655 ist->next_dts = AV_NOPTS_VALUE;
630902a1 1656 init_pts_correction(&ist->pts_ctx);
630902a1
AK
1657
1658 return 0;
1659}
1660
3b266da3
AK
1661static InputStream *get_input_stream(OutputStream *ost)
1662{
1663 if (ost->source_index >= 0)
1664 return input_streams[ost->source_index];
1665
1666 if (ost->filter) {
1667 FilterGraph *fg = ost->filter->graph;
1668 int i;
1669
1670 for (i = 0; i < fg->nb_inputs; i++)
38313626 1671 if (fg->inputs[i]->ist->dec_ctx->codec_type == ost->enc_ctx->codec_type)
3b266da3
AK
1672 return fg->inputs[i]->ist;
1673 }
1674
1675 return NULL;
1676}
1677
1c169782
AK
1678/* open the muxer when all the streams are initialized */
1679static int check_init_output_file(OutputFile *of, int file_index)
1680{
1681 int ret, i;
1682
1683 for (i = 0; i < of->ctx->nb_streams; i++) {
1684 OutputStream *ost = output_streams[of->ost_index + i];
1685 if (!ost->initialized)
1686 return 0;
1687 }
1688
1689 of->ctx->interrupt_callback = int_cb;
1690
1691 ret = avformat_write_header(of->ctx, &of->opts);
1692 if (ret < 0) {
1693 char errbuf[128];
1694
1695 av_strerror(ret, errbuf, sizeof(errbuf));
1696
1697 av_log(NULL, AV_LOG_ERROR,
1698 "Could not write header for output file #%d "
1699 "(incorrect codec parameters ?): %s",
1700 file_index, errbuf);
1701 return ret;
1702 }
1703 assert_avoptions(of->opts);
1704 of->header_written = 1;
1705
1706 av_dump_format(of->ctx, file_index, of->ctx->filename, 1);
1707
1708 if (want_sdp)
1709 print_sdp();
1710
398f015f
AK
1711 /* flush the muxing queues */
1712 for (i = 0; i < of->ctx->nb_streams; i++) {
1713 OutputStream *ost = output_streams[of->ost_index + i];
1714
1715 while (av_fifo_size(ost->muxing_queue)) {
1716 AVPacket pkt;
1717 av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
1718 write_packet(of, &pkt, ost);
1719 }
1720 }
1721
1c169782
AK
1722 return 0;
1723}
1724
4426540f
AK
1725static int init_output_bsfs(OutputStream *ost)
1726{
1727 AVBSFContext *ctx;
1728 int i, ret;
1729
1730 if (!ost->nb_bitstream_filters)
1731 return 0;
1732
1733 ost->bsf_ctx = av_mallocz_array(ost->nb_bitstream_filters, sizeof(*ost->bsf_ctx));
1734 if (!ost->bsf_ctx)
1735 return AVERROR(ENOMEM);
1736
1737 for (i = 0; i < ost->nb_bitstream_filters; i++) {
1738 ret = av_bsf_alloc(ost->bitstream_filters[i], &ctx);
1739 if (ret < 0) {
41ed7ab4 1740 av_log(NULL, AV_LOG_ERROR, "Error allocating a bitstream filter context\n");
4426540f
AK
1741 return ret;
1742 }
1743 ost->bsf_ctx[i] = ctx;
1744
1745 ret = avcodec_parameters_copy(ctx->par_in,
1746 i ? ost->bsf_ctx[i - 1]->par_out : ost->st->codecpar);
1747 if (ret < 0)
1748 return ret;
1749
1750 ctx->time_base_in = i ? ost->bsf_ctx[i - 1]->time_base_out : ost->st->time_base;
1751
1752 ret = av_bsf_init(ctx);
1753 if (ret < 0) {
41ed7ab4 1754 av_log(NULL, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
4426540f
AK
1755 ost->bitstream_filters[i]->name);
1756 return ret;
1757 }
1758 }
1759
1760 ctx = ost->bsf_ctx[ost->nb_bitstream_filters - 1];
1761 ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
1762 if (ret < 0)
1763 return ret;
1764
1765 ost->st->time_base = ctx->time_base_out;
1766
1767 return 0;
1768}
1769
6ed0f70f
AK
1770static int init_output_stream_streamcopy(OutputStream *ost)
1771{
1772 OutputFile *of = output_files[ost->file_index];
1773 InputStream *ist = get_input_stream(ost);
1774 AVCodecParameters *par_dst = ost->st->codecpar;
1775 AVCodecParameters *par_src = ist->st->codecpar;
1776 AVRational sar;
1777 int i;
1778 uint64_t extra_size;
1779
1780 extra_size = (uint64_t)par_src->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE;
1781 if (extra_size > INT_MAX) {
1782 return AVERROR(EINVAL);
1783 }
1784
1785 ost->st->disposition = ist->st->disposition;
1786
1787 /* if stream_copy is selected, no need to decode or encode */
1788 par_dst->codec_id = par_src->codec_id;
1789 par_dst->codec_type = par_src->codec_type;
1790
1791 if (!par_dst->codec_tag) {
1792 if (!of->ctx->oformat->codec_tag ||
1793 av_codec_get_id (of->ctx->oformat->codec_tag, par_src->codec_tag) == par_dst->codec_id ||
1794 av_codec_get_tag(of->ctx->oformat->codec_tag, par_src->codec_id) <= 0)
1795 par_dst->codec_tag = par_src->codec_tag;
1796 }
1797
1798 par_dst->bit_rate = par_src->bit_rate;
1799 par_dst->field_order = par_src->field_order;
1800 par_dst->chroma_location = par_src->chroma_location;
1801
1802 if (par_src->extradata) {
1803 par_dst->extradata = av_mallocz(extra_size);
1804 if (!par_dst->extradata) {
1805 return AVERROR(ENOMEM);
1806 }
1807 memcpy(par_dst->extradata, par_src->extradata, par_src->extradata_size);
1808 par_dst->extradata_size = par_src->extradata_size;
1809 }
1810
1811 ost->st->time_base = ist->st->time_base;
1812
1813 if (ist->st->nb_side_data) {
1814 ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
1815 sizeof(*ist->st->side_data));
1816 if (!ost->st->side_data)
1817 return AVERROR(ENOMEM);
1818
1819 for (i = 0; i < ist->st->nb_side_data; i++) {
1820 const AVPacketSideData *sd_src = &ist->st->side_data[i];
1821 AVPacketSideData *sd_dst = &ost->st->side_data[i];
1822
1823 sd_dst->data = av_malloc(sd_src->size);
1824 if (!sd_dst->data)
1825 return AVERROR(ENOMEM);
1826 memcpy(sd_dst->data, sd_src->data, sd_src->size);
1827 sd_dst->size = sd_src->size;
1828 sd_dst->type = sd_src->type;
1829 ost->st->nb_side_data++;
1830 }
1831 }
1832
1833 ost->parser = av_parser_init(par_dst->codec_id);
1834 ost->parser_avctx = avcodec_alloc_context3(NULL);
1835 if (!ost->parser_avctx)
1836 return AVERROR(ENOMEM);
1837
1838 switch (par_dst->codec_type) {
1839 case AVMEDIA_TYPE_AUDIO:
1840 if (audio_volume != 256) {
1841 av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
1842 exit_program(1);
1843 }
1844 par_dst->channel_layout = par_src->channel_layout;
1845 par_dst->sample_rate = par_src->sample_rate;
1846 par_dst->channels = par_src->channels;
1847 par_dst->block_align = par_src->block_align;
1848 break;
1849 case AVMEDIA_TYPE_VIDEO:
1850 par_dst->format = par_src->format;
1851 par_dst->width = par_src->width;
1852 par_dst->height = par_src->height;
1853 if (ost->frame_aspect_ratio)
1854 sar = av_d2q(ost->frame_aspect_ratio * par_dst->height / par_dst->width, 255);
1855 else if (ist->st->sample_aspect_ratio.num)
1856 sar = ist->st->sample_aspect_ratio;
1857 else
1858 sar = par_src->sample_aspect_ratio;
1859 ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
1860 break;
1861 case AVMEDIA_TYPE_SUBTITLE:
1862 par_dst->width = par_src->width;
1863 par_dst->height = par_src->height;
1864 break;
1865 case AVMEDIA_TYPE_DATA:
1866 case AVMEDIA_TYPE_ATTACHMENT:
1867 break;
1868 default:
1869 abort();
1870 }
1871
1872 return 0;
1873}
1874
ab7b0389
AK
1875static int init_output_stream(OutputStream *ost, char *error, int error_len)
1876{
1877 int ret = 0;
1878
1879 if (ost->encoding_needed) {
1880 AVCodec *codec = ost->enc;
1881 AVCodecContext *dec = NULL;
1882 InputStream *ist;
1883
1884 if ((ist = get_input_stream(ost)))
1885 dec = ist->dec_ctx;
1886 if (dec && dec->subtitle_header) {
1887 ost->enc_ctx->subtitle_header = av_malloc(dec->subtitle_header_size);
1888 if (!ost->enc_ctx->subtitle_header)
1889 return AVERROR(ENOMEM);
1890 memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
1891 ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
1892 }
1893 if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
1894 av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
ab7b0389 1895
c15f6098
AK
1896 if (ost->filter && ost->filter->filter->inputs[0]->hw_frames_ctx) {
1897 ost->enc_ctx->hw_frames_ctx = av_buffer_ref(ost->filter->filter->inputs[0]->hw_frames_ctx);
1898 if (!ost->enc_ctx->hw_frames_ctx)
1899 return AVERROR(ENOMEM);
1900 }
1901
ab7b0389
AK
1902 if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
1903 if (ret == AVERROR_EXPERIMENTAL)
1904 abort_codec_experimental(codec, 1);
1905 snprintf(error, error_len,
1906 "Error while opening encoder for output stream #%d:%d - "
1907 "maybe incorrect parameters such as bit_rate, rate, width or height",
1908 ost->file_index, ost->index);
1909 return ret;
1910 }
1911 assert_avoptions(ost->encoder_opts);
1912 if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
1913 av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
1914 "It takes bits/s as argument, not kbits/s\n");
1915
15e84ed3 1916 ret = avcodec_parameters_from_context(ost->st->codecpar, ost->enc_ctx);
ab7b0389
AK
1917 if (ret < 0) {
1918 av_log(NULL, AV_LOG_FATAL,
1919 "Error initializing the output stream codec context.\n");
1920 exit_program(1);
1921 }
1922
e63e3797
AK
1923 if (ost->enc_ctx->nb_coded_side_data) {
1924 int i;
1925
1926 ost->st->side_data = av_realloc_array(NULL, ost->enc_ctx->nb_coded_side_data,
1927 sizeof(*ost->st->side_data));
1928 if (!ost->st->side_data)
1929 return AVERROR(ENOMEM);
1930
1931 for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
1932 const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
1933 AVPacketSideData *sd_dst = &ost->st->side_data[i];
1934
1935 sd_dst->data = av_malloc(sd_src->size);
1936 if (!sd_dst->data)
1937 return AVERROR(ENOMEM);
1938 memcpy(sd_dst->data, sd_src->data, sd_src->size);
1939 sd_dst->size = sd_src->size;
1940 sd_dst->type = sd_src->type;
1941 ost->st->nb_side_data++;
1942 }
1943 }
1944
ab7b0389 1945 ost->st->time_base = ost->enc_ctx->time_base;
5e184062 1946 } else if (ost->stream_copy) {
6ed0f70f
AK
1947 ret = init_output_stream_streamcopy(ost);
1948 if (ret < 0)
1949 return ret;
1950
15e84ed3 1951 /*
35c85806
AK
1952 * FIXME: will the codec context used by the parser during streamcopy
1953 * This should go away with the new parser API.
15e84ed3 1954 */
35c85806 1955 ret = avcodec_parameters_to_context(ost->parser_avctx, ost->st->codecpar);
15e84ed3
AK
1956 if (ret < 0)
1957 return ret;
ab7b0389
AK
1958 }
1959
4426540f
AK
1960 /* initialize bitstream filters for the output stream
1961 * needs to be done here, because the codec id for streamcopy is not
1962 * known until now */
1963 ret = init_output_bsfs(ost);
1964 if (ret < 0)
1965 return ret;
1966
1c169782
AK
1967 ost->initialized = 1;
1968
1969 ret = check_init_output_file(output_files[ost->file_index], ost->file_index);
1970 if (ret < 0)
1971 return ret;
1972
ab7b0389
AK
1973 return ret;
1974}
1975
19ad5673
AK
1976static void parse_forced_key_frames(char *kf, OutputStream *ost,
1977 AVCodecContext *avctx)
1978{
1979 char *p;
1980 int n = 1, i;
1981 int64_t t;
1982
1983 for (p = kf; *p; p++)
1984 if (*p == ',')
1985 n++;
1986 ost->forced_kf_count = n;
1987 ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
1988 if (!ost->forced_kf_pts) {
1989 av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
636ced8e 1990 exit_program(1);
19ad5673 1991 }
4c679750
RD
1992
1993 p = kf;
19ad5673 1994 for (i = 0; i < n; i++) {
4c679750
RD
1995 char *next = strchr(p, ',');
1996
1997 if (next)
1998 *next++ = 0;
1999
19ad5673
AK
2000 t = parse_time_or_die("force_key_frames", p, 1);
2001 ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
4c679750
RD
2002
2003 p = next;
19ad5673
AK
2004 }
2005}
2006
6656370b
AK
2007static void set_encoder_id(OutputFile *of, OutputStream *ost)
2008{
2009 AVDictionaryEntry *e;
2010
2011 uint8_t *encoder_string;
2012 int encoder_string_len;
2013 int format_flags = 0;
2014
2015 e = av_dict_get(of->opts, "fflags", NULL, 0);
2016 if (e) {
2017 const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
2018 if (!o)
2019 return;
2020 av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
2021 }
2022
2023 encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
2024 encoder_string = av_mallocz(encoder_string_len);
2025 if (!encoder_string)
2026 exit_program(1);
2027
2028 if (!(format_flags & AVFMT_FLAG_BITEXACT))
2029 av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
2030 av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
2031 av_dict_set(&ost->st->metadata, "encoder", encoder_string,
2032 AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
2033}
2034
ea9367e9 2035static int transcode_init(void)
6291d7e4 2036{
2c474ddb 2037 int ret = 0, i, j, k;
1bb77e51 2038 AVFormatContext *oc;
4288e031 2039 OutputStream *ost;
6291d7e4
AK
2040 InputStream *ist;
2041 char error[1024];
b0c9e8e0 2042
f4805328
AK
2043 /* init framerate emulation */
2044 for (i = 0; i < nb_input_files; i++) {
2e215267 2045 InputFile *ifile = input_files[i];
f4805328
AK
2046 if (ifile->rate_emu)
2047 for (j = 0; j < ifile->nb_streams; j++)
d0c09302 2048 input_streams[j + ifile->ist_index]->start = av_gettime_relative();
f4805328 2049 }
6291d7e4 2050
6291d7e4 2051 /* for each output stream, we compute the right encoding parameters */
4288e031 2052 for (i = 0; i < nb_output_streams; i++) {
2e215267
AK
2053 ost = output_streams[i];
2054 oc = output_files[ost->file_index]->ctx;
3b266da3 2055 ist = get_input_stream(ost);
6291d7e4 2056
4dbc6cee
AK
2057 if (ost->attachment_filename)
2058 continue;
2059
3b266da3 2060 if (ist) {
3b266da3 2061 ost->st->disposition = ist->st->disposition;
3b266da3 2062 }
6291d7e4 2063
6ed0f70f 2064 if (!ost->stream_copy) {
15e84ed3
AK
2065 AVCodecContext *enc_ctx = ost->enc_ctx;
2066 AVCodecContext *dec_ctx = NULL;
2067
6656370b
AK
2068 set_encoder_id(output_files[ost->file_index], ost);
2069
15e84ed3
AK
2070 if (ist) {
2071 dec_ctx = ist->dec_ctx;
2072
2073 enc_ctx->bits_per_raw_sample = dec_ctx->bits_per_raw_sample;
2074 enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
2075 }
2076
fb472e1a
AK
2077#if CONFIG_LIBMFX
2078 if (qsv_transcode_init(ost))
2079 exit_program(1);
2080#endif
2081
73c6ec6d
AK
2082 if ((enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
2083 enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
2084 filtergraph_is_simple(ost->filter->graph)) {
2085 FilterGraph *fg = ost->filter->graph;
722ec3eb
AK
2086
2087 ret = ifilter_parameters_from_decoder(fg->inputs[0],
2088 dec_ctx);
2089 if (ret < 0) {
2090 av_log(NULL, AV_LOG_FATAL, "Error initializing filter input\n");
2091 exit_program(1);
2092 }
2093
8daf21d5 2094 if (configure_filtergraph(fg)) {
3b266da3 2095 av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
636ced8e 2096 exit_program(1);
3b266da3 2097 }
369cb092 2098 }
3b266da3 2099
65ed9e75 2100 switch (enc_ctx->codec_type) {
369cb092 2101 case AVMEDIA_TYPE_AUDIO:
65ed9e75
AK
2102 enc_ctx->sample_fmt = ost->filter->filter->inputs[0]->format;
2103 enc_ctx->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
2104 enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2105 enc_ctx->channels = av_get_channel_layout_nb_channels(enc_ctx->channel_layout);
2106 enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate };
369cb092
AK
2107 break;
2108 case AVMEDIA_TYPE_VIDEO:
65ed9e75 2109 enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;
6291d7e4 2110
65ed9e75
AK
2111 enc_ctx->width = ost->filter->filter->inputs[0]->w;
2112 enc_ctx->height = ost->filter->filter->inputs[0]->h;
2113 enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3b266da3 2114 ost->frame_aspect_ratio ? // overridden by the -aspect cli option
65ed9e75 2115 av_d2q(ost->frame_aspect_ratio * enc_ctx->height/enc_ctx->width, 255) :
3b266da3 2116 ost->filter->filter->inputs[0]->sample_aspect_ratio;
65ed9e75 2117 enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;
b7327887 2118
93afb6c9
AK
2119 ost->st->avg_frame_rate = ost->frame_rate;
2120
650a5206 2121 if (dec_ctx &&
65ed9e75
AK
2122 (enc_ctx->width != dec_ctx->width ||
2123 enc_ctx->height != dec_ctx->height ||
2124 enc_ctx->pix_fmt != dec_ctx->pix_fmt)) {
2125 enc_ctx->bits_per_raw_sample = 0;
b7327887
AK
2126 }
2127
19ad5673
AK
2128 if (ost->forced_keyframes)
2129 parse_forced_key_frames(ost->forced_keyframes, ost,
38313626 2130 ost->enc_ctx);
6291d7e4
AK
2131 break;
2132 case AVMEDIA_TYPE_SUBTITLE:
65ed9e75 2133 enc_ctx->time_base = (AVRational){1, 1000};
6291d7e4
AK
2134 break;
2135 default:
2136 abort();
2137 break;
2138 }
6291d7e4 2139 }
6291d7e4
AK
2140 }
2141
5b9cdf8c
AK
2142 /* init input streams */
2143 for (i = 0; i < nb_input_streams; i++)
2144 if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
2145 goto dump_format;
2146
6291d7e4 2147 /* open each encoder */
4288e031 2148 for (i = 0; i < nb_output_streams; i++) {
ab7b0389
AK
2149 ret = init_output_stream(output_streams[i], error, sizeof(error));
2150 if (ret < 0)
2151 goto dump_format;
6291d7e4
AK
2152 }
2153
6291d7e4 2154
2c474ddb
AK
2155 /* discard unused programs */
2156 for (i = 0; i < nb_input_files; i++) {
2e215267 2157 InputFile *ifile = input_files[i];
2c474ddb
AK
2158 for (j = 0; j < ifile->ctx->nb_programs; j++) {
2159 AVProgram *p = ifile->ctx->programs[j];
2160 int discard = AVDISCARD_ALL;
2161
2162 for (k = 0; k < p->nb_stream_indexes; k++)
2e215267 2163 if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2c474ddb
AK
2164 discard = AVDISCARD_DEFAULT;
2165 break;
2166 }
2167 p->discard = discard;
2168 }
2169 }
2170
6291d7e4 2171 dump_format:
6291d7e4 2172 /* dump the stream mapping */
e3245b26 2173 av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3b266da3
AK
2174 for (i = 0; i < nb_input_streams; i++) {
2175 ist = input_streams[i];
2176
2177 for (j = 0; j < ist->nb_filters; j++) {
49670e42 2178 if (!filtergraph_is_simple(ist->filters[j]->graph)) {
3b266da3
AK
2179 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
2180 ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
cf6c38c6 2181 ist->filters[j]->name);
3b266da3
AK
2182 if (nb_filtergraphs > 1)
2183 av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2184 av_log(NULL, AV_LOG_INFO, "\n");
2185 }
2186 }
2187 }
2188
e3245b26 2189 for (i = 0; i < nb_output_streams; i++) {
2e215267 2190 ost = output_streams[i];
4dbc6cee
AK
2191
2192 if (ost->attachment_filename) {
2193 /* an attached file */
2194 av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2195 ost->attachment_filename, ost->file_index, ost->index);
2196 continue;
2197 }
3b266da3 2198
49670e42 2199 if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
3b266da3 2200 /* output from a complex graph */
cf6c38c6 2201 av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
3b266da3
AK
2202 if (nb_filtergraphs > 1)
2203 av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2204
2205 av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2206 ost->index, ost->enc ? ost->enc->name : "?");
2207 continue;
2208 }
2209
9a414d89 2210 av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2e215267
AK
2211 input_streams[ost->source_index]->file_index,
2212 input_streams[ost->source_index]->st->index,
e3245b26
AK
2213 ost->file_index,
2214 ost->index);
2e215267 2215 if (ost->sync_ist != input_streams[ost->source_index])
9a414d89 2216 av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
e3245b26
AK
2217 ost->sync_ist->file_index,
2218 ost->sync_ist->st->index);
3d813e4c 2219 if (ost->stream_copy)
e3245b26 2220 av_log(NULL, AV_LOG_INFO, " (copy)");
39ec5e1c
LB
2221 else {
2222 const AVCodec *in_codec = input_streams[ost->source_index]->dec;
2223 const AVCodec *out_codec = ost->enc;
2224 const char *decoder_name = "?";
2225 const char *in_codec_name = "?";
2226 const char *encoder_name = "?";
2227 const char *out_codec_name = "?";
aa1a1b24 2228 const AVCodecDescriptor *desc;
39ec5e1c
LB
2229
2230 if (in_codec) {
2231 decoder_name = in_codec->name;
aa1a1b24
HS
2232 desc = avcodec_descriptor_get(in_codec->id);
2233 if (desc)
2234 in_codec_name = desc->name;
39ec5e1c
LB
2235 if (!strcmp(decoder_name, in_codec_name))
2236 decoder_name = "native";
2237 }
2238
2239 if (out_codec) {
2240 encoder_name = out_codec->name;
aa1a1b24
HS
2241 desc = avcodec_descriptor_get(out_codec->id);
2242 if (desc)
2243 out_codec_name = desc->name;
71d6551e 2244 if (!strcmp(encoder_name, out_codec_name))
39ec5e1c
LB
2245 encoder_name = "native";
2246 }
2247
2248 av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
2249 in_codec_name, decoder_name,
2250 out_codec_name, encoder_name);
2251 }
e3245b26 2252 av_log(NULL, AV_LOG_INFO, "\n");
6291d7e4
AK
2253 }
2254
2255 if (ret) {
e3245b26 2256 av_log(NULL, AV_LOG_ERROR, "%s\n", error);
eaf2d37a 2257 return ret;
6291d7e4
AK
2258 }
2259
eaf2d37a
AC
2260 return 0;
2261}
2262
c1ef30a6 2263/* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
2f51ec2b
AK
2264static int need_output(void)
2265{
2266 int i;
2267
2268 for (i = 0; i < nb_output_streams; i++) {
2269 OutputStream *ost = output_streams[i];
2270 OutputFile *of = output_files[ost->file_index];
2271 AVFormatContext *os = output_files[ost->file_index]->ctx;
2272
57d24225 2273 if (ost->finished ||
2f51ec2b
AK
2274 (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2275 continue;
e58b75f7 2276 if (ost->frame_number >= ost->max_frames) {
2f51ec2b
AK
2277 int j;
2278 for (j = 0; j < of->ctx->nb_streams; j++)
57d24225 2279 output_streams[of->ost_index + j]->finished = 1;
2f51ec2b
AK
2280 continue;
2281 }
2282
2283 return 1;
2284 }
2285
2286 return 0;
2287}
2288
83916029 2289static InputFile *select_input_file(void)
a508e7a1 2290{
83916029 2291 InputFile *ifile = NULL;
a508e7a1 2292 int64_t ipts_min = INT64_MAX;
83916029 2293 int i;
a508e7a1
AK
2294
2295 for (i = 0; i < nb_input_streams; i++) {
2296 InputStream *ist = input_streams[i];
2297 int64_t ipts = ist->last_dts;
2298
0b26ef42 2299 if (ist->discard || input_files[ist->file_index]->eagain)
a508e7a1
AK
2300 continue;
2301 if (!input_files[ist->file_index]->eof_reached) {
2302 if (ipts < ipts_min) {
2303 ipts_min = ipts;
83916029 2304 ifile = input_files[ist->file_index];
a508e7a1
AK
2305 }
2306 }
2307 }
2308
83916029 2309 return ifile;
a508e7a1
AK
2310}
2311
47b812e9 2312#if HAVE_PTHREADS
5db5169e
AK
2313static void *input_thread(void *arg)
2314{
2315 InputFile *f = arg;
2316 int ret = 0;
2317
2318 while (!transcoding_finished && ret >= 0) {
2319 AVPacket pkt;
2320 ret = av_read_frame(f->ctx, &pkt);
2321
2322 if (ret == AVERROR(EAGAIN)) {
896bb0d7 2323 av_usleep(10000);
5db5169e
AK
2324 ret = 0;
2325 continue;
2326 } else if (ret < 0)
2327 break;
2328
2329 pthread_mutex_lock(&f->fifo_lock);
2330 while (!av_fifo_space(f->fifo))
2331 pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
2332
5db5169e
AK
2333 av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2334
2335 pthread_mutex_unlock(&f->fifo_lock);
2336 }
2337
2338 f->finished = 1;
2339 return NULL;
2340}
2341
2342static void free_input_threads(void)
2343{
2344 int i;
2345
2346 if (nb_input_files == 1)
2347 return;
2348
2349 transcoding_finished = 1;
2350
2351 for (i = 0; i < nb_input_files; i++) {
2352 InputFile *f = input_files[i];
2353 AVPacket pkt;
2354
9034b0ed 2355 if (!f->fifo || f->joined)
5db5169e
AK
2356 continue;
2357
2358 pthread_mutex_lock(&f->fifo_lock);
2359 while (av_fifo_size(f->fifo)) {
2360 av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
ce70f28a 2361 av_packet_unref(&pkt);
5db5169e
AK
2362 }
2363 pthread_cond_signal(&f->fifo_cond);
2364 pthread_mutex_unlock(&f->fifo_lock);
2365
2366 pthread_join(f->thread, NULL);
2367 f->joined = 1;
2368
2369 while (av_fifo_size(f->fifo)) {
2370 av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
ce70f28a 2371 av_packet_unref(&pkt);
5db5169e
AK
2372 }
2373 av_fifo_free(f->fifo);
2374 }
2375}
2376
2377static int init_input_threads(void)
2378{
2379 int i, ret;
2380
2381 if (nb_input_files == 1)
2382 return 0;
2383
2384 for (i = 0; i < nb_input_files; i++) {
2385 InputFile *f = input_files[i];
2386
2387 if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2388 return AVERROR(ENOMEM);
2389
2390 pthread_mutex_init(&f->fifo_lock, NULL);
2391 pthread_cond_init (&f->fifo_cond, NULL);
2392
2393 if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2394 return AVERROR(ret);
2395 }
2396 return 0;
2397}
2398
2399static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
2400{
2401 int ret = 0;
2402
2403 pthread_mutex_lock(&f->fifo_lock);
2404
2405 if (av_fifo_size(f->fifo)) {
2406 av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2407 pthread_cond_signal(&f->fifo_cond);
2408 } else {
2409 if (f->finished)
2410 ret = AVERROR_EOF;
2411 else
2412 ret = AVERROR(EAGAIN);
2413 }
2414
2415 pthread_mutex_unlock(&f->fifo_lock);
2416
2417 return ret;
2418}
2419#endif
2420
2421static int get_input_packet(InputFile *f, AVPacket *pkt)
2422{
b4a5a292
AK
2423 if (f->rate_emu) {
2424 int i;
2425 for (i = 0; i < f->nb_streams; i++) {
2426 InputStream *ist = input_streams[f->ist_index + i];
2427 int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
d0c09302 2428 int64_t now = av_gettime_relative() - ist->start;
b4a5a292
AK
2429 if (pts > now)
2430 return AVERROR(EAGAIN);
2431 }
2432 }
2433
47b812e9 2434#if HAVE_PTHREADS
5db5169e
AK
2435 if (nb_input_files > 1)
2436 return get_input_packet_mt(f, pkt);
2437#endif
2438 return av_read_frame(f->ctx, pkt);
2439}
2440
0b26ef42
AK
2441static int got_eagain(void)
2442{
2443 int i;
2444 for (i = 0; i < nb_input_files; i++)
2445 if (input_files[i]->eagain)
2446 return 1;
2447 return 0;
2448}
2449
2450static void reset_eagain(void)
2451{
2452 int i;
2453 for (i = 0; i < nb_input_files; i++)
2454 input_files[i]->eagain = 0;
2455}
2456
16b0c929
AH
2457// set duration to max(tmp, duration) in a proper time base and return duration's time_base
2458static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
2459 AVRational time_base)
2460{
2461 int ret;
2462
2463 if (!*duration) {
2464 *duration = tmp;
2465 return tmp_time_base;
2466 }
2467
2468 ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
2469 if (ret < 0) {
2470 *duration = tmp;
2471 return tmp_time_base;
2472 }
2473
2474 return time_base;
2475}
2476
2477static int seek_to_start(InputFile *ifile, AVFormatContext *is)
2478{
2479 InputStream *ist;
2480 AVCodecContext *avctx;
2481 int i, ret, has_audio = 0;
2482 int64_t duration = 0;
2483
2484 ret = av_seek_frame(is, -1, is->start_time, 0);
2485 if (ret < 0)
2486 return ret;
2487
2488 for (i = 0; i < ifile->nb_streams; i++) {
2489 ist = input_streams[ifile->ist_index + i];
2490 avctx = ist->dec_ctx;
2491
2492 // flush decoders
2493 if (ist->decoding_needed) {
2494 process_input_packet(ist, NULL, 1);
2495 avcodec_flush_buffers(avctx);
2496 }
2497
2498 /* duration is the length of the last frame in a stream
2499 * when audio stream is present we don't care about
2500 * last video frame length because it's not defined exactly */
2501 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
2502 has_audio = 1;
2503 }
2504
2505 for (i = 0; i < ifile->nb_streams; i++) {
2506 ist = input_streams[ifile->ist_index + i];
2507 avctx = ist->dec_ctx;
2508
2509 if (has_audio) {
2510 if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
2511 AVRational sample_rate = {1, avctx->sample_rate};
2512
2513 duration = av_rescale_q(ist->nb_samples, sample_rate, ist->st->time_base);
2514 } else
2515 continue;
2516 } else {
2517 if (ist->framerate.num) {
2518 duration = av_rescale_q(1, ist->framerate, ist->st->time_base);
2519 } else if (ist->st->avg_frame_rate.num) {
2520 duration = av_rescale_q(1, ist->st->avg_frame_rate, ist->st->time_base);
2521 } else duration = 1;
2522 }
2523 if (!ifile->duration)
2524 ifile->time_base = ist->st->time_base;
2525 /* the total duration of the stream, max_pts - min_pts is
2526 * the duration of the stream without the last frame */
2527 duration += ist->max_pts - ist->min_pts;
2528 ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
2529 ifile->time_base);
2530 }
2531
cd0e0881
AH
2532 if (ifile->loop > 0)
2533 ifile->loop--;
16b0c929
AH
2534
2535 return ret;
2536}
2537
c1ef30a6 2538/*
0c00fd80
AK
2539 * Read one packet from an input file and send it for
2540 * - decoding -> lavfi (audio/video)
2541 * - decoding -> encoding -> muxing (subtitles)
2542 * - muxing (streamcopy)
2543 *
c1ef30a6 2544 * Return
0c00fd80
AK
2545 * - 0 -- one packet was read and processed
2546 * - AVERROR(EAGAIN) -- no packets were available for selected file,
2547 * this function should be called again
2548 * - AVERROR_EOF -- this function should not be called again
2549 */
2550static int process_input(void)
2551{
2552 InputFile *ifile;
2553 AVFormatContext *is;
2554 InputStream *ist;
2555 AVPacket pkt;
2556 int ret, i, j;
16b0c929 2557 int64_t duration;
0c00fd80
AK
2558
2559 /* select the stream that we must read now */
2560 ifile = select_input_file();
2561 /* if none, if is finished */
2562 if (!ifile) {
2563 if (got_eagain()) {
2564 reset_eagain();
2565 av_usleep(10000);
2566 return AVERROR(EAGAIN);
2567 }
2568 av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from.\n");
2569 return AVERROR_EOF;
2570 }
2571
2572 is = ifile->ctx;
2573 ret = get_input_packet(ifile, &pkt);
2574
2575 if (ret == AVERROR(EAGAIN)) {
2576 ifile->eagain = 1;
2577 return ret;
2578 }
cd0e0881 2579 if (ret < 0 && ifile->loop) {
16b0c929
AH
2580 if ((ret = seek_to_start(ifile, is)) < 0)
2581 return ret;
2582 ret = get_input_packet(ifile, &pkt);
2583 }
0c00fd80
AK
2584 if (ret < 0) {
2585 if (ret != AVERROR_EOF) {
2586 print_error(is->filename, ret);
2587 if (exit_on_error)
636ced8e 2588 exit_program(1);
0c00fd80
AK
2589 }
2590 ifile->eof_reached = 1;
2591
2592 for (i = 0; i < ifile->nb_streams; i++) {
2593 ist = input_streams[ifile->ist_index + i];
2594 if (ist->decoding_needed)
16b0c929 2595 process_input_packet(ist, NULL, 0);
0c00fd80
AK
2596
2597 /* mark all outputs that don't go through lavfi as finished */
2598 for (j = 0; j < nb_output_streams; j++) {
2599 OutputStream *ost = output_streams[j];
2600
2601 if (ost->source_index == ifile->ist_index + i &&
2602 (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
48e50921 2603 finish_output_stream(ost);
0c00fd80
AK
2604 }
2605 }
2606
3c0df905 2607 return AVERROR(EAGAIN);
0c00fd80
AK
2608 }
2609
2610 reset_eagain();
2611
2612 if (do_pkt_dump) {
2613 av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
2614 is->streams[pkt.stream_index]);
2615 }
2616 /* the following test is needed in case new streams appear
2617 dynamically in stream : we ignore them */
2618 if (pkt.stream_index >= ifile->nb_streams)
2619 goto discard_packet;
2620
2621 ist = input_streams[ifile->ist_index + pkt.stream_index];
47543450
AK
2622
2623 ist->data_size += pkt.size;
59444c76 2624 ist->nb_packets++;
47543450 2625
0c00fd80
AK
2626 if (ist->discard)
2627 goto discard_packet;
2628
59444c76
AK
2629 /* add the stream-global side data to the first packet */
2630 if (ist->nb_packets == 1)
2631 for (i = 0; i < ist->st->nb_side_data; i++) {
2632 AVPacketSideData *src_sd = &ist->st->side_data[i];
2633 uint8_t *dst_data;
2634
2635 if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
2636 continue;
16302246
MS
2637 if (ist->autorotate && src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
2638 continue;
59444c76
AK
2639
2640 dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
2641 if (!dst_data)
2642 exit_program(1);
2643
2644 memcpy(dst_data, src_sd->data, src_sd->size);
2645 }
2646
0c00fd80
AK
2647 if (pkt.dts != AV_NOPTS_VALUE)
2648 pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2649 if (pkt.pts != AV_NOPTS_VALUE)
2650 pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2651
2652 if (pkt.pts != AV_NOPTS_VALUE)
2653 pkt.pts *= ist->ts_scale;
2654 if (pkt.dts != AV_NOPTS_VALUE)
2655 pkt.dts *= ist->ts_scale;
2656
6cfbe1de
LB
2657 if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
2658 ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
2659 pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
0c00fd80
AK
2660 (is->iformat->flags & AVFMT_TS_DISCONT)) {
2661 int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2662 int64_t delta = pkt_dts - ist->next_dts;
2663
2664 if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
2665 ifile->ts_offset -= delta;
2666 av_log(NULL, AV_LOG_DEBUG,
2667 "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2668 delta, ifile->ts_offset);
2669 pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2670 if (pkt.pts != AV_NOPTS_VALUE)
2671 pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2672 }
2673 }
16b0c929
AH
2674 duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
2675 if (pkt.pts != AV_NOPTS_VALUE) {
2676 pkt.pts += duration;
2677 ist->max_pts = FFMAX(pkt.pts, ist->max_pts);
2678 ist->min_pts = FFMIN(pkt.pts, ist->min_pts);
2679 }
2680
2681 if (pkt.dts != AV_NOPTS_VALUE)
2682 pkt.dts += duration;
0c00fd80 2683
16b0c929 2684 process_input_packet(ist, &pkt, 0);
0c00fd80
AK
2685
2686discard_packet:
ce70f28a 2687 av_packet_unref(&pkt);
0c00fd80
AK
2688
2689 return 0;
2690}
2691
eaf2d37a
AC
2692/*
2693 * The following code is the main loop of the file converter
2694 */
ea9367e9 2695static int transcode(void)
eaf2d37a 2696{
0c00fd80
AK
2697 int ret, i, need_input = 1;
2698 AVFormatContext *os;
eaf2d37a
AC
2699 OutputStream *ost;
2700 InputStream *ist;
eaf2d37a
AC
2701 int64_t timer_start;
2702
ea9367e9 2703 ret = transcode_init();
eaf2d37a
AC
2704 if (ret < 0)
2705 goto fail;
2706
e3245b26 2707 av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
6291d7e4
AK
2708 term_init();
2709
d0c09302 2710 timer_start = av_gettime_relative();
6291d7e4 2711
47b812e9 2712#if HAVE_PTHREADS
5db5169e
AK
2713 if ((ret = init_input_threads()) < 0)
2714 goto fail;
2715#endif
2716
c0fbf971 2717 while (!received_sigterm) {
3b266da3 2718 /* check if there's any stream where output is still needed */
2f51ec2b
AK
2719 if (!need_output()) {
2720 av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
3b266da3 2721 break;
2f51ec2b 2722 }
3b266da3 2723
0c00fd80
AK
2724 /* read and process one input packet if needed */
2725 if (need_input) {
2726 ret = process_input();
2727 if (ret == AVERROR_EOF)
2728 need_input = 0;
6291d7e4
AK
2729 }
2730
0c00fd80 2731 ret = poll_filters();
63f7f8d1 2732 if (ret < 0 && ret != AVERROR_EOF) {
7ebf1b4a
LB
2733 char errbuf[128];
2734 av_strerror(ret, errbuf, sizeof(errbuf));
6291d7e4 2735
7ebf1b4a
LB
2736 av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
2737 break;
6291d7e4
AK
2738 }
2739
6291d7e4 2740 /* dump report by using the output first video and audio streams */
ea9367e9 2741 print_report(0, timer_start);
6291d7e4 2742 }
47b812e9 2743#if HAVE_PTHREADS
5db5169e
AK
2744 free_input_threads();
2745#endif
6291d7e4
AK
2746
2747 /* at the end of stream, we must flush the decoder buffers */
2748 for (i = 0; i < nb_input_streams; i++) {
2e215267 2749 ist = input_streams[i];
9e8aae44 2750 if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
16b0c929 2751 process_input_packet(ist, NULL, 0);
6291d7e4
AK
2752 }
2753 }
560f7774 2754 poll_filters();
ea9367e9 2755 flush_encoders();
6291d7e4
AK
2756
2757 term_exit();
2758
2759 /* write the trailer if needed and close file */
7636c8c6 2760 for (i = 0; i < nb_output_files; i++) {
2e215267 2761 os = output_files[i]->ctx;
1c169782
AK
2762 if (!output_files[i]->header_written) {
2763 av_log(NULL, AV_LOG_ERROR,
2764 "Nothing was written into output file %d (%s), because "
2765 "at least one of its streams received no packets.\n",
2766 i, os->filename);
2767 continue;
2768 }
6291d7e4
AK
2769 av_write_trailer(os);
2770 }
2771
2772 /* dump report by using the first video and audio streams */
ea9367e9 2773 print_report(1, timer_start);
6291d7e4
AK
2774
2775 /* close each encoder */
4288e031 2776 for (i = 0; i < nb_output_streams; i++) {
2e215267 2777 ost = output_streams[i];
6291d7e4 2778 if (ost->encoding_needed) {
38313626 2779 av_freep(&ost->enc_ctx->stats_in);
6291d7e4 2780 }
6291d7e4
AK
2781 }
2782
2783 /* close each decoder */
2784 for (i = 0; i < nb_input_streams; i++) {
2e215267 2785 ist = input_streams[i];
6291d7e4 2786 if (ist->decoding_needed) {
41776ba9 2787 avcodec_close(ist->dec_ctx);
07fd0a22 2788 if (ist->hwaccel_uninit)
41776ba9 2789 ist->hwaccel_uninit(ist->dec_ctx);
6291d7e4
AK
2790 }
2791 }
2792
5d273d3e
MT
2793 av_buffer_unref(&hw_device_ctx);
2794
6291d7e4
AK
2795 /* finished ! */
2796 ret = 0;
2797
2798 fail:
47b812e9 2799#if HAVE_PTHREADS
5db5169e
AK
2800 free_input_threads();
2801#endif
6291d7e4 2802
4288e031
AK
2803 if (output_streams) {
2804 for (i = 0; i < nb_output_streams; i++) {
2e215267 2805 ost = output_streams[i];
6291d7e4 2806 if (ost) {
6291d7e4
AK
2807 if (ost->logfile) {
2808 fclose(ost->logfile);
2809 ost->logfile = NULL;
2810 }
6291d7e4 2811 av_free(ost->forced_kf_pts);
9580818c 2812 av_dict_free(&ost->encoder_opts);
5c7db097 2813 av_dict_free(&ost->resample_opts);
6291d7e4
AK
2814 }
2815 }
6291d7e4
AK
2816 }
2817 return ret;
2818}
2819
f5e66827 2820static int64_t getutime(void)
a2c0b830 2821{
f5e66827
AK
2822#if HAVE_GETRUSAGE
2823 struct rusage rusage;
a2c0b830 2824
f5e66827
AK
2825 getrusage(RUSAGE_SELF, &rusage);
2826 return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
2827#elif HAVE_GETPROCESSTIMES
2828 HANDLE proc;
2829 FILETIME c, e, k, u;
2830 proc = GetCurrentProcess();
2831 GetProcessTimes(proc, &c, &e, &k, &u);
2832 return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
2833#else
d0c09302 2834 return av_gettime_relative();
f5e66827 2835#endif
a2c0b830
AK
2836}
2837
f5e66827 2838static int64_t getmaxrss(void)
6291d7e4 2839{
f5e66827
AK
2840#if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
2841 struct rusage rusage;
2842 getrusage(RUSAGE_SELF, &rusage);
2843 return (int64_t)rusage.ru_maxrss * 1024;
2844#elif HAVE_GETPROCESSMEMORYINFO
2845 HANDLE proc;
2846 PROCESS_MEMORY_COUNTERS memcounters;
2847 proc = GetCurrentProcess();
2848 memcounters.cb = sizeof(memcounters);
2849 GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
2850 return memcounters.PeakPagefileUsage;
2851#else
6291d7e4 2852 return 0;
f5e66827 2853#endif
6291d7e4
AK
2854}
2855
6291d7e4
AK
2856int main(int argc, char **argv)
2857{
1c169782 2858 int i, ret;
6291d7e4
AK
2859 int64_t ti;
2860
636ced8e 2861 register_exit(avconv_cleanup);
5e3f9979 2862
6291d7e4 2863 av_log_set_flags(AV_LOG_SKIP_REPEATED);
182cbe43 2864 parse_loglevel(argc, argv, options);
6291d7e4
AK
2865
2866 avcodec_register_all();
2867#if CONFIG_AVDEVICE
2868 avdevice_register_all();
2869#endif
6291d7e4 2870 avfilter_register_all();
6291d7e4 2871 av_register_all();
776f2bb9 2872 avformat_network_init();
6291d7e4 2873
6291d7e4
AK
2874 show_banner();
2875
77bd1bc7
AK
2876 /* parse options and open all input/output files */
2877 ret = avconv_parse_options(argc, argv);
2878 if (ret < 0)
636ced8e 2879 exit_program(1);
6291d7e4 2880
7636c8c6 2881 if (nb_output_files <= 0 && nb_input_files == 0) {
6291d7e4 2882 show_usage();
e3245b26 2883 av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
636ced8e 2884 exit_program(1);
6291d7e4
AK
2885 }
2886
2887 /* file converter / grab */
2888 if (nb_output_files <= 0) {
2889 fprintf(stderr, "At least one output file must be specified\n");
636ced8e 2890 exit_program(1);
6291d7e4
AK
2891 }
2892
1c169782
AK
2893 for (i = 0; i < nb_output_files; i++) {
2894 if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
2895 want_sdp = 0;
2896 }
2897
6291d7e4 2898 ti = getutime();
ea9367e9 2899 if (transcode() < 0)
636ced8e 2900 exit_program(1);
6291d7e4
AK
2901 ti = getutime() - ti;
2902 if (do_benchmark) {
2903 int maxrss = getmaxrss() / 1024;
2904 printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
2905 }
2906
636ced8e 2907 exit_program(0);
dad09ff9 2908 return 0;
6291d7e4 2909}