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