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