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