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