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