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