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