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