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