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