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