FFmpeg  2.1.1
ffmpeg.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2000-2003 Fabrice Bellard
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 /**
22  * @file
23  * multimedia converter based on the FFmpeg libraries
24  */
25 
26 #include "config.h"
27 #include <ctype.h>
28 #include <string.h>
29 #include <math.h>
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <limits.h>
33 #if HAVE_ISATTY
34 #if HAVE_IO_H
35 #include <io.h>
36 #endif
37 #if HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #endif
41 #include "libavformat/avformat.h"
42 #include "libavdevice/avdevice.h"
43 #include "libswscale/swscale.h"
44 #include "libswresample/swresample.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/channel_layout.h"
47 #include "libavutil/parseutils.h"
48 #include "libavutil/samplefmt.h"
49 #include "libavutil/fifo.h"
50 #include "libavutil/intreadwrite.h"
51 #include "libavutil/dict.h"
52 #include "libavutil/mathematics.h"
53 #include "libavutil/pixdesc.h"
54 #include "libavutil/avstring.h"
55 #include "libavutil/libm.h"
56 #include "libavutil/imgutils.h"
57 #include "libavutil/timestamp.h"
58 #include "libavutil/bprint.h"
59 #include "libavutil/time.h"
60 #include "libavformat/os_support.h"
61 
62 #include "libavformat/ffm.h" // not public API
63 
64 # include "libavfilter/avcodec.h"
65 # include "libavfilter/avfilter.h"
66 # include "libavfilter/buffersrc.h"
67 # include "libavfilter/buffersink.h"
68 
69 #if HAVE_SYS_RESOURCE_H
70 #include <sys/time.h>
71 #include <sys/types.h>
72 #include <sys/resource.h>
73 #elif HAVE_GETPROCESSTIMES
74 #include <windows.h>
75 #endif
76 #if HAVE_GETPROCESSMEMORYINFO
77 #include <windows.h>
78 #include <psapi.h>
79 #endif
80 
81 #if HAVE_SYS_SELECT_H
82 #include <sys/select.h>
83 #endif
84 
85 #if HAVE_TERMIOS_H
86 #include <fcntl.h>
87 #include <sys/ioctl.h>
88 #include <sys/time.h>
89 #include <termios.h>
90 #elif HAVE_KBHIT
91 #include <conio.h>
92 #endif
93 
94 #if HAVE_PTHREADS
95 #include <pthread.h>
96 #endif
97 
98 #include <time.h>
99 
100 #include "ffmpeg.h"
101 #include "cmdutils.h"
102 
103 #include "libavutil/avassert.h"
104 
105 const char program_name[] = "ffmpeg";
106 const int program_birth_year = 2000;
107 
108 static FILE *vstats_file;
109 
110 const char *const forced_keyframes_const_names[] = {
111  "n",
112  "n_forced",
113  "prev_forced_n",
114  "prev_forced_t",
115  "t",
116  NULL
117 };
118 
119 static void do_video_stats(OutputStream *ost, int frame_size);
120 static int64_t getutime(void);
121 static int64_t getmaxrss(void);
122 
123 static int run_as_daemon = 0;
124 static int64_t video_size = 0;
125 static int64_t audio_size = 0;
126 static int64_t subtitle_size = 0;
127 static int64_t extra_size = 0;
128 static int nb_frames_dup = 0;
129 static int nb_frames_drop = 0;
130 static int64_t decode_error_stat[2];
131 
132 static int current_time;
134 
136 
137 #if HAVE_PTHREADS
138 /* signal to input threads that they should exit; set by the main thread */
140 #endif
141 
142 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
143 
148 
153 
156 
157 #if HAVE_TERMIOS_H
158 
159 /* init terminal so that we can grab keys */
160 static struct termios oldtty;
161 static int restore_tty;
162 #endif
163 
164 static void free_input_threads(void);
165 
166 
167 /* sub2video hack:
168  Convert subtitles to video with alpha to insert them in filter graphs.
169  This is a temporary solution until libavfilter gets real subtitles support.
170  */
171 
173 {
174  int ret;
175  AVFrame *frame = ist->sub2video.frame;
176 
177  av_frame_unref(frame);
178  ist->sub2video.frame->width = ist->sub2video.w;
179  ist->sub2video.frame->height = ist->sub2video.h;
181  if ((ret = av_frame_get_buffer(frame, 32)) < 0)
182  return ret;
183  memset(frame->data[0], 0, frame->height * frame->linesize[0]);
184  return 0;
185 }
186 
187 static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
188  AVSubtitleRect *r)
189 {
190  uint32_t *pal, *dst2;
191  uint8_t *src, *src2;
192  int x, y;
193 
194  if (r->type != SUBTITLE_BITMAP) {
195  av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
196  return;
197  }
198  if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
199  av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");
200  return;
201  }
202 
203  dst += r->y * dst_linesize + r->x * 4;
204  src = r->pict.data[0];
205  pal = (uint32_t *)r->pict.data[1];
206  for (y = 0; y < r->h; y++) {
207  dst2 = (uint32_t *)dst;
208  src2 = src;
209  for (x = 0; x < r->w; x++)
210  *(dst2++) = pal[*(src2++)];
211  dst += dst_linesize;
212  src += r->pict.linesize[0];
213  }
214 }
215 
216 static void sub2video_push_ref(InputStream *ist, int64_t pts)
217 {
218  AVFrame *frame = ist->sub2video.frame;
219  int i;
220 
221  av_assert1(frame->data[0]);
222  ist->sub2video.last_pts = frame->pts = pts;
223  for (i = 0; i < ist->nb_filters; i++)
227 }
228 
229 static void sub2video_update(InputStream *ist, AVSubtitle *sub)
230 {
231  int w = ist->sub2video.w, h = ist->sub2video.h;
232  AVFrame *frame = ist->sub2video.frame;
233  int8_t *dst;
234  int dst_linesize;
235  int num_rects, i;
236  int64_t pts, end_pts;
237 
238  if (!frame)
239  return;
240  if (sub) {
241  pts = av_rescale_q(sub->pts + sub->start_display_time * 1000,
242  AV_TIME_BASE_Q, ist->st->time_base);
243  end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000,
244  AV_TIME_BASE_Q, ist->st->time_base);
245  num_rects = sub->num_rects;
246  } else {
247  pts = ist->sub2video.end_pts;
248  end_pts = INT64_MAX;
249  num_rects = 0;
250  }
251  if (sub2video_get_blank_frame(ist) < 0) {
252  av_log(ist->st->codec, AV_LOG_ERROR,
253  "Impossible to get a blank canvas.\n");
254  return;
255  }
256  dst = frame->data [0];
257  dst_linesize = frame->linesize[0];
258  for (i = 0; i < num_rects; i++)
259  sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);
260  sub2video_push_ref(ist, pts);
261  ist->sub2video.end_pts = end_pts;
262 }
263 
264 static void sub2video_heartbeat(InputStream *ist, int64_t pts)
265 {
266  InputFile *infile = input_files[ist->file_index];
267  int i, j, nb_reqs;
268  int64_t pts2;
269 
270  /* When a frame is read from a file, examine all sub2video streams in
271  the same file and send the sub2video frame again. Otherwise, decoded
272  video frames could be accumulating in the filter graph while a filter
273  (possibly overlay) is desperately waiting for a subtitle frame. */
274  for (i = 0; i < infile->nb_streams; i++) {
275  InputStream *ist2 = input_streams[infile->ist_index + i];
276  if (!ist2->sub2video.frame)
277  continue;
278  /* subtitles seem to be usually muxed ahead of other streams;
279  if not, substracting a larger time here is necessary */
280  pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
281  /* do not send the heartbeat frame if the subtitle is already ahead */
282  if (pts2 <= ist2->sub2video.last_pts)
283  continue;
284  if (pts2 >= ist2->sub2video.end_pts || !ist2->sub2video.frame->data[0])
285  sub2video_update(ist2, NULL);
286  for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
287  nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
288  if (nb_reqs)
289  sub2video_push_ref(ist2, pts2);
290  }
291 }
292 
293 static void sub2video_flush(InputStream *ist)
294 {
295  int i;
296 
297  for (i = 0; i < ist->nb_filters; i++)
298  av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
299 }
300 
301 /* end of sub2video hack */
302 
303 void term_exit(void)
304 {
305  av_log(NULL, AV_LOG_QUIET, "%s", "");
306 #if HAVE_TERMIOS_H
307  if(restore_tty)
308  tcsetattr (0, TCSANOW, &oldtty);
309 #endif
310 }
311 
312 static volatile int received_sigterm = 0;
313 static volatile int received_nb_signals = 0;
314 
315 static void
317 {
318  received_sigterm = sig;
320  term_exit();
321  if(received_nb_signals > 3)
322  exit_program(123);
323 }
324 
325 void term_init(void)
326 {
327 #if HAVE_TERMIOS_H
328  if(!run_as_daemon){
329  struct termios tty;
330  int istty = 1;
331 #if HAVE_ISATTY
332  istty = isatty(0) && isatty(2);
333 #endif
334  if (istty && tcgetattr (0, &tty) == 0) {
335  oldtty = tty;
336  restore_tty = 1;
337 
338  tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
339  |INLCR|IGNCR|ICRNL|IXON);
340  tty.c_oflag |= OPOST;
341  tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
342  tty.c_cflag &= ~(CSIZE|PARENB);
343  tty.c_cflag |= CS8;
344  tty.c_cc[VMIN] = 1;
345  tty.c_cc[VTIME] = 0;
346 
347  tcsetattr (0, TCSANOW, &tty);
348  }
349  signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
350  }
351 #endif
353 
354  signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
355  signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
356 #ifdef SIGXCPU
357  signal(SIGXCPU, sigterm_handler);
358 #endif
359 }
360 
361 /* read a key without blocking */
362 static int read_key(void)
363 {
364  unsigned char ch;
365 #if HAVE_TERMIOS_H
366  int n = 1;
367  struct timeval tv;
368  fd_set rfds;
369 
370  FD_ZERO(&rfds);
371  FD_SET(0, &rfds);
372  tv.tv_sec = 0;
373  tv.tv_usec = 0;
374  n = select(1, &rfds, NULL, NULL, &tv);
375  if (n > 0) {
376  n = read(0, &ch, 1);
377  if (n == 1)
378  return ch;
379 
380  return n;
381  }
382 #elif HAVE_KBHIT
383 # if HAVE_PEEKNAMEDPIPE
384  static int is_pipe;
385  static HANDLE input_handle;
386  DWORD dw, nchars;
387  if(!input_handle){
388  input_handle = GetStdHandle(STD_INPUT_HANDLE);
389  is_pipe = !GetConsoleMode(input_handle, &dw);
390  }
391 
392  if (stdin->_cnt > 0) {
393  read(0, &ch, 1);
394  return ch;
395  }
396  if (is_pipe) {
397  /* When running under a GUI, you will end here. */
398  if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
399  // input pipe may have been closed by the program that ran ffmpeg
400  return -1;
401  }
402  //Read it
403  if(nchars != 0) {
404  read(0, &ch, 1);
405  return ch;
406  }else{
407  return -1;
408  }
409  }
410 # endif
411  if(kbhit())
412  return(getch());
413 #endif
414  return -1;
415 }
416 
417 static int decode_interrupt_cb(void *ctx)
418 {
419  return received_nb_signals > 1;
420 }
421 
423 
424 static void ffmpeg_cleanup(int ret)
425 {
426  int i, j;
427 
428  if (do_benchmark) {
429  int maxrss = getmaxrss() / 1024;
430  printf("bench: maxrss=%ikB\n", maxrss);
431  }
432 
433  for (i = 0; i < nb_filtergraphs; i++) {
434  avfilter_graph_free(&filtergraphs[i]->graph);
435  for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
436  av_freep(&filtergraphs[i]->inputs[j]->name);
437  av_freep(&filtergraphs[i]->inputs[j]);
438  }
439  av_freep(&filtergraphs[i]->inputs);
440  for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
441  av_freep(&filtergraphs[i]->outputs[j]->name);
442  av_freep(&filtergraphs[i]->outputs[j]);
443  }
444  av_freep(&filtergraphs[i]->outputs);
445  av_freep(&filtergraphs[i]->graph_desc);
446  av_freep(&filtergraphs[i]);
447  }
448  av_freep(&filtergraphs);
449 
451 
452  /* close files */
453  for (i = 0; i < nb_output_files; i++) {
454  AVFormatContext *s = output_files[i]->ctx;
455  if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE) && s->pb)
456  avio_close(s->pb);
458  av_dict_free(&output_files[i]->opts);
459  av_freep(&output_files[i]);
460  }
461  for (i = 0; i < nb_output_streams; i++) {
462  AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
463  while (bsfc) {
464  AVBitStreamFilterContext *next = bsfc->next;
466  bsfc = next;
467  }
468  output_streams[i]->bitstream_filters = NULL;
469  avcodec_free_frame(&output_streams[i]->filtered_frame);
470 
471  av_freep(&output_streams[i]->forced_keyframes);
472  av_expr_free(output_streams[i]->forced_keyframes_pexpr);
473  av_freep(&output_streams[i]->avfilter);
474  av_freep(&output_streams[i]->logfile_prefix);
475  av_freep(&output_streams[i]);
476  }
477 #if HAVE_PTHREADS
479 #endif
480  for (i = 0; i < nb_input_files; i++) {
481  avformat_close_input(&input_files[i]->ctx);
482  av_freep(&input_files[i]);
483  }
484  for (i = 0; i < nb_input_streams; i++) {
485  av_frame_free(&input_streams[i]->decoded_frame);
486  av_frame_free(&input_streams[i]->filter_frame);
487  av_dict_free(&input_streams[i]->opts);
488  avsubtitle_free(&input_streams[i]->prev_sub.subtitle);
489  av_frame_free(&input_streams[i]->sub2video.frame);
490  av_freep(&input_streams[i]->filters);
491  av_freep(&input_streams[i]);
492  }
493 
494  if (vstats_file)
495  fclose(vstats_file);
497 
498  av_freep(&input_streams);
499  av_freep(&input_files);
500  av_freep(&output_streams);
501  av_freep(&output_files);
502 
503  uninit_opts();
504 
506 
507  if (received_sigterm) {
508  av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
509  (int) received_sigterm);
510  }
511  term_exit();
512 }
513 
515 {
517  if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
518  av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
519  exit_program(1);
520  }
521 }
522 
523 static void abort_codec_experimental(AVCodec *c, int encoder)
524 {
525  exit_program(1);
526 }
527 
528 static void update_benchmark(const char *fmt, ...)
529 {
530  if (do_benchmark_all) {
531  int64_t t = getutime();
532  va_list va;
533  char buf[1024];
534 
535  if (fmt) {
536  va_start(va, fmt);
537  vsnprintf(buf, sizeof(buf), fmt, va);
538  va_end(va);
539  printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
540  }
541  current_time = t;
542  }
543 }
544 
546 {
548  AVCodecContext *avctx = ost->st->codec;
549  int ret;
550 
553  pkt->pts = pkt->dts = AV_NOPTS_VALUE;
554 
555  /*
556  * Audio encoders may split the packets -- #frames in != #packets out.
557  * But there is no reordering, so we can limit the number of output packets
558  * by simply dropping them here.
559  * Counting encoded video frames needs to be done separately because of
560  * reordering, see do_video_out()
561  */
562  if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
563  if (ost->frame_number >= ost->max_frames) {
564  av_free_packet(pkt);
565  return;
566  }
567  ost->frame_number++;
568  }
569 
570  while (bsfc) {
571  AVPacket new_pkt = *pkt;
572  int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
573  &new_pkt.data, &new_pkt.size,
574  pkt->data, pkt->size,
575  pkt->flags & AV_PKT_FLAG_KEY);
576  if(a == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
577  uint8_t *t = av_malloc(new_pkt.size + FF_INPUT_BUFFER_PADDING_SIZE); //the new should be a subset of the old so cannot overflow
578  if(t) {
579  memcpy(t, new_pkt.data, new_pkt.size);
580  memset(t + new_pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
581  new_pkt.data = t;
582  new_pkt.buf = NULL;
583  a = 1;
584  } else
585  a = AVERROR(ENOMEM);
586  }
587  if (a > 0) {
588  av_free_packet(pkt);
589  new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
590  av_buffer_default_free, NULL, 0);
591  if (!new_pkt.buf)
592  exit_program(1);
593  } else if (a < 0) {
594  av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
595  bsfc->filter->name, pkt->stream_index,
596  avctx->codec ? avctx->codec->name : "copy");
597  print_error("", a);
598  if (exit_on_error)
599  exit_program(1);
600  }
601  *pkt = new_pkt;
602 
603  bsfc = bsfc->next;
604  }
605 
606  if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
607  (avctx->codec_type == AVMEDIA_TYPE_AUDIO || avctx->codec_type == AVMEDIA_TYPE_VIDEO) &&
608  pkt->dts != AV_NOPTS_VALUE &&
609  ost->last_mux_dts != AV_NOPTS_VALUE) {
610  int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
611  if (pkt->dts < max) {
612  int loglevel = max - pkt->dts > 2 || avctx->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
613  av_log(s, loglevel, "Non-monotonous DTS in output stream "
614  "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
615  ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
616  if (exit_on_error) {
617  av_log(NULL, AV_LOG_FATAL, "aborting.\n");
618  exit_program(1);
619  }
620  av_log(s, loglevel, "changing to %"PRId64". This may result "
621  "in incorrect timestamps in the output file.\n",
622  max);
623  if(pkt->pts >= pkt->dts)
624  pkt->pts = FFMAX(pkt->pts, max);
625  pkt->dts = max;
626  }
627  }
628  ost->last_mux_dts = pkt->dts;
629 
630  pkt->stream_index = ost->index;
631 
632  if (debug_ts) {
633  av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
634  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
636  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
637  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
638  pkt->size
639  );
640  }
641 
642  ret = av_interleaved_write_frame(s, pkt);
643  if (ret < 0) {
644  print_error("av_interleaved_write_frame()", ret);
645  exit_program(1);
646  }
647 }
648 
650 {
651  OutputFile *of = output_files[ost->file_index];
652 
653  ost->finished = 1;
654  if (of->shortest) {
655  int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, AV_TIME_BASE_Q);
656  of->recording_time = FFMIN(of->recording_time, end);
657  }
658 }
659 
661 {
662  OutputFile *of = output_files[ost->file_index];
663 
664  if (of->recording_time != INT64_MAX &&
666  AV_TIME_BASE_Q) >= 0) {
667  close_output_stream(ost);
668  return 0;
669  }
670  return 1;
671 }
672 
674  AVFrame *frame)
675 {
676  AVCodecContext *enc = ost->st->codec;
677  AVPacket pkt;
678  int got_packet = 0;
679 
680  av_init_packet(&pkt);
681  pkt.data = NULL;
682  pkt.size = 0;
683 
684  if (!check_recording_time(ost))
685  return;
686 
687  if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
688  frame->pts = ost->sync_opts;
689  ost->sync_opts = frame->pts + frame->nb_samples;
690 
691  av_assert0(pkt.size || !pkt.data);
692  update_benchmark(NULL);
693  if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
694  av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
695  exit_program(1);
696  }
697  update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
698 
699  if (got_packet) {
700  if (pkt.pts != AV_NOPTS_VALUE)
701  pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
702  if (pkt.dts != AV_NOPTS_VALUE)
703  pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
704  if (pkt.duration > 0)
705  pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
706 
707  if (debug_ts) {
708  av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
709  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
710  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
711  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
712  }
713 
714  audio_size += pkt.size;
715  write_frame(s, &pkt, ost);
716 
717  av_free_packet(&pkt);
718  }
719 }
720 
722  OutputStream *ost,
723  InputStream *ist,
724  AVSubtitle *sub)
725 {
726  int subtitle_out_max_size = 1024 * 1024;
727  int subtitle_out_size, nb, i;
728  AVCodecContext *enc;
729  AVPacket pkt;
730  int64_t pts;
731 
732  if (sub->pts == AV_NOPTS_VALUE) {
733  av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
734  if (exit_on_error)
735  exit_program(1);
736  return;
737  }
738 
739  enc = ost->st->codec;
740 
741  if (!subtitle_out) {
742  subtitle_out = av_malloc(subtitle_out_max_size);
743  }
744 
745  /* Note: DVB subtitle need one packet to draw them and one other
746  packet to clear them */
747  /* XXX: signal it in the codec context ? */
749  nb = 2;
750  else
751  nb = 1;
752 
753  /* shift timestamp to honor -ss and make check_recording_time() work with -t */
754  pts = sub->pts;
755  if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
756  pts -= output_files[ost->file_index]->start_time;
757  for (i = 0; i < nb; i++) {
758  ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
759  if (!check_recording_time(ost))
760  return;
761 
762  sub->pts = pts;
763  // start_display_time is required to be 0
764  sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
766  sub->start_display_time = 0;
767  if (i == 1)
768  sub->num_rects = 0;
769  subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
770  subtitle_out_max_size, sub);
771  if (subtitle_out_size < 0) {
772  av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
773  exit_program(1);
774  }
775 
776  av_init_packet(&pkt);
777  pkt.data = subtitle_out;
778  pkt.size = subtitle_out_size;
779  pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
780  pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
781  if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
782  /* XXX: the pts correction is handled here. Maybe handling
783  it in the codec would be better */
784  if (i == 0)
785  pkt.pts += 90 * sub->start_display_time;
786  else
787  pkt.pts += 90 * sub->end_display_time;
788  }
790  write_frame(s, &pkt, ost);
791  }
792 }
793 
795  OutputStream *ost,
796  AVFrame *in_picture)
797 {
798  int ret, format_video_sync;
799  AVPacket pkt;
800  AVCodecContext *enc = ost->st->codec;
801  int nb_frames, i;
802  double sync_ipts, delta;
803  double duration = 0;
804  int frame_size = 0;
805  InputStream *ist = NULL;
806 
807  if (ost->source_index >= 0)
808  ist = input_streams[ost->source_index];
809 
810  if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
811  duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
812 
813  sync_ipts = in_picture->pts;
814  delta = sync_ipts - ost->sync_opts + duration;
815 
816  /* by default, we output a single frame */
817  nb_frames = 1;
818 
819  format_video_sync = video_sync_method;
820  if (format_video_sync == VSYNC_AUTO) {
822  if ( ist
823  && format_video_sync == VSYNC_CFR
824  && input_files[ist->file_index]->ctx->nb_streams == 1
825  && input_files[ist->file_index]->input_ts_offset == 0) {
826  format_video_sync = VSYNC_VSCFR;
827  }
828  }
829 
830  switch (format_video_sync) {
831  case VSYNC_VSCFR:
832  if (ost->frame_number == 0 && delta - duration >= 0.5) {
833  av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta - duration));
834  delta = duration;
835  ost->sync_opts = lrint(sync_ipts);
836  }
837  case VSYNC_CFR:
838  // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
839  if (delta < -1.1)
840  nb_frames = 0;
841  else if (delta > 1.1)
842  nb_frames = lrintf(delta);
843  break;
844  case VSYNC_VFR:
845  if (delta <= -0.6)
846  nb_frames = 0;
847  else if (delta > 0.6)
848  ost->sync_opts = lrint(sync_ipts);
849  break;
850  case VSYNC_DROP:
851  case VSYNC_PASSTHROUGH:
852  ost->sync_opts = lrint(sync_ipts);
853  break;
854  default:
855  av_assert0(0);
856  }
857 
858  nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
859  if (nb_frames == 0) {
860  nb_frames_drop++;
861  av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
862  return;
863  } else if (nb_frames > 1) {
864  if (nb_frames > dts_error_threshold * 30) {
865  av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
866  nb_frames_drop++;
867  return;
868  }
869  nb_frames_dup += nb_frames - 1;
870  av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
871  }
872 
873  /* duplicates frame if needed */
874  for (i = 0; i < nb_frames; i++) {
875  av_init_packet(&pkt);
876  pkt.data = NULL;
877  pkt.size = 0;
878 
879  in_picture->pts = ost->sync_opts;
880 
881 #if 1
882  if (!check_recording_time(ost))
883 #else
884  if (ost->frame_number >= ost->max_frames)
885 #endif
886  return;
887 
888  if (s->oformat->flags & AVFMT_RAWPICTURE &&
889  enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
890  /* raw pictures are written as AVPicture structure to
891  avoid any copies. We support temporarily the older
892  method. */
893  enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
894  enc->coded_frame->top_field_first = in_picture->top_field_first;
895  if (enc->coded_frame->interlaced_frame)
897  else
899  pkt.data = (uint8_t *)in_picture;
900  pkt.size = sizeof(AVPicture);
901  pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
902  pkt.flags |= AV_PKT_FLAG_KEY;
903 
904  video_size += pkt.size;
905  write_frame(s, &pkt, ost);
906  } else {
907  int got_packet, forced_keyframe = 0;
908  double pts_time;
909 
911  ost->top_field_first >= 0)
912  in_picture->top_field_first = !!ost->top_field_first;
913 
914  if (in_picture->interlaced_frame) {
915  if (enc->codec->id == AV_CODEC_ID_MJPEG)
916  enc->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
917  else
918  enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
919  } else
921 
922  in_picture->quality = ost->st->codec->global_quality;
923  if (!enc->me_threshold)
924  in_picture->pict_type = 0;
925 
926  pts_time = in_picture->pts != AV_NOPTS_VALUE ?
927  in_picture->pts * av_q2d(enc->time_base) : NAN;
928  if (ost->forced_kf_index < ost->forced_kf_count &&
929  in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
930  ost->forced_kf_index++;
931  forced_keyframe = 1;
932  } else if (ost->forced_keyframes_pexpr) {
933  double res;
934  ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
937  av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
943  res);
944  if (res) {
945  forced_keyframe = 1;
951  }
952 
954  }
955  if (forced_keyframe) {
956  in_picture->pict_type = AV_PICTURE_TYPE_I;
957  av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
958  }
959 
960  update_benchmark(NULL);
961  ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);
962  update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
963  if (ret < 0) {
964  av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
965  exit_program(1);
966  }
967 
968  if (got_packet) {
969  if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
970  pkt.pts = ost->sync_opts;
971 
972  if (pkt.pts != AV_NOPTS_VALUE)
973  pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
974  if (pkt.dts != AV_NOPTS_VALUE)
975  pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
976 
977  if (debug_ts) {
978  av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
979  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
980  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
981  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
982  }
983 
984  frame_size = pkt.size;
985  video_size += pkt.size;
986  write_frame(s, &pkt, ost);
987  av_free_packet(&pkt);
988 
989  /* if two pass, output log */
990  if (ost->logfile && enc->stats_out) {
991  fprintf(ost->logfile, "%s", enc->stats_out);
992  }
993  }
994  }
995  ost->sync_opts++;
996  /*
997  * For video, number of frames in == number of packets out.
998  * But there may be reordering, so we can't throw away frames on encoder
999  * flush, we need to limit them here, before they go into encoder.
1000  */
1001  ost->frame_number++;
1002 
1003  if (vstats_filename && frame_size)
1004  do_video_stats(ost, frame_size);
1005  }
1006 }
1007 
1008 static double psnr(double d)
1009 {
1010  return -10.0 * log(d) / log(10.0);
1011 }
1012 
1014 {
1015  AVCodecContext *enc;
1016  int frame_number;
1017  double ti1, bitrate, avg_bitrate;
1018 
1019  /* this is executed just the first time do_video_stats is called */
1020  if (!vstats_file) {
1021  vstats_file = fopen(vstats_filename, "w");
1022  if (!vstats_file) {
1023  perror("fopen");
1024  exit_program(1);
1025  }
1026  }
1027 
1028  enc = ost->st->codec;
1029  if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1030  frame_number = ost->st->nb_frames;
1031  fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1032  if (enc->flags&CODEC_FLAG_PSNR)
1033  fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1034 
1035  fprintf(vstats_file,"f_size= %6d ", frame_size);
1036  /* compute pts value */
1037  ti1 = ost->st->pts.val * av_q2d(enc->time_base);
1038  if (ti1 < 0.01)
1039  ti1 = 0.01;
1040 
1041  bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1042  avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1043  fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1044  (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1045  fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1046  }
1047 }
1048 
1049 /**
1050  * Get and encode new output from any of the filtergraphs, without causing
1051  * activity.
1052  *
1053  * @return 0 for success, <0 for severe errors
1054  */
1055 static int reap_filters(void)
1056 {
1057  AVFrame *filtered_frame = NULL;
1058  int i;
1059  int64_t frame_pts;
1060 
1061  /* Reap all buffers present in the buffer sinks */
1062  for (i = 0; i < nb_output_streams; i++) {
1063  OutputStream *ost = output_streams[i];
1064  OutputFile *of = output_files[ost->file_index];
1065  int ret = 0;
1066 
1067  if (!ost->filter)
1068  continue;
1069 
1070  if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
1071  return AVERROR(ENOMEM);
1072  } else
1074  filtered_frame = ost->filtered_frame;
1075 
1076  while (1) {
1077  ret = av_buffersink_get_frame_flags(ost->filter->filter, filtered_frame,
1079  if (ret < 0) {
1080  if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
1081  av_log(NULL, AV_LOG_WARNING,
1082  "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
1083  }
1084  break;
1085  }
1086  frame_pts = AV_NOPTS_VALUE;
1087  if (filtered_frame->pts != AV_NOPTS_VALUE) {
1088  int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1089  filtered_frame->pts = frame_pts = av_rescale_q(filtered_frame->pts,
1090  ost->filter->filter->inputs[0]->time_base,
1091  ost->st->codec->time_base) -
1092  av_rescale_q(start_time,
1094  ost->st->codec->time_base);
1095  }
1096  //if (ost->source_index >= 0)
1097  // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
1098 
1099 
1100  switch (ost->filter->filter->inputs[0]->type) {
1101  case AVMEDIA_TYPE_VIDEO:
1102  filtered_frame->pts = frame_pts;
1103  if (!ost->frame_aspect_ratio.num)
1104  ost->st->codec->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
1105 
1106  do_video_out(of->ctx, ost, filtered_frame);
1107  break;
1108  case AVMEDIA_TYPE_AUDIO:
1109  filtered_frame->pts = frame_pts;
1110  if (!(ost->st->codec->codec->capabilities & CODEC_CAP_PARAM_CHANGE) &&
1111  ost->st->codec->channels != av_frame_get_channels(filtered_frame)) {
1112  av_log(NULL, AV_LOG_ERROR,
1113  "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1114  break;
1115  }
1116  do_audio_out(of->ctx, ost, filtered_frame);
1117  break;
1118  default:
1119  // TODO support subtitle filters
1120  av_assert0(0);
1121  }
1122 
1123  av_frame_unref(filtered_frame);
1124  }
1125  }
1126 
1127  return 0;
1128 }
1129 
1130 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
1131 {
1132  char buf[1024];
1133  AVBPrint buf_script;
1134  OutputStream *ost;
1135  AVFormatContext *oc;
1136  int64_t total_size;
1137  AVCodecContext *enc;
1138  int frame_number, vid, i;
1139  double bitrate;
1140  int64_t pts = INT64_MIN;
1141  static int64_t last_time = -1;
1142  static int qp_histogram[52];
1143  int hours, mins, secs, us;
1144 
1145  if (!print_stats && !is_last_report && !progress_avio)
1146  return;
1147 
1148  if (!is_last_report) {
1149  if (last_time == -1) {
1150  last_time = cur_time;
1151  return;
1152  }
1153  if ((cur_time - last_time) < 500000)
1154  return;
1155  last_time = cur_time;
1156  }
1157 
1158 
1159  oc = output_files[0]->ctx;
1160 
1161  total_size = avio_size(oc->pb);
1162  if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
1163  total_size = avio_tell(oc->pb);
1164 
1165  buf[0] = '\0';
1166  vid = 0;
1167  av_bprint_init(&buf_script, 0, 1);
1168  for (i = 0; i < nb_output_streams; i++) {
1169  float q = -1;
1170  ost = output_streams[i];
1171  enc = ost->st->codec;
1172  if (!ost->stream_copy && enc->coded_frame)
1173  q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1174  if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1175  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1176  av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1177  ost->file_index, ost->index, q);
1178  }
1179  if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1180  float fps, t = (cur_time-timer_start) / 1000000.0;
1181 
1182  frame_number = ost->frame_number;
1183  fps = t > 1 ? frame_number / t : 0;
1184  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
1185  frame_number, fps < 9.95, fps, q);
1186  av_bprintf(&buf_script, "frame=%d\n", frame_number);
1187  av_bprintf(&buf_script, "fps=%.1f\n", fps);
1188  av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1189  ost->file_index, ost->index, q);
1190  if (is_last_report)
1191  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1192  if (qp_hist) {
1193  int j;
1194  int qp = lrintf(q);
1195  if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1196  qp_histogram[qp]++;
1197  for (j = 0; j < 32; j++)
1198  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
1199  }
1200  if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
1201  int j;
1202  double error, error_sum = 0;
1203  double scale, scale_sum = 0;
1204  double p;
1205  char type[3] = { 'Y','U','V' };
1206  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1207  for (j = 0; j < 3; j++) {
1208  if (is_last_report) {
1209  error = enc->error[j];
1210  scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1211  } else {
1212  error = enc->coded_frame->error[j];
1213  scale = enc->width * enc->height * 255.0 * 255.0;
1214  }
1215  if (j)
1216  scale /= 4;
1217  error_sum += error;
1218  scale_sum += scale;
1219  p = psnr(error / scale);
1220  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
1221  av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
1222  ost->file_index, ost->index, type[j] | 32, p);
1223  }
1224  p = psnr(error_sum / scale_sum);
1225  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1226  av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
1227  ost->file_index, ost->index, p);
1228  }
1229  vid = 1;
1230  }
1231  /* compute min output value */
1232  if ((is_last_report || !ost->finished) && ost->st->pts.val != AV_NOPTS_VALUE)
1233  pts = FFMAX(pts, av_rescale_q(ost->st->pts.val,
1234  ost->st->time_base, AV_TIME_BASE_Q));
1235  }
1236 
1237  secs = pts / AV_TIME_BASE;
1238  us = pts % AV_TIME_BASE;
1239  mins = secs / 60;
1240  secs %= 60;
1241  hours = mins / 60;
1242  mins %= 60;
1243 
1244  bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
1245 
1246  if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1247  "size=N/A time=");
1248  else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1249  "size=%8.0fkB time=", total_size / 1024.0);
1250  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1251  "%02d:%02d:%02d.%02d ", hours, mins, secs,
1252  (100 * us) / AV_TIME_BASE);
1253  if (bitrate < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1254  "bitrate=N/A");
1255  else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1256  "bitrate=%6.1fkbits/s", bitrate);
1257  if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
1258  else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
1259  av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
1260  av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
1261  hours, mins, secs, us);
1262 
1264  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1266  av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
1267  av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
1268 
1269  if (print_stats || is_last_report) {
1270  if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
1271  fprintf(stderr, "%s \r", buf);
1272  } else
1273  av_log(NULL, AV_LOG_INFO, "%s \r", buf);
1274 
1275  fflush(stderr);
1276  }
1277 
1278  if (progress_avio) {
1279  av_bprintf(&buf_script, "progress=%s\n",
1280  is_last_report ? "end" : "continue");
1281  avio_write(progress_avio, buf_script.str,
1282  FFMIN(buf_script.len, buf_script.size - 1));
1283  avio_flush(progress_avio);
1284  av_bprint_finalize(&buf_script, NULL);
1285  if (is_last_report) {
1286  avio_close(progress_avio);
1287  progress_avio = NULL;
1288  }
1289  }
1290 
1291  if (is_last_report) {
1292  int64_t raw= audio_size + video_size + subtitle_size + extra_size;
1293  av_log(NULL, AV_LOG_INFO, "\n");
1294  av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
1295  video_size / 1024.0,
1296  audio_size / 1024.0,
1297  subtitle_size / 1024.0,
1298  extra_size / 1024.0,
1299  100.0 * (total_size - raw) / raw
1300  );
1301  if(video_size + audio_size + subtitle_size + extra_size == 0){
1302  av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
1303  }
1304  }
1305 }
1306 
1307 static void flush_encoders(void)
1308 {
1309  int i, ret;
1310 
1311  for (i = 0; i < nb_output_streams; i++) {
1312  OutputStream *ost = output_streams[i];
1313  AVCodecContext *enc = ost->st->codec;
1314  AVFormatContext *os = output_files[ost->file_index]->ctx;
1315  int stop_encoding = 0;
1316 
1317  if (!ost->encoding_needed)
1318  continue;
1319 
1320  if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1321  continue;
1323  continue;
1324 
1325  for (;;) {
1326  int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
1327  const char *desc;
1328  int64_t *size;
1329 
1330  switch (ost->st->codec->codec_type) {
1331  case AVMEDIA_TYPE_AUDIO:
1332  encode = avcodec_encode_audio2;
1333  desc = "Audio";
1334  size = &audio_size;
1335  break;
1336  case AVMEDIA_TYPE_VIDEO:
1337  encode = avcodec_encode_video2;
1338  desc = "Video";
1339  size = &video_size;
1340  break;
1341  default:
1342  stop_encoding = 1;
1343  }
1344 
1345  if (encode) {
1346  AVPacket pkt;
1347  int got_packet;
1348  av_init_packet(&pkt);
1349  pkt.data = NULL;
1350  pkt.size = 0;
1351 
1352  update_benchmark(NULL);
1353  ret = encode(enc, &pkt, NULL, &got_packet);
1354  update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
1355  if (ret < 0) {
1356  av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
1357  exit_program(1);
1358  }
1359  *size += pkt.size;
1360  if (ost->logfile && enc->stats_out) {
1361  fprintf(ost->logfile, "%s", enc->stats_out);
1362  }
1363  if (!got_packet) {
1364  stop_encoding = 1;
1365  break;
1366  }
1367  if (pkt.pts != AV_NOPTS_VALUE)
1368  pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1369  if (pkt.dts != AV_NOPTS_VALUE)
1370  pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1371  if (pkt.duration > 0)
1372  pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1373  write_frame(os, &pkt, ost);
1375  do_video_stats(ost, pkt.size);
1376  }
1377  }
1378 
1379  if (stop_encoding)
1380  break;
1381  }
1382  }
1383 }
1384 
1385 /*
1386  * Check whether a packet from ist should be written into ost at this time
1387  */
1389 {
1390  OutputFile *of = output_files[ost->file_index];
1391  int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
1392 
1393  if (ost->source_index != ist_index)
1394  return 0;
1395 
1396  if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
1397  return 0;
1398 
1399  return 1;
1400 }
1401 
1402 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1403 {
1404  OutputFile *of = output_files[ost->file_index];
1405  InputFile *f = input_files [ist->file_index];
1406  int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1407  int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
1408  int64_t ist_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ist->st->time_base);
1409  AVPicture pict;
1410  AVPacket opkt;
1411 
1412  av_init_packet(&opkt);
1413 
1414  if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1416  return;
1417 
1418  if (pkt->pts == AV_NOPTS_VALUE) {
1419  if (!ost->frame_number && ist->pts < start_time &&
1420  !ost->copy_prior_start)
1421  return;
1422  } else {
1423  if (!ost->frame_number && pkt->pts < ist_tb_start_time &&
1424  !ost->copy_prior_start)
1425  return;
1426  }
1427 
1428  if (of->recording_time != INT64_MAX &&
1429  ist->pts >= of->recording_time + start_time) {
1430  close_output_stream(ost);
1431  return;
1432  }
1433 
1434  if (f->recording_time != INT64_MAX) {
1435  start_time = f->ctx->start_time;
1436  if (f->start_time != AV_NOPTS_VALUE)
1437  start_time += f->start_time;
1438  if (ist->pts >= f->recording_time + start_time) {
1439  close_output_stream(ost);
1440  return;
1441  }
1442  }
1443 
1444  /* force the input stream PTS */
1445  if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1446  audio_size += pkt->size;
1447  else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1448  video_size += pkt->size;
1449  ost->sync_opts++;
1450  } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1451  subtitle_size += pkt->size;
1452  }
1453 
1454  if (pkt->pts != AV_NOPTS_VALUE)
1455  opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1456  else
1457  opkt.pts = AV_NOPTS_VALUE;
1458 
1459  if (pkt->dts == AV_NOPTS_VALUE)
1460  opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
1461  else
1462  opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1463  opkt.dts -= ost_tb_start_time;
1464 
1465  if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
1466  int duration = av_get_audio_frame_duration(ist->st->codec, pkt->size);
1467  if(!duration)
1468  duration = ist->st->codec->frame_size;
1469  opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
1471  ost->st->time_base) - ost_tb_start_time;
1472  }
1473 
1474  opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1475  opkt.flags = pkt->flags;
1476 
1477  // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1478  if ( ost->st->codec->codec_id != AV_CODEC_ID_H264
1479  && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
1480  && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
1481  && ost->st->codec->codec_id != AV_CODEC_ID_VC1
1482  ) {
1483  if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY)) {
1484  opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
1485  if (!opkt.buf)
1486  exit_program(1);
1487  }
1488  } else {
1489  opkt.data = pkt->data;
1490  opkt.size = pkt->size;
1491  }
1492 
1493  if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
1494  /* store AVPicture in AVPacket, as expected by the output format */
1495  avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1496  opkt.data = (uint8_t *)&pict;
1497  opkt.size = sizeof(AVPicture);
1498  opkt.flags |= AV_PKT_FLAG_KEY;
1499  }
1500 
1501  write_frame(of->ctx, &opkt, ost);
1502  ost->st->codec->frame_number++;
1503 }
1504 
1506 {
1507  AVCodecContext *dec = ist->st->codec;
1508 
1509  if (!dec->channel_layout) {
1510  char layout_name[256];
1511 
1512  if (dec->channels > ist->guess_layout_max)
1513  return 0;
1515  if (!dec->channel_layout)
1516  return 0;
1517  av_get_channel_layout_string(layout_name, sizeof(layout_name),
1518  dec->channels, dec->channel_layout);
1519  av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
1520  "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1521  }
1522  return 1;
1523 }
1524 
1525 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1526 {
1527  AVFrame *decoded_frame, *f;
1528  AVCodecContext *avctx = ist->st->codec;
1529  int i, ret, err = 0, resample_changed;
1530  AVRational decoded_frame_tb;
1531 
1532  if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1533  return AVERROR(ENOMEM);
1534  if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1535  return AVERROR(ENOMEM);
1536  decoded_frame = ist->decoded_frame;
1537 
1538  update_benchmark(NULL);
1539  ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1540  update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
1541 
1542  if (ret >= 0 && avctx->sample_rate <= 0) {
1543  av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
1544  ret = AVERROR_INVALIDDATA;
1545  }
1546 
1547  if (*got_output || ret<0 || pkt->size)
1548  decode_error_stat[ret<0] ++;
1549 
1550  if (!*got_output || ret < 0) {
1551  if (!pkt->size) {
1552  for (i = 0; i < ist->nb_filters; i++)
1553 #if 1
1554  av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
1555 #else
1556  av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
1557 #endif
1558  }
1559  return ret;
1560  }
1561 
1562 #if 1
1563  /* increment next_dts to use for the case where the input stream does not
1564  have timestamps or there are multiple frames in the packet */
1565  ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1566  avctx->sample_rate;
1567  ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1568  avctx->sample_rate;
1569 #endif
1570 
1571  resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
1572  ist->resample_channels != avctx->channels ||
1573  ist->resample_channel_layout != decoded_frame->channel_layout ||
1574  ist->resample_sample_rate != decoded_frame->sample_rate;
1575  if (resample_changed) {
1576  char layout1[64], layout2[64];
1577 
1578  if (!guess_input_channel_layout(ist)) {
1579  av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1580  "layout for Input Stream #%d.%d\n", ist->file_index,
1581  ist->st->index);
1582  exit_program(1);
1583  }
1584  decoded_frame->channel_layout = avctx->channel_layout;
1585 
1586  av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
1588  av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
1589  decoded_frame->channel_layout);
1590 
1591  av_log(NULL, AV_LOG_INFO,
1592  "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",
1593  ist->file_index, ist->st->index,
1595  ist->resample_channels, layout1,
1596  decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
1597  avctx->channels, layout2);
1598 
1599  ist->resample_sample_fmt = decoded_frame->format;
1600  ist->resample_sample_rate = decoded_frame->sample_rate;
1601  ist->resample_channel_layout = decoded_frame->channel_layout;
1602  ist->resample_channels = avctx->channels;
1603 
1604  for (i = 0; i < nb_filtergraphs; i++)
1605  if (ist_in_filtergraph(filtergraphs[i], ist)) {
1606  FilterGraph *fg = filtergraphs[i];
1607  int j;
1608  if (configure_filtergraph(fg) < 0) {
1609  av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1610  exit_program(1);
1611  }
1612  for (j = 0; j < fg->nb_outputs; j++) {
1613  OutputStream *ost = fg->outputs[j]->ost;
1614  if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
1617  ost->st->codec->frame_size);
1618  }
1619  }
1620  }
1621 
1622  /* if the decoder provides a pts, use it instead of the last packet pts.
1623  the decoder could be delaying output by a packet or more. */
1624  if (decoded_frame->pts != AV_NOPTS_VALUE) {
1625  ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
1626  decoded_frame_tb = avctx->time_base;
1627  } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
1628  decoded_frame->pts = decoded_frame->pkt_pts;
1629  pkt->pts = AV_NOPTS_VALUE;
1630  decoded_frame_tb = ist->st->time_base;
1631  } else if (pkt->pts != AV_NOPTS_VALUE) {
1632  decoded_frame->pts = pkt->pts;
1633  pkt->pts = AV_NOPTS_VALUE;
1634  decoded_frame_tb = ist->st->time_base;
1635  }else {
1636  decoded_frame->pts = ist->dts;
1637  decoded_frame_tb = AV_TIME_BASE_Q;
1638  }
1639  if (decoded_frame->pts != AV_NOPTS_VALUE)
1640  decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
1641  (AVRational){1, ist->st->codec->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
1642  (AVRational){1, ist->st->codec->sample_rate});
1643  for (i = 0; i < ist->nb_filters; i++) {
1644  if (i < ist->nb_filters - 1) {
1645  f = ist->filter_frame;
1646  err = av_frame_ref(f, decoded_frame);
1647  if (err < 0)
1648  break;
1649  } else
1650  f = decoded_frame;
1651  err = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,
1653  if (err == AVERROR_EOF)
1654  err = 0; /* ignore */
1655  if (err < 0)
1656  break;
1657  }
1658  decoded_frame->pts = AV_NOPTS_VALUE;
1659 
1660  av_frame_unref(ist->filter_frame);
1661  av_frame_unref(decoded_frame);
1662  return err < 0 ? err : ret;
1663 }
1664 
1665 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
1666 {
1667  AVFrame *decoded_frame, *f;
1668  void *buffer_to_free = NULL;
1669  int i, ret = 0, err = 0, resample_changed;
1670  int64_t best_effort_timestamp;
1671  AVRational *frame_sample_aspect;
1672 
1673  if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
1674  return AVERROR(ENOMEM);
1675  if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
1676  return AVERROR(ENOMEM);
1677  decoded_frame = ist->decoded_frame;
1678  pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
1679 
1680  update_benchmark(NULL);
1681  ret = avcodec_decode_video2(ist->st->codec,
1682  decoded_frame, got_output, pkt);
1683  update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
1684 
1685  if (*got_output || ret<0 || pkt->size)
1686  decode_error_stat[ret<0] ++;
1687 
1688  if (!*got_output || ret < 0) {
1689  if (!pkt->size) {
1690  for (i = 0; i < ist->nb_filters; i++)
1691 #if 1
1692  av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
1693 #else
1694  av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
1695 #endif
1696  }
1697  return ret;
1698  }
1699 
1700  if(ist->top_field_first>=0)
1701  decoded_frame->top_field_first = ist->top_field_first;
1702 
1703  best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
1704  if(best_effort_timestamp != AV_NOPTS_VALUE)
1705  ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
1706 
1707  if (debug_ts) {
1708  av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
1709  "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
1710  ist->st->index, av_ts2str(decoded_frame->pts),
1711  av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
1712  best_effort_timestamp,
1713  av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
1714  decoded_frame->key_frame, decoded_frame->pict_type);
1715  }
1716 
1717  pkt->size = 0;
1718 
1719  if (ist->st->sample_aspect_ratio.num)
1720  decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1721 
1722  resample_changed = ist->resample_width != decoded_frame->width ||
1723  ist->resample_height != decoded_frame->height ||
1724  ist->resample_pix_fmt != decoded_frame->format;
1725  if (resample_changed) {
1726  av_log(NULL, AV_LOG_INFO,
1727  "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1728  ist->file_index, ist->st->index,
1730  decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
1731 
1732  ist->resample_width = decoded_frame->width;
1733  ist->resample_height = decoded_frame->height;
1734  ist->resample_pix_fmt = decoded_frame->format;
1735 
1736  for (i = 0; i < nb_filtergraphs; i++) {
1737  if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
1738  configure_filtergraph(filtergraphs[i]) < 0) {
1739  av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1740  exit_program(1);
1741  }
1742  }
1743  }
1744 
1745  frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
1746  for (i = 0; i < ist->nb_filters; i++) {
1747  if (!frame_sample_aspect->num)
1748  *frame_sample_aspect = ist->st->sample_aspect_ratio;
1749 
1750  if (i < ist->nb_filters - 1) {
1751  f = ist->filter_frame;
1752  err = av_frame_ref(f, decoded_frame);
1753  if (err < 0)
1754  break;
1755  } else
1756  f = decoded_frame;
1758  if (ret == AVERROR_EOF) {
1759  ret = 0; /* ignore */
1760  } else if (ret < 0) {
1761  av_log(NULL, AV_LOG_FATAL,
1762  "Failed to inject frame into filter network: %s\n", av_err2str(ret));
1763  exit_program(1);
1764  }
1765  }
1766 
1768  av_frame_unref(decoded_frame);
1769  av_free(buffer_to_free);
1770  return err < 0 ? err : ret;
1771 }
1772 
1773 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1774 {
1775  AVSubtitle subtitle;
1776  int i, ret = avcodec_decode_subtitle2(ist->st->codec,
1777  &subtitle, got_output, pkt);
1778 
1779  if (*got_output || ret<0 || pkt->size)
1780  decode_error_stat[ret<0] ++;
1781 
1782  if (ret < 0 || !*got_output) {
1783  if (!pkt->size)
1784  sub2video_flush(ist);
1785  return ret;
1786  }
1787 
1788  if (ist->fix_sub_duration) {
1789  if (ist->prev_sub.got_output) {
1790  int end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
1791  1000, AV_TIME_BASE);
1792  if (end < ist->prev_sub.subtitle.end_display_time) {
1793  av_log(ist->st->codec, AV_LOG_DEBUG,
1794  "Subtitle duration reduced from %d to %d\n",
1795  ist->prev_sub.subtitle.end_display_time, end);
1797  }
1798  }
1799  FFSWAP(int, *got_output, ist->prev_sub.got_output);
1800  FFSWAP(int, ret, ist->prev_sub.ret);
1801  FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
1802  }
1803 
1804  sub2video_update(ist, &subtitle);
1805 
1806  if (!*got_output || !subtitle.num_rects)
1807  return ret;
1808 
1809  for (i = 0; i < nb_output_streams; i++) {
1810  OutputStream *ost = output_streams[i];
1811 
1812  if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1813  continue;
1814 
1815  do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
1816  }
1817 
1818  avsubtitle_free(&subtitle);
1819  return ret;
1820 }
1821 
1822 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1823 static int output_packet(InputStream *ist, const AVPacket *pkt)
1824 {
1825  int ret = 0, i;
1826  int got_output = 0;
1827 
1828  AVPacket avpkt;
1829  if (!ist->saw_first_ts) {
1830  ist->dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
1831  ist->pts = 0;
1832  if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
1833  ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1834  ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
1835  }
1836  ist->saw_first_ts = 1;
1837  }
1838 
1839  if (ist->next_dts == AV_NOPTS_VALUE)
1840  ist->next_dts = ist->dts;
1841  if (ist->next_pts == AV_NOPTS_VALUE)
1842  ist->next_pts = ist->pts;
1843 
1844  if (pkt == NULL) {
1845  /* EOF handling */
1846  av_init_packet(&avpkt);
1847  avpkt.data = NULL;
1848  avpkt.size = 0;
1849  goto handle_eof;
1850  } else {
1851  avpkt = *pkt;
1852  }
1853 
1854  if (pkt->dts != AV_NOPTS_VALUE) {
1855  ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1856  if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
1857  ist->next_pts = ist->pts = ist->dts;
1858  }
1859 
1860  // while we have more to decode or while the decoder did output something on EOF
1861  while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
1862  int duration;
1863  handle_eof:
1864 
1865  ist->pts = ist->next_pts;
1866  ist->dts = ist->next_dts;
1867 
1868  if (avpkt.size && avpkt.size != pkt->size) {
1870  "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1871  ist->showed_multi_packet_warning = 1;
1872  }
1873 
1874  switch (ist->st->codec->codec_type) {
1875  case AVMEDIA_TYPE_AUDIO:
1876  ret = decode_audio (ist, &avpkt, &got_output);
1877  break;
1878  case AVMEDIA_TYPE_VIDEO:
1879  ret = decode_video (ist, &avpkt, &got_output);
1880  if (avpkt.duration) {
1881  duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
1882  } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
1883  int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
1884  duration = ((int64_t)AV_TIME_BASE *
1885  ist->st->codec->time_base.num * ticks) /
1886  ist->st->codec->time_base.den;
1887  } else
1888  duration = 0;
1889 
1890  if(ist->dts != AV_NOPTS_VALUE && duration) {
1891  ist->next_dts += duration;
1892  }else
1893  ist->next_dts = AV_NOPTS_VALUE;
1894 
1895  if (got_output)
1896  ist->next_pts += duration; //FIXME the duration is not correct in some cases
1897  break;
1898  case AVMEDIA_TYPE_SUBTITLE:
1899  ret = transcode_subtitles(ist, &avpkt, &got_output);
1900  break;
1901  default:
1902  return -1;
1903  }
1904 
1905  if (ret < 0)
1906  return ret;
1907 
1908  avpkt.dts=
1909  avpkt.pts= AV_NOPTS_VALUE;
1910 
1911  // touch data and size only if not EOF
1912  if (pkt) {
1913  if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
1914  ret = avpkt.size;
1915  avpkt.data += ret;
1916  avpkt.size -= ret;
1917  }
1918  if (!got_output) {
1919  continue;
1920  }
1921  }
1922 
1923  /* handle stream copy */
1924  if (!ist->decoding_needed) {
1925  ist->dts = ist->next_dts;
1926  switch (ist->st->codec->codec_type) {
1927  case AVMEDIA_TYPE_AUDIO:
1928  ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1929  ist->st->codec->sample_rate;
1930  break;
1931  case AVMEDIA_TYPE_VIDEO:
1932  if (ist->framerate.num) {
1933  // TODO: Remove work-around for c99-to-c89 issue 7
1934  AVRational time_base_q = AV_TIME_BASE_Q;
1935  int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
1936  ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
1937  } else if (pkt->duration) {
1938  ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1939  } else if(ist->st->codec->time_base.num != 0) {
1940  int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
1941  ist->next_dts += ((int64_t)AV_TIME_BASE *
1942  ist->st->codec->time_base.num * ticks) /
1943  ist->st->codec->time_base.den;
1944  }
1945  break;
1946  }
1947  ist->pts = ist->dts;
1948  ist->next_pts = ist->next_dts;
1949  }
1950  for (i = 0; pkt && i < nb_output_streams; i++) {
1951  OutputStream *ost = output_streams[i];
1952 
1953  if (!check_output_constraints(ist, ost) || ost->encoding_needed)
1954  continue;
1955 
1956  do_streamcopy(ist, ost, pkt);
1957  }
1958 
1959  return 0;
1960 }
1961 
1962 static void print_sdp(void)
1963 {
1964  char sdp[16384];
1965  int i;
1966  AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
1967 
1968  if (!avc)
1969  exit_program(1);
1970  for (i = 0; i < nb_output_files; i++)
1971  avc[i] = output_files[i]->ctx;
1972 
1973  av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
1974  printf("SDP:\n%s\n", sdp);
1975  fflush(stdout);
1976  av_freep(&avc);
1977 }
1978 
1979 static int init_input_stream(int ist_index, char *error, int error_len)
1980 {
1981  int ret;
1982  InputStream *ist = input_streams[ist_index];
1983 
1984  if (ist->decoding_needed) {
1985  AVCodec *codec = ist->dec;
1986  if (!codec) {
1987  snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
1988  avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
1989  return AVERROR(EINVAL);
1990  }
1991 
1992  av_opt_set_int(ist->st->codec, "refcounted_frames", 1, 0);
1993 
1994  if (!av_dict_get(ist->opts, "threads", NULL, 0))
1995  av_dict_set(&ist->opts, "threads", "auto", 0);
1996  if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
1997  char errbuf[128];
1998  if (ret == AVERROR_EXPERIMENTAL)
1999  abort_codec_experimental(codec, 0);
2000 
2001  av_strerror(ret, errbuf, sizeof(errbuf));
2002 
2003  snprintf(error, error_len,
2004  "Error while opening decoder for input stream "
2005  "#%d:%d : %s",
2006  ist->file_index, ist->st->index, errbuf);
2007  return ret;
2008  }
2009  assert_avoptions(ist->opts);
2010  }
2011 
2012  ist->next_pts = AV_NOPTS_VALUE;
2013  ist->next_dts = AV_NOPTS_VALUE;
2014  ist->is_start = 1;
2015 
2016  return 0;
2017 }
2018 
2020 {
2021  if (ost->source_index >= 0)
2022  return input_streams[ost->source_index];
2023  return NULL;
2024 }
2025 
2026 static int compare_int64(const void *a, const void *b)
2027 {
2028  int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
2029  return va < vb ? -1 : va > vb ? +1 : 0;
2030 }
2031 
2032 static void parse_forced_key_frames(char *kf, OutputStream *ost,
2033  AVCodecContext *avctx)
2034 {
2035  char *p;
2036  int n = 1, i, size, index = 0;
2037  int64_t t, *pts;
2038 
2039  for (p = kf; *p; p++)
2040  if (*p == ',')
2041  n++;
2042  size = n;
2043  pts = av_malloc(sizeof(*pts) * size);
2044  if (!pts) {
2045  av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
2046  exit_program(1);
2047  }
2048 
2049  p = kf;
2050  for (i = 0; i < n; i++) {
2051  char *next = strchr(p, ',');
2052 
2053  if (next)
2054  *next++ = 0;
2055 
2056  if (!memcmp(p, "chapters", 8)) {
2057 
2058  AVFormatContext *avf = output_files[ost->file_index]->ctx;
2059  int j;
2060 
2061  if (avf->nb_chapters > INT_MAX - size ||
2062  !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
2063  sizeof(*pts)))) {
2064  av_log(NULL, AV_LOG_FATAL,
2065  "Could not allocate forced key frames array.\n");
2066  exit_program(1);
2067  }
2068  t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
2069  t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2070 
2071  for (j = 0; j < avf->nb_chapters; j++) {
2072  AVChapter *c = avf->chapters[j];
2073  av_assert1(index < size);
2074  pts[index++] = av_rescale_q(c->start, c->time_base,
2075  avctx->time_base) + t;
2076  }
2077 
2078  } else {
2079 
2080  t = parse_time_or_die("force_key_frames", p, 1);
2081  av_assert1(index < size);
2082  pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2083 
2084  }
2085 
2086  p = next;
2087  }
2088 
2089  av_assert0(index == size);
2090  qsort(pts, size, sizeof(*pts), compare_int64);
2091  ost->forced_kf_count = size;
2092  ost->forced_kf_pts = pts;
2093 }
2094 
2095 static void report_new_stream(int input_index, AVPacket *pkt)
2096 {
2097  InputFile *file = input_files[input_index];
2098  AVStream *st = file->ctx->streams[pkt->stream_index];
2099 
2100  if (pkt->stream_index < file->nb_streams_warn)
2101  return;
2102  av_log(file->ctx, AV_LOG_WARNING,
2103  "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
2105  input_index, pkt->stream_index,
2106  pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
2107  file->nb_streams_warn = pkt->stream_index + 1;
2108 }
2109 
2110 static int transcode_init(void)
2111 {
2112  int ret = 0, i, j, k;
2113  AVFormatContext *oc;
2114  AVCodecContext *codec;
2115  OutputStream *ost;
2116  InputStream *ist;
2117  char error[1024];
2118  int want_sdp = 1;
2119 
2120  for (i = 0; i < nb_filtergraphs; i++) {
2121  FilterGraph *fg = filtergraphs[i];
2122  for (j = 0; j < fg->nb_outputs; j++) {
2123  OutputFilter *ofilter = fg->outputs[j];
2124  if (!ofilter->ost || ofilter->ost->source_index >= 0)
2125  continue;
2126  if (fg->nb_inputs != 1)
2127  continue;
2128  for (k = nb_input_streams-1; k >= 0 ; k--)
2129  if (fg->inputs[0]->ist == input_streams[k])
2130  break;
2131  ofilter->ost->source_index = k;
2132  }
2133  }
2134 
2135  /* init framerate emulation */
2136  for (i = 0; i < nb_input_files; i++) {
2137  InputFile *ifile = input_files[i];
2138  if (ifile->rate_emu)
2139  for (j = 0; j < ifile->nb_streams; j++)
2140  input_streams[j + ifile->ist_index]->start = av_gettime();
2141  }
2142 
2143  /* output stream init */
2144  for (i = 0; i < nb_output_files; i++) {
2145  oc = output_files[i]->ctx;
2146  if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2147  av_dump_format(oc, i, oc->filename, 1);
2148  av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2149  return AVERROR(EINVAL);
2150  }
2151  }
2152 
2153  /* init complex filtergraphs */
2154  for (i = 0; i < nb_filtergraphs; i++)
2155  if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2156  return ret;
2157 
2158  /* for each output stream, we compute the right encoding parameters */
2159  for (i = 0; i < nb_output_streams; i++) {
2160  AVCodecContext *icodec = NULL;
2161  ost = output_streams[i];
2162  oc = output_files[ost->file_index]->ctx;
2163  ist = get_input_stream(ost);
2164 
2165  if (ost->attachment_filename)
2166  continue;
2167 
2168  codec = ost->st->codec;
2169 
2170  if (ist) {
2171  icodec = ist->st->codec;
2172 
2173  ost->st->disposition = ist->st->disposition;
2174  codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2176  } else {
2177  for (j=0; j<oc->nb_streams; j++) {
2178  AVStream *st = oc->streams[j];
2179  if (st != ost->st && st->codec->codec_type == codec->codec_type)
2180  break;
2181  }
2182  if (j == oc->nb_streams)
2183  if (codec->codec_type == AVMEDIA_TYPE_AUDIO || codec->codec_type == AVMEDIA_TYPE_VIDEO)
2185  }
2186 
2187  if (ost->stream_copy) {
2188  AVRational sar;
2189  uint64_t extra_size;
2190 
2191  av_assert0(ist && !ost->filter);
2192 
2193  extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2194 
2195  if (extra_size > INT_MAX) {
2196  return AVERROR(EINVAL);
2197  }
2198 
2199  /* if stream_copy is selected, no need to decode or encode */
2200  codec->codec_id = icodec->codec_id;
2201  codec->codec_type = icodec->codec_type;
2202 
2203  if (!codec->codec_tag) {
2204  unsigned int codec_tag;
2205  if (!oc->oformat->codec_tag ||
2206  av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2207  !av_codec_get_tag2(oc->oformat->codec_tag, icodec->codec_id, &codec_tag))
2208  codec->codec_tag = icodec->codec_tag;
2209  }
2210 
2211  codec->bit_rate = icodec->bit_rate;
2212  codec->rc_max_rate = icodec->rc_max_rate;
2213  codec->rc_buffer_size = icodec->rc_buffer_size;
2214  codec->field_order = icodec->field_order;
2215  codec->extradata = av_mallocz(extra_size);
2216  if (!codec->extradata) {
2217  return AVERROR(ENOMEM);
2218  }
2219  memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2220  codec->extradata_size= icodec->extradata_size;
2222 
2223  codec->time_base = ist->st->time_base;
2224  /*
2225  * Avi is a special case here because it supports variable fps but
2226  * having the fps and timebase differe significantly adds quite some
2227  * overhead
2228  */
2229  if(!strcmp(oc->oformat->name, "avi")) {
2230  if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
2231  && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
2232  && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
2233  && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
2234  || copy_tb==2){
2235  codec->time_base.num = ist->st->r_frame_rate.den;
2236  codec->time_base.den = 2*ist->st->r_frame_rate.num;
2237  codec->ticks_per_frame = 2;
2238  } else if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2239  && av_q2d(ist->st->time_base) < 1.0/500
2240  || copy_tb==0){
2241  codec->time_base = icodec->time_base;
2242  codec->time_base.num *= icodec->ticks_per_frame;
2243  codec->time_base.den *= 2;
2244  codec->ticks_per_frame = 2;
2245  }
2246  } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2247  && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2248  && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
2249  && strcmp(oc->oformat->name, "f4v")
2250  ) {
2251  if( copy_tb<0 && icodec->time_base.den
2252  && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
2253  && av_q2d(ist->st->time_base) < 1.0/500
2254  || copy_tb==0){
2255  codec->time_base = icodec->time_base;
2256  codec->time_base.num *= icodec->ticks_per_frame;
2257  }
2258  }
2259  if ( codec->codec_tag == AV_RL32("tmcd")
2260  && icodec->time_base.num < icodec->time_base.den
2261  && icodec->time_base.num > 0
2262  && 121LL*icodec->time_base.num > icodec->time_base.den) {
2263  codec->time_base = icodec->time_base;
2264  }
2265 
2266  if (ist && !ost->frame_rate.num)
2267  ost->frame_rate = ist->framerate;
2268  if(ost->frame_rate.num)
2269  codec->time_base = av_inv_q(ost->frame_rate);
2270 
2271  av_reduce(&codec->time_base.num, &codec->time_base.den,
2272  codec->time_base.num, codec->time_base.den, INT_MAX);
2273 
2274  switch (codec->codec_type) {
2275  case AVMEDIA_TYPE_AUDIO:
2276  if (audio_volume != 256) {
2277  av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2278  exit_program(1);
2279  }
2280  codec->channel_layout = icodec->channel_layout;
2281  codec->sample_rate = icodec->sample_rate;
2282  codec->channels = icodec->channels;
2283  codec->frame_size = icodec->frame_size;
2284  codec->audio_service_type = icodec->audio_service_type;
2285  codec->block_align = icodec->block_align;
2286  if((codec->block_align == 1 || codec->block_align == 1152 || codec->block_align == 576) && codec->codec_id == AV_CODEC_ID_MP3)
2287  codec->block_align= 0;
2288  if(codec->codec_id == AV_CODEC_ID_AC3)
2289  codec->block_align= 0;
2290  break;
2291  case AVMEDIA_TYPE_VIDEO:
2292  codec->pix_fmt = icodec->pix_fmt;
2293  codec->width = icodec->width;
2294  codec->height = icodec->height;
2295  codec->has_b_frames = icodec->has_b_frames;
2296  if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
2297  sar =
2299  (AVRational){ codec->height, codec->width });
2300  av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
2301  "with stream copy may produce invalid files\n");
2302  }
2303  else if (ist->st->sample_aspect_ratio.num)
2304  sar = ist->st->sample_aspect_ratio;
2305  else
2306  sar = icodec->sample_aspect_ratio;
2307  ost->st->sample_aspect_ratio = codec->sample_aspect_ratio = sar;
2308  ost->st->avg_frame_rate = ist->st->avg_frame_rate;
2309  break;
2310  case AVMEDIA_TYPE_SUBTITLE:
2311  codec->width = icodec->width;
2312  codec->height = icodec->height;
2313  break;
2314  case AVMEDIA_TYPE_DATA:
2316  break;
2317  default:
2318  abort();
2319  }
2320  } else {
2321  if (!ost->enc)
2322  ost->enc = avcodec_find_encoder(codec->codec_id);
2323  if (!ost->enc) {
2324  /* should only happen when a default codec is not present. */
2325  snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
2326  avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
2327  ret = AVERROR(EINVAL);
2328  goto dump_format;
2329  }
2330 
2331  if (ist)
2332  ist->decoding_needed++;
2333  ost->encoding_needed = 1;
2334 
2335  if (!ost->filter &&
2336  (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2337  codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
2338  FilterGraph *fg;
2339  fg = init_simple_filtergraph(ist, ost);
2340  if (configure_filtergraph(fg)) {
2341  av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2342  exit_program(1);
2343  }
2344  }
2345 
2346  if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2347  if (ost->filter && !ost->frame_rate.num)
2349  if (ist && !ost->frame_rate.num)
2350  ost->frame_rate = ist->framerate;
2351  if (ist && !ost->frame_rate.num)
2352  ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
2353 // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
2354  if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2356  ost->frame_rate = ost->enc->supported_framerates[idx];
2357  }
2358  }
2359 
2360  switch (codec->codec_type) {
2361  case AVMEDIA_TYPE_AUDIO:
2362  codec->sample_fmt = ost->filter->filter->inputs[0]->format;
2363  codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
2364  codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2366  codec->time_base = (AVRational){ 1, codec->sample_rate };
2367  break;
2368  case AVMEDIA_TYPE_VIDEO:
2369  codec->time_base = av_inv_q(ost->frame_rate);
2370  if (ost->filter && !(codec->time_base.num && codec->time_base.den))
2371  codec->time_base = ost->filter->filter->inputs[0]->time_base;
2372  if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
2374  av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
2375  "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
2376  }
2377  for (j = 0; j < ost->forced_kf_count; j++)
2378  ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
2380  codec->time_base);
2381 
2382  codec->width = ost->filter->filter->inputs[0]->w;
2383  codec->height = ost->filter->filter->inputs[0]->h;
2384  codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
2385  ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
2386  av_mul_q(ost->frame_aspect_ratio, (AVRational){ codec->height, codec->width }) :
2388  if (!strncmp(ost->enc->name, "libx264", 7) &&
2389  codec->pix_fmt == AV_PIX_FMT_NONE &&
2391  av_log(NULL, AV_LOG_WARNING,
2392  "No pixel format specified, %s for H.264 encoding chosen.\n"
2393  "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
2395  if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
2396  codec->pix_fmt == AV_PIX_FMT_NONE &&
2398  av_log(NULL, AV_LOG_WARNING,
2399  "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
2400  "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
2402  codec->pix_fmt = ost->filter->filter->inputs[0]->format;
2403 
2404  if (!icodec ||
2405  codec->width != icodec->width ||
2406  codec->height != icodec->height ||
2407  codec->pix_fmt != icodec->pix_fmt) {
2409  }
2410 
2411  if (ost->forced_keyframes) {
2412  if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
2414  forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
2415  if (ret < 0) {
2416  av_log(NULL, AV_LOG_ERROR,
2417  "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
2418  return ret;
2419  }
2424  } else {
2426  }
2427  }
2428  break;
2429  case AVMEDIA_TYPE_SUBTITLE:
2430  codec->time_base = (AVRational){1, 1000};
2431  if (!codec->width) {
2432  codec->width = input_streams[ost->source_index]->st->codec->width;
2433  codec->height = input_streams[ost->source_index]->st->codec->height;
2434  }
2435  break;
2436  default:
2437  abort();
2438  break;
2439  }
2440  /* two pass mode */
2441  if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
2442  char logfilename[1024];
2443  FILE *f;
2444 
2445  snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2446  ost->logfile_prefix ? ost->logfile_prefix :
2448  i);
2449  if (!strcmp(ost->enc->name, "libx264")) {
2450  av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2451  } else {
2452  if (codec->flags & CODEC_FLAG_PASS2) {
2453  char *logbuffer;
2454  size_t logbuffer_size;
2455  if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2456  av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2457  logfilename);
2458  exit_program(1);
2459  }
2460  codec->stats_in = logbuffer;
2461  }
2462  if (codec->flags & CODEC_FLAG_PASS1) {
2463  f = fopen(logfilename, "wb");
2464  if (!f) {
2465  av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2466  logfilename, strerror(errno));
2467  exit_program(1);
2468  }
2469  ost->logfile = f;
2470  }
2471  }
2472  }
2473  }
2474  }
2475 
2476  /* open each encoder */
2477  for (i = 0; i < nb_output_streams; i++) {
2478  ost = output_streams[i];
2479  if (ost->encoding_needed) {
2480  AVCodec *codec = ost->enc;
2481  AVCodecContext *dec = NULL;
2482 
2483  if ((ist = get_input_stream(ost)))
2484  dec = ist->st->codec;
2485  if (dec && dec->subtitle_header) {
2486  /* ASS code assumes this buffer is null terminated so add extra byte. */
2487  ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
2488  if (!ost->st->codec->subtitle_header) {
2489  ret = AVERROR(ENOMEM);
2490  goto dump_format;
2491  }
2492  memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2493  ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
2494  }
2495  if (!av_dict_get(ost->opts, "threads", NULL, 0))
2496  av_dict_set(&ost->opts, "threads", "auto", 0);
2497  if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
2498  if (ret == AVERROR_EXPERIMENTAL)
2499  abort_codec_experimental(codec, 1);
2500  snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2501  ost->file_index, ost->index);
2502  goto dump_format;
2503  }
2504  if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
2505  !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
2506  av_buffersink_set_frame_size(ost->filter->filter,
2507  ost->st->codec->frame_size);
2508  assert_avoptions(ost->opts);
2509  if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2510  av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2511  " It takes bits/s as argument, not kbits/s\n");
2512  extra_size += ost->st->codec->extradata_size;
2513 
2514  if (ost->st->codec->me_threshold)
2515  input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
2516  } else {
2517  av_opt_set_dict(ost->st->codec, &ost->opts);
2518  }
2519  }
2520 
2521  /* init input streams */
2522  for (i = 0; i < nb_input_streams; i++)
2523  if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
2524  for (i = 0; i < nb_output_streams; i++) {
2525  ost = output_streams[i];
2526  avcodec_close(ost->st->codec);
2527  }
2528  goto dump_format;
2529  }
2530 
2531  /* discard unused programs */
2532  for (i = 0; i < nb_input_files; i++) {
2533  InputFile *ifile = input_files[i];
2534  for (j = 0; j < ifile->ctx->nb_programs; j++) {
2535  AVProgram *p = ifile->ctx->programs[j];
2536  int discard = AVDISCARD_ALL;
2537 
2538  for (k = 0; k < p->nb_stream_indexes; k++)
2539  if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2540  discard = AVDISCARD_DEFAULT;
2541  break;
2542  }
2543  p->discard = discard;
2544  }
2545  }
2546 
2547  /* open files and write file headers */
2548  for (i = 0; i < nb_output_files; i++) {
2549  oc = output_files[i]->ctx;
2550  oc->interrupt_callback = int_cb;
2551  if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
2552  char errbuf[128];
2553  av_strerror(ret, errbuf, sizeof(errbuf));
2554  snprintf(error, sizeof(error),
2555  "Could not write header for output file #%d "
2556  "(incorrect codec parameters ?): %s",
2557  i, errbuf);
2558  ret = AVERROR(EINVAL);
2559  goto dump_format;
2560  }
2561 // assert_avoptions(output_files[i]->opts);
2562  if (strcmp(oc->oformat->name, "rtp")) {
2563  want_sdp = 0;
2564  }
2565  }
2566 
2567  dump_format:
2568  /* dump the file output parameters - cannot be done before in case
2569  of stream copy */
2570  for (i = 0; i < nb_output_files; i++) {
2571  av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
2572  }
2573 
2574  /* dump the stream mapping */
2575  av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2576  for (i = 0; i < nb_input_streams; i++) {
2577  ist = input_streams[i];
2578 
2579  for (j = 0; j < ist->nb_filters; j++) {
2580  if (ist->filters[j]->graph->graph_desc) {
2581  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
2582  ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2583  ist->filters[j]->name);
2584  if (nb_filtergraphs > 1)
2585  av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2586  av_log(NULL, AV_LOG_INFO, "\n");
2587  }
2588  }
2589  }
2590 
2591  for (i = 0; i < nb_output_streams; i++) {
2592  ost = output_streams[i];
2593 
2594  if (ost->attachment_filename) {
2595  /* an attached file */
2596  av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2597  ost->attachment_filename, ost->file_index, ost->index);
2598  continue;
2599  }
2600 
2601  if (ost->filter && ost->filter->graph->graph_desc) {
2602  /* output from a complex graph */
2603  av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
2604  if (nb_filtergraphs > 1)
2605  av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2606 
2607  av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2608  ost->index, ost->enc ? ost->enc->name : "?");
2609  continue;
2610  }
2611 
2612  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2613  input_streams[ost->source_index]->file_index,
2614  input_streams[ost->source_index]->st->index,
2615  ost->file_index,
2616  ost->index);
2617  if (ost->sync_ist != input_streams[ost->source_index])
2618  av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2619  ost->sync_ist->file_index,
2620  ost->sync_ist->st->index);
2621  if (ost->stream_copy)
2622  av_log(NULL, AV_LOG_INFO, " (copy)");
2623  else
2624  av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
2625  input_streams[ost->source_index]->dec->name : "?",
2626  ost->enc ? ost->enc->name : "?");
2627  av_log(NULL, AV_LOG_INFO, "\n");
2628  }
2629 
2630  if (ret) {
2631  av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2632  return ret;
2633  }
2634 
2635  if (want_sdp) {
2636  print_sdp();
2637  }
2638 
2639  return 0;
2640 }
2641 
2642 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
2643 static int need_output(void)
2644 {
2645  int i;
2646 
2647  for (i = 0; i < nb_output_streams; i++) {
2648  OutputStream *ost = output_streams[i];
2649  OutputFile *of = output_files[ost->file_index];
2650  AVFormatContext *os = output_files[ost->file_index]->ctx;
2651 
2652  if (ost->finished ||
2653  (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2654  continue;
2655  if (ost->frame_number >= ost->max_frames) {
2656  int j;
2657  for (j = 0; j < of->ctx->nb_streams; j++)
2658  close_output_stream(output_streams[of->ost_index + j]);
2659  continue;
2660  }
2661 
2662  return 1;
2663  }
2664 
2665  return 0;
2666 }
2667 
2668 /**
2669  * Select the output stream to process.
2670  *
2671  * @return selected output stream, or NULL if none available
2672  */
2674 {
2675  int i;
2676  int64_t opts_min = INT64_MAX;
2677  OutputStream *ost_min = NULL;
2678 
2679  for (i = 0; i < nb_output_streams; i++) {
2680  OutputStream *ost = output_streams[i];
2681  int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
2682  AV_TIME_BASE_Q);
2683  if (!ost->unavailable && !ost->finished && opts < opts_min) {
2684  opts_min = opts;
2685  ost_min = ost;
2686  }
2687  }
2688  return ost_min;
2689 }
2690 
2692 {
2693  int i, ret, key;
2694  static int64_t last_time;
2695  if (received_nb_signals)
2696  return AVERROR_EXIT;
2697  /* read_key() returns 0 on EOF */
2698  if(cur_time - last_time >= 100000 && !run_as_daemon){
2699  key = read_key();
2700  last_time = cur_time;
2701  }else
2702  key = -1;
2703  if (key == 'q')
2704  return AVERROR_EXIT;
2705  if (key == '+') av_log_set_level(av_log_get_level()+10);
2706  if (key == '-') av_log_set_level(av_log_get_level()-10);
2707  if (key == 's') qp_hist ^= 1;
2708  if (key == 'h'){
2709  if (do_hex_dump){
2710  do_hex_dump = do_pkt_dump = 0;
2711  } else if(do_pkt_dump){
2712  do_hex_dump = 1;
2713  } else
2714  do_pkt_dump = 1;
2716  }
2717  if (key == 'c' || key == 'C'){
2718  char buf[4096], target[64], command[256], arg[256] = {0};
2719  double time;
2720  int k, n = 0;
2721  fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
2722  i = 0;
2723  while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
2724  if (k > 0)
2725  buf[i++] = k;
2726  buf[i] = 0;
2727  if (k > 0 &&
2728  (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
2729  av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
2730  target, time, command, arg);
2731  for (i = 0; i < nb_filtergraphs; i++) {
2732  FilterGraph *fg = filtergraphs[i];
2733  if (fg->graph) {
2734  if (time < 0) {
2735  ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
2736  key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
2737  fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
2738  } else if (key == 'c') {
2739  fprintf(stderr, "Queing commands only on filters supporting the specific command is unsupported\n");
2740  ret = AVERROR_PATCHWELCOME;
2741  } else {
2742  ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
2743  }
2744  }
2745  }
2746  } else {
2747  av_log(NULL, AV_LOG_ERROR,
2748  "Parse error, at least 3 arguments were expected, "
2749  "only %d given in string '%s'\n", n, buf);
2750  }
2751  }
2752  if (key == 'd' || key == 'D'){
2753  int debug=0;
2754  if(key == 'D') {
2755  debug = input_streams[0]->st->codec->debug<<1;
2756  if(!debug) debug = 1;
2757  while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
2758  debug += debug;
2759  }else
2760  if(scanf("%d", &debug)!=1)
2761  fprintf(stderr,"error parsing debug value\n");
2762  for(i=0;i<nb_input_streams;i++) {
2763  input_streams[i]->st->codec->debug = debug;
2764  }
2765  for(i=0;i<nb_output_streams;i++) {
2766  OutputStream *ost = output_streams[i];
2767  ost->st->codec->debug = debug;
2768  }
2769  if(debug) av_log_set_level(AV_LOG_DEBUG);
2770  fprintf(stderr,"debug=%d\n", debug);
2771  }
2772  if (key == '?'){
2773  fprintf(stderr, "key function\n"
2774  "? show this help\n"
2775  "+ increase verbosity\n"
2776  "- decrease verbosity\n"
2777  "c Send command to first matching filter supporting it\n"
2778  "C Send/Que command to all matching filters\n"
2779  "D cycle through available debug modes\n"
2780  "h dump packets/hex press to cycle through the 3 states\n"
2781  "q quit\n"
2782  "s Show QP histogram\n"
2783  );
2784  }
2785  return 0;
2786 }
2787 
2788 #if HAVE_PTHREADS
2789 static void *input_thread(void *arg)
2790 {
2791  InputFile *f = arg;
2792  int ret = 0;
2793 
2794  while (!transcoding_finished && ret >= 0) {
2795  AVPacket pkt;
2796  ret = av_read_frame(f->ctx, &pkt);
2797 
2798  if (ret == AVERROR(EAGAIN)) {
2799  av_usleep(10000);
2800  ret = 0;
2801  continue;
2802  } else if (ret < 0)
2803  break;
2804 
2806  while (!av_fifo_space(f->fifo))
2808 
2809  av_dup_packet(&pkt);
2810  av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2811 
2813  }
2814 
2815  f->finished = 1;
2816  return NULL;
2817 }
2818 
2819 static void free_input_threads(void)
2820 {
2821  int i;
2822 
2823  if (nb_input_files == 1)
2824  return;
2825 
2827 
2828  for (i = 0; i < nb_input_files; i++) {
2829  InputFile *f = input_files[i];
2830  AVPacket pkt;
2831 
2832  if (!f->fifo || f->joined)
2833  continue;
2834 
2836  while (av_fifo_size(f->fifo)) {
2837  av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2838  av_free_packet(&pkt);
2839  }
2842 
2843  pthread_join(f->thread, NULL);
2844  f->joined = 1;
2845 
2846  while (av_fifo_size(f->fifo)) {
2847  av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2848  av_free_packet(&pkt);
2849  }
2850  av_fifo_free(f->fifo);
2851  }
2852 }
2853 
2854 static int init_input_threads(void)
2855 {
2856  int i, ret;
2857 
2858  if (nb_input_files == 1)
2859  return 0;
2860 
2861  for (i = 0; i < nb_input_files; i++) {
2862  InputFile *f = input_files[i];
2863 
2864  if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2865  return AVERROR(ENOMEM);
2866 
2867  pthread_mutex_init(&f->fifo_lock, NULL);
2868  pthread_cond_init (&f->fifo_cond, NULL);
2869 
2870  if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2871  return AVERROR(ret);
2872  }
2873  return 0;
2874 }
2875 
2877 {
2878  int ret = 0;
2879 
2881 
2882  if (av_fifo_size(f->fifo)) {
2883  av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2885  } else {
2886  if (f->finished)
2887  ret = AVERROR_EOF;
2888  else
2889  ret = AVERROR(EAGAIN);
2890  }
2891 
2893 
2894  return ret;
2895 }
2896 #endif
2897 
2899 {
2900  if (f->rate_emu) {
2901  int i;
2902  for (i = 0; i < f->nb_streams; i++) {
2903  InputStream *ist = input_streams[f->ist_index + i];
2904  int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
2905  int64_t now = av_gettime() - ist->start;
2906  if (pts > now)
2907  return AVERROR(EAGAIN);
2908  }
2909  }
2910 
2911 #if HAVE_PTHREADS
2912  if (nb_input_files > 1)
2913  return get_input_packet_mt(f, pkt);
2914 #endif
2915  return av_read_frame(f->ctx, pkt);
2916 }
2917 
2918 static int got_eagain(void)
2919 {
2920  int i;
2921  for (i = 0; i < nb_output_streams; i++)
2922  if (output_streams[i]->unavailable)
2923  return 1;
2924  return 0;
2925 }
2926 
2927 static void reset_eagain(void)
2928 {
2929  int i;
2930  for (i = 0; i < nb_input_files; i++)
2931  input_files[i]->eagain = 0;
2932  for (i = 0; i < nb_output_streams; i++)
2933  output_streams[i]->unavailable = 0;
2934 }
2935 
2936 /*
2937  * Return
2938  * - 0 -- one packet was read and processed
2939  * - AVERROR(EAGAIN) -- no packets were available for selected file,
2940  * this function should be called again
2941  * - AVERROR_EOF -- this function should not be called again
2942  */
2943 static int process_input(int file_index)
2944 {
2945  InputFile *ifile = input_files[file_index];
2946  AVFormatContext *is;
2947  InputStream *ist;
2948  AVPacket pkt;
2949  int ret, i, j;
2950 
2951  is = ifile->ctx;
2952  ret = get_input_packet(ifile, &pkt);
2953 
2954  if (ret == AVERROR(EAGAIN)) {
2955  ifile->eagain = 1;
2956  return ret;
2957  }
2958  if (ret < 0) {
2959  if (ret != AVERROR_EOF) {
2960  print_error(is->filename, ret);
2961  if (exit_on_error)
2962  exit_program(1);
2963  }
2964  ifile->eof_reached = 1;
2965 
2966  for (i = 0; i < ifile->nb_streams; i++) {
2967  ist = input_streams[ifile->ist_index + i];
2968  if (ist->decoding_needed)
2969  output_packet(ist, NULL);
2970 
2971  /* mark all outputs that don't go through lavfi as finished */
2972  for (j = 0; j < nb_output_streams; j++) {
2973  OutputStream *ost = output_streams[j];
2974 
2975  if (ost->source_index == ifile->ist_index + i &&
2976  (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
2977  close_output_stream(ost);
2978  }
2979  }
2980 
2981  return AVERROR(EAGAIN);
2982  }
2983 
2984  reset_eagain();
2985 
2986  if (do_pkt_dump) {
2988  is->streams[pkt.stream_index]);
2989  }
2990  /* the following test is needed in case new streams appear
2991  dynamically in stream : we ignore them */
2992  if (pkt.stream_index >= ifile->nb_streams) {
2993  report_new_stream(file_index, &pkt);
2994  goto discard_packet;
2995  }
2996 
2997  ist = input_streams[ifile->ist_index + pkt.stream_index];
2998  if (ist->discard)
2999  goto discard_packet;
3000 
3001  if (debug_ts) {
3002  av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
3003  "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
3007  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3008  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3009  av_ts2str(input_files[ist->file_index]->ts_offset),
3010  av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3011  }
3012 
3013  if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
3014  int64_t stime, stime2;
3015  // Correcting starttime based on the enabled streams
3016  // FIXME this ideally should be done before the first use of starttime but we do not know which are the enabled streams at that point.
3017  // so we instead do it here as part of discontinuity handling
3018  if ( ist->next_dts == AV_NOPTS_VALUE
3019  && ifile->ts_offset == -is->start_time
3020  && (is->iformat->flags & AVFMT_TS_DISCONT)) {
3021  int64_t new_start_time = INT64_MAX;
3022  for (i=0; i<is->nb_streams; i++) {
3023  AVStream *st = is->streams[i];
3024  if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
3025  continue;
3026  new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
3027  }
3028  if (new_start_time > is->start_time) {
3029  av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
3030  ifile->ts_offset = -new_start_time;
3031  }
3032  }
3033 
3034  stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
3035  stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
3036  ist->wrap_correction_done = 1;
3037 
3038  if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
3039  pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
3040  ist->wrap_correction_done = 0;
3041  }
3042  if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
3043  pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
3044  ist->wrap_correction_done = 0;
3045  }
3046  }
3047 
3048  if (pkt.dts != AV_NOPTS_VALUE)
3049  pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3050  if (pkt.pts != AV_NOPTS_VALUE)
3051  pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
3052 
3053  if (pkt.pts != AV_NOPTS_VALUE)
3054  pkt.pts *= ist->ts_scale;
3055  if (pkt.dts != AV_NOPTS_VALUE)
3056  pkt.dts *= ist->ts_scale;
3057 
3058  if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
3059  && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
3060  int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3061  int64_t delta = pkt_dts - ifile->last_ts;
3062  if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3063  (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3065  ifile->ts_offset -= delta;
3066  av_log(NULL, AV_LOG_DEBUG,
3067  "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3068  delta, ifile->ts_offset);
3069  pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3070  if (pkt.pts != AV_NOPTS_VALUE)
3071  pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3072  }
3073  }
3074 
3075  if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
3076  !copy_ts) {
3077  int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3078  int64_t delta = pkt_dts - ist->next_dts;
3079  if (is->iformat->flags & AVFMT_TS_DISCONT) {
3080  if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
3081  (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
3083  pkt_dts + AV_TIME_BASE/10 < ist->pts){
3084  ifile->ts_offset -= delta;
3085  av_log(NULL, AV_LOG_DEBUG,
3086  "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
3087  delta, ifile->ts_offset);
3088  pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3089  if (pkt.pts != AV_NOPTS_VALUE)
3090  pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
3091  }
3092  } else {
3093  if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3095  ) {
3096  av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
3097  pkt.dts = AV_NOPTS_VALUE;
3098  }
3099  if (pkt.pts != AV_NOPTS_VALUE){
3100  int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3101  delta = pkt_pts - ist->next_dts;
3102  if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3104  ) {
3105  av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3106  pkt.pts = AV_NOPTS_VALUE;
3107  }
3108  }
3109  }
3110  }
3111 
3112  if (pkt.dts != AV_NOPTS_VALUE)
3113  ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
3114 
3115  if (debug_ts) {
3116  av_log(NULL, AV_LOG_INFO, "demuxer+ffmpeg -> ist_index:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
3118  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3119  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3120  av_ts2str(input_files[ist->file_index]->ts_offset),
3121  av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3122  }
3123 
3124  sub2video_heartbeat(ist, pkt.pts);
3125 
3126  ret = output_packet(ist, &pkt);
3127  if (ret < 0) {
3128  char buf[128];
3129  av_strerror(ret, buf, sizeof(buf));
3130  av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
3131  ist->file_index, ist->st->index, buf);
3132  if (exit_on_error)
3133  exit_program(1);
3134  }
3135 
3136 discard_packet:
3137  av_free_packet(&pkt);
3138 
3139  return 0;
3140 }
3141 
3142 /**
3143  * Perform a step of transcoding for the specified filter graph.
3144  *
3145  * @param[in] graph filter graph to consider
3146  * @param[out] best_ist input stream where a frame would allow to continue
3147  * @return 0 for success, <0 for error
3148  */
3149 static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
3150 {
3151  int i, ret;
3152  int nb_requests, nb_requests_max = 0;
3153  InputFilter *ifilter;
3154  InputStream *ist;
3155 
3156  *best_ist = NULL;
3157  ret = avfilter_graph_request_oldest(graph->graph);
3158  if (ret >= 0)
3159  return reap_filters();
3160 
3161  if (ret == AVERROR_EOF) {
3162  ret = reap_filters();
3163  for (i = 0; i < graph->nb_outputs; i++)
3164  close_output_stream(graph->outputs[i]->ost);
3165  return ret;
3166  }
3167  if (ret != AVERROR(EAGAIN))
3168  return ret;
3169 
3170  for (i = 0; i < graph->nb_inputs; i++) {
3171  ifilter = graph->inputs[i];
3172  ist = ifilter->ist;
3173  if (input_files[ist->file_index]->eagain ||
3174  input_files[ist->file_index]->eof_reached)
3175  continue;
3176  nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
3177  if (nb_requests > nb_requests_max) {
3178  nb_requests_max = nb_requests;
3179  *best_ist = ist;
3180  }
3181  }
3182 
3183  if (!*best_ist)
3184  for (i = 0; i < graph->nb_outputs; i++)
3185  graph->outputs[i]->ost->unavailable = 1;
3186 
3187  return 0;
3188 }
3189 
3190 /**
3191  * Run a single step of transcoding.
3192  *
3193  * @return 0 for success, <0 for error
3194  */
3195 static int transcode_step(void)
3196 {
3197  OutputStream *ost;
3198  InputStream *ist;
3199  int ret;
3200 
3201  ost = choose_output();
3202  if (!ost) {
3203  if (got_eagain()) {
3204  reset_eagain();
3205  av_usleep(10000);
3206  return 0;
3207  }
3208  av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
3209  return AVERROR_EOF;
3210  }
3211 
3212  if (ost->filter) {
3213  if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
3214  return ret;
3215  if (!ist)
3216  return 0;
3217  } else {
3218  av_assert0(ost->source_index >= 0);
3219  ist = input_streams[ost->source_index];
3220  }
3221 
3222  ret = process_input(ist->file_index);
3223  if (ret == AVERROR(EAGAIN)) {
3224  if (input_files[ist->file_index]->eagain)
3225  ost->unavailable = 1;
3226  return 0;
3227  }
3228  if (ret < 0)
3229  return ret == AVERROR_EOF ? 0 : ret;
3230 
3231  return reap_filters();
3232 }
3233 
3234 /*
3235  * The following code is the main loop of the file converter
3236  */
3237 static int transcode(void)
3238 {
3239  int ret, i;
3240  AVFormatContext *os;
3241  OutputStream *ost;
3242  InputStream *ist;
3243  int64_t timer_start;
3244 
3245  ret = transcode_init();
3246  if (ret < 0)
3247  goto fail;
3248 
3249  if (stdin_interaction) {
3250  av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3251  }
3252 
3253  timer_start = av_gettime();
3254 
3255 #if HAVE_PTHREADS
3256  if ((ret = init_input_threads()) < 0)
3257  goto fail;
3258 #endif
3259 
3260  while (!received_sigterm) {
3261  int64_t cur_time= av_gettime();
3262 
3263  /* if 'q' pressed, exits */
3264  if (stdin_interaction)
3265  if (check_keyboard_interaction(cur_time) < 0)
3266  break;
3267 
3268  /* check if there's any stream where output is still needed */
3269  if (!need_output()) {
3270  av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
3271  break;
3272  }
3273 
3274  ret = transcode_step();
3275  if (ret < 0) {
3276  if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
3277  continue;
3278 
3279  av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
3280  break;
3281  }
3282 
3283  /* dump report by using the output first video and audio streams */
3284  print_report(0, timer_start, cur_time);
3285  }
3286 #if HAVE_PTHREADS
3288 #endif
3289 
3290  /* at the end of stream, we must flush the decoder buffers */
3291  for (i = 0; i < nb_input_streams; i++) {
3292  ist = input_streams[i];
3293  if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3294  output_packet(ist, NULL);
3295  }
3296  }
3297  flush_encoders();
3298 
3299  term_exit();
3300 
3301  /* write the trailer if needed and close file */
3302  for (i = 0; i < nb_output_files; i++) {
3303  os = output_files[i]->ctx;
3304  av_write_trailer(os);
3305  }
3306 
3307  /* dump report by using the first video and audio streams */
3308  print_report(1, timer_start, av_gettime());
3309 
3310  /* close each encoder */
3311  for (i = 0; i < nb_output_streams; i++) {
3312  ost = output_streams[i];
3313  if (ost->encoding_needed) {
3314  av_freep(&ost->st->codec->stats_in);
3315  avcodec_close(ost->st->codec);
3316  }
3317  }
3318 
3319  /* close each decoder */
3320  for (i = 0; i < nb_input_streams; i++) {
3321  ist = input_streams[i];
3322  if (ist->decoding_needed) {
3323  avcodec_close(ist->st->codec);
3324  }
3325  }
3326 
3327  /* finished ! */
3328  ret = 0;
3329 
3330  fail:
3331 #if HAVE_PTHREADS
3333 #endif
3334 
3335  if (output_streams) {
3336  for (i = 0; i < nb_output_streams; i++) {
3337  ost = output_streams[i];
3338  if (ost) {
3339  if (ost->stream_copy)
3340  av_freep(&ost->st->codec->extradata);
3341  if (ost->logfile) {
3342  fclose(ost->logfile);
3343  ost->logfile = NULL;
3344  }
3345  av_freep(&ost->st->codec->subtitle_header);
3346  av_freep(&ost->forced_kf_pts);
3347  av_freep(&ost->apad);
3348  av_dict_free(&ost->opts);
3349  av_dict_free(&ost->swr_opts);
3350  av_dict_free(&ost->resample_opts);
3351  }
3352  }
3353  }
3354  return ret;
3355 }
3356 
3357 
3358 static int64_t getutime(void)
3359 {
3360 #if HAVE_GETRUSAGE
3361  struct rusage rusage;
3362 
3363  getrusage(RUSAGE_SELF, &rusage);
3364  return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3365 #elif HAVE_GETPROCESSTIMES
3366  HANDLE proc;
3367  FILETIME c, e, k, u;
3368  proc = GetCurrentProcess();
3369  GetProcessTimes(proc, &c, &e, &k, &u);
3370  return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3371 #else
3372  return av_gettime();
3373 #endif
3374 }
3375 
3376 static int64_t getmaxrss(void)
3377 {
3378 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3379  struct rusage rusage;
3380  getrusage(RUSAGE_SELF, &rusage);
3381  return (int64_t)rusage.ru_maxrss * 1024;
3382 #elif HAVE_GETPROCESSMEMORYINFO
3383  HANDLE proc;
3384  PROCESS_MEMORY_COUNTERS memcounters;
3385  proc = GetCurrentProcess();
3386  memcounters.cb = sizeof(memcounters);
3387  GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
3388  return memcounters.PeakPagefileUsage;
3389 #else
3390  return 0;
3391 #endif
3392 }
3393 
3394 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
3395 {
3396 }
3397 
3398 int main(int argc, char **argv)
3399 {
3400  int ret;
3401  int64_t ti;
3402 
3404 
3405  setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
3406 
3408  parse_loglevel(argc, argv, options);
3409 
3410  if(argc>1 && !strcmp(argv[1], "-d")){
3411  run_as_daemon=1;
3413  argc--;
3414  argv++;
3415  }
3416 
3418 #if CONFIG_AVDEVICE
3420 #endif
3422  av_register_all();
3424 
3425  show_banner(argc, argv, options);
3426 
3427  term_init();
3428 
3429  /* parse options and open all input/output files */
3430  ret = ffmpeg_parse_options(argc, argv);
3431  if (ret < 0)
3432  exit_program(1);
3433 
3434  if (nb_output_files <= 0 && nb_input_files == 0) {
3435  show_usage();
3436  av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
3437  exit_program(1);
3438  }
3439 
3440  /* file converter / grab */
3441  if (nb_output_files <= 0) {
3442  av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
3443  exit_program(1);
3444  }
3445 
3446 // if (nb_input_files == 0) {
3447 // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
3448 // exit_program(1);
3449 // }
3450 
3451  current_time = ti = getutime();
3452  if (transcode() < 0)
3453  exit_program(1);
3454  ti = getutime() - ti;
3455  if (do_benchmark) {
3456  printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3457  }
3458  av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
3461  exit_program(69);
3462 
3463  exit_program(received_nb_signals ? 255 : 0);
3464  return 0;
3465 }
unsigned int nb_chapters
Number of chapters in AVChapter array.
Definition: avformat.h:1125
int64_t pts
current pts of the decoded frame (in AV_TIME_BASE units)
Definition: ffmpeg.h:233
const char * name
Definition: avisynth_c.h:675
int got_output
Definition: ffmpeg.h:258
static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
Definition: ffmpeg.c:1402
int64_t first_dts
Definition: avformat.h:795
int guess_input_channel_layout(InputStream *ist)
Definition: ffmpeg.c:1505
int frame_number
Definition: ffmpeg.h:323
Definition: ffmpeg.h:307
const char * s
Definition: avisynth_c.h:668
Bytestream IO Context.
Definition: avio.h:68
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
Definition: ffmpeg.h:382
void term_init(void)
Definition: ffmpeg.c:325
#define AVERROR_PATCHWELCOME
int nb_outputs
Definition: ffmpeg.h:214
char * key
Definition: dict.h:81
int size
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:279
AVDictionary * swr_opts
Definition: ffmpeg.h:365
int resample_channels
Definition: ffmpeg.h:253
This structure describes decoded (raw) audio or video data.
Definition: frame.h:96
int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, int flags, double ts)
Queue a command for one or more filter instances.
void term_exit(void)
Definition: ffmpeg.c:303
int stream_copy
Definition: ffmpeg.h:370
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file ensuring correct interleaving.
Definition: mux.c:757
int x
top left corner of pict, undefined when pict is not set
Definition: avcodec.h:3151
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1161
static av_always_inline int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
Definition: os2threads.h:149
const char * av_get_sample_fmt_name(enum AVSampleFormat sample_fmt)
Return the name of sample_fmt, or NULL if sample_fmt is not recognized.
Definition: samplefmt.c:47
AVRational frame_rate
Definition: ffmpeg.h:339
int64_t * forced_kf_pts
Definition: ffmpeg.h:346
int av_frame_get_buffer(AVFrame *frame, int align)
Allocate new buffer(s) for audio or video data.
Definition: frame.c:234
double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
Evaluate a previously parsed expression.
Definition: eval.c:692
static void sub2video_flush(InputStream *ist)
Definition: ffmpeg.c:293
#define AVFMT_TS_NONSTRICT
Format does not require strictly increasing timestamps, but they must still be monotonic.
Definition: avformat.h:365
unsigned av_buffersrc_get_nb_failed_requests(AVFilterContext *buffer_src)
Get the number of failed requests.
Definition: buffersrc.c:316
#define CODEC_FLAG_PASS2
Use internal 2pass ratecontrol in second pass mode.
Definition: avcodec.h:704
static int process_input(int file_index)
Definition: ffmpeg.c:2943
#define CODEC_CAP_VARIABLE_FRAME_SIZE
Audio encoder supports receiving a different number of samples in each call.
Definition: avcodec.h:827
int avformat_write_header(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and write the stream header to an output media file.
Definition: mux.c:387
int exit_on_error
Definition: ffmpeg_opt.c:82
const char * fmt
Definition: avisynth_c.h:669
int linesize[AV_NUM_DATA_POINTERS]
number of bytes per line
Definition: avcodec.h:3123
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: avcodec.h:4153
static const AVFilterPad outputs[]
Definition: af_ashowinfo.c:111
#define av_ts2timestr(ts, tb)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:72
int64_t pos
byte position in stream, -1 if unknown
Definition: avcodec.h:1092
uint8_t * subtitle_header
Header containing style information for text subtitles.
Definition: avcodec.h:2788
int avio_close(AVIOContext *s)
Close the resource accessed by the AVIOContext s and free it.
Definition: aviobuf.c:860
AVStream * st
Definition: ffmpeg.h:321
#define AV_DICT_DONT_OVERWRITE
Don&#39;t overwrite existing entries.
Definition: dict.h:75
#define CODEC_FLAG_PASS1
Use internal 2pass ratecontrol in first pass mode.
Definition: avcodec.h:703
static int run_as_daemon
Definition: ffmpeg.c:123
int av_usleep(unsigned usec)
Sleep for a period of time.
Definition: time.c:56
void av_log_set_level(int level)
Set the log level.
Definition: log.c:293
AVRational framerate
Definition: ffmpeg.h:243
int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
Check validity and configure all the links and formats in the graph.
int av_buffersrc_add_frame(AVFilterContext *ctx, AVFrame *frame)
Add a frame to the buffer source.
Definition: buffersrc.c:87
AVFrame * avcodec_alloc_frame(void)
Allocate an AVFrame and set its fields to default values.
Definition: utils.c:1071
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:261
static int64_t audio_size
Definition: ffmpeg.c:125
AVDictionaryEntry * av_dict_get(AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:39
static int64_t cur_time
Definition: ffserver.c:324
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:686
int decoding_needed
Definition: ffmpeg.h:221
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:733
int num
numerator
Definition: rational.h:44
FilterGraph * init_simple_filtergraph(InputStream *ist, OutputStream *ost)
static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
Definition: ffmpeg.c:1130
#define vsnprintf
Definition: snprintf.h:36
int index
stream index in AVFormatContext
Definition: avformat.h:668
int size
Definition: avcodec.h:1064
static int64_t getmaxrss(void)
Definition: ffmpeg.c:3376
const char * b
Definition: vf_curves.c:105
static int nb_frames_dup
Definition: ffmpeg.c:128
static InputStream * get_input_stream(OutputStream *ost)
Definition: ffmpeg.c:2019
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
Definition: pixdesc.c:1860
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel...
Definition: avcodec.h:1517
int eagain
Definition: ffmpeg.h:283
void avfilter_graph_free(AVFilterGraph **graph)
Free a graph, destroy its links, and set *graph to NULL.
void show_banner(int argc, char **argv, const OptionDef *options)
Print the program banner to stderr.
Definition: cmdutils.c:1082
void av_log(void *avcl, int level, const char *fmt,...) av_printf_format(3
Send the specified message to the log if the level is less than or equal to the current av_log_level...
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1342
AVBitStreamFilterContext * bitstream_filters
Definition: ffmpeg.h:333
int av_expr_parse(AVExpr **expr, const char *s, const char *const *const_names, const char *const *func1_names, double(*const *funcs1)(void *, double), const char *const *func2_names, double(*const *funcs2)(void *, double, double), int log_offset, void *log_ctx)
Parse an expression.
Definition: eval.c:641
static void abort_codec_experimental(AVCodec *c, int encoder)
Definition: ffmpeg.c:523
unsigned num_rects
Definition: avcodec.h:3180
AVFrame * filter_frame
Definition: ffmpeg.h:224
static int transcode_init(void)
Definition: ffmpeg.c:2110
static int compare_int64(const void *a, const void *b)
Definition: ffmpeg.c:2026
int do_benchmark_all
Definition: ffmpeg_opt.c:76
enum AVMediaType type
Definition: avcodec.h:2935
static int init_input_threads(void)
Definition: ffmpeg.c:2854
av_dlog(ac->avr,"%d samples - audio_convert: %s to %s (%s)\n", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt), use_generic?ac->func_descr_generic:ac->func_descr)
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:173
discard all
Definition: avcodec.h:618
int void avio_flush(AVIOContext *s)
Force flushing of buffered data to the output s.
Definition: aviobuf.c:193
int64_t input_ts_offset
Definition: ffmpeg.h:285
int do_hex_dump
Definition: ffmpeg_opt.c:77
int avcodec_encode_audio2(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr)
Encode a frame of audio.
Definition: utils.c:1597
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition: avcodec.h:2570
int nb_input_streams
Definition: ffmpeg.c:145
void avcodec_register_all(void)
Register all the codecs, parsers and bitstream filters which were enabled at configuration time...
Definition: allcodecs.c:67
void av_expr_free(AVExpr *e)
Free a parsed expression previously created with av_expr_parse().
Definition: eval.c:303
int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub, int *got_sub_ptr, AVPacket *avpkt)
Decode a subtitle message.
Definition: utils.c:2390
Pixel format.
Definition: avcodec.h:4533
int av_dup_packet(AVPacket *pkt)
Definition: avpacket.c:247
static void report_new_stream(int input_index, AVPacket *pkt)
Definition: ffmpeg.c:2095
Picture data structure.
Definition: avcodec.h:3121
struct AVBitStreamFilterContext * next
Definition: avcodec.h:4774
AVCodec.
Definition: avcodec.h:2922
#define VSYNC_VFR
Definition: ffmpeg.h:53
int block_align
number of bytes per packet if constant and known or 0 Used by some WAV based audio codecs...
Definition: avcodec.h:1910
int avpicture_fill(AVPicture *picture, const uint8_t *ptr, enum AVPixelFormat pix_fmt, int width, int height)
Setup the picture fields based on the specified image parameters and the provided image data buffer...
Definition: avpicture.c:34
int print_stats
Definition: ffmpeg_opt.c:83
float dts_error_threshold
Definition: ffmpeg_opt.c:69
int64_t start_time
start time in microseconds == AV_TIME_BASE units
Definition: ffmpeg.h:383
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1254
static int decode_interrupt_cb(void *ctx)
Definition: ffmpeg.c:417
AVBufferRef * buf
A reference to the reference-counted buffer where the packet data is stored.
Definition: avcodec.h:1046
#define log2(x)
Definition: libm.h:122
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avcodec.h:1265
void av_freep(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:234
enum AVAudioServiceType audio_service_type
Type of service that the audio stream conveys.
Definition: avcodec.h:1948
if((e=av_dict_get(options,"", NULL, AV_DICT_IGNORE_SUFFIX)))
Definition: avfilter.c:965
int encoding_needed
Definition: ffmpeg.h:322
static void update_benchmark(const char *fmt,...)
Definition: ffmpeg.c:528
static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
Definition: ffmpeg.c:3394
static int check_keyboard_interaction(int64_t cur_time)
Definition: ffmpeg.c:2691
Format I/O context.
Definition: avformat.h:968
struct InputStream * ist
Definition: ffmpeg.h:189
int av_fifo_size(AVFifoBuffer *f)
Return the amount of data in bytes in the AVFifoBuffer, that is the amount of data you can read from ...
Definition: fifo.c:54
unsigned int nb_stream_indexes
Definition: avformat.h:917
#define AV_LOG_QUIET
Print no output.
Definition: avcodec.h:4129
#define CODEC_FLAG_PSNR
error[?] variables will be set during encoding.
Definition: avcodec.h:707
int64_t cur_dts
Definition: avformat.h:796
int w
width of pict, undefined when pict is not set
Definition: avcodec.h:3153
#define AVFMT_NOTIMESTAMPS
Format does not need / have any timestamps.
Definition: avformat.h:354
AVFilterGraph * graph
Definition: ffmpeg.h:208
static uint8_t * res
Definition: ffhash.c:43
char * logfile_prefix
Definition: ffmpeg.h:357
static uint8_t * subtitle_out
Definition: ffmpeg.c:135
#define DEFAULT_PASS_LOGFILENAME_PREFIX
Definition: ffmpeg.c:142
static int64_t start_time
Definition: ffplay.c:305
int copy_initial_nonkeyframes
Definition: ffmpeg.h:372
void register_exit(void(*cb)(int ret))
Register a program-specific cleanup routine.
Definition: cmdutils.c:117
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1881
int flags
can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_RAWPICTURE, AVFMT_GLOBALHEADER, AVFMT_NOTIMESTAMPS, AVFMT_VARIABLE_FPS, AVFMT_NODIMENSIONS, AVFMT_NOSTREAMS, AVFMT_ALLOW_FLUSH, AVFMT_TS_NONSTRICT
Definition: avformat.h:414
uint8_t
static void * input_thread(void *arg)
Definition: ffmpeg.c:2789
int av_parser_change(AVCodecParserContext *s, AVCodecContext *avctx, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int keyframe)
Definition: parser.c:171
float delta
static void sub2video_push_ref(InputStream *ist, int64_t pts)
Definition: ffmpeg.c:216
int subtitle_header_size
Definition: avcodec.h:2789
int flags
Can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_SHOW_IDS, AVFMT_GENERIC_INDEX, AVFMT_TS_DISCONT, AVFMT_NOBINSEARCH, AVFMT_NOGENSEARCH, AVFMT_NO_BYTE_SEEK, AVFMT_SEEK_TO_PTS.
Definition: avformat.h:492
enum AVCodecID av_codec_get_id(const struct AVCodecTag *const *tags, unsigned int tag)
Get the AVCodecID for the given codec tag tag.
miscellaneous OS support macros and functions.
int is_start
Definition: ffmpeg.h:239
attribute_deprecated void(* destruct)(struct AVPacket *)
Definition: avcodec.h:1088
int stdin_interaction
Definition: ffmpeg_opt.c:85
FILE * logfile
Definition: ffmpeg.h:358
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:67
AVDictionary * opts
Definition: ffmpeg.h:364
#define ECHO(name, type, min, max)
Definition: af_aecho.c:183
static int need_output(void)
Definition: ffmpeg.c:2643
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:182
#define AVERROR_EXIT
static double psnr(double d)
Definition: ffmpeg.c:1008
const char * name
Name of the codec implementation.
Definition: avcodec.h:2929
int do_benchmark
Definition: ffmpeg_opt.c:75
int audio_sync_method
Definition: ffmpeg_opt.c:72
int av_frame_ref(AVFrame *dst, AVFrame *src)
Setup a new reference to the data described by a given frame.
Definition: frame.c:247
int shortest
Definition: ffmpeg.h:386
int avcodec_encode_video2(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr)
Encode a frame of video.
Definition: utils.c:1834
int av_codec_get_tag2(const struct AVCodecTag *const *tags, enum AVCodecID id, unsigned int *tag)
Get the codec tag for the given codec id.
void avfilter_register_all(void)
Initialize the filter system.
Definition: allfilters.c:40
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:248
static int64_t getutime(void)
Definition: ffmpeg.c:3358
AVBufferRef * av_buffer_create(uint8_t *data, int size, void(*free)(void *opaque, uint8_t *data), void *opaque, int flags)
Create an AVBuffer from an existing array.
Definition: buffer.c:27
Immediately push the frame to the output.
Definition: buffersrc.h:48
static double av_q2d(AVRational a)
Convert rational to double.
Definition: rational.h:69
int nb_streams
Definition: ffmpeg.h:290
pthread_t thread
Definition: ffmpeg.h:297
#define AV_DISPOSITION_DEFAULT
Definition: avformat.h:622
AVRational av_mul_q(AVRational b, AVRational c) av_const
Multiply two rationals.
Definition: rational.c:79
AVDictionary * resample_opts
Definition: ffmpeg.h:366
static void parse_forced_key_frames(char *kf, OutputStream *ost, AVCodecContext *avctx)
Definition: ffmpeg.c:2032
list ifile
Definition: normalize.py:6
AVFilterContext * filter
Definition: ffmpeg.h:195
int avformat_network_init(void)
Do global initialization of network components.
Definition: utils.c:4031
char av_get_picture_type_char(enum AVPictureType pict_type)
Return a single letter to describe the given picture type pict_type.
Definition: utils.c:82
int nb_input_files
Definition: ffmpeg.c:147
static int read_key(void)
Definition: ffmpeg.c:362
#define AV_LOG_VERBOSE
Detailed information.
Definition: avcodec.h:4163
#define lrintf(x)
Definition: libm_mips.h:70
int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size)
Generate an SDP for an RTP session.
Definition: sdp.c:703
static void do_video_stats(OutputStream *ost, int frame_size)
Definition: ffmpeg.c:1013
int resample_sample_rate
Definition: ffmpeg.h:252
static av_always_inline int pthread_cond_signal(pthread_cond_t *cond)
Definition: os2threads.h:127
int interlaced_frame
The content of the picture is interlaced.
Definition: frame.h:293
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:347
#define AVFMT_NOSTREAMS
Format does not require any streams.
Definition: avformat.h:359
void parse_loglevel(int argc, char **argv, const OptionDef *options)
Find the &#39;-loglevel&#39; option in the command line args and apply it.
Definition: cmdutils.c:478
void av_fifo_free(AVFifoBuffer *f)
Free an AVFifoBuffer.
Definition: fifo.c:40
int h
height of pict, undefined when pict is not set
Definition: avcodec.h:3154
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:2563
AVCodec * dec
Definition: ffmpeg.h:222
#define FFSWAP(type, a, b)
Definition: avcodec.h:928
static int64_t duration
Definition: ffplay.c:306
enum AVDiscard discard
selects which program to discard and which to feed to the caller
Definition: avformat.h:915
int top_field_first
Definition: ffmpeg.h:244
uint8_t * data[AV_NUM_DATA_POINTERS]
pointers to the image data planes
Definition: avcodec.h:3122
int nb_output_streams
Definition: ffmpeg.c:150
int file_index
Definition: ffmpeg.h:218
int duration
Duration of this packet in AVStream-&gt;time_base units, 0 if unknown.
Definition: avcodec.h:1085
const OptionDef options[]
Definition: ffserver.c:4682
enum AVChromaLocation chroma_sample_location
This defines the location of chroma samples.
Definition: avcodec.h:1855
struct InputStream::sub2video sub2video
int resample_pix_fmt
Definition: ffmpeg.h:249
int resample_height
Definition: ffmpeg.h:247
int wrap_correction_done
Definition: ffmpeg.h:234
int64_t filter_in_rescale_delta_last
Definition: ffmpeg.h:236
#define AVERROR_EXPERIMENTAL
static const vf_info_t *const filters[]
Definition: vf_mp.c:134
static void sub2video_heartbeat(InputStream *ist, int64_t pts)
Definition: ffmpeg.c:264
int ist_in_filtergraph(FilterGraph *fg, InputStream *ist)
int64_t next_dts
Definition: ffmpeg.h:229
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1113
static AVFrame * frame
Definition: demuxing.c:51
AVRational av_buffersink_get_frame_rate(AVFilterContext *ctx)
Get the frame rate of the input.
Definition: buffersink.c:357
void av_buffer_default_free(void *opaque, uint8_t *data)
Default free callback, which calls av_free() on the buffer data.
Definition: buffer.c:60
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq) av_const
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:130
static const uint8_t frame_size[4]
Definition: g723_1_data.h:58
void av_dump_format(AVFormatContext *ic, int index, const char *url, int is_output)
Definition: utils.c:3585
Callback for checking whether to abort blocking functions.
Definition: avio.h:51
int avcodec_close(AVCodecContext *avctx)
Close a given AVCodecContext and free all the data associated with it (but not the AVCodecContext its...
Definition: utils.c:2505
enum AVCodecID id
Definition: avcodec.h:2936
#define av_err2str(errnum)
AVSubtitleRect ** rects
Definition: avcodec.h:3181
int rate_emu
Definition: ffmpeg.h:293
int width
width and height of the video frame
Definition: frame.h:145
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: avcodec.h:4147
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition: avcodec.h:1427
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:219
static void reset_eagain(void)
Definition: ffmpeg.c:2927
static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
Definition: ffmpeg.c:545
int avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture, int *got_picture_ptr, const AVPacket *avpkt)
Decode the video frame of size avpkt-&gt;size from avpkt-&gt;data into picture.
Definition: utils.c:2029
int ffmpeg_parse_options(int argc, char **argv)
Definition: ffmpeg_opt.c:2519
FilterGraph ** filtergraphs
Definition: ffmpeg.c:154
const AVIOInterruptCB int_cb
Definition: ffmpeg.c:422
AVFilterContext * filter
Definition: ffmpeg.h:188
#define CODEC_CAP_PARAM_CHANGE
Codec supports changed parameters at any point.
Definition: avcodec.h:819
const AVRational * supported_framerates
array of supported framerates, or NULL if any, array is terminated by {0,0}
Definition: avcodec.h:2942
#define CODEC_FLAG_INTERLACED_ME
interlaced motion estimation
Definition: avcodec.h:718
int64_t start
Definition: ffmpeg.h:226
#define CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
Definition: avcodec.h:769
int y
top left corner of pict, undefined when pict is not set
Definition: avcodec.h:3152
char filename[1024]
input or output filename
Definition: avformat.h:1018
unsigned m
Definition: audioconvert.c:186
int64_t last_mux_dts
Definition: ffmpeg.h:332
int video_sync_method
Definition: ffmpeg_opt.c:73
static int64_t decode_error_stat[2]
Definition: ffmpeg.c:130
#define VSYNC_VSCFR
Definition: ffmpeg.h:54
int avfilter_link_get_channels(AVFilterLink *link)
Get the number of channels of a link.
Definition: avfilter.c:172
AVCodec * avcodec_find_encoder(enum AVCodecID id)
Find a registered encoder with a matching codec ID.
Definition: utils.c:2588
static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
Definition: ffmpeg.c:1773
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:110
static void do_video_out(AVFormatContext *s, OutputStream *ost, AVFrame *in_picture)
Definition: ffmpeg.c:794
const char * r
Definition: vf_curves.c:103
const char *const forced_keyframes_const_names[]
Definition: ffmpeg.c:110
int capabilities
Codec capabilities.
Definition: avcodec.h:2941
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: avcodec.h:4168
void av_bitstream_filter_close(AVBitStreamFilterContext *bsf)
Release bitstream filter context.
unsigned int nb_programs
Definition: avformat.h:1075
void av_dict_free(AVDictionary **m)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:162
struct AVInputFormat * iformat
Can only be iformat or oformat, not both at the same time.
Definition: avformat.h:981
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: avcodec.h:398
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition: utils.c:2626
struct AVCodec * codec
Definition: avcodec.h:1155
const char * arg
Definition: jacosubdec.c:69
int flags
CODEC_FLAG_*.
Definition: avcodec.h:1234
int av_opt_set_int(void *obj, const char *name, int64_t val, int search_flags)
Definition: opt.c:426
#define AV_LOG_SKIP_REPEATED
Skip repeated messages, this requires the user app to use av_log() instead of (f)printf as the 2 woul...
Definition: avcodec.h:4294
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition: bprint.c:235
int finished
Definition: ffmpeg.h:368
int rc_max_rate
maximum bitrate
Definition: avcodec.h:2213
int av_log_get_level(void)
Get the current log level.
Definition: log.c:288
int av_frame_get_channels(const AVFrame *frame)
static int check_recording_time(OutputStream *ost)
Definition: ffmpeg.c:660
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:123
int force_fps
Definition: ffmpeg.h:340
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:740
New fields can be added to the end with minor version bumps.
Definition: avformat.h:912
int qp_hist
Definition: ffmpeg_opt.c:84
static char logfilename[1024]
Definition: ffserver.c:270
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1069
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:1934
int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b)
Compare 2 timestamps each in its own timebases.
Definition: mathematics.c:135
int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int(*func)(void *, void *, int))
Feed data from a user-supplied callback to an AVFifoBuffer.
Definition: fifo.c:99
void * av_opt_ptr(const AVClass *avclass, void *obj, const char *name)
Gets a pointer to the requested field in a struct.
Definition: opt.c:1412
uint32_t end_display_time
Definition: avcodec.h:3179
int64_t pts
Same as packet pts, in AV_TIME_BASE.
Definition: avcodec.h:3182
int rc_buffer_size
decoder bitstream buffer size
Definition: avcodec.h:2191
OutputFilter * filter
Definition: ffmpeg.h:360
struct AVBitStreamFilter * filter
Definition: avcodec.h:4772
uint64_t channel_layout
Channel layout of the audio data.
Definition: frame.h:354
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:35
AVRational frame_aspect_ratio
Definition: ffmpeg.h:343
AVDictionary * opts
Definition: ffmpeg.h:242
const int program_birth_year
program birth year, defined by the program for show_banner()
Definition: ffmpeg.c:106
goto fail
Definition: avfilter.c:963
const char * av_get_media_type_string(enum AVMediaType media_type)
Return a string describing the media_type enum, NULL if media_type is unknown.
Definition: utils.c:70
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Init a print buffer.
Definition: bprint.c:69
#define FF_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding...
Definition: avcodec.h:580
unsigned int nb_streams
A list of all streams in the file.
Definition: avformat.h:1015
#define FF_ARRAY_ELEMS(a)
Definition: avcodec.h:929
int av_buffersink_get_frame_flags(AVFilterContext *ctx, AVFrame *frame, int flags)
Get a frame with filtered data from sink and put it in frame.
Definition: buffersink.c:127
static int nb_frames_drop
Definition: ffmpeg.c:129
A bitmap, pict will be set.
Definition: avcodec.h:3133
int nb_output_files
Definition: ffmpeg.c:152
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:39
Buffer to print data progressively.
Definition: bprint.h:77
int bit_rate
the average bitrate
Definition: avcodec.h:1204
static int64_t video_size
Definition: ffmpeg.c:124
static int transcoding_finished
Definition: ffmpeg.c:139
enum AVPictureType pict_type
Picture type of the frame.
Definition: frame.h:167
static int transcode(void)
Definition: ffmpeg.c:3237
Opaque data information usually continuous.
Definition: avcodec.h:2233
AVPicture pict
data+linesize for the bitmap of this subtitle.
Definition: avcodec.h:3161
int64_t av_rescale(int64_t a, int64_t b, int64_t c) av_const
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:118
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Definition: frame.c:351
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avcodec.h:2284
float y
#define VSYNC_AUTO
Definition: ffmpeg.h:50
void av_log_set_callback(void(*callback)(void *, int, const char *, va_list))
Set the logging callback.
Definition: log.c:303
char * stats_in
pass2 encoding statistics input buffer Concatenated stuff from stats_out of pass1 should be placed he...
Definition: avcodec.h:2384
int saw_first_ts
Definition: ffmpeg.h:240
static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
Definition: ffmpeg.c:1525
struct OutputStream * ost
Definition: ffmpeg.h:196
ret
Definition: avfilter.c:961
int width
picture width / height.
Definition: avcodec.h:1314
PVOID HANDLE
char * apad
Definition: ffmpeg.h:367
AVFifoBuffer * fifo
Definition: ffmpeg.h:302
int av_buffersrc_add_ref(AVFilterContext *buffer_src, AVFilterBufferRef *picref, int flags)
Add buffer data in picref to buffer_src.
AVStream ** streams
Definition: avformat.h:1016
double forced_keyframes_expr_const_values[FKF_NB]
Definition: ffmpeg.h:351
void * av_malloc(size_t size) av_malloc_attrib 1(1)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:73
#define FF_DEBUG_DCT_COEFF
Definition: avcodec.h:2449
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:357
#define FFMIN(a, b)
Definition: avcodec.h:925
#define AV_PIX_FMT_RGB32
Definition: avcodec.h:4928
uint64_t error[AV_NUM_DATA_POINTERS]
error
Definition: frame.h:277
int nb_filtergraphs
Definition: ffmpeg.c:155
static av_always_inline int pthread_join(pthread_t thread, void **value_ptr)
Definition: os2threads.h:76
static av_always_inline int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
Definition: os2threads.h:83
int64_t last_ts
Definition: ffmpeg.h:287
static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
Definition: ffmpeg.c:2876
const char * name
Definition: avformat.h:395
int quality
quality (between 1 (good) and FF_LAMBDA_MAX (bad))
Definition: frame.h:208
int do_pkt_dump
Definition: ffmpeg_opt.c:78
int avcodec_decode_audio4(AVCodecContext *avctx, AVFrame *frame, int *got_frame_ptr, const AVPacket *avpkt)
Decode the audio frame of size avpkt-&gt;size from avpkt-&gt;data into frame.
Definition: utils.c:2164
int64_t max_frames
Definition: ffmpeg.h:335
#define CODEC_FLAG_INTERLACED_DCT
Use interlaced DCT.
Definition: avcodec.h:711
#define AV_BUFFERSINK_FLAG_NO_REQUEST
Tell av_buffersink_get_buffer_ref() not to request a frame from its input.
Definition: buffersink.h:110
float u
int n
Definition: avisynth_c.h:588
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
Definition: avcodec.h:1274
#define AVFILTER_CMD_FLAG_ONE
Stop once a filter understood the command (for target=all for example), fast filters are favored auto...
Definition: avfilter.h:957
static int reap_filters(void)
Get and encode new output from any of the filtergraphs, without causing activity. ...
Definition: ffmpeg.c:1055
static int output_packet(InputStream *ist, const AVPacket *pkt)
Definition: ffmpeg.c:1823
char * stats_out
pass1 encoding statistics output buffer
Definition: avcodec.h:2376
static int restore_tty
Definition: ffmpeg.c:161
static int got_eagain(void)
Definition: ffmpeg.c:2918
preferred ID for MPEG-1/2 video decoding
Definition: avcodec.h:107
int finished
Definition: ffmpeg.h:298
static void sub2video_update(InputStream *ist, AVSubtitle *sub)
Definition: ffmpeg.c:229
int av_find_nearest_q_idx(AVRational q, const AVRational *q_list)
Find the nearest value in q_list to q.
Definition: rational.c:140
#define FF_DEBUG_VIS_MB_TYPE
Definition: avcodec.h:2457
void exit_program(int ret)
Wraps exit with a program-specific cleanup routine.
Definition: cmdutils.c:122
int ret
Definition: ffmpeg.h:259
int audio_volume
Definition: ffmpeg_opt.c:71
Stream structure.
Definition: avformat.h:667
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames...
Definition: frame.h:157
InputFilter ** filters
Definition: ffmpeg.h:274
int fix_sub_duration
Definition: ffmpeg.h:256
#define VSYNC_DROP
Definition: ffmpeg.h:55
int64_t recording_time
Definition: ffmpeg.h:289
int avformat_network_deinit(void)
Undo the initialization done by avformat_network_init.
Definition: utils.c:4043
int frame_size
Number of samples per channel in an audio frame.
Definition: avcodec.h:1893
static av_always_inline int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
Definition: os2threads.h:62
planar YUV 4:2:0, 12bpp, (1 Cr &amp; Cb sample per 2x2 Y samples)
Definition: avcodec.h:4534
void av_buffersink_set_frame_size(AVFilterContext *ctx, unsigned frame_size)
Set the frame size for an audio buffer sink.
Definition: buffersink.c:260
static int sub2video_get_blank_frame(InputStream *ist)
Definition: ffmpeg.c:172
#define AV_LOG_INFO
Standard information.
Definition: avcodec.h:4158
pthread_mutex_t fifo_lock
Definition: ffmpeg.h:300
int av_bitstream_filter_filter(AVBitStreamFilterContext *bsfc, AVCodecContext *avctx, const char *args, uint8_t **poutbuf, int *poutbuf_size, const uint8_t *buf, int buf_size, int keyframe)
Filter bitstream.
int ost_index
Definition: ffmpeg.h:381
AVS_Value src
Definition: avisynth_c.h:523
enum AVMediaType codec_type
Definition: avcodec.h:1154
double ts_scale
Definition: ffmpeg.h:238
int unavailable
Definition: ffmpeg.h:369
int me_threshold
Motion estimation threshold below which no motion estimation is performed, but instead the user speci...
Definition: avcodec.h:1706
#define FFMAX(a, b)
Definition: avcodec.h:923
static int init_input_stream(int ist_index, char *error, int error_len)
Definition: ffmpeg.c:1979
enum AVCodecID codec_id
Definition: avcodec.h:1157
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avcodec.h:2290
int av_opt_set_dict(void *obj, struct AVDictionary **options)
Set all the options from a given dictionary on an object.
Definition: opt.c:1326
Keep a reference to the frame.
Definition: buffersrc.h:55
static int64_t extra_size
Definition: ffmpeg.c:127
static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h, AVSubtitleRect *r)
Definition: ffmpeg.c:187
float max_error_rate
Definition: ffmpeg_opt.c:87
int sample_rate
samples per second
Definition: avcodec.h:1873
static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
Definition: ffmpeg.c:1665
int64_t av_rescale_delta(AVRational in_tb, int64_t in_ts, AVRational fs_tb, int duration, int64_t *last, AVRational out_tb)
Rescale a timestamp while preserving known durations.
Definition: mathematics.c:152
int ist_index
Definition: ffmpeg.h:284
#define AVFMT_RAWPICTURE
Format wants AVPicture structure for raw picture data.
Definition: avformat.h:350
int debug
debug
Definition: avcodec.h:2442
static void print_sdp(void)
Definition: ffmpeg.c:1962
int guess_layout_max
Definition: ffmpeg.h:245
int64_t start_time
Definition: ffmpeg.h:288
main external API structure.
Definition: avcodec.h:1146
static int64_t subtitle_size
Definition: ffmpeg.c:126
static void ffmpeg_cleanup(int ret)
Definition: ffmpeg.c:424
static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
Definition: vf_drawtext.c:602
void * av_realloc_f(void *ptr, size_t nelem, size_t elsize)
Allocate or reallocate a block of memory.
Definition: mem.c:168
void avsubtitle_free(AVSubtitle *sub)
Free all allocated data in the given subtitle struct.
Definition: utils.c:2474
AVRational sample_aspect_ratio
Sample aspect ratio for the video frame, 0/1 if unknown/unspecified.
Definition: frame.h:177
const char * attachment_filename
Definition: ffmpeg.h:371
unsigned int codec_tag
fourcc (LSB first, so &quot;ABCD&quot; -&gt; (&#39;D&#39;&lt;&lt;24) + (&#39;C&#39;&lt;&lt;16) + (&#39;B&#39;&lt;&lt;8) + &#39;A&#39;).
Definition: avcodec.h:1172
static int check_output_constraints(InputStream *ist, OutputStream *ost)
Definition: ffmpeg.c:1388
int avfilter_graph_request_oldest(AVFilterGraph *graph)
Request a frame on the oldest sink link.
void assert_avoptions(AVDictionary *m)
Definition: ffmpeg.c:514
AVIOContext * pb
I/O context.
Definition: avformat.h:1001
void * buf
Definition: avisynth_c.h:594
void avdevice_register_all(void)
Initialize libavdevice and register all the input and output devices.
Definition: alldevices.c:40
AVFrame * decoded_frame
Definition: ffmpeg.h:223
int extradata_size
Definition: avcodec.h:1255
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:62
Replacements for frequently missing libm functions.
static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
Perform a step of transcoding for the specified filter graph.
Definition: ffmpeg.c:3149
AVStream * st
Definition: ffmpeg.h:219
void avcodec_get_frame_defaults(AVFrame *frame)
Set the fields of the given AVFrame to default values.
Definition: utils.c:1046
#define VSYNC_PASSTHROUGH
Definition: ffmpeg.h:51
int sample_rate
Sample rate of the audio data.
Definition: frame.h:349
int configure_filtergraph(FilterGraph *fg)
OutputStream ** output_streams
Definition: ffmpeg.c:149
int index
Definition: gxfenc.c:89
static const AVFilterPad inputs[]
Definition: af_ashowinfo.c:102
AVFilterLink ** inputs
array of pointers to input links
Definition: avfilter.h:635
rational number numerator/denominator
Definition: rational.h:43
int file_index
Definition: ffmpeg.h:318
AVFrame * coded_frame
the picture in the bitstream
Definition: avcodec.h:2588
uint8_t * data
Definition: avcodec.h:1063
static int current_time
Definition: ffmpeg.c:132
int64_t sync_opts
Definition: ffmpeg.h:327
char * vstats_filename
Definition: ffmpeg_opt.c:65
int64_t parse_time_or_die(const char *context, const char *timestr, int is_duration)
Parse a string specifying a time and return its corresponding value as a number of microseconds...
Definition: cmdutils.c:151
AVFifoBuffer * av_fifo_alloc(unsigned int size)
Initialize an AVFifoBuffer.
Definition: fifo.c:27
discard useless packets like 0 size packets in avi
Definition: avcodec.h:614
static av_always_inline av_const long int lrint(double x)
Definition: libm.h:148
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:124
int nb_streams_warn
Definition: ffmpeg.h:292
#define AVFMT_TS_DISCONT
Format allows timestamp discontinuities.
Definition: avformat.h:356
uint64_t error[AV_NUM_DATA_POINTERS]
error
Definition: avcodec.h:2520
int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition: utils.c:1157
int showed_multi_packet_warning
Definition: ffmpeg.h:241
#define snprintf
Definition: snprintf.h:34
int frame_bits_per_raw_sample
Definition: ffmpeg_opt.c:86
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:3271
int64_t ts_offset
Definition: ffmpeg.h:286
uint32_t DWORD
static void do_subtitle_out(AVFormatContext *s, OutputStream *ost, InputStream *ist, AVSubtitle *sub)
Definition: ffmpeg.c:721
static int transcode_step(void)
Run a single step of transcoding.
Definition: ffmpeg.c:3195
static void free_input_threads(void)
Definition: ffmpeg.c:2819
int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
Return audio frame duration.
Definition: utils.c:2946
#define type
int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void(*func)(void *, void *, int))
Feed data from an AVFifoBuffer to a user-supplied callback.
Definition: fifo.c:127
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition: utils.c:1432
int64_t pkt_pts
PTS copied from the AVPacket that was decoded to produce this frame.
Definition: frame.h:187
AVFrame * filtered_frame
Definition: ffmpeg.h:336
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:53
int source_index
Definition: ffmpeg.h:320
static volatile int received_nb_signals
Definition: ffmpeg.c:313
int copy_prior_start
Definition: ffmpeg.h:373
struct InputStream::@39 prev_sub
int cmdutils_read_file(const char *filename, char **bufptr, size_t *size)
Read the file with name filename, and put its content in a newly allocated 0-terminated buffer...
Definition: cmdutils.c:1789
int global_quality
Global quality for codecs which cannot change it per frame.
Definition: avcodec.h:1220
int nb_filters
Definition: ffmpeg.h:275
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition: rational.h:122
int64_t val
Definition: avformat.h:323
#define AVERROR_EOF
static const uint16_t scale[4]
int64_t start_time
Decoding: position of the first frame of the component, in AV_TIME_BASE fractional seconds...
Definition: avformat.h:1025
uint8_t level
Definition: svq3.c:146
AVExpr * forced_keyframes_pexpr
Definition: ffmpeg.h:350
int64_t dts
dts of the last packet read for this stream (in AV_TIME_BASE units)
Definition: ffmpeg.h:230
struct AVCodecParserContext * parser
Definition: avformat.h:813
int av_strerror(int errnum, char *errbuf, size_t errbuf_size)
Put a description of the AVERROR code errnum in errbuf.
Definition: error.c:53
int resample_sample_fmt
Definition: ffmpeg.h:251
int forced_kf_count
Definition: ffmpeg.h:347
int64_t av_frame_get_best_effort_timestamp(const AVFrame *frame)
Accessors for some AVFrame fields.
int64_t start
Definition: avformat.h:945
char * forced_keyframes
Definition: ffmpeg.h:349
int resample_width
Definition: ffmpeg.h:248
int64_t next_pts
synthetic pts for the next decode frame (in AV_TIME_BASE units)
Definition: ffmpeg.h:232
void print_error(const char *filename, int err)
Print an error message to stderr, indicating filename and a human readable description of the error c...
Definition: cmdutils.c:1009
struct FilterGraph * graph
Definition: ffmpeg.h:197
uint64_t limit_filesize
Definition: ffmpeg.h:384
static float t
Definition: muxing.c:123
#define FF_DEBUG_MV
Definition: avcodec.h:2448
AVIOContext * progress_avio
Definition: ffmpeg.c:133
int reinit_filters
Definition: ffmpeg.h:277
#define VSYNC_CFR
Definition: ffmpeg.h:52
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base...
Definition: avformat.h:713
static double c[64]
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:724
uint32_t start_display_time
Definition: avcodec.h:3178
int pts_wrap_bits
number of bits in pts (used for wrapping control)
Definition: avformat.h:784
static av_always_inline int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr)
Definition: os2threads.h:111
AVRational time_base
time base in which the start/end timestamps are specified
Definition: avformat.h:944
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:49
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:722
static FILE * vstats_file
Definition: ffmpeg.c:108
int den
denominator
Definition: rational.h:45
struct AVCodecTag *const * codec_tag
List of supported codec_id-codec_tag pairs, ordered by &quot;better choice first&quot;.
Definition: avformat.h:420
void uninit_opts(void)
Uninitialize the cmdutils option system, in particular free the *_opts contexts and their contents...
Definition: cmdutils.c:83
int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
Send a command to one or more filter instances.
int copy_ts
Definition: ffmpeg_opt.c:79
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:3309
static int filter_frame(AVFilterLink *inlink, AVFrame *insamplesref)
Definition: af_aconvert.c:146
AVFormatContext * ctx
Definition: ffmpeg.h:281
static struct termios oldtty
Definition: ffmpeg.c:160
AVCodec * enc
Definition: ffmpeg.h:334
AVSubtitle subtitle
Definition: ffmpeg.h:260
void av_bprintf(AVBPrint *buf, const char *fmt,...) av_printf_format(2
Append a formatted string to a print buffer.
int eof_reached
Definition: ffmpeg.h:282
int forced_kf_index
Definition: ffmpeg.h:348
static void do_audio_out(AVFormatContext *s, OutputStream *ost, AVFrame *frame)
Definition: ffmpeg.c:673
struct AVOutputFormat * oformat
Definition: avformat.h:982
#define AVERROR_INVALIDDATA
int top_field_first
If the content is interlaced, is top field displayed first.
Definition: frame.h:298
#define NAN
Definition: math.h:28
#define AV_RL32(x)
Definition: intreadwrite.h:275
float dts_delta_threshold
Definition: ffmpeg_opt.c:68
struct AVFrac pts
encoding: pts generation when outputting stream
Definition: avformat.h:692
int channels
number of audio channels
Definition: avcodec.h:1874
static av_always_inline int pthread_mutex_unlock(pthread_mutex_t *mutex)
Definition: os2threads.h:104
int top_field_first
Definition: ffmpeg.h:341
OutputFilter ** outputs
Definition: ffmpeg.h:213
InputFile ** input_files
Definition: ffmpeg.c:146
void av_log_set_flags(int arg)
Definition: log.c:298
int key_frame
1 -&gt; keyframe, 0-&gt; not
Definition: frame.h:162
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition: avcodec.h:2257
Opaque data information usually sparse.
Definition: avcodec.h:2235
AVFormatContext * ctx
Definition: ffmpeg.h:379
#define AVERROR(e)
pthread_cond_t fifo_cond
Definition: ffmpeg.h:301
void avcodec_free_frame(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: utils.c:1084
void show_usage(void)
Definition: ffmpeg_opt.c:2469
int64_t dts
Decompression timestamp in AVStream-&gt;time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1062
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:800
int repeat_pict
This field is used for proper frame duration computation in lavf.
Definition: avcodec.h:3945
int height
Definition: frame.h:145
InputFilter ** inputs
Definition: ffmpeg.h:211
enum AVFieldOrder field_order
Field order.
Definition: avcodec.h:1870
#define AV_DICT_IGNORE_SUFFIX
Definition: dict.h:68
OutputFile ** output_files
Definition: ffmpeg.c:151
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition: avcodec.h:4141
static av_always_inline int pthread_mutex_lock(pthread_mutex_t *mutex)
Definition: os2threads.h:97
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
static void flush_encoders(void)
Definition: ffmpeg.c:1307
int copy_tb
Definition: ffmpeg_opt.c:80
static volatile int received_sigterm
Definition: ffmpeg.c:312
static AVPacket pkt
Definition: demuxing.c:52
int discard
Definition: ffmpeg.h:220
static int get_input_packet(InputFile *f, AVPacket *pkt)
Definition: ffmpeg.c:2898
void av_pkt_dump_log2(void *avcl, int level, AVPacket *pkt, int dump_payload, AVStream *st)
Send a nice dump of a packet to the log.
Definition: utils.c:3794
int main(int argc, char **argv)
Definition: main.c:22
int stream_index
Definition: avcodec.h:1065
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:703
enum AVSubtitleType type
Definition: avcodec.h:3162
int64_t first_pts
Definition: ffmpeg.h:330
AVProgram ** programs
Definition: avformat.h:1076
int nb_inputs
Definition: ffmpeg.h:212
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:726
int index
Definition: ffmpeg.h:319
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:839
AVChapter ** chapters
Definition: avformat.h:1126
int av_fifo_space(AVFifoBuffer *f)
Return the amount of space in bytes in the AVFifoBuffer, that is the amount of data you can write int...
Definition: fifo.c:59
unsigned int * stream_index
Definition: avformat.h:916
uint64_t resample_channel_layout
Definition: ffmpeg.h:254
This structure stores compressed data.
Definition: avcodec.h:1040
void av_register_all(void)
Initialize libavformat and register all the muxers, demuxers and protocols.
Definition: allformats.c:52
int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size, const AVSubtitle *sub)
Definition: utils.c:1911
const char * name
Definition: avcodec.h:4779
int debug_ts
Definition: ffmpeg_opt.c:81
static OutputStream * choose_output(void)
Select the output stream to process.
Definition: ffmpeg.c:2673
int av_buffersrc_add_frame_flags(AVFilterContext *buffer_src, AVFrame *frame, int flags)
Add a frame to the buffer source.
Definition: buffersrc.c:95
int nb_samples
number of audio samples (per channel) described by this frame
Definition: frame.h:150
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:107
#define av_ts2str(ts)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:50
static void sigterm_handler(int sig)
Definition: ffmpeg.c:316
int64_t pts
Presentation timestamp in AVStream-&gt;time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1056
for(j=16;j >0;--j)
const AVClass * avcodec_get_frame_class(void)
Get the AVClass for AVFrame.
Definition: options.c:274
const char program_name[]
program name, defined by the program for show_version().
Definition: ffmpeg.c:105
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avcodec.h:2278
#define FF_DEBUG_VIS_QP
Definition: avcodec.h:2456
int joined
Definition: ffmpeg.h:299
void * av_mallocz(size_t size) av_malloc_attrib 1(1)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:241
InputStream ** input_streams
Definition: ffmpeg.c:144
void av_get_channel_layout_string(char *buf, int buf_size, int nb_channels, uint64_t channel_layout)
Return a description of a channel layout.
Definition: ffmpeg.h:311
static void close_output_stream(OutputStream *ost)
Definition: ffmpeg.c:649
int64_t av_get_default_channel_layout(int nb_channels)
Return default channel layout for a given number of channels.