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