MobileFFmpeg iOS / tvOS API  4.4
fftools_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 
26 /*
27  * CHANGES 06.2020
28  * - ignoring signals implemented
29  * - cancel_operation() method signature updated with id
30  * - cancel by execution id implemented
31  *
32  * CHANGES 01.2020
33  * - ffprobe support changes
34  *
35  * CHANGES 12.2019
36  * - concurrent execution support
37  *
38  * CHANGES 08.2018
39  * --------------------------------------------------------
40  * - fftools_ prefix added to file name and parent headers
41  * - forward_report() method, report_callback function pointer and set_report_callback() setter
42  * method added to forward stats.
43  * - forward_report() call added from print_report()
44  * - cancel_operation() method added to trigger sigterm_handler
45  * - (!received_sigterm) validation added inside ifilter_send_eof() to complete cancellation
46  *
47  * CHANGES 07.2018
48  * --------------------------------------------------------
49  * - main() function renamed as ffmpeg_execute()
50  * - exit_program() implemented with setjmp
51  * - extern longjmp_value added to access exit code stored in exit_program()
52  * - ffmpeg_var_cleanup() method added
53  */
54 
55 #include "config.h"
56 #include <ctype.h>
57 #include <string.h>
58 #include <math.h>
59 #include <stdlib.h>
60 #include <errno.h>
61 #include <limits.h>
62 #include <stdatomic.h>
63 #include <stdint.h>
64 
65 #include "mobileffmpeg_exception.h"
66 
67 #if HAVE_IO_H
68 #include <io.h>
69 #endif
70 #if HAVE_UNISTD_H
71 #include <unistd.h>
72 #endif
73 
74 #include "libavformat/avformat.h"
75 #include "libavdevice/avdevice.h"
76 #include "libswresample/swresample.h"
77 #include "libavutil/opt.h"
78 #include "libavutil/channel_layout.h"
79 #include "libavutil/parseutils.h"
80 #include "libavutil/samplefmt.h"
81 #include "libavutil/fifo.h"
82 #include "libavutil/hwcontext.h"
83 #include "libavutil/internal.h"
84 #include "libavutil/intreadwrite.h"
85 #include "libavutil/dict.h"
86 #include "libavutil/display.h"
87 #include "libavutil/mathematics.h"
88 #include "libavutil/pixdesc.h"
89 #include "libavutil/avstring.h"
90 #include "libavutil/libm.h"
91 #include "libavutil/imgutils.h"
92 #include "libavutil/timestamp.h"
93 #include "libavutil/bprint.h"
94 #include "libavutil/time.h"
95 #include "libavutil/thread.h"
96 #include "libavutil/threadmessage.h"
97 #include "libavcodec/mathops.h"
98 #include "libavformat/os_support.h"
99 
100 # include "libavfilter/avfilter.h"
101 # include "libavfilter/buffersrc.h"
102 # include "libavfilter/buffersink.h"
103 
104 #if HAVE_SYS_RESOURCE_H
105 #include <sys/time.h>
106 #include <sys/types.h>
107 #include <sys/resource.h>
108 #elif HAVE_GETPROCESSTIMES
109 #include <windows.h>
110 #endif
111 #if HAVE_GETPROCESSMEMORYINFO
112 #include <windows.h>
113 #include <psapi.h>
114 #endif
115 #if HAVE_SETCONSOLECTRLHANDLER
116 #include <windows.h>
117 #endif
118 
119 
120 #if HAVE_SYS_SELECT_H
121 #include <sys/select.h>
122 #endif
123 
124 #if HAVE_TERMIOS_H
125 #include <fcntl.h>
126 #include <sys/ioctl.h>
127 #include <sys/time.h>
128 #include <termios.h>
129 #elif HAVE_KBHIT
130 #include <conio.h>
131 #endif
132 
133 #include <time.h>
134 
135 #include "fftools_ffmpeg.h"
136 #include "fftools_cmdutils.h"
137 
138 #include "libavutil/avassert.h"
139 
140 static FILE *vstats_file;
141 
142 const char *const forced_keyframes_const_names[] = {
143  "n",
144  "n_forced",
145  "prev_forced_n",
146  "prev_forced_t",
147  "t",
148  NULL
149 };
150 
151 typedef struct BenchmarkTimeStamps {
152  int64_t real_usec;
153  int64_t user_usec;
154  int64_t sys_usec;
156 
157 static void do_video_stats(OutputStream *ost, int frame_size);
159 static int64_t getmaxrss(void);
161 
162 __thread int run_as_daemon = 0;
163 __thread int nb_frames_dup = 0;
164 __thread unsigned dup_warning = 1000;
165 __thread int nb_frames_drop = 0;
166 __thread int64_t decode_error_stat[2];
167 
168 __thread int want_sdp = 1;
169 
171 __thread AVIOContext *progress_avio = NULL;
172 
173 __thread uint8_t *subtitle_out;
174 
175 __thread InputStream **input_streams = NULL;
176 __thread int nb_input_streams = 0;
177 __thread InputFile **input_files = NULL;
178 __thread int nb_input_files = 0;
179 
180 __thread OutputStream **output_streams = NULL;
181 __thread int nb_output_streams = 0;
182 __thread OutputFile **output_files = NULL;
183 __thread int nb_output_files = 0;
184 
186 __thread int nb_filtergraphs;
187 
188 void (*report_callback)(int, float, float, int64_t, int, double, double) = NULL;
189 
190 extern __thread int file_overwrite;
191 extern __thread int no_file_overwrite;
192 extern __thread int ignore_unknown_streams;
193 extern __thread int copy_unknown_streams;
194 extern int opt_map(void *optctx, const char *opt, const char *arg);
195 extern int opt_map_channel(void *optctx, const char *opt, const char *arg);
196 extern int opt_recording_timestamp(void *optctx, const char *opt, const char *arg);
197 extern int opt_data_frames(void *optctx, const char *opt, const char *arg);
198 extern int opt_progress(void *optctx, const char *opt, const char *arg);
199 extern int opt_target(void *optctx, const char *opt, const char *arg);
200 extern int opt_vsync(void *optctx, const char *opt, const char *arg);
201 extern int opt_abort_on(void *optctx, const char *opt, const char *arg);
202 extern int opt_qscale(void *optctx, const char *opt, const char *arg);
203 extern int opt_profile(void *optctx, const char *opt, const char *arg);
204 extern int opt_filter_complex(void *optctx, const char *opt, const char *arg);
205 extern int opt_filter_complex_script(void *optctx, const char *opt, const char *arg);
206 extern int opt_attach(void *optctx, const char *opt, const char *arg);
207 extern int opt_video_frames(void *optctx, const char *opt, const char *arg);
208 extern __thread int intra_only;
209 extern int opt_video_codec(void *optctx, const char *opt, const char *arg);
210 extern int opt_sameq(void *optctx, const char *opt, const char *arg);
211 extern int opt_timecode(void *optctx, const char *opt, const char *arg);
212 extern __thread int do_psnr;
213 extern int opt_vstats_file(void *optctx, const char *opt, const char *arg);
214 extern int opt_vstats(void *optctx, const char *opt, const char *arg);
215 extern int opt_video_frames(void *optctx, const char *opt, const char *arg);
216 extern int opt_old2new(void *optctx, const char *opt, const char *arg);
217 extern int opt_streamid(void *optctx, const char *opt, const char *arg);
218 extern int opt_bitrate(void *optctx, const char *opt, const char *arg);
219 extern int show_hwaccels(void *optctx, const char *opt, const char *arg);
220 extern int opt_video_filters(void *optctx, const char *opt, const char *arg);
221 extern int opt_audio_frames(void *optctx, const char *opt, const char *arg);
222 extern int opt_audio_qscale(void *optctx, const char *opt, const char *arg);
223 extern int opt_audio_codec(void *optctx, const char *opt, const char *arg);
224 extern int opt_channel_layout(void *optctx, const char *opt, const char *arg);
225 extern int opt_preset(void *optctx, const char *opt, const char *arg);
226 extern int opt_audio_filters(void *optctx, const char *opt, const char *arg);
227 extern int opt_subtitle_codec(void *optctx, const char *opt, const char *arg);
228 extern int opt_video_channel(void *optctx, const char *opt, const char *arg);
229 extern int opt_video_standard(void *optctx, const char *opt, const char *arg);
230 extern int opt_sdp_file(void *optctx, const char *opt, const char *arg);
231 extern int opt_data_codec(void *optctx, const char *opt, const char *arg);
232 extern int opt_init_hw_device(void *optctx, const char *opt, const char *arg);
233 extern int opt_filter_hw_device(void *optctx, const char *opt, const char *arg);
234 extern __thread int input_sync;
235 
236 #if HAVE_TERMIOS_H
237 
238 /* init terminal so that we can grab keys */
239 __thread struct termios oldtty;
240 __thread int restore_tty;
241 #endif
242 
243 #if HAVE_THREADS
244 static void free_input_threads(void);
245 #endif
246 
247 extern volatile int handleSIGQUIT;
248 extern volatile int handleSIGINT;
249 extern volatile int handleSIGTERM;
250 extern volatile int handleSIGXCPU;
251 extern volatile int handleSIGPIPE;
252 
253 extern __thread volatile long executionId;
254 extern int cancelRequested(long executionId);
255 extern void removeExecution(long executionId);
256 
257 /* sub2video hack:
258  Convert subtitles to video with alpha to insert them in filter graphs.
259  This is a temporary solution until libavfilter gets real subtitles support.
260  */
261 
263 {
264  int ret;
265  AVFrame *frame = ist->sub2video.frame;
266 
267  av_frame_unref(frame);
268  ist->sub2video.frame->width = ist->dec_ctx->width ? ist->dec_ctx->width : ist->sub2video.w;
269  ist->sub2video.frame->height = ist->dec_ctx->height ? ist->dec_ctx->height : ist->sub2video.h;
270  ist->sub2video.frame->format = AV_PIX_FMT_RGB32;
271  if ((ret = av_frame_get_buffer(frame, 32)) < 0)
272  return ret;
273  memset(frame->data[0], 0, frame->height * frame->linesize[0]);
274  return 0;
275 }
276 
277 static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
278  AVSubtitleRect *r)
279 {
280  uint32_t *pal, *dst2;
281  uint8_t *src, *src2;
282  int x, y;
283 
284  if (r->type != SUBTITLE_BITMAP) {
285  av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
286  return;
287  }
288  if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
289  av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle (%d %d %d %d) overflowing %d %d\n",
290  r->x, r->y, r->w, r->h, w, h
291  );
292  return;
293  }
294 
295  dst += r->y * dst_linesize + r->x * 4;
296  src = r->data[0];
297  pal = (uint32_t *)r->data[1];
298  for (y = 0; y < r->h; y++) {
299  dst2 = (uint32_t *)dst;
300  src2 = src;
301  for (x = 0; x < r->w; x++)
302  *(dst2++) = pal[*(src2++)];
303  dst += dst_linesize;
304  src += r->linesize[0];
305  }
306 }
307 
308 static void sub2video_push_ref(InputStream *ist, int64_t pts)
309 {
310  AVFrame *frame = ist->sub2video.frame;
311  int i;
312  int ret;
313 
314  av_assert1(frame->data[0]);
315  ist->sub2video.last_pts = frame->pts = pts;
316  for (i = 0; i < ist->nb_filters; i++) {
317  ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, frame,
318  AV_BUFFERSRC_FLAG_KEEP_REF |
319  AV_BUFFERSRC_FLAG_PUSH);
320  if (ret != AVERROR_EOF && ret < 0)
321  av_log(NULL, AV_LOG_WARNING, "Error while add the frame to buffer source(%s).\n",
322  av_err2str(ret));
323  }
324 }
325 
326 void sub2video_update(InputStream *ist, AVSubtitle *sub)
327 {
328  AVFrame *frame = ist->sub2video.frame;
329  int8_t *dst;
330  int dst_linesize;
331  int num_rects, i;
332  int64_t pts, end_pts;
333 
334  if (!frame)
335  return;
336  if (sub) {
337  pts = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
338  AV_TIME_BASE_Q, ist->st->time_base);
339  end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000LL,
340  AV_TIME_BASE_Q, ist->st->time_base);
341  num_rects = sub->num_rects;
342  } else {
343  pts = ist->sub2video.end_pts;
344  end_pts = INT64_MAX;
345  num_rects = 0;
346  }
347  if (sub2video_get_blank_frame(ist) < 0) {
348  av_log(ist->dec_ctx, AV_LOG_ERROR,
349  "Impossible to get a blank canvas.\n");
350  return;
351  }
352  dst = frame->data [0];
353  dst_linesize = frame->linesize[0];
354  for (i = 0; i < num_rects; i++)
355  sub2video_copy_rect(dst, dst_linesize, frame->width, frame->height, sub->rects[i]);
356  sub2video_push_ref(ist, pts);
357  ist->sub2video.end_pts = end_pts;
358 }
359 
360 static void sub2video_heartbeat(InputStream *ist, int64_t pts)
361 {
362  InputFile *infile = input_files[ist->file_index];
363  int i, j, nb_reqs;
364  int64_t pts2;
365 
366  /* When a frame is read from a file, examine all sub2video streams in
367  the same file and send the sub2video frame again. Otherwise, decoded
368  video frames could be accumulating in the filter graph while a filter
369  (possibly overlay) is desperately waiting for a subtitle frame. */
370  for (i = 0; i < infile->nb_streams; i++) {
371  InputStream *ist2 = input_streams[infile->ist_index + i];
372  if (!ist2->sub2video.frame)
373  continue;
374  /* subtitles seem to be usually muxed ahead of other streams;
375  if not, subtracting a larger time here is necessary */
376  pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
377  /* do not send the heartbeat frame if the subtitle is already ahead */
378  if (pts2 <= ist2->sub2video.last_pts)
379  continue;
380  if (pts2 >= ist2->sub2video.end_pts ||
381  (!ist2->sub2video.frame->data[0] && ist2->sub2video.end_pts < INT64_MAX))
382  sub2video_update(ist2, NULL);
383  for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
384  nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
385  if (nb_reqs)
386  sub2video_push_ref(ist2, pts2);
387  }
388 }
389 
390 static void sub2video_flush(InputStream *ist)
391 {
392  int i;
393  int ret;
394 
395  if (ist->sub2video.end_pts < INT64_MAX)
396  sub2video_update(ist, NULL);
397  for (i = 0; i < ist->nb_filters; i++) {
398  ret = av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
399  if (ret != AVERROR_EOF && ret < 0)
400  av_log(NULL, AV_LOG_WARNING, "Flush the frame error.\n");
401  }
402 }
403 
404 /* end of sub2video hack */
405 
406 static void term_exit_sigsafe(void)
407 {
408 #if HAVE_TERMIOS_H
409  if(restore_tty)
410  tcsetattr (0, TCSANOW, &oldtty);
411 #endif
412 }
413 
414 void term_exit(void)
415 {
416  av_log(NULL, AV_LOG_QUIET, "%s", "");
418 }
419 
420 static volatile int received_sigterm = 0;
421 static volatile int received_nb_signals = 0;
422 __thread atomic_int transcode_init_done = ATOMIC_VAR_INIT(0);
423 __thread volatile int ffmpeg_exited = 0;
424 __thread volatile int main_ffmpeg_return_code = 0;
425 extern __thread volatile int longjmp_value;
426 
427 static void
429 {
430  int ret;
431  received_sigterm = sig;
434  if(received_nb_signals > 3) {
435  ret = write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
436  strlen("Received > 3 system signals, hard exiting\n"));
437  if (ret < 0) { /* Do nothing */ };
438  exit(123);
439  }
440 }
441 
442 #if HAVE_SETCONSOLECTRLHANDLER
443 static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
444 {
445  av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
446 
447  switch (fdwCtrlType)
448  {
449  case CTRL_C_EVENT:
450  case CTRL_BREAK_EVENT:
451  sigterm_handler(SIGINT);
452  return TRUE;
453 
454  case CTRL_CLOSE_EVENT:
455  case CTRL_LOGOFF_EVENT:
456  case CTRL_SHUTDOWN_EVENT:
457  sigterm_handler(SIGTERM);
458  /* Basically, with these 3 events, when we return from this method the
459  process is hard terminated, so stall as long as we need to
460  to try and let the main thread(s) clean up and gracefully terminate
461  (we have at most 5 seconds, but should be done far before that). */
462  while (!ffmpeg_exited) {
463  Sleep(0);
464  }
465  return TRUE;
466 
467  default:
468  av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
469  return FALSE;
470  }
471 }
472 #endif
473 
474 void term_init(void)
475 {
476 #if HAVE_TERMIOS_H
478  struct termios tty;
479  if (tcgetattr (0, &tty) == 0) {
480  oldtty = tty;
481  restore_tty = 1;
482 
483  tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
484  |INLCR|IGNCR|ICRNL|IXON);
485  tty.c_oflag |= OPOST;
486  tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
487  tty.c_cflag &= ~(CSIZE|PARENB);
488  tty.c_cflag |= CS8;
489  tty.c_cc[VMIN] = 1;
490  tty.c_cc[VTIME] = 0;
491 
492  tcsetattr (0, TCSANOW, &tty);
493  }
494  if (handleSIGQUIT == 1) {
495  signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
496  }
497  }
498 #endif
499 
500  if (handleSIGINT == 1) {
501  signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
502  }
503  if (handleSIGTERM == 1) {
504  signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
505  }
506 #ifdef SIGXCPU
507  if (handleSIGXCPU == 1) {
508  signal(SIGXCPU, sigterm_handler);
509  }
510 #endif
511 #ifdef SIGPIPE
512  if (handleSIGPIPE == 1) {
513  signal(SIGPIPE, SIG_IGN); /* Broken pipe (POSIX). */
514  }
515 #endif
516 #if HAVE_SETCONSOLECTRLHANDLER
517  SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
518 #endif
519 }
520 
521 /* read a key without blocking */
522 static int read_key(void)
523 {
524  unsigned char ch;
525 #if HAVE_TERMIOS_H
526  int n = 1;
527  struct timeval tv;
528  fd_set rfds;
529 
530  FD_ZERO(&rfds);
531  FD_SET(0, &rfds);
532  tv.tv_sec = 0;
533  tv.tv_usec = 0;
534  n = select(1, &rfds, NULL, NULL, &tv);
535  if (n > 0) {
536  n = read(0, &ch, 1);
537  if (n == 1)
538  return ch;
539 
540  return n;
541  }
542 #elif HAVE_KBHIT
543 # if HAVE_PEEKNAMEDPIPE
544  static int is_pipe;
545  static HANDLE input_handle;
546  DWORD dw, nchars;
547  if(!input_handle){
548  input_handle = GetStdHandle(STD_INPUT_HANDLE);
549  is_pipe = !GetConsoleMode(input_handle, &dw);
550  }
551 
552  if (is_pipe) {
553  /* When running under a GUI, you will end here. */
554  if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
555  // input pipe may have been closed by the program that ran ffmpeg
556  return -1;
557  }
558  //Read it
559  if(nchars != 0) {
560  read(0, &ch, 1);
561  return ch;
562  }else{
563  return -1;
564  }
565  }
566 # endif
567  if(kbhit())
568  return(getch());
569 #endif
570  return -1;
571 }
572 
573 int decode_interrupt_cb(void *ctx);
574 
575 int decode_interrupt_cb(void *ctx)
576 {
577  return received_nb_signals > atomic_load(&transcode_init_done);
578 }
579 
580 __thread const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
581 
582 static void ffmpeg_cleanup(int ret)
583 {
584  int i, j;
585 
586  if (do_benchmark) {
587  int maxrss = getmaxrss() / 1024;
588  av_log(NULL, AV_LOG_INFO, "bench: maxrss=%ikB\n", maxrss);
589  }
590 
591  for (i = 0; i < nb_filtergraphs; i++) {
592  FilterGraph *fg = filtergraphs[i];
593  avfilter_graph_free(&fg->graph);
594  for (j = 0; j < fg->nb_inputs; j++) {
595  while (av_fifo_size(fg->inputs[j]->frame_queue)) {
596  AVFrame *frame;
597  av_fifo_generic_read(fg->inputs[j]->frame_queue, &frame,
598  sizeof(frame), NULL);
599  av_frame_free(&frame);
600  }
601  av_fifo_freep(&fg->inputs[j]->frame_queue);
602  if (fg->inputs[j]->ist->sub2video.sub_queue) {
603  while (av_fifo_size(fg->inputs[j]->ist->sub2video.sub_queue)) {
604  AVSubtitle sub;
605  av_fifo_generic_read(fg->inputs[j]->ist->sub2video.sub_queue,
606  &sub, sizeof(sub), NULL);
607  avsubtitle_free(&sub);
608  }
609  av_fifo_freep(&fg->inputs[j]->ist->sub2video.sub_queue);
610  }
611  av_buffer_unref(&fg->inputs[j]->hw_frames_ctx);
612  av_freep(&fg->inputs[j]->name);
613  av_freep(&fg->inputs[j]);
614  }
615  av_freep(&fg->inputs);
616  for (j = 0; j < fg->nb_outputs; j++) {
617  av_freep(&fg->outputs[j]->name);
618  av_freep(&fg->outputs[j]->formats);
619  av_freep(&fg->outputs[j]->channel_layouts);
620  av_freep(&fg->outputs[j]->sample_rates);
621  av_freep(&fg->outputs[j]);
622  }
623  av_freep(&fg->outputs);
624  av_freep(&fg->graph_desc);
625 
626  av_freep(&filtergraphs[i]);
627  }
628  av_freep(&filtergraphs);
629 
630  av_freep(&subtitle_out);
631 
632  /* close files */
633  for (i = 0; i < nb_output_files; i++) {
634  OutputFile *of = output_files[i];
635  AVFormatContext *s;
636  if (!of)
637  continue;
638  s = of->ctx;
639  if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
640  avio_closep(&s->pb);
641  avformat_free_context(s);
642  av_dict_free(&of->opts);
643 
644  av_freep(&output_files[i]);
645  }
646  for (i = 0; i < nb_output_streams; i++) {
647  OutputStream *ost = output_streams[i];
648 
649  if (!ost)
650  continue;
651 
652  for (j = 0; j < ost->nb_bitstream_filters; j++)
653  av_bsf_free(&ost->bsf_ctx[j]);
654  av_freep(&ost->bsf_ctx);
655 
656  av_frame_free(&ost->filtered_frame);
657  av_frame_free(&ost->last_frame);
658  av_dict_free(&ost->encoder_opts);
659 
660  av_freep(&ost->forced_keyframes);
661  av_expr_free(ost->forced_keyframes_pexpr);
662  av_freep(&ost->avfilter);
663  av_freep(&ost->logfile_prefix);
664 
665  av_freep(&ost->audio_channels_map);
666  ost->audio_channels_mapped = 0;
667 
668  av_dict_free(&ost->sws_dict);
669  av_dict_free(&ost->swr_opts);
670 
671  avcodec_free_context(&ost->enc_ctx);
672  avcodec_parameters_free(&ost->ref_par);
673 
674  if (ost->muxing_queue) {
675  while (av_fifo_size(ost->muxing_queue)) {
676  AVPacket pkt;
677  av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
678  av_packet_unref(&pkt);
679  }
680  av_fifo_freep(&ost->muxing_queue);
681  }
682 
683  av_freep(&output_streams[i]);
684  }
685 #if HAVE_THREADS
686  free_input_threads();
687 #endif
688  for (i = 0; i < nb_input_files; i++) {
689  avformat_close_input(&input_files[i]->ctx);
690  av_freep(&input_files[i]);
691  }
692  for (i = 0; i < nb_input_streams; i++) {
693  InputStream *ist = input_streams[i];
694 
695  av_frame_free(&ist->decoded_frame);
696  av_frame_free(&ist->filter_frame);
697  av_dict_free(&ist->decoder_opts);
698  avsubtitle_free(&ist->prev_sub.subtitle);
699  av_frame_free(&ist->sub2video.frame);
700  av_freep(&ist->filters);
701  av_freep(&ist->hwaccel_device);
702  av_freep(&ist->dts_buffer);
703 
704  avcodec_free_context(&ist->dec_ctx);
705 
706  av_freep(&input_streams[i]);
707  }
708 
709  if (vstats_file) {
710  if (fclose(vstats_file))
711  av_log(NULL, AV_LOG_ERROR,
712  "Error closing vstats file, loss of information possible: %s\n",
713  av_err2str(AVERROR(errno)));
714  }
715  av_freep(&vstats_filename);
716 
717  av_freep(&input_streams);
718  av_freep(&input_files);
719  av_freep(&output_streams);
720  av_freep(&output_files);
721 
722  uninit_opts();
723 
724  avformat_network_deinit();
725 
726  if (received_sigterm) {
727  av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
728  (int) received_sigterm);
729  } else if (cancelRequested(executionId)) {
730  av_log(NULL, AV_LOG_INFO, "Exiting normally, received cancel signal.\n");
731  } else if (ret && atomic_load(&transcode_init_done)) {
732  av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
733  }
734  term_exit();
735  ffmpeg_exited = 1;
736 }
737 
738 void remove_avoptions(AVDictionary **a, AVDictionary *b)
739 {
740  AVDictionaryEntry *t = NULL;
741 
742  while ((t = av_dict_get(b, "", t, AV_DICT_IGNORE_SUFFIX))) {
743  av_dict_set(a, t->key, NULL, AV_DICT_MATCH_CASE);
744  }
745 }
746 
747 void assert_avoptions(AVDictionary *m)
748 {
749  AVDictionaryEntry *t;
750  if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
751  av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
752  exit_program(1);
753  }
754 }
755 
756 static void abort_codec_experimental(AVCodec *c, int encoder)
757 {
758  exit_program(1);
759 }
760 
761 static void update_benchmark(const char *fmt, ...)
762 {
763  if (do_benchmark_all) {
765  va_list va;
766  char buf[1024];
767 
768  if (fmt) {
769  va_start(va, fmt);
770  vsnprintf(buf, sizeof(buf), fmt, va);
771  va_end(va);
772  av_log(NULL, AV_LOG_INFO,
773  "bench: %8" PRIu64 " user %8" PRIu64 " sys %8" PRIu64 " real %s \n",
776  t.real_usec - current_time.real_usec, buf);
777  }
778  current_time = t;
779  }
780 }
781 
782 static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
783 {
784  int i;
785  for (i = 0; i < nb_output_streams; i++) {
786  OutputStream *ost2 = output_streams[i];
787  ost2->finished |= ost == ost2 ? this_stream : others;
788  }
789 }
790 
791 static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
792 {
793  AVFormatContext *s = of->ctx;
794  AVStream *st = ost->st;
795  int ret;
796 
797  /*
798  * Audio encoders may split the packets -- #frames in != #packets out.
799  * But there is no reordering, so we can limit the number of output packets
800  * by simply dropping them here.
801  * Counting encoded video frames needs to be done separately because of
802  * reordering, see do_video_out().
803  * Do not count the packet when unqueued because it has been counted when queued.
804  */
805  if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed) && !unqueue) {
806  if (ost->frame_number >= ost->max_frames) {
807  av_packet_unref(pkt);
808  return;
809  }
810  ost->frame_number++;
811  }
812 
813  if (!of->header_written) {
814  AVPacket tmp_pkt = {0};
815  /* the muxer is not initialized yet, buffer the packet */
816  if (!av_fifo_space(ost->muxing_queue)) {
817  int new_size = FFMIN(2 * av_fifo_size(ost->muxing_queue),
818  ost->max_muxing_queue_size);
819  if (new_size <= av_fifo_size(ost->muxing_queue)) {
820  av_log(NULL, AV_LOG_ERROR,
821  "Too many packets buffered for output stream %d:%d.\n",
822  ost->file_index, ost->st->index);
823  exit_program(1);
824  }
825  ret = av_fifo_realloc2(ost->muxing_queue, new_size);
826  if (ret < 0)
827  exit_program(1);
828  }
829  ret = av_packet_make_refcounted(pkt);
830  if (ret < 0)
831  exit_program(1);
832  av_packet_move_ref(&tmp_pkt, pkt);
833  av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);
834  return;
835  }
836 
837  if ((st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
838  (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
839  pkt->pts = pkt->dts = AV_NOPTS_VALUE;
840 
841  if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
842  int i;
843  uint8_t *sd = av_packet_get_side_data(pkt, AV_PKT_DATA_QUALITY_STATS,
844  NULL);
845  ost->quality = sd ? AV_RL32(sd) : -1;
846  ost->pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;
847 
848  for (i = 0; i<FF_ARRAY_ELEMS(ost->error); i++) {
849  if (sd && i < sd[5])
850  ost->error[i] = AV_RL64(sd + 8 + 8*i);
851  else
852  ost->error[i] = -1;
853  }
854 
855  if (ost->frame_rate.num && ost->is_cfr) {
856  if (pkt->duration > 0)
857  av_log(NULL, AV_LOG_WARNING, "Overriding packet duration by frame rate, this should not happen\n");
858  pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
859  ost->mux_timebase);
860  }
861  }
862 
863  av_packet_rescale_ts(pkt, ost->mux_timebase, ost->st->time_base);
864 
865  if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
866  if (pkt->dts != AV_NOPTS_VALUE &&
867  pkt->pts != AV_NOPTS_VALUE &&
868  pkt->dts > pkt->pts) {
869  av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
870  pkt->dts, pkt->pts,
871  ost->file_index, ost->st->index);
872  pkt->pts =
873  pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1
874  - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)
875  - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);
876  }
877  if ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO || st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) &&
878  pkt->dts != AV_NOPTS_VALUE &&
879  !(st->codecpar->codec_id == AV_CODEC_ID_VP9 && ost->stream_copy) &&
880  ost->last_mux_dts != AV_NOPTS_VALUE) {
881  int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
882  if (pkt->dts < max) {
883  int loglevel = max - pkt->dts > 2 || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
884  av_log(s, loglevel, "Non-monotonous DTS in output stream "
885  "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
886  ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
887  if (exit_on_error) {
888  av_log(NULL, AV_LOG_FATAL, "aborting.\n");
889  exit_program(1);
890  }
891  av_log(s, loglevel, "changing to %"PRId64". This may result "
892  "in incorrect timestamps in the output file.\n",
893  max);
894  if (pkt->pts >= pkt->dts)
895  pkt->pts = FFMAX(pkt->pts, max);
896  pkt->dts = max;
897  }
898  }
899  }
900  ost->last_mux_dts = pkt->dts;
901 
902  ost->data_size += pkt->size;
903  ost->packets_written++;
904 
905  pkt->stream_index = ost->index;
906 
907  if (debug_ts) {
908  av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
909  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
910  av_get_media_type_string(ost->enc_ctx->codec_type),
911  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
912  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
913  pkt->size
914  );
915  }
916 
917  ret = av_interleaved_write_frame(s, pkt);
918  if (ret < 0) {
919  print_error("av_interleaved_write_frame()", ret);
922  }
923  av_packet_unref(pkt);
924 }
925 
927 {
928  OutputFile *of = output_files[ost->file_index];
929 
930  ost->finished |= ENCODER_FINISHED;
931  if (of->shortest) {
932  int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, AV_TIME_BASE_Q);
933  of->recording_time = FFMIN(of->recording_time, end);
934  }
935 }
936 
937 /*
938  * Send a single packet to the output, applying any bitstream filters
939  * associated with the output stream. This may result in any number
940  * of packets actually being written, depending on what bitstream
941  * filters are applied. The supplied packet is consumed and will be
942  * blank (as if newly-allocated) when this function returns.
943  *
944  * If eof is set, instead indicate EOF to all bitstream filters and
945  * therefore flush any delayed packets to the output. A blank packet
946  * must be supplied in this case.
947  */
948 static void output_packet(OutputFile *of, AVPacket *pkt,
949  OutputStream *ost, int eof)
950 {
951  int ret = 0;
952 
953  /* apply the output bitstream filters, if any */
954  if (ost->nb_bitstream_filters) {
955  int idx;
956 
957  ret = av_bsf_send_packet(ost->bsf_ctx[0], eof ? NULL : pkt);
958  if (ret < 0)
959  goto finish;
960 
961  eof = 0;
962  idx = 1;
963  while (idx) {
964  /* get a packet from the previous filter up the chain */
965  ret = av_bsf_receive_packet(ost->bsf_ctx[idx - 1], pkt);
966  if (ret == AVERROR(EAGAIN)) {
967  ret = 0;
968  idx--;
969  continue;
970  } else if (ret == AVERROR_EOF) {
971  eof = 1;
972  } else if (ret < 0)
973  goto finish;
974 
975  /* send it to the next filter down the chain or to the muxer */
976  if (idx < ost->nb_bitstream_filters) {
977  ret = av_bsf_send_packet(ost->bsf_ctx[idx], eof ? NULL : pkt);
978  if (ret < 0)
979  goto finish;
980  idx++;
981  eof = 0;
982  } else if (eof)
983  goto finish;
984  else
985  write_packet(of, pkt, ost, 0);
986  }
987  } else if (!eof)
988  write_packet(of, pkt, ost, 0);
989 
990 finish:
991  if (ret < 0 && ret != AVERROR_EOF) {
992  av_log(NULL, AV_LOG_ERROR, "Error applying bitstream filters to an output "
993  "packet for stream #%d:%d.\n", ost->file_index, ost->index);
994  if(exit_on_error)
995  exit_program(1);
996  }
997 }
998 
1000 {
1001  OutputFile *of = output_files[ost->file_index];
1002 
1003  if (of->recording_time != INT64_MAX &&
1004  av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
1005  AV_TIME_BASE_Q) >= 0) {
1006  close_output_stream(ost);
1007  return 0;
1008  }
1009  return 1;
1010 }
1011 
1012 static void do_audio_out(OutputFile *of, OutputStream *ost,
1013  AVFrame *frame)
1014 {
1015  AVCodecContext *enc = ost->enc_ctx;
1016  AVPacket pkt;
1017  int ret;
1018 
1019  av_init_packet(&pkt);
1020  pkt.data = NULL;
1021  pkt.size = 0;
1022 
1023  if (!check_recording_time(ost))
1024  return;
1025 
1026  if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
1027  frame->pts = ost->sync_opts;
1028  ost->sync_opts = frame->pts + frame->nb_samples;
1029  ost->samples_encoded += frame->nb_samples;
1030  ost->frames_encoded++;
1031 
1032  av_assert0(pkt.size || !pkt.data);
1033  update_benchmark(NULL);
1034  if (debug_ts) {
1035  av_log(NULL, AV_LOG_INFO, "encoder <- type:audio "
1036  "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1037  av_ts2str(frame->pts), av_ts2timestr(frame->pts, &enc->time_base),
1038  enc->time_base.num, enc->time_base.den);
1039  }
1040 
1041  ret = avcodec_send_frame(enc, frame);
1042  if (ret < 0)
1043  goto error;
1044 
1045  while (1) {
1046  ret = avcodec_receive_packet(enc, &pkt);
1047  if (ret == AVERROR(EAGAIN))
1048  break;
1049  if (ret < 0)
1050  goto error;
1051 
1052  update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
1053 
1054  av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
1055 
1056  if (debug_ts) {
1057  av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
1058  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1059  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
1060  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
1061  }
1062 
1063  output_packet(of, &pkt, ost, 0);
1064  }
1065 
1066  return;
1067 error:
1068  av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1069  exit_program(1);
1070 }
1071 
1072 static void do_subtitle_out(OutputFile *of,
1073  OutputStream *ost,
1074  AVSubtitle *sub)
1075 {
1076  int subtitle_out_max_size = 1024 * 1024;
1077  int subtitle_out_size, nb, i;
1078  AVCodecContext *enc;
1079  AVPacket pkt;
1080  int64_t pts;
1081 
1082  if (sub->pts == AV_NOPTS_VALUE) {
1083  av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1084  if (exit_on_error)
1085  exit_program(1);
1086  return;
1087  }
1088 
1089  enc = ost->enc_ctx;
1090 
1091  if (!subtitle_out) {
1092  subtitle_out = av_malloc(subtitle_out_max_size);
1093  if (!subtitle_out) {
1094  av_log(NULL, AV_LOG_FATAL, "Failed to allocate subtitle_out\n");
1095  exit_program(1);
1096  }
1097  }
1098 
1099  /* Note: DVB subtitle need one packet to draw them and one other
1100  packet to clear them */
1101  /* XXX: signal it in the codec context ? */
1102  if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1103  nb = 2;
1104  else
1105  nb = 1;
1106 
1107  /* shift timestamp to honor -ss and make check_recording_time() work with -t */
1108  pts = sub->pts;
1109  if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
1110  pts -= output_files[ost->file_index]->start_time;
1111  for (i = 0; i < nb; i++) {
1112  unsigned save_num_rects = sub->num_rects;
1113 
1114  ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
1115  if (!check_recording_time(ost))
1116  return;
1117 
1118  sub->pts = pts;
1119  // start_display_time is required to be 0
1120  sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1121  sub->end_display_time -= sub->start_display_time;
1122  sub->start_display_time = 0;
1123  if (i == 1)
1124  sub->num_rects = 0;
1125 
1126  ost->frames_encoded++;
1127 
1128  subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1129  subtitle_out_max_size, sub);
1130  if (i == 1)
1131  sub->num_rects = save_num_rects;
1132  if (subtitle_out_size < 0) {
1133  av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1134  exit_program(1);
1135  }
1136 
1137  av_init_packet(&pkt);
1138  pkt.data = subtitle_out;
1139  pkt.size = subtitle_out_size;
1140  pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->mux_timebase);
1141  pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
1142  if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
1143  /* XXX: the pts correction is handled here. Maybe handling
1144  it in the codec would be better */
1145  if (i == 0)
1146  pkt.pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
1147  else
1148  pkt.pts += av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
1149  }
1150  pkt.dts = pkt.pts;
1151  output_packet(of, &pkt, ost, 0);
1152  }
1153 }
1154 
1155 static void do_video_out(OutputFile *of,
1156  OutputStream *ost,
1157  AVFrame *next_picture,
1158  double sync_ipts)
1159 {
1160  int ret, format_video_sync;
1161  AVPacket pkt;
1162  AVCodecContext *enc = ost->enc_ctx;
1163  AVCodecParameters *mux_par = ost->st->codecpar;
1164  AVRational frame_rate;
1165  int nb_frames, nb0_frames, i;
1166  double delta, delta0;
1167  double duration = 0;
1168  int frame_size = 0;
1169  InputStream *ist = NULL;
1170  AVFilterContext *filter = ost->filter->filter;
1171 
1172  if (ost->source_index >= 0)
1173  ist = input_streams[ost->source_index];
1174 
1175  frame_rate = av_buffersink_get_frame_rate(filter);
1176  if (frame_rate.num > 0 && frame_rate.den > 0)
1177  duration = 1/(av_q2d(frame_rate) * av_q2d(enc->time_base));
1178 
1179  if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
1180  duration = FFMIN(duration, 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base)));
1181 
1182  if (!ost->filters_script &&
1183  !ost->filters &&
1184  (nb_filtergraphs == 0 || !filtergraphs[0]->graph_desc) &&
1185  next_picture &&
1186  ist &&
1187  lrintf(next_picture->pkt_duration * av_q2d(ist->st->time_base) / av_q2d(enc->time_base)) > 0) {
1188  duration = lrintf(next_picture->pkt_duration * av_q2d(ist->st->time_base) / av_q2d(enc->time_base));
1189  }
1190 
1191  if (!next_picture) {
1192  //end, flushing
1193  nb0_frames = nb_frames = mid_pred(ost->last_nb0_frames[0],
1194  ost->last_nb0_frames[1],
1195  ost->last_nb0_frames[2]);
1196  } else {
1197  delta0 = sync_ipts - ost->sync_opts; // delta0 is the "drift" between the input frame (next_picture) and where it would fall in the output.
1198  delta = delta0 + duration;
1199 
1200  /* by default, we output a single frame */
1201  nb0_frames = 0; // tracks the number of times the PREVIOUS frame should be duplicated, mostly for variable framerate (VFR)
1202  nb_frames = 1;
1203 
1204  format_video_sync = video_sync_method;
1205  if (format_video_sync == VSYNC_AUTO) {
1206  if(!strcmp(of->ctx->oformat->name, "avi")) {
1207  format_video_sync = VSYNC_VFR;
1208  } else
1209  format_video_sync = (of->ctx->oformat->flags & AVFMT_VARIABLE_FPS) ? ((of->ctx->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
1210  if ( ist
1211  && format_video_sync == VSYNC_CFR
1212  && input_files[ist->file_index]->ctx->nb_streams == 1
1213  && input_files[ist->file_index]->input_ts_offset == 0) {
1214  format_video_sync = VSYNC_VSCFR;
1215  }
1216  if (format_video_sync == VSYNC_CFR && copy_ts) {
1217  format_video_sync = VSYNC_VSCFR;
1218  }
1219  }
1220  ost->is_cfr = (format_video_sync == VSYNC_CFR || format_video_sync == VSYNC_VSCFR);
1221 
1222  if (delta0 < 0 &&
1223  delta > 0 &&
1224  format_video_sync != VSYNC_PASSTHROUGH &&
1225  format_video_sync != VSYNC_DROP) {
1226  if (delta0 < -0.6) {
1227  av_log(NULL, AV_LOG_VERBOSE, "Past duration %f too large\n", -delta0);
1228  } else
1229  av_log(NULL, AV_LOG_DEBUG, "Clipping frame in rate conversion by %f\n", -delta0);
1230  sync_ipts = ost->sync_opts;
1231  duration += delta0;
1232  delta0 = 0;
1233  }
1234 
1235  switch (format_video_sync) {
1236  case VSYNC_VSCFR:
1237  if (ost->frame_number == 0 && delta0 >= 0.5) {
1238  av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta0));
1239  delta = duration;
1240  delta0 = 0;
1241  ost->sync_opts = lrint(sync_ipts);
1242  }
1243  case VSYNC_CFR:
1244  // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1245  if (frame_drop_threshold && delta < frame_drop_threshold && ost->frame_number) {
1246  nb_frames = 0;
1247  } else if (delta < -1.1)
1248  nb_frames = 0;
1249  else if (delta > 1.1) {
1250  nb_frames = lrintf(delta);
1251  if (delta0 > 1.1)
1252  nb0_frames = lrintf(delta0 - 0.6);
1253  }
1254  break;
1255  case VSYNC_VFR:
1256  if (delta <= -0.6)
1257  nb_frames = 0;
1258  else if (delta > 0.6)
1259  ost->sync_opts = lrint(sync_ipts);
1260  break;
1261  case VSYNC_DROP:
1262  case VSYNC_PASSTHROUGH:
1263  ost->sync_opts = lrint(sync_ipts);
1264  break;
1265  default:
1266  av_assert0(0);
1267  }
1268  }
1269 
1270  nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1271  nb0_frames = FFMIN(nb0_frames, nb_frames);
1272 
1273  memmove(ost->last_nb0_frames + 1,
1274  ost->last_nb0_frames,
1275  sizeof(ost->last_nb0_frames[0]) * (FF_ARRAY_ELEMS(ost->last_nb0_frames) - 1));
1276  ost->last_nb0_frames[0] = nb0_frames;
1277 
1278  if (nb0_frames == 0 && ost->last_dropped) {
1279  nb_frames_drop++;
1280  av_log(NULL, AV_LOG_VERBOSE,
1281  "*** dropping frame %d from stream %d at ts %"PRId64"\n",
1282  ost->frame_number, ost->st->index, ost->last_frame->pts);
1283  }
1284  if (nb_frames > (nb0_frames && ost->last_dropped) + (nb_frames > nb0_frames)) {
1285  if (nb_frames > dts_error_threshold * 30) {
1286  av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
1287  nb_frames_drop++;
1288  return;
1289  }
1290  nb_frames_dup += nb_frames - (nb0_frames && ost->last_dropped) - (nb_frames > nb0_frames);
1291  av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1292  if (nb_frames_dup > dup_warning) {
1293  av_log(NULL, AV_LOG_WARNING, "More than %d frames duplicated\n", dup_warning);
1294  dup_warning *= 10;
1295  }
1296  }
1297  ost->last_dropped = nb_frames == nb0_frames && next_picture;
1298 
1299  /* duplicates frame if needed */
1300  for (i = 0; i < nb_frames; i++) {
1301  AVFrame *in_picture;
1302  int forced_keyframe = 0;
1303  double pts_time;
1304  av_init_packet(&pkt);
1305  pkt.data = NULL;
1306  pkt.size = 0;
1307 
1308  if (i < nb0_frames && ost->last_frame) {
1309  in_picture = ost->last_frame;
1310  } else
1311  in_picture = next_picture;
1312 
1313  if (!in_picture)
1314  return;
1315 
1316  in_picture->pts = ost->sync_opts;
1317 
1318  if (!check_recording_time(ost))
1319  return;
1320 
1321  if (enc->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&
1322  ost->top_field_first >= 0)
1323  in_picture->top_field_first = !!ost->top_field_first;
1324 
1325  if (in_picture->interlaced_frame) {
1326  if (enc->codec->id == AV_CODEC_ID_MJPEG)
1327  mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
1328  else
1329  mux_par->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
1330  } else
1331  mux_par->field_order = AV_FIELD_PROGRESSIVE;
1332 
1333  in_picture->quality = enc->global_quality;
1334  in_picture->pict_type = 0;
1335 
1336  if (ost->forced_kf_ref_pts == AV_NOPTS_VALUE &&
1337  in_picture->pts != AV_NOPTS_VALUE)
1338  ost->forced_kf_ref_pts = in_picture->pts;
1339 
1340  pts_time = in_picture->pts != AV_NOPTS_VALUE ?
1341  (in_picture->pts - ost->forced_kf_ref_pts) * av_q2d(enc->time_base) : NAN;
1342  if (ost->forced_kf_index < ost->forced_kf_count &&
1343  in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1344  ost->forced_kf_index++;
1345  forced_keyframe = 1;
1346  } else if (ost->forced_keyframes_pexpr) {
1347  double res;
1348  ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
1349  res = av_expr_eval(ost->forced_keyframes_pexpr,
1351  ff_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
1357  res);
1358  if (res) {
1359  forced_keyframe = 1;
1365  }
1366 
1368  } else if ( ost->forced_keyframes
1369  && !strncmp(ost->forced_keyframes, "source", 6)
1370  && in_picture->key_frame==1) {
1371  forced_keyframe = 1;
1372  }
1373 
1374  if (forced_keyframe) {
1375  in_picture->pict_type = AV_PICTURE_TYPE_I;
1376  av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
1377  }
1378 
1379  update_benchmark(NULL);
1380  if (debug_ts) {
1381  av_log(NULL, AV_LOG_INFO, "encoder <- type:video "
1382  "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1383  av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
1384  enc->time_base.num, enc->time_base.den);
1385  }
1386 
1387  ost->frames_encoded++;
1388 
1389  ret = avcodec_send_frame(enc, in_picture);
1390  if (ret < 0)
1391  goto error;
1392  // Make sure Closed Captions will not be duplicated
1393  av_frame_remove_side_data(in_picture, AV_FRAME_DATA_A53_CC);
1394 
1395  while (1) {
1396  ret = avcodec_receive_packet(enc, &pkt);
1397  update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
1398  if (ret == AVERROR(EAGAIN))
1399  break;
1400  if (ret < 0)
1401  goto error;
1402 
1403  if (debug_ts) {
1404  av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1405  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1406  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &enc->time_base),
1407  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));
1408  }
1409 
1410  if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & AV_CODEC_CAP_DELAY))
1411  pkt.pts = ost->sync_opts;
1412 
1413  av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
1414 
1415  if (debug_ts) {
1416  av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1417  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1418  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->mux_timebase),
1419  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->mux_timebase));
1420  }
1421 
1422  frame_size = pkt.size;
1423  output_packet(of, &pkt, ost, 0);
1424 
1425  /* if two pass, output log */
1426  if (ost->logfile && enc->stats_out) {
1427  fprintf(ost->logfile, "%s", enc->stats_out);
1428  }
1429  }
1430  ost->sync_opts++;
1431  /*
1432  * For video, number of frames in == number of packets out.
1433  * But there may be reordering, so we can't throw away frames on encoder
1434  * flush, we need to limit them here, before they go into encoder.
1435  */
1436  ost->frame_number++;
1437 
1438  if (vstats_filename && frame_size)
1439  do_video_stats(ost, frame_size);
1440  }
1441 
1442  if (!ost->last_frame)
1443  ost->last_frame = av_frame_alloc();
1444  av_frame_unref(ost->last_frame);
1445  if (next_picture && ost->last_frame)
1446  av_frame_ref(ost->last_frame, next_picture);
1447  else
1448  av_frame_free(&ost->last_frame);
1449 
1450  return;
1451 error:
1452  av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1453  exit_program(1);
1454 }
1455 
1456 static double psnr(double d)
1457 {
1458  return -10.0 * log10(d);
1459 }
1460 
1461 static void do_video_stats(OutputStream *ost, int frame_size)
1462 {
1463  AVCodecContext *enc;
1464  int frame_number;
1465  double ti1, bitrate, avg_bitrate;
1466 
1467  /* this is executed just the first time do_video_stats is called */
1468  if (!vstats_file) {
1469  vstats_file = fopen(vstats_filename, "w");
1470  if (!vstats_file) {
1471  perror("fopen");
1472  exit_program(1);
1473  }
1474  }
1475 
1476  enc = ost->enc_ctx;
1477  if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1478  frame_number = ost->st->nb_frames;
1479  if (vstats_version <= 1) {
1480  fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
1481  ost->quality / (float)FF_QP2LAMBDA);
1482  } else {
1483  fprintf(vstats_file, "out= %2d st= %2d frame= %5d q= %2.1f ", ost->file_index, ost->index, frame_number,
1484  ost->quality / (float)FF_QP2LAMBDA);
1485  }
1486 
1487  if (ost->error[0]>=0 && (enc->flags & AV_CODEC_FLAG_PSNR))
1488  fprintf(vstats_file, "PSNR= %6.2f ", psnr(ost->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1489 
1490  fprintf(vstats_file,"f_size= %6d ", frame_size);
1491  /* compute pts value */
1492  ti1 = av_stream_get_end_pts(ost->st) * av_q2d(ost->st->time_base);
1493  if (ti1 < 0.01)
1494  ti1 = 0.01;
1495 
1496  bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1497  avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
1498  fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1499  (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
1500  fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(ost->pict_type));
1501  }
1502 }
1503 
1504 static int init_output_stream(OutputStream *ost, char *error, int error_len);
1505 
1507 {
1508  OutputFile *of = output_files[ost->file_index];
1509  int i;
1510 
1512 
1513  if (of->shortest) {
1514  for (i = 0; i < of->ctx->nb_streams; i++)
1516  }
1517 }
1518 
1525 static int reap_filters(int flush)
1526 {
1527  AVFrame *filtered_frame = NULL;
1528  int i;
1529 
1530  /* Reap all buffers present in the buffer sinks */
1531  for (i = 0; i < nb_output_streams; i++) {
1532  OutputStream *ost = output_streams[i];
1533  OutputFile *of = output_files[ost->file_index];
1534  AVFilterContext *filter;
1535  AVCodecContext *enc = ost->enc_ctx;
1536  int ret = 0;
1537 
1538  if (!ost->filter || !ost->filter->graph->graph)
1539  continue;
1540  filter = ost->filter->filter;
1541 
1542  if (!ost->initialized) {
1543  char error[1024] = "";
1544  ret = init_output_stream(ost, error, sizeof(error));
1545  if (ret < 0) {
1546  av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
1547  ost->file_index, ost->index, error);
1548  exit_program(1);
1549  }
1550  }
1551 
1552  if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
1553  return AVERROR(ENOMEM);
1554  }
1555  filtered_frame = ost->filtered_frame;
1556 
1557  while (1) {
1558  double float_pts = AV_NOPTS_VALUE; // this is identical to filtered_frame.pts but with higher precision
1559  ret = av_buffersink_get_frame_flags(filter, filtered_frame,
1560  AV_BUFFERSINK_FLAG_NO_REQUEST);
1561  if (ret < 0) {
1562  if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
1563  av_log(NULL, AV_LOG_WARNING,
1564  "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
1565  } else if (flush && ret == AVERROR_EOF) {
1566  if (av_buffersink_get_type(filter) == AVMEDIA_TYPE_VIDEO)
1567  do_video_out(of, ost, NULL, AV_NOPTS_VALUE);
1568  }
1569  break;
1570  }
1571  if (ost->finished) {
1572  av_frame_unref(filtered_frame);
1573  continue;
1574  }
1575  if (filtered_frame->pts != AV_NOPTS_VALUE) {
1576  int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
1577  AVRational filter_tb = av_buffersink_get_time_base(filter);
1578  AVRational tb = enc->time_base;
1579  int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
1580 
1581  tb.den <<= extra_bits;
1582  float_pts =
1583  av_rescale_q(filtered_frame->pts, filter_tb, tb) -
1584  av_rescale_q(start_time, AV_TIME_BASE_Q, tb);
1585  float_pts /= 1 << extra_bits;
1586  // avoid exact midoints to reduce the chance of rounding differences, this can be removed in case the fps code is changed to work with integers
1587  float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
1588 
1589  filtered_frame->pts =
1590  av_rescale_q(filtered_frame->pts, filter_tb, enc->time_base) -
1591  av_rescale_q(start_time, AV_TIME_BASE_Q, enc->time_base);
1592  }
1593 
1594  switch (av_buffersink_get_type(filter)) {
1595  case AVMEDIA_TYPE_VIDEO:
1596  if (!ost->frame_aspect_ratio.num)
1597  enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
1598 
1599  if (debug_ts) {
1600  av_log(NULL, AV_LOG_INFO, "filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
1601  av_ts2str(filtered_frame->pts), av_ts2timestr(filtered_frame->pts, &enc->time_base),
1602  float_pts,
1603  enc->time_base.num, enc->time_base.den);
1604  }
1605 
1606  do_video_out(of, ost, filtered_frame, float_pts);
1607  break;
1608  case AVMEDIA_TYPE_AUDIO:
1609  if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&
1610  enc->channels != filtered_frame->channels) {
1611  av_log(NULL, AV_LOG_ERROR,
1612  "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1613  break;
1614  }
1615  do_audio_out(of, ost, filtered_frame);
1616  break;
1617  default:
1618  // TODO support subtitle filters
1619  av_assert0(0);
1620  }
1621 
1622  av_frame_unref(filtered_frame);
1623  }
1624  }
1625 
1626  return 0;
1627 }
1628 
1629 static void print_final_stats(int64_t total_size)
1630 {
1631  uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
1632  uint64_t subtitle_size = 0;
1633  uint64_t data_size = 0;
1634  float percent = -1.0;
1635  int i, j;
1636  int pass1_used = 1;
1637 
1638  for (i = 0; i < nb_output_streams; i++) {
1639  OutputStream *ost = output_streams[i];
1640  switch (ost->enc_ctx->codec_type) {
1641  case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
1642  case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
1643  case AVMEDIA_TYPE_SUBTITLE: subtitle_size += ost->data_size; break;
1644  default: other_size += ost->data_size; break;
1645  }
1646  extra_size += ost->enc_ctx->extradata_size;
1647  data_size += ost->data_size;
1648  if ( (ost->enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
1649  != AV_CODEC_FLAG_PASS1)
1650  pass1_used = 0;
1651  }
1652 
1653  if (data_size && total_size>0 && total_size >= data_size)
1654  percent = 100.0 * (total_size - data_size) / data_size;
1655 
1656  av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0fkB other streams:%1.0fkB global headers:%1.0fkB muxing overhead: ",
1657  video_size / 1024.0,
1658  audio_size / 1024.0,
1659  subtitle_size / 1024.0,
1660  other_size / 1024.0,
1661  extra_size / 1024.0);
1662  if (percent >= 0.0)
1663  av_log(NULL, AV_LOG_INFO, "%f%%", percent);
1664  else
1665  av_log(NULL, AV_LOG_INFO, "unknown");
1666  av_log(NULL, AV_LOG_INFO, "\n");
1667 
1668  /* print verbose per-stream stats */
1669  for (i = 0; i < nb_input_files; i++) {
1670  InputFile *f = input_files[i];
1671  uint64_t total_packets = 0, total_size = 0;
1672 
1673  av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
1674  i, f->ctx->url);
1675 
1676  for (j = 0; j < f->nb_streams; j++) {
1677  InputStream *ist = input_streams[f->ist_index + j];
1678  enum AVMediaType type = ist->dec_ctx->codec_type;
1679 
1680  total_size += ist->data_size;
1681  total_packets += ist->nb_packets;
1682 
1683  av_log(NULL, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
1684  i, j, media_type_string(type));
1685  av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
1686  ist->nb_packets, ist->data_size);
1687 
1688  if (ist->decoding_needed) {
1689  av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
1690  ist->frames_decoded);
1691  if (type == AVMEDIA_TYPE_AUDIO)
1692  av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
1693  av_log(NULL, AV_LOG_VERBOSE, "; ");
1694  }
1695 
1696  av_log(NULL, AV_LOG_VERBOSE, "\n");
1697  }
1698 
1699  av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
1700  total_packets, total_size);
1701  }
1702 
1703  for (i = 0; i < nb_output_files; i++) {
1704  OutputFile *of = output_files[i];
1705  uint64_t total_packets = 0, total_size = 0;
1706 
1707  av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
1708  i, of->ctx->url);
1709 
1710  for (j = 0; j < of->ctx->nb_streams; j++) {
1711  OutputStream *ost = output_streams[of->ost_index + j];
1712  enum AVMediaType type = ost->enc_ctx->codec_type;
1713 
1714  total_size += ost->data_size;
1715  total_packets += ost->packets_written;
1716 
1717  av_log(NULL, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
1718  i, j, media_type_string(type));
1719  if (ost->encoding_needed) {
1720  av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
1721  ost->frames_encoded);
1722  if (type == AVMEDIA_TYPE_AUDIO)
1723  av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
1724  av_log(NULL, AV_LOG_VERBOSE, "; ");
1725  }
1726 
1727  av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
1728  ost->packets_written, ost->data_size);
1729 
1730  av_log(NULL, AV_LOG_VERBOSE, "\n");
1731  }
1732 
1733  av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
1734  total_packets, total_size);
1735  }
1736  if(video_size + data_size + audio_size + subtitle_size + extra_size == 0){
1737  av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded ");
1738  if (pass1_used) {
1739  av_log(NULL, AV_LOG_WARNING, "\n");
1740  } else {
1741  av_log(NULL, AV_LOG_WARNING, "(check -ss / -t / -frames parameters if used)\n");
1742  }
1743  }
1744 }
1745 
1746 
1747 static void forward_report(int is_last_report, int64_t timer_start, int64_t cur_time)
1748 {
1749  AVFormatContext *oc = NULL;
1750  AVCodecContext *enc = NULL;
1751  OutputStream *ost = NULL;
1752  static int64_t last_time = -1;
1753  int64_t pts = INT64_MIN + 1;
1754  int vid, i;
1755 
1756  int frame_number = 0;
1757  float fps = 0;
1758  float quality = 0;
1759  int64_t total_size = 0;
1760  int seconds = 0;
1761  double bitrate = 0.0;
1762  double speed = 0.0;
1763 
1764  // 1. calculate operation duration
1765  if (!is_last_report) {
1766  if (last_time == -1) {
1767  last_time = cur_time;
1768  return;
1769  }
1770  if ((cur_time - last_time) < 500000) {
1771  return;
1772  }
1773  last_time = cur_time;
1774  }
1775  float t = (cur_time-timer_start) / 1000000.0;
1776 
1777  oc = output_files[0]->ctx;
1778 
1779  // 2. calculate size
1780  total_size = avio_size(oc->pb);
1781  if (total_size <= 0) {
1782  total_size = avio_tell(oc->pb);
1783  }
1784 
1785  vid = 0;
1786  for (i = 0; i < nb_output_streams; i++) {
1787  ost = output_streams[i];
1788  enc = ost->enc_ctx;
1789 
1790  if (!ost->stream_copy) {
1791 
1792  // 3. extract quality
1793  quality = ost->quality / (float) FF_QP2LAMBDA;
1794  }
1795 
1796  if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1797 
1798  // 4. extract frame number
1799  frame_number = ost->frame_number;
1800 
1801  // 5. calculate fps
1802  fps = t > 1 ? frame_number / t : 0;
1803  }
1804 
1805  // 6. calculate time
1806  if (av_stream_get_end_pts(ost->st) != AV_NOPTS_VALUE)
1807  pts = FFMAX(pts, av_rescale_q(av_stream_get_end_pts(ost->st),
1808  ost->st->time_base, AV_TIME_BASE_Q));
1809 
1810  vid = 1;
1811  }
1812 
1813  // 7. calculate time, with microseconds to milliseconds conversion
1814  seconds = FFABS(pts) / 1000;
1815 
1816  // 8. calculating kbit/s value
1817  bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
1818 
1819  // 9. calculate processing speed = processed stream duration/operation duration
1820  speed = t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
1821 
1822  // FORWARD DATA
1823  if (report_callback != NULL) {
1824  report_callback(frame_number, fps, quality, total_size, seconds, bitrate, speed);
1825  }
1826 }
1827 
1828 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
1829 {
1830  AVBPrint buf, buf_script;
1831  OutputStream *ost;
1832  AVFormatContext *oc;
1833  int64_t total_size;
1834  AVCodecContext *enc;
1835  int frame_number, vid, i;
1836  double bitrate;
1837  double speed;
1838  int64_t pts = INT64_MIN + 1;
1839  static int64_t last_time = -1;
1840  static int qp_histogram[52];
1841  int hours, mins, secs, us;
1842  const char *hours_sign;
1843  int ret;
1844  float t;
1845 
1846  // FORWARD IT BEFORE PROCESSING
1847  forward_report(is_last_report, timer_start, cur_time);
1848 
1849  if (!print_stats && !is_last_report && !progress_avio)
1850  return;
1851 
1852  if (!is_last_report) {
1853  if (last_time == -1) {
1854  last_time = cur_time;
1855  return;
1856  }
1857  if ((cur_time - last_time) < 500000)
1858  return;
1859  last_time = cur_time;
1860  }
1861 
1862  t = (cur_time-timer_start) / 1000000.0;
1863 
1864 
1865  oc = output_files[0]->ctx;
1866 
1867  total_size = avio_size(oc->pb);
1868  if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
1869  total_size = avio_tell(oc->pb);
1870 
1871  vid = 0;
1872  av_bprint_init(&buf, 0, AV_BPRINT_SIZE_AUTOMATIC);
1873  av_bprint_init(&buf_script, 0, AV_BPRINT_SIZE_AUTOMATIC);
1874  for (i = 0; i < nb_output_streams; i++) {
1875  float q = -1;
1876  ost = output_streams[i];
1877  enc = ost->enc_ctx;
1878  if (!ost->stream_copy)
1879  q = ost->quality / (float) FF_QP2LAMBDA;
1880 
1881  if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1882  av_bprintf(&buf, "q=%2.1f ", q);
1883  av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1884  ost->file_index, ost->index, q);
1885  }
1886  if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1887  float fps;
1888 
1889  frame_number = ost->frame_number;
1890  fps = t > 1 ? frame_number / t : 0;
1891  av_bprintf(&buf, "frame=%5d fps=%3.*f q=%3.1f ",
1892  frame_number, fps < 9.95, fps, q);
1893  av_bprintf(&buf_script, "frame=%d\n", frame_number);
1894  av_bprintf(&buf_script, "fps=%.2f\n", fps);
1895  av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1896  ost->file_index, ost->index, q);
1897  if (is_last_report)
1898  av_bprintf(&buf, "L");
1899  if (qp_hist) {
1900  int j;
1901  int qp = lrintf(q);
1902  if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1903  qp_histogram[qp]++;
1904  for (j = 0; j < 32; j++)
1905  av_bprintf(&buf, "%X", av_log2(qp_histogram[j] + 1));
1906  }
1907 
1908  if ((enc->flags & AV_CODEC_FLAG_PSNR) && (ost->pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {
1909  int j;
1910  double error, error_sum = 0;
1911  double scale, scale_sum = 0;
1912  double p;
1913  char type[3] = { 'Y','U','V' };
1914  av_bprintf(&buf, "PSNR=");
1915  for (j = 0; j < 3; j++) {
1916  if (is_last_report) {
1917  error = enc->error[j];
1918  scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1919  } else {
1920  error = ost->error[j];
1921  scale = enc->width * enc->height * 255.0 * 255.0;
1922  }
1923  if (j)
1924  scale /= 4;
1925  error_sum += error;
1926  scale_sum += scale;
1927  p = psnr(error / scale);
1928  av_bprintf(&buf, "%c:%2.2f ", type[j], p);
1929  av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
1930  ost->file_index, ost->index, type[j] | 32, p);
1931  }
1932  p = psnr(error_sum / scale_sum);
1933  av_bprintf(&buf, "*:%2.2f ", psnr(error_sum / scale_sum));
1934  av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
1935  ost->file_index, ost->index, p);
1936  }
1937  vid = 1;
1938  }
1939  /* compute min output value */
1940  if (av_stream_get_end_pts(ost->st) != AV_NOPTS_VALUE)
1941  pts = FFMAX(pts, av_rescale_q(av_stream_get_end_pts(ost->st),
1942  ost->st->time_base, AV_TIME_BASE_Q));
1943  if (is_last_report)
1944  nb_frames_drop += ost->last_dropped;
1945  }
1946 
1947  secs = FFABS(pts) / AV_TIME_BASE;
1948  us = FFABS(pts) % AV_TIME_BASE;
1949  mins = secs / 60;
1950  secs %= 60;
1951  hours = mins / 60;
1952  mins %= 60;
1953  hours_sign = (pts < 0) ? "-" : "";
1954 
1955  bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
1956  speed = t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
1957 
1958  if (total_size < 0) av_bprintf(&buf, "size=N/A time=");
1959  else av_bprintf(&buf, "size=%8.0fkB time=", total_size / 1024.0);
1960  if (pts == AV_NOPTS_VALUE) {
1961  av_bprintf(&buf, "N/A ");
1962  } else {
1963  av_bprintf(&buf, "%s%02d:%02d:%02d.%02d ",
1964  hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
1965  }
1966 
1967  if (bitrate < 0) {
1968  av_bprintf(&buf, "bitrate=N/A");
1969  av_bprintf(&buf_script, "bitrate=N/A\n");
1970  }else{
1971  av_bprintf(&buf, "bitrate=%6.1fkbits/s", bitrate);
1972  av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
1973  }
1974 
1975  if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
1976  else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
1977  if (pts == AV_NOPTS_VALUE) {
1978  av_bprintf(&buf_script, "out_time_us=N/A\n");
1979  av_bprintf(&buf_script, "out_time_ms=N/A\n");
1980  av_bprintf(&buf_script, "out_time=N/A\n");
1981  } else {
1982  av_bprintf(&buf_script, "out_time_us=%"PRId64"\n", pts);
1983  av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
1984  av_bprintf(&buf_script, "out_time=%s%02d:%02d:%02d.%06d\n",
1985  hours_sign, hours, mins, secs, us);
1986  }
1987 
1989  av_bprintf(&buf, " dup=%d drop=%d", nb_frames_dup, nb_frames_drop);
1990  av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
1991  av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
1992 
1993  if (speed < 0) {
1994  av_bprintf(&buf, " speed=N/A");
1995  av_bprintf(&buf_script, "speed=N/A\n");
1996  } else {
1997  av_bprintf(&buf, " speed=%4.3gx", speed);
1998  av_bprintf(&buf_script, "speed=%4.3gx\n", speed);
1999  }
2000 
2001  if (print_stats || is_last_report) {
2002  const char end = is_last_report ? '\n' : '\r';
2003  if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
2004  fprintf(stderr, "%s %c", buf.str, end);
2005  } else
2006  av_log(NULL, AV_LOG_INFO, "%s %c", buf.str, end);
2007 
2008  fflush(stderr);
2009  }
2010  av_bprint_finalize(&buf, NULL);
2011 
2012  if (progress_avio) {
2013  av_bprintf(&buf_script, "progress=%s\n",
2014  is_last_report ? "end" : "continue");
2015  avio_write(progress_avio, buf_script.str,
2016  FFMIN(buf_script.len, buf_script.size - 1));
2017  avio_flush(progress_avio);
2018  av_bprint_finalize(&buf_script, NULL);
2019  if (is_last_report) {
2020  if ((ret = avio_closep(&progress_avio)) < 0)
2021  av_log(NULL, AV_LOG_ERROR,
2022  "Error closing progress log, loss of information possible: %s\n", av_err2str(ret));
2023  }
2024  }
2025 
2026  if (is_last_report)
2027  print_final_stats(total_size);
2028 }
2029 
2030 static void ifilter_parameters_from_codecpar(InputFilter *ifilter, AVCodecParameters *par)
2031 {
2032  // We never got any input. Set a fake format, which will
2033  // come from libavformat.
2034  ifilter->format = par->format;
2035  ifilter->sample_rate = par->sample_rate;
2036  ifilter->channels = par->channels;
2037  ifilter->channel_layout = par->channel_layout;
2038  ifilter->width = par->width;
2039  ifilter->height = par->height;
2040  ifilter->sample_aspect_ratio = par->sample_aspect_ratio;
2041 }
2042 
2043 static void flush_encoders(void)
2044 {
2045  int i, ret;
2046 
2047  for (i = 0; i < nb_output_streams; i++) {
2048  OutputStream *ost = output_streams[i];
2049  AVCodecContext *enc = ost->enc_ctx;
2050  OutputFile *of = output_files[ost->file_index];
2051 
2052  if (!ost->encoding_needed)
2053  continue;
2054 
2055  // Try to enable encoding with no input frames.
2056  // Maybe we should just let encoding fail instead.
2057  if (!ost->initialized) {
2058  FilterGraph *fg = ost->filter->graph;
2059  char error[1024] = "";
2060 
2061  av_log(NULL, AV_LOG_WARNING,
2062  "Finishing stream %d:%d without any data written to it.\n",
2063  ost->file_index, ost->st->index);
2064 
2065  if (ost->filter && !fg->graph) {
2066  int x;
2067  for (x = 0; x < fg->nb_inputs; x++) {
2068  InputFilter *ifilter = fg->inputs[x];
2069  if (ifilter->format < 0)
2070  ifilter_parameters_from_codecpar(ifilter, ifilter->ist->st->codecpar);
2071  }
2072 
2074  continue;
2075 
2076  ret = configure_filtergraph(fg);
2077  if (ret < 0) {
2078  av_log(NULL, AV_LOG_ERROR, "Error configuring filter graph\n");
2079  exit_program(1);
2080  }
2081 
2082  finish_output_stream(ost);
2083  }
2084 
2085  ret = init_output_stream(ost, error, sizeof(error));
2086  if (ret < 0) {
2087  av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
2088  ost->file_index, ost->index, error);
2089  exit_program(1);
2090  }
2091  }
2092 
2093  if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
2094  continue;
2095 
2096  if (enc->codec_type != AVMEDIA_TYPE_VIDEO && enc->codec_type != AVMEDIA_TYPE_AUDIO)
2097  continue;
2098 
2099  for (;;) {
2100  const char *desc = NULL;
2101  AVPacket pkt;
2102  int pkt_size;
2103 
2104  switch (enc->codec_type) {
2105  case AVMEDIA_TYPE_AUDIO:
2106  desc = "audio";
2107  break;
2108  case AVMEDIA_TYPE_VIDEO:
2109  desc = "video";
2110  break;
2111  default:
2112  av_assert0(0);
2113  }
2114 
2115  av_init_packet(&pkt);
2116  pkt.data = NULL;
2117  pkt.size = 0;
2118 
2119  update_benchmark(NULL);
2120 
2121  while ((ret = avcodec_receive_packet(enc, &pkt)) == AVERROR(EAGAIN)) {
2122  ret = avcodec_send_frame(enc, NULL);
2123  if (ret < 0) {
2124  av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
2125  desc,
2126  av_err2str(ret));
2127  exit_program(1);
2128  }
2129  }
2130 
2131  update_benchmark("flush_%s %d.%d", desc, ost->file_index, ost->index);
2132  if (ret < 0 && ret != AVERROR_EOF) {
2133  av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
2134  desc,
2135  av_err2str(ret));
2136  exit_program(1);
2137  }
2138  if (ost->logfile && enc->stats_out) {
2139  fprintf(ost->logfile, "%s", enc->stats_out);
2140  }
2141  if (ret == AVERROR_EOF) {
2142  output_packet(of, &pkt, ost, 1);
2143  break;
2144  }
2145  if (ost->finished & MUXER_FINISHED) {
2146  av_packet_unref(&pkt);
2147  continue;
2148  }
2149  av_packet_rescale_ts(&pkt, enc->time_base, ost->mux_timebase);
2150  pkt_size = pkt.size;
2151  output_packet(of, &pkt, ost, 0);
2152  if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
2153  do_video_stats(ost, pkt_size);
2154  }
2155  }
2156  }
2157 }
2158 
2159 /*
2160  * Check whether a packet from ist should be written into ost at this time
2161  */
2163 {
2164  OutputFile *of = output_files[ost->file_index];
2165  int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
2166 
2167  if (ost->source_index != ist_index)
2168  return 0;
2169 
2170  if (ost->finished)
2171  return 0;
2172 
2173  if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
2174  return 0;
2175 
2176  return 1;
2177 }
2178 
2179 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
2180 {
2181  OutputFile *of = output_files[ost->file_index];
2182  InputFile *f = input_files [ist->file_index];
2183  int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
2184  int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->mux_timebase);
2185  AVPacket opkt;
2186 
2187  // EOF: flush output bitstream filters.
2188  if (!pkt) {
2189  av_init_packet(&opkt);
2190  opkt.data = NULL;
2191  opkt.size = 0;
2192  output_packet(of, &opkt, ost, 1);
2193  return;
2194  }
2195 
2196  if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
2198  return;
2199 
2200  if (!ost->frame_number && !ost->copy_prior_start) {
2201  int64_t comp_start = start_time;
2202  if (copy_ts && f->start_time != AV_NOPTS_VALUE)
2203  comp_start = FFMAX(start_time, f->start_time + f->ts_offset);
2204  if (pkt->pts == AV_NOPTS_VALUE ?
2205  ist->pts < comp_start :
2206  pkt->pts < av_rescale_q(comp_start, AV_TIME_BASE_Q, ist->st->time_base))
2207  return;
2208  }
2209 
2210  if (of->recording_time != INT64_MAX &&
2211  ist->pts >= of->recording_time + start_time) {
2212  close_output_stream(ost);
2213  return;
2214  }
2215 
2216  if (f->recording_time != INT64_MAX) {
2217  start_time = f->ctx->start_time;
2218  if (f->start_time != AV_NOPTS_VALUE && copy_ts)
2219  start_time += f->start_time;
2220  if (ist->pts >= f->recording_time + start_time) {
2221  close_output_stream(ost);
2222  return;
2223  }
2224  }
2225 
2226  /* force the input stream PTS */
2227  if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
2228  ost->sync_opts++;
2229 
2230  if (av_packet_ref(&opkt, pkt) < 0)
2231  exit_program(1);
2232 
2233  if (pkt->pts != AV_NOPTS_VALUE)
2234  opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->mux_timebase) - ost_tb_start_time;
2235 
2236  if (pkt->dts == AV_NOPTS_VALUE)
2237  opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->mux_timebase);
2238  else
2239  opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->mux_timebase);
2240  opkt.dts -= ost_tb_start_time;
2241 
2242  if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
2243  int duration = av_get_audio_frame_duration(ist->dec_ctx, pkt->size);
2244  if(!duration)
2245  duration = ist->dec_ctx->frame_size;
2246  opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
2247  (AVRational){1, ist->dec_ctx->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
2248  ost->mux_timebase) - ost_tb_start_time;
2249  }
2250 
2251  opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->mux_timebase);
2252 
2253  output_packet(of, &opkt, ost, 0);
2254 }
2255 
2257 {
2258  AVCodecContext *dec = ist->dec_ctx;
2259 
2260  if (!dec->channel_layout) {
2261  char layout_name[256];
2262 
2263  if (dec->channels > ist->guess_layout_max)
2264  return 0;
2265  dec->channel_layout = av_get_default_channel_layout(dec->channels);
2266  if (!dec->channel_layout)
2267  return 0;
2268  av_get_channel_layout_string(layout_name, sizeof(layout_name),
2269  dec->channels, dec->channel_layout);
2270  av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
2271  "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
2272  }
2273  return 1;
2274 }
2275 
2276 static void check_decode_result(InputStream *ist, int *got_output, int ret)
2277 {
2278  if (*got_output || ret<0)
2279  decode_error_stat[ret<0] ++;
2280 
2281  if (ret < 0 && exit_on_error)
2282  exit_program(1);
2283 
2284  if (*got_output && ist) {
2285  if (ist->decoded_frame->decode_error_flags || (ist->decoded_frame->flags & AV_FRAME_FLAG_CORRUPT)) {
2286  av_log(NULL, exit_on_error ? AV_LOG_FATAL : AV_LOG_WARNING,
2287  "%s: corrupt decoded frame in stream %d\n", input_files[ist->file_index]->ctx->url, ist->st->index);
2288  if (exit_on_error)
2289  exit_program(1);
2290  }
2291  }
2292 }
2293 
2294 // Filters can be configured only if the formats of all inputs are known.
2296 {
2297  int i;
2298  for (i = 0; i < fg->nb_inputs; i++) {
2299  if (fg->inputs[i]->format < 0 && (fg->inputs[i]->type == AVMEDIA_TYPE_AUDIO ||
2300  fg->inputs[i]->type == AVMEDIA_TYPE_VIDEO))
2301  return 0;
2302  }
2303  return 1;
2304 }
2305 
2306 static int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame)
2307 {
2308  FilterGraph *fg = ifilter->graph;
2309  int need_reinit, ret, i;
2310 
2311  /* determine if the parameters for this input changed */
2312  need_reinit = ifilter->format != frame->format;
2313 
2314  switch (ifilter->ist->st->codecpar->codec_type) {
2315  case AVMEDIA_TYPE_AUDIO:
2316  need_reinit |= ifilter->sample_rate != frame->sample_rate ||
2317  ifilter->channels != frame->channels ||
2318  ifilter->channel_layout != frame->channel_layout;
2319  break;
2320  case AVMEDIA_TYPE_VIDEO:
2321  need_reinit |= ifilter->width != frame->width ||
2322  ifilter->height != frame->height;
2323  break;
2324  }
2325 
2326  if (!ifilter->ist->reinit_filters && fg->graph)
2327  need_reinit = 0;
2328 
2329  if (!!ifilter->hw_frames_ctx != !!frame->hw_frames_ctx ||
2330  (ifilter->hw_frames_ctx && ifilter->hw_frames_ctx->data != frame->hw_frames_ctx->data))
2331  need_reinit = 1;
2332 
2333  if (need_reinit) {
2334  ret = ifilter_parameters_from_frame(ifilter, frame);
2335  if (ret < 0)
2336  return ret;
2337  }
2338 
2339  /* (re)init the graph if possible, otherwise buffer the frame and return */
2340  if (need_reinit || !fg->graph) {
2341  for (i = 0; i < fg->nb_inputs; i++) {
2342  if (!ifilter_has_all_input_formats(fg)) {
2343  AVFrame *tmp = av_frame_clone(frame);
2344  if (!tmp)
2345  return AVERROR(ENOMEM);
2346  av_frame_unref(frame);
2347 
2348  if (!av_fifo_space(ifilter->frame_queue)) {
2349  ret = av_fifo_realloc2(ifilter->frame_queue, 2 * av_fifo_size(ifilter->frame_queue));
2350  if (ret < 0) {
2351  av_frame_free(&tmp);
2352  return ret;
2353  }
2354  }
2355  av_fifo_generic_write(ifilter->frame_queue, &tmp, sizeof(tmp), NULL);
2356  return 0;
2357  }
2358  }
2359 
2360  ret = reap_filters(1);
2361  if (ret < 0 && ret != AVERROR_EOF) {
2362  av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
2363  return ret;
2364  }
2365 
2366  ret = configure_filtergraph(fg);
2367  if (ret < 0) {
2368  av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
2369  return ret;
2370  }
2371  }
2372 
2373  ret = av_buffersrc_add_frame_flags(ifilter->filter, frame, AV_BUFFERSRC_FLAG_PUSH);
2374  if (ret < 0) {
2375  if (ret != AVERROR_EOF)
2376  av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
2377  return ret;
2378  }
2379 
2380  return 0;
2381 }
2382 
2383 static int ifilter_send_eof(InputFilter *ifilter, int64_t pts)
2384 {
2385  int ret = 0;
2386 
2387  ifilter->eof = 1;
2388 
2389  if (ifilter->filter) {
2390 
2391  /* THIS VALIDATION IS REQUIRED TO COMPLETE CANCELLATION */
2393  ret = av_buffersrc_close(ifilter->filter, pts, AV_BUFFERSRC_FLAG_PUSH);
2394  }
2395  if (ret < 0)
2396  return ret;
2397  } else {
2398  // the filtergraph was never configured
2399  if (ifilter->format < 0)
2400  ifilter_parameters_from_codecpar(ifilter, ifilter->ist->st->codecpar);
2401  if (ifilter->format < 0 && (ifilter->type == AVMEDIA_TYPE_AUDIO || ifilter->type == AVMEDIA_TYPE_VIDEO)) {
2402  av_log(NULL, AV_LOG_ERROR, "Cannot determine format of input stream %d:%d after EOF\n", ifilter->ist->file_index, ifilter->ist->st->index);
2403  return AVERROR_INVALIDDATA;
2404  }
2405  }
2406 
2407  return 0;
2408 }
2409 
2410 // This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
2411 // There is the following difference: if you got a frame, you must call
2412 // it again with pkt=NULL. pkt==NULL is treated differently from pkt->size==0
2413 // (pkt==NULL means get more output, pkt->size==0 is a flush/drain packet)
2414 static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
2415 {
2416  int ret;
2417 
2418  *got_frame = 0;
2419 
2420  if (pkt) {
2421  ret = avcodec_send_packet(avctx, pkt);
2422  // In particular, we don't expect AVERROR(EAGAIN), because we read all
2423  // decoded frames with avcodec_receive_frame() until done.
2424  if (ret < 0 && ret != AVERROR_EOF)
2425  return ret;
2426  }
2427 
2428  ret = avcodec_receive_frame(avctx, frame);
2429  if (ret < 0 && ret != AVERROR(EAGAIN))
2430  return ret;
2431  if (ret >= 0)
2432  *got_frame = 1;
2433 
2434  return 0;
2435 }
2436 
2437 static int send_frame_to_filters(InputStream *ist, AVFrame *decoded_frame)
2438 {
2439  int i, ret;
2440  AVFrame *f;
2441 
2442  av_assert1(ist->nb_filters > 0); /* ensure ret is initialized */
2443  for (i = 0; i < ist->nb_filters; i++) {
2444  if (i < ist->nb_filters - 1) {
2445  f = ist->filter_frame;
2446  ret = av_frame_ref(f, decoded_frame);
2447  if (ret < 0)
2448  break;
2449  } else
2450  f = decoded_frame;
2451  ret = ifilter_send_frame(ist->filters[i], f);
2452  if (ret == AVERROR_EOF)
2453  ret = 0; /* ignore */
2454  if (ret < 0) {
2455  av_log(NULL, AV_LOG_ERROR,
2456  "Failed to inject frame into filter network: %s\n", av_err2str(ret));
2457  break;
2458  }
2459  }
2460  return ret;
2461 }
2462 
2463 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output,
2464  int *decode_failed)
2465 {
2466  AVFrame *decoded_frame;
2467  AVCodecContext *avctx = ist->dec_ctx;
2468  int ret, err = 0;
2469  AVRational decoded_frame_tb;
2470 
2471  if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
2472  return AVERROR(ENOMEM);
2473  if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
2474  return AVERROR(ENOMEM);
2475  decoded_frame = ist->decoded_frame;
2476 
2477  update_benchmark(NULL);
2478  ret = decode(avctx, decoded_frame, got_output, pkt);
2479  update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
2480  if (ret < 0)
2481  *decode_failed = 1;
2482 
2483  if (ret >= 0 && avctx->sample_rate <= 0) {
2484  av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
2485  ret = AVERROR_INVALIDDATA;
2486  }
2487 
2488  if (ret != AVERROR_EOF)
2489  check_decode_result(ist, got_output, ret);
2490 
2491  if (!*got_output || ret < 0)
2492  return ret;
2493 
2494  ist->samples_decoded += decoded_frame->nb_samples;
2495  ist->frames_decoded++;
2496 
2497  /* increment next_dts to use for the case where the input stream does not
2498  have timestamps or there are multiple frames in the packet */
2499  ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2500  avctx->sample_rate;
2501  ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
2502  avctx->sample_rate;
2503 
2504  if (decoded_frame->pts != AV_NOPTS_VALUE) {
2505  decoded_frame_tb = ist->st->time_base;
2506  } else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
2507  decoded_frame->pts = pkt->pts;
2508  decoded_frame_tb = ist->st->time_base;
2509  }else {
2510  decoded_frame->pts = ist->dts;
2511  decoded_frame_tb = AV_TIME_BASE_Q;
2512  }
2513  if (decoded_frame->pts != AV_NOPTS_VALUE)
2514  decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
2515  (AVRational){1, avctx->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
2516  (AVRational){1, avctx->sample_rate});
2517  ist->nb_samples = decoded_frame->nb_samples;
2518  err = send_frame_to_filters(ist, decoded_frame);
2519 
2520  av_frame_unref(ist->filter_frame);
2521  av_frame_unref(decoded_frame);
2522  return err < 0 ? err : ret;
2523 }
2524 
2525 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *duration_pts, int eof,
2526  int *decode_failed)
2527 {
2528  AVFrame *decoded_frame;
2529  int i, ret = 0, err = 0;
2530  int64_t best_effort_timestamp;
2531  int64_t dts = AV_NOPTS_VALUE;
2532  AVPacket avpkt;
2533 
2534  // With fate-indeo3-2, we're getting 0-sized packets before EOF for some
2535  // reason. This seems like a semi-critical bug. Don't trigger EOF, and
2536  // skip the packet.
2537  if (!eof && pkt && pkt->size == 0)
2538  return 0;
2539 
2540  if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
2541  return AVERROR(ENOMEM);
2542  if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
2543  return AVERROR(ENOMEM);
2544  decoded_frame = ist->decoded_frame;
2545  if (ist->dts != AV_NOPTS_VALUE)
2546  dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
2547  if (pkt) {
2548  avpkt = *pkt;
2549  avpkt.dts = dts; // ffmpeg.c probably shouldn't do this
2550  }
2551 
2552  // The old code used to set dts on the drain packet, which does not work
2553  // with the new API anymore.
2554  if (eof) {
2555  void *new = av_realloc_array(ist->dts_buffer, ist->nb_dts_buffer + 1, sizeof(ist->dts_buffer[0]));
2556  if (!new)
2557  return AVERROR(ENOMEM);
2558  ist->dts_buffer = new;
2559  ist->dts_buffer[ist->nb_dts_buffer++] = dts;
2560  }
2561 
2562  update_benchmark(NULL);
2563  ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt ? &avpkt : NULL);
2564  update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2565  if (ret < 0)
2566  *decode_failed = 1;
2567 
2568  // The following line may be required in some cases where there is no parser
2569  // or the parser does not has_b_frames correctly
2570  if (ist->st->codecpar->video_delay < ist->dec_ctx->has_b_frames) {
2571  if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
2572  ist->st->codecpar->video_delay = ist->dec_ctx->has_b_frames;
2573  } else
2574  av_log(ist->dec_ctx, AV_LOG_WARNING,
2575  "video_delay is larger in decoder than demuxer %d > %d.\n"
2576  "If you want to help, upload a sample "
2577  "of this file to ftp://upload.ffmpeg.org/incoming/ "
2578  "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n",
2579  ist->dec_ctx->has_b_frames,
2580  ist->st->codecpar->video_delay);
2581  }
2582 
2583  if (ret != AVERROR_EOF)
2584  check_decode_result(ist, got_output, ret);
2585 
2586  if (*got_output && ret >= 0) {
2587  if (ist->dec_ctx->width != decoded_frame->width ||
2588  ist->dec_ctx->height != decoded_frame->height ||
2589  ist->dec_ctx->pix_fmt != decoded_frame->format) {
2590  av_log(NULL, AV_LOG_DEBUG, "Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
2591  decoded_frame->width,
2592  decoded_frame->height,
2593  decoded_frame->format,
2594  ist->dec_ctx->width,
2595  ist->dec_ctx->height,
2596  ist->dec_ctx->pix_fmt);
2597  }
2598  }
2599 
2600  if (!*got_output || ret < 0)
2601  return ret;
2602 
2603  if(ist->top_field_first>=0)
2604  decoded_frame->top_field_first = ist->top_field_first;
2605 
2606  ist->frames_decoded++;
2607 
2608  if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
2609  err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
2610  if (err < 0)
2611  goto fail;
2612  }
2613  ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
2614 
2615  best_effort_timestamp= decoded_frame->best_effort_timestamp;
2616  *duration_pts = decoded_frame->pkt_duration;
2617 
2618  if (ist->framerate.num)
2619  best_effort_timestamp = ist->cfr_next_pts++;
2620 
2621  if (eof && best_effort_timestamp == AV_NOPTS_VALUE && ist->nb_dts_buffer > 0) {
2622  best_effort_timestamp = ist->dts_buffer[0];
2623 
2624  for (i = 0; i < ist->nb_dts_buffer - 1; i++)
2625  ist->dts_buffer[i] = ist->dts_buffer[i + 1];
2626  ist->nb_dts_buffer--;
2627  }
2628 
2629  if(best_effort_timestamp != AV_NOPTS_VALUE) {
2630  int64_t ts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
2631 
2632  if (ts != AV_NOPTS_VALUE)
2633  ist->next_pts = ist->pts = ts;
2634  }
2635 
2636  if (debug_ts) {
2637  av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
2638  "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d time_base:%d/%d\n",
2639  ist->st->index, av_ts2str(decoded_frame->pts),
2640  av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
2641  best_effort_timestamp,
2642  av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
2643  decoded_frame->key_frame, decoded_frame->pict_type,
2644  ist->st->time_base.num, ist->st->time_base.den);
2645  }
2646 
2647  if (ist->st->sample_aspect_ratio.num)
2648  decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
2649 
2650  err = send_frame_to_filters(ist, decoded_frame);
2651 
2652 fail:
2653  av_frame_unref(ist->filter_frame);
2654  av_frame_unref(decoded_frame);
2655  return err < 0 ? err : ret;
2656 }
2657 
2658 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output,
2659  int *decode_failed)
2660 {
2661  AVSubtitle subtitle;
2662  int free_sub = 1;
2663  int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
2664  &subtitle, got_output, pkt);
2665 
2666  check_decode_result(NULL, got_output, ret);
2667 
2668  if (ret < 0 || !*got_output) {
2669  *decode_failed = 1;
2670  if (!pkt->size)
2671  sub2video_flush(ist);
2672  return ret;
2673  }
2674 
2675  if (ist->fix_sub_duration) {
2676  int end = 1;
2677  if (ist->prev_sub.got_output) {
2678  end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
2679  1000, AV_TIME_BASE);
2680  if (end < ist->prev_sub.subtitle.end_display_time) {
2681  av_log(ist->dec_ctx, AV_LOG_DEBUG,
2682  "Subtitle duration reduced from %"PRId32" to %d%s\n",
2683  ist->prev_sub.subtitle.end_display_time, end,
2684  end <= 0 ? ", dropping it" : "");
2685  ist->prev_sub.subtitle.end_display_time = end;
2686  }
2687  }
2688  FFSWAP(int, *got_output, ist->prev_sub.got_output);
2689  FFSWAP(int, ret, ist->prev_sub.ret);
2690  FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
2691  if (end <= 0)
2692  goto out;
2693  }
2694 
2695  if (!*got_output)
2696  return ret;
2697 
2698  if (ist->sub2video.frame) {
2699  sub2video_update(ist, &subtitle);
2700  } else if (ist->nb_filters) {
2701  if (!ist->sub2video.sub_queue)
2702  ist->sub2video.sub_queue = av_fifo_alloc(8 * sizeof(AVSubtitle));
2703  if (!ist->sub2video.sub_queue)
2704  exit_program(1);
2705  if (!av_fifo_space(ist->sub2video.sub_queue)) {
2706  ret = av_fifo_realloc2(ist->sub2video.sub_queue, 2 * av_fifo_size(ist->sub2video.sub_queue));
2707  if (ret < 0)
2708  exit_program(1);
2709  }
2710  av_fifo_generic_write(ist->sub2video.sub_queue, &subtitle, sizeof(subtitle), NULL);
2711  free_sub = 0;
2712  }
2713 
2714  if (!subtitle.num_rects)
2715  goto out;
2716 
2717  ist->frames_decoded++;
2718 
2719  for (i = 0; i < nb_output_streams; i++) {
2720  OutputStream *ost = output_streams[i];
2721 
2722  if (!check_output_constraints(ist, ost) || !ost->encoding_needed
2723  || ost->enc->type != AVMEDIA_TYPE_SUBTITLE)
2724  continue;
2725 
2726  do_subtitle_out(output_files[ost->file_index], ost, &subtitle);
2727  }
2728 
2729 out:
2730  if (free_sub)
2731  avsubtitle_free(&subtitle);
2732  return ret;
2733 }
2734 
2736 {
2737  int i, ret;
2738  /* TODO keep pts also in stream time base to avoid converting back */
2739  int64_t pts = av_rescale_q_rnd(ist->pts, AV_TIME_BASE_Q, ist->st->time_base,
2740  AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX);
2741 
2742  for (i = 0; i < ist->nb_filters; i++) {
2743  ret = ifilter_send_eof(ist->filters[i], pts);
2744  if (ret < 0)
2745  return ret;
2746  }
2747  return 0;
2748 }
2749 
2750 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2751 static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
2752 {
2753  int ret = 0, i;
2754  int repeating = 0;
2755  int eof_reached = 0;
2756 
2757  AVPacket avpkt;
2758  if (!ist->saw_first_ts) {
2759  ist->dts = ist->st->avg_frame_rate.num ? - ist->dec_ctx->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
2760  ist->pts = 0;
2761  if (pkt && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
2762  ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2763  ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
2764  }
2765  ist->saw_first_ts = 1;
2766  }
2767 
2768  if (ist->next_dts == AV_NOPTS_VALUE)
2769  ist->next_dts = ist->dts;
2770  if (ist->next_pts == AV_NOPTS_VALUE)
2771  ist->next_pts = ist->pts;
2772 
2773  if (!pkt) {
2774  /* EOF handling */
2775  av_init_packet(&avpkt);
2776  avpkt.data = NULL;
2777  avpkt.size = 0;
2778  } else {
2779  avpkt = *pkt;
2780  }
2781 
2782  if (pkt && pkt->dts != AV_NOPTS_VALUE) {
2783  ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2784  if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2785  ist->next_pts = ist->pts = ist->dts;
2786  }
2787 
2788  // while we have more to decode or while the decoder did output something on EOF
2789  while (ist->decoding_needed) {
2790  int64_t duration_dts = 0;
2791  int64_t duration_pts = 0;
2792  int got_output = 0;
2793  int decode_failed = 0;
2794 
2795  ist->pts = ist->next_pts;
2796  ist->dts = ist->next_dts;
2797 
2798  switch (ist->dec_ctx->codec_type) {
2799  case AVMEDIA_TYPE_AUDIO:
2800  ret = decode_audio (ist, repeating ? NULL : &avpkt, &got_output,
2801  &decode_failed);
2802  break;
2803  case AVMEDIA_TYPE_VIDEO:
2804  ret = decode_video (ist, repeating ? NULL : &avpkt, &got_output, &duration_pts, !pkt,
2805  &decode_failed);
2806  if (!repeating || !pkt || got_output) {
2807  if (pkt && pkt->duration) {
2808  duration_dts = av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2809  } else if(ist->dec_ctx->framerate.num != 0 && ist->dec_ctx->framerate.den != 0) {
2810  int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict+1 : ist->dec_ctx->ticks_per_frame;
2811  duration_dts = ((int64_t)AV_TIME_BASE *
2812  ist->dec_ctx->framerate.den * ticks) /
2813  ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
2814  }
2815 
2816  if(ist->dts != AV_NOPTS_VALUE && duration_dts) {
2817  ist->next_dts += duration_dts;
2818  }else
2819  ist->next_dts = AV_NOPTS_VALUE;
2820  }
2821 
2822  if (got_output) {
2823  if (duration_pts > 0) {
2824  ist->next_pts += av_rescale_q(duration_pts, ist->st->time_base, AV_TIME_BASE_Q);
2825  } else {
2826  ist->next_pts += duration_dts;
2827  }
2828  }
2829  break;
2830  case AVMEDIA_TYPE_SUBTITLE:
2831  if (repeating)
2832  break;
2833  ret = transcode_subtitles(ist, &avpkt, &got_output, &decode_failed);
2834  if (!pkt && ret >= 0)
2835  ret = AVERROR_EOF;
2836  break;
2837  default:
2838  return -1;
2839  }
2840 
2841  if (ret == AVERROR_EOF) {
2842  eof_reached = 1;
2843  break;
2844  }
2845 
2846  if (ret < 0) {
2847  if (decode_failed) {
2848  av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
2849  ist->file_index, ist->st->index, av_err2str(ret));
2850  } else {
2851  av_log(NULL, AV_LOG_FATAL, "Error while processing the decoded "
2852  "data for stream #%d:%d\n", ist->file_index, ist->st->index);
2853  }
2854  if (!decode_failed || exit_on_error)
2855  exit_program(1);
2856  break;
2857  }
2858 
2859  if (got_output)
2860  ist->got_output = 1;
2861 
2862  if (!got_output)
2863  break;
2864 
2865  // During draining, we might get multiple output frames in this loop.
2866  // ffmpeg.c does not drain the filter chain on configuration changes,
2867  // which means if we send multiple frames at once to the filters, and
2868  // one of those frames changes configuration, the buffered frames will
2869  // be lost. This can upset certain FATE tests.
2870  // Decode only 1 frame per call on EOF to appease these FATE tests.
2871  // The ideal solution would be to rewrite decoding to use the new
2872  // decoding API in a better way.
2873  if (!pkt)
2874  break;
2875 
2876  repeating = 1;
2877  }
2878 
2879  /* after flushing, send an EOF on all the filter inputs attached to the stream */
2880  /* except when looping we need to flush but not to send an EOF */
2881  if (!pkt && ist->decoding_needed && eof_reached && !no_eof) {
2882  int ret = send_filter_eof(ist);
2883  if (ret < 0) {
2884  av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
2885  exit_program(1);
2886  }
2887  }
2888 
2889  /* handle stream copy */
2890  if (!ist->decoding_needed && pkt) {
2891  ist->dts = ist->next_dts;
2892  switch (ist->dec_ctx->codec_type) {
2893  case AVMEDIA_TYPE_AUDIO:
2894  av_assert1(pkt->duration >= 0);
2895  if (ist->dec_ctx->sample_rate) {
2896  ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
2897  ist->dec_ctx->sample_rate;
2898  } else {
2899  ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2900  }
2901  break;
2902  case AVMEDIA_TYPE_VIDEO:
2903  if (ist->framerate.num) {
2904  // TODO: Remove work-around for c99-to-c89 issue 7
2905  AVRational time_base_q = AV_TIME_BASE_Q;
2906  int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
2907  ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
2908  } else if (pkt->duration) {
2909  ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2910  } else if(ist->dec_ctx->framerate.num != 0) {
2911  int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
2912  ist->next_dts += ((int64_t)AV_TIME_BASE *
2913  ist->dec_ctx->framerate.den * ticks) /
2914  ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
2915  }
2916  break;
2917  }
2918  ist->pts = ist->dts;
2919  ist->next_pts = ist->next_dts;
2920  }
2921  for (i = 0; i < nb_output_streams; i++) {
2922  OutputStream *ost = output_streams[i];
2923 
2924  if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2925  continue;
2926 
2927  do_streamcopy(ist, ost, pkt);
2928  }
2929 
2930  return !eof_reached;
2931 }
2932 
2933 static void print_sdp(void)
2934 {
2935  char sdp[16384];
2936  int i;
2937  int j;
2938  AVIOContext *sdp_pb;
2939  AVFormatContext **avc;
2940 
2941  for (i = 0; i < nb_output_files; i++) {
2942  if (!output_files[i]->header_written)
2943  return;
2944  }
2945 
2946  avc = av_malloc_array(nb_output_files, sizeof(*avc));
2947  if (!avc)
2948  exit_program(1);
2949  for (i = 0, j = 0; i < nb_output_files; i++) {
2950  if (!strcmp(output_files[i]->ctx->oformat->name, "rtp")) {
2951  avc[j] = output_files[i]->ctx;
2952  j++;
2953  }
2954  }
2955 
2956  if (!j)
2957  goto fail;
2958 
2959  av_sdp_create(avc, j, sdp, sizeof(sdp));
2960 
2961  if (!sdp_filename) {
2962  av_log(NULL, AV_LOG_STDERR, "SDP:\n%s\n", sdp);
2963  fflush(stdout);
2964  } else {
2965  if (avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL) < 0) {
2966  av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
2967  } else {
2968  avio_printf(sdp_pb, "SDP:\n%s", sdp);
2969  avio_closep(&sdp_pb);
2970  av_freep(&sdp_filename);
2971  }
2972  }
2973 
2974 fail:
2975  av_freep(&avc);
2976 }
2977 
2978 static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
2979 {
2980  InputStream *ist = s->opaque;
2981  const enum AVPixelFormat *p;
2982  int ret;
2983 
2984  for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
2985  const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
2986  const AVCodecHWConfig *config = NULL;
2987  int i;
2988 
2989  if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
2990  break;
2991 
2992  if (ist->hwaccel_id == HWACCEL_GENERIC ||
2993  ist->hwaccel_id == HWACCEL_AUTO) {
2994  for (i = 0;; i++) {
2995  config = avcodec_get_hw_config(s->codec, i);
2996  if (!config)
2997  break;
2998  if (!(config->methods &
2999  AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX))
3000  continue;
3001  if (config->pix_fmt == *p)
3002  break;
3003  }
3004  }
3005  if (config) {
3006  if (config->device_type != ist->hwaccel_device_type) {
3007  // Different hwaccel offered, ignore.
3008  continue;
3009  }
3010 
3011  ret = hwaccel_decode_init(s);
3012  if (ret < 0) {
3013  if (ist->hwaccel_id == HWACCEL_GENERIC) {
3014  av_log(NULL, AV_LOG_FATAL,
3015  "%s hwaccel requested for input stream #%d:%d, "
3016  "but cannot be initialized.\n",
3017  av_hwdevice_get_type_name(config->device_type),
3018  ist->file_index, ist->st->index);
3019  return AV_PIX_FMT_NONE;
3020  }
3021  continue;
3022  }
3023  } else {
3024  const HWAccel *hwaccel = NULL;
3025  int i;
3026  for (i = 0; hwaccels[i].name; i++) {
3027  if (hwaccels[i].pix_fmt == *p) {
3028  hwaccel = &hwaccels[i];
3029  break;
3030  }
3031  }
3032  if (!hwaccel) {
3033  // No hwaccel supporting this pixfmt.
3034  continue;
3035  }
3036  if (hwaccel->id != ist->hwaccel_id) {
3037  // Does not match requested hwaccel.
3038  continue;
3039  }
3040 
3041  ret = hwaccel->init(s);
3042  if (ret < 0) {
3043  av_log(NULL, AV_LOG_FATAL,
3044  "%s hwaccel requested for input stream #%d:%d, "
3045  "but cannot be initialized.\n", hwaccel->name,
3046  ist->file_index, ist->st->index);
3047  return AV_PIX_FMT_NONE;
3048  }
3049  }
3050 
3051  if (ist->hw_frames_ctx) {
3052  s->hw_frames_ctx = av_buffer_ref(ist->hw_frames_ctx);
3053  if (!s->hw_frames_ctx)
3054  return AV_PIX_FMT_NONE;
3055  }
3056 
3057  ist->hwaccel_pix_fmt = *p;
3058  break;
3059  }
3060 
3061  return *p;
3062 }
3063 
3064 static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
3065 {
3066  InputStream *ist = s->opaque;
3067 
3068  if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
3069  return ist->hwaccel_get_buffer(s, frame, flags);
3070 
3071  return avcodec_default_get_buffer2(s, frame, flags);
3072 }
3073 
3074 static int init_input_stream(int ist_index, char *error, int error_len)
3075 {
3076  int ret;
3077  InputStream *ist = input_streams[ist_index];
3078 
3079  if (ist->decoding_needed) {
3080  AVCodec *codec = ist->dec;
3081  if (!codec) {
3082  snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
3083  avcodec_get_name(ist->dec_ctx->codec_id), ist->file_index, ist->st->index);
3084  return AVERROR(EINVAL);
3085  }
3086 
3087  ist->dec_ctx->opaque = ist;
3088  ist->dec_ctx->get_format = get_format;
3089  ist->dec_ctx->get_buffer2 = get_buffer;
3090  ist->dec_ctx->thread_safe_callbacks = 1;
3091 
3092  av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
3093  if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
3094  (ist->decoding_needed & DECODING_FOR_OST)) {
3095  av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
3097  av_log(NULL, AV_LOG_WARNING, "Warning using DVB subtitles for filtering and output at the same time is not fully supported, also see -compute_edt [0|1]\n");
3098  }
3099 
3100  av_dict_set(&ist->decoder_opts, "sub_text_format", "ass", AV_DICT_DONT_OVERWRITE);
3101 
3102  /* Useful for subtitles retiming by lavf (FIXME), skipping samples in
3103  * audio, and video decoders such as cuvid or mediacodec */
3104  ist->dec_ctx->pkt_timebase = ist->st->time_base;
3105 
3106  if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
3107  av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
3108  /* Attached pics are sparse, therefore we would not want to delay their decoding till EOF. */
3109  if (ist->st->disposition & AV_DISPOSITION_ATTACHED_PIC)
3110  av_dict_set(&ist->decoder_opts, "threads", "1", 0);
3111 
3112  ret = hw_device_setup_for_decode(ist);
3113  if (ret < 0) {
3114  snprintf(error, error_len, "Device setup failed for "
3115  "decoder on input stream #%d:%d : %s",
3116  ist->file_index, ist->st->index, av_err2str(ret));
3117  return ret;
3118  }
3119 
3120  if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
3121  if (ret == AVERROR_EXPERIMENTAL)
3122  abort_codec_experimental(codec, 0);
3123 
3124  snprintf(error, error_len,
3125  "Error while opening decoder for input stream "
3126  "#%d:%d : %s",
3127  ist->file_index, ist->st->index, av_err2str(ret));
3128  return ret;
3129  }
3131  }
3132 
3133  ist->next_pts = AV_NOPTS_VALUE;
3134  ist->next_dts = AV_NOPTS_VALUE;
3135 
3136  return 0;
3137 }
3138 
3140 {
3141  if (ost->source_index >= 0)
3142  return input_streams[ost->source_index];
3143  return NULL;
3144 }
3145 
3146 static int compare_int64(const void *a, const void *b)
3147 {
3148  return FFDIFFSIGN(*(const int64_t *)a, *(const int64_t *)b);
3149 }
3150 
3151 /* open the muxer when all the streams are initialized */
3152 static int check_init_output_file(OutputFile *of, int file_index)
3153 {
3154  int ret, i;
3155 
3156  for (i = 0; i < of->ctx->nb_streams; i++) {
3157  OutputStream *ost = output_streams[of->ost_index + i];
3158  if (!ost->initialized)
3159  return 0;
3160  }
3161 
3162  of->ctx->interrupt_callback = int_cb;
3163 
3164  ret = avformat_write_header(of->ctx, &of->opts);
3165  if (ret < 0) {
3166  av_log(NULL, AV_LOG_ERROR,
3167  "Could not write header for output file #%d "
3168  "(incorrect codec parameters ?): %s\n",
3169  file_index, av_err2str(ret));
3170  return ret;
3171  }
3172  //assert_avoptions(of->opts);
3173  of->header_written = 1;
3174 
3175  av_dump_format(of->ctx, file_index, of->ctx->url, 1);
3176 
3177  if (sdp_filename || want_sdp)
3178  print_sdp();
3179 
3180  /* flush the muxing queues */
3181  for (i = 0; i < of->ctx->nb_streams; i++) {
3182  OutputStream *ost = output_streams[of->ost_index + i];
3183 
3184  /* try to improve muxing time_base (only possible if nothing has been written yet) */
3185  if (!av_fifo_size(ost->muxing_queue))
3186  ost->mux_timebase = ost->st->time_base;
3187 
3188  while (av_fifo_size(ost->muxing_queue)) {
3189  AVPacket pkt;
3190  av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
3191  write_packet(of, &pkt, ost, 1);
3192  }
3193  }
3194 
3195  return 0;
3196 }
3197 
3199 {
3200  AVBSFContext *ctx;
3201  int i, ret;
3202 
3203  if (!ost->nb_bitstream_filters)
3204  return 0;
3205 
3206  for (i = 0; i < ost->nb_bitstream_filters; i++) {
3207  ctx = ost->bsf_ctx[i];
3208 
3209  ret = avcodec_parameters_copy(ctx->par_in,
3210  i ? ost->bsf_ctx[i - 1]->par_out : ost->st->codecpar);
3211  if (ret < 0)
3212  return ret;
3213 
3214  ctx->time_base_in = i ? ost->bsf_ctx[i - 1]->time_base_out : ost->st->time_base;
3215 
3216  ret = av_bsf_init(ctx);
3217  if (ret < 0) {
3218  av_log(NULL, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
3219  ost->bsf_ctx[i]->filter->name);
3220  return ret;
3221  }
3222  }
3223 
3224  ctx = ost->bsf_ctx[ost->nb_bitstream_filters - 1];
3225  ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
3226  if (ret < 0)
3227  return ret;
3228 
3229  ost->st->time_base = ctx->time_base_out;
3230 
3231  return 0;
3232 }
3233 
3235 {
3236  OutputFile *of = output_files[ost->file_index];
3237  InputStream *ist = get_input_stream(ost);
3238  AVCodecParameters *par_dst = ost->st->codecpar;
3239  AVCodecParameters *par_src = ost->ref_par;
3240  AVRational sar;
3241  int i, ret;
3242  uint32_t codec_tag = par_dst->codec_tag;
3243 
3244  av_assert0(ist && !ost->filter);
3245 
3246  ret = avcodec_parameters_to_context(ost->enc_ctx, ist->st->codecpar);
3247  if (ret >= 0)
3248  ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
3249  if (ret < 0) {
3250  av_log(NULL, AV_LOG_FATAL,
3251  "Error setting up codec context options.\n");
3252  return ret;
3253  }
3254 
3255  ret = avcodec_parameters_from_context(par_src, ost->enc_ctx);
3256  if (ret < 0) {
3257  av_log(NULL, AV_LOG_FATAL,
3258  "Error getting reference codec parameters.\n");
3259  return ret;
3260  }
3261 
3262  if (!codec_tag) {
3263  unsigned int codec_tag_tmp;
3264  if (!of->ctx->oformat->codec_tag ||
3265  av_codec_get_id (of->ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
3266  !av_codec_get_tag2(of->ctx->oformat->codec_tag, par_src->codec_id, &codec_tag_tmp))
3267  codec_tag = par_src->codec_tag;
3268  }
3269 
3270  ret = avcodec_parameters_copy(par_dst, par_src);
3271  if (ret < 0)
3272  return ret;
3273 
3274  par_dst->codec_tag = codec_tag;
3275 
3276  if (!ost->frame_rate.num)
3277  ost->frame_rate = ist->framerate;
3278  ost->st->avg_frame_rate = ost->frame_rate;
3279 
3280  ret = avformat_transfer_internal_stream_timing_info(of->ctx->oformat, ost->st, ist->st, copy_tb);
3281  if (ret < 0)
3282  return ret;
3283 
3284  // copy timebase while removing common factors
3285  if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
3286  ost->st->time_base = av_add_q(av_stream_get_codec_timebase(ost->st), (AVRational){0, 1});
3287 
3288  // copy estimated duration as a hint to the muxer
3289  if (ost->st->duration <= 0 && ist->st->duration > 0)
3290  ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
3291 
3292  // copy disposition
3293  ost->st->disposition = ist->st->disposition;
3294 
3295  if (ist->st->nb_side_data) {
3296  for (i = 0; i < ist->st->nb_side_data; i++) {
3297  const AVPacketSideData *sd_src = &ist->st->side_data[i];
3298  uint8_t *dst_data;
3299 
3300  dst_data = av_stream_new_side_data(ost->st, sd_src->type, sd_src->size);
3301  if (!dst_data)
3302  return AVERROR(ENOMEM);
3303  memcpy(dst_data, sd_src->data, sd_src->size);
3304  }
3305  }
3306 
3307  if (ost->rotate_overridden) {
3308  uint8_t *sd = av_stream_new_side_data(ost->st, AV_PKT_DATA_DISPLAYMATRIX,
3309  sizeof(int32_t) * 9);
3310  if (sd)
3311  av_display_rotation_set((int32_t *)sd, -ost->rotate_override_value);
3312  }
3313 
3314  switch (par_dst->codec_type) {
3315  case AVMEDIA_TYPE_AUDIO:
3316  if (audio_volume != 256) {
3317  av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
3318  exit_program(1);
3319  }
3320  if((par_dst->block_align == 1 || par_dst->block_align == 1152 || par_dst->block_align == 576) && par_dst->codec_id == AV_CODEC_ID_MP3)
3321  par_dst->block_align= 0;
3322  if(par_dst->codec_id == AV_CODEC_ID_AC3)
3323  par_dst->block_align= 0;
3324  break;
3325  case AVMEDIA_TYPE_VIDEO:
3326  if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
3327  sar =
3328  av_mul_q(ost->frame_aspect_ratio,
3329  (AVRational){ par_dst->height, par_dst->width });
3330  av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
3331  "with stream copy may produce invalid files\n");
3332  }
3333  else if (ist->st->sample_aspect_ratio.num)
3334  sar = ist->st->sample_aspect_ratio;
3335  else
3336  sar = par_src->sample_aspect_ratio;
3337  ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
3338  ost->st->avg_frame_rate = ist->st->avg_frame_rate;
3339  ost->st->r_frame_rate = ist->st->r_frame_rate;
3340  break;
3341  }
3342 
3343  ost->mux_timebase = ist->st->time_base;
3344 
3345  return 0;
3346 }
3347 
3349 {
3350  AVDictionaryEntry *e;
3351 
3352  uint8_t *encoder_string;
3353  int encoder_string_len;
3354  int format_flags = 0;
3355  int codec_flags = ost->enc_ctx->flags;
3356 
3357  if (av_dict_get(ost->st->metadata, "encoder", NULL, 0))
3358  return;
3359 
3360  e = av_dict_get(of->opts, "fflags", NULL, 0);
3361  if (e) {
3362  const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
3363  if (!o)
3364  return;
3365  av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
3366  }
3367  e = av_dict_get(ost->encoder_opts, "flags", NULL, 0);
3368  if (e) {
3369  const AVOption *o = av_opt_find(ost->enc_ctx, "flags", NULL, 0, 0);
3370  if (!o)
3371  return;
3372  av_opt_eval_flags(ost->enc_ctx, o, e->value, &codec_flags);
3373  }
3374 
3375  encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
3376  encoder_string = av_mallocz(encoder_string_len);
3377  if (!encoder_string)
3378  exit_program(1);
3379 
3380  if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & AV_CODEC_FLAG_BITEXACT))
3381  av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
3382  else
3383  av_strlcpy(encoder_string, "Lavc ", encoder_string_len);
3384  av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
3385  av_dict_set(&ost->st->metadata, "encoder", encoder_string,
3386  AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
3387 }
3388 
3389 static void parse_forced_key_frames(char *kf, OutputStream *ost,
3390  AVCodecContext *avctx)
3391 {
3392  char *p;
3393  int n = 1, i, size, index = 0;
3394  int64_t t, *pts;
3395 
3396  for (p = kf; *p; p++)
3397  if (*p == ',')
3398  n++;
3399  size = n;
3400  pts = av_malloc_array(size, sizeof(*pts));
3401  if (!pts) {
3402  av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3403  exit_program(1);
3404  }
3405 
3406  p = kf;
3407  for (i = 0; i < n; i++) {
3408  char *next = strchr(p, ',');
3409 
3410  if (next)
3411  *next++ = 0;
3412 
3413  if (!memcmp(p, "chapters", 8)) {
3414 
3415  AVFormatContext *avf = output_files[ost->file_index]->ctx;
3416  int j;
3417 
3418  if (avf->nb_chapters > INT_MAX - size ||
3419  !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
3420  sizeof(*pts)))) {
3421  av_log(NULL, AV_LOG_FATAL,
3422  "Could not allocate forced key frames array.\n");
3423  exit_program(1);
3424  }
3425  t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
3426  t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3427 
3428  for (j = 0; j < avf->nb_chapters; j++) {
3429  AVChapter *c = avf->chapters[j];
3430  av_assert1(index < size);
3431  pts[index++] = av_rescale_q(c->start, c->time_base,
3432  avctx->time_base) + t;
3433  }
3434 
3435  } else {
3436 
3437  t = parse_time_or_die("force_key_frames", p, 1);
3438  av_assert1(index < size);
3439  pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3440 
3441  }
3442 
3443  p = next;
3444  }
3445 
3446  av_assert0(index == size);
3447  qsort(pts, size, sizeof(*pts), compare_int64);
3448  ost->forced_kf_count = size;
3449  ost->forced_kf_pts = pts;
3450 }
3451 
3452 static void init_encoder_time_base(OutputStream *ost, AVRational default_time_base)
3453 {
3454  InputStream *ist = get_input_stream(ost);
3455  AVCodecContext *enc_ctx = ost->enc_ctx;
3456  AVFormatContext *oc;
3457 
3458  if (ost->enc_timebase.num > 0) {
3459  enc_ctx->time_base = ost->enc_timebase;
3460  return;
3461  }
3462 
3463  if (ost->enc_timebase.num < 0) {
3464  if (ist) {
3465  enc_ctx->time_base = ist->st->time_base;
3466  return;
3467  }
3468 
3469  oc = output_files[ost->file_index]->ctx;
3470  av_log(oc, AV_LOG_WARNING, "Input stream data not available, using default time base\n");
3471  }
3472 
3473  enc_ctx->time_base = default_time_base;
3474 }
3475 
3477 {
3478  InputStream *ist = get_input_stream(ost);
3479  AVCodecContext *enc_ctx = ost->enc_ctx;
3480  AVCodecContext *dec_ctx = NULL;
3481  AVFormatContext *oc = output_files[ost->file_index]->ctx;
3482  int j, ret;
3483 
3485 
3486  // Muxers use AV_PKT_DATA_DISPLAYMATRIX to signal rotation. On the other
3487  // hand, the legacy API makes demuxers set "rotate" metadata entries,
3488  // which have to be filtered out to prevent leaking them to output files.
3489  av_dict_set(&ost->st->metadata, "rotate", NULL, 0);
3490 
3491  if (ist) {
3492  ost->st->disposition = ist->st->disposition;
3493 
3494  dec_ctx = ist->dec_ctx;
3495 
3496  enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
3497  } else {
3498  for (j = 0; j < oc->nb_streams; j++) {
3499  AVStream *st = oc->streams[j];
3500  if (st != ost->st && st->codecpar->codec_type == ost->st->codecpar->codec_type)
3501  break;
3502  }
3503  if (j == oc->nb_streams)
3504  if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
3505  ost->st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
3506  ost->st->disposition = AV_DISPOSITION_DEFAULT;
3507  }
3508 
3509  if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3510  if (!ost->frame_rate.num)
3511  ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
3512  if (ist && !ost->frame_rate.num)
3513  ost->frame_rate = ist->framerate;
3514  if (ist && !ost->frame_rate.num)
3515  ost->frame_rate = ist->st->r_frame_rate;
3516  if (ist && !ost->frame_rate.num) {
3517  ost->frame_rate = (AVRational){25, 1};
3518  av_log(NULL, AV_LOG_WARNING,
3519  "No information "
3520  "about the input framerate is available. Falling "
3521  "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
3522  "if you want a different framerate.\n",
3523  ost->file_index, ost->index);
3524  }
3525 
3526  if (ost->enc->supported_framerates && !ost->force_fps) {
3527  int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
3528  ost->frame_rate = ost->enc->supported_framerates[idx];
3529  }
3530  // reduce frame rate for mpeg4 to be within the spec limits
3531  if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
3532  av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
3533  ost->frame_rate.num, ost->frame_rate.den, 65535);
3534  }
3535  }
3536 
3537  switch (enc_ctx->codec_type) {
3538  case AVMEDIA_TYPE_AUDIO:
3539  enc_ctx->sample_fmt = av_buffersink_get_format(ost->filter->filter);
3540  if (dec_ctx)
3541  enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,
3542  av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
3543  enc_ctx->sample_rate = av_buffersink_get_sample_rate(ost->filter->filter);
3544  enc_ctx->channel_layout = av_buffersink_get_channel_layout(ost->filter->filter);
3545  enc_ctx->channels = av_buffersink_get_channels(ost->filter->filter);
3546 
3547  init_encoder_time_base(ost, av_make_q(1, enc_ctx->sample_rate));
3548  break;
3549 
3550  case AVMEDIA_TYPE_VIDEO:
3551  init_encoder_time_base(ost, av_inv_q(ost->frame_rate));
3552 
3553  if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
3554  enc_ctx->time_base = av_buffersink_get_time_base(ost->filter->filter);
3555  if ( av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
3556  && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
3557  av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
3558  "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3559  }
3560  for (j = 0; j < ost->forced_kf_count; j++)
3561  ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
3562  AV_TIME_BASE_Q,
3563  enc_ctx->time_base);
3564 
3565  enc_ctx->width = av_buffersink_get_w(ost->filter->filter);
3566  enc_ctx->height = av_buffersink_get_h(ost->filter->filter);
3567  enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3568  ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
3569  av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :
3570  av_buffersink_get_sample_aspect_ratio(ost->filter->filter);
3571 
3572  enc_ctx->pix_fmt = av_buffersink_get_format(ost->filter->filter);
3573  if (dec_ctx)
3574  enc_ctx->bits_per_raw_sample = FFMIN(dec_ctx->bits_per_raw_sample,
3575  av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
3576 
3577  enc_ctx->framerate = ost->frame_rate;
3578 
3579  ost->st->avg_frame_rate = ost->frame_rate;
3580 
3581  if (!dec_ctx ||
3582  enc_ctx->width != dec_ctx->width ||
3583  enc_ctx->height != dec_ctx->height ||
3584  enc_ctx->pix_fmt != dec_ctx->pix_fmt) {
3585  enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample;
3586  }
3587 
3588  if (ost->top_field_first == 0) {
3589  enc_ctx->field_order = AV_FIELD_BB;
3590  } else if (ost->top_field_first == 1) {
3591  enc_ctx->field_order = AV_FIELD_TT;
3592  }
3593 
3594  if (ost->forced_keyframes) {
3595  if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
3596  ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
3597  forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
3598  if (ret < 0) {
3599  av_log(NULL, AV_LOG_ERROR,
3600  "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
3601  return ret;
3602  }
3607 
3608  // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
3609  // parse it only for static kf timings
3610  } else if(strncmp(ost->forced_keyframes, "source", 6)) {
3612  }
3613  }
3614  break;
3615  case AVMEDIA_TYPE_SUBTITLE:
3616  enc_ctx->time_base = AV_TIME_BASE_Q;
3617  if (!enc_ctx->width) {
3618  enc_ctx->width = input_streams[ost->source_index]->st->codecpar->width;
3619  enc_ctx->height = input_streams[ost->source_index]->st->codecpar->height;
3620  }
3621  break;
3622  case AVMEDIA_TYPE_DATA:
3623  break;
3624  default:
3625  abort();
3626  break;
3627  }
3628 
3629  ost->mux_timebase = enc_ctx->time_base;
3630 
3631  return 0;
3632 }
3633 
3634 static int init_output_stream(OutputStream *ost, char *error, int error_len)
3635 {
3636  int ret = 0;
3637 
3638  if (ost->encoding_needed) {
3639  AVCodec *codec = ost->enc;
3640  AVCodecContext *dec = NULL;
3641  InputStream *ist;
3642 
3643  ret = init_output_stream_encode(ost);
3644  if (ret < 0)
3645  return ret;
3646 
3647  if ((ist = get_input_stream(ost)))
3648  dec = ist->dec_ctx;
3649  if (dec && dec->subtitle_header) {
3650  /* ASS code assumes this buffer is null terminated so add extra byte. */
3651  ost->enc_ctx->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
3652  if (!ost->enc_ctx->subtitle_header)
3653  return AVERROR(ENOMEM);
3654  memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
3655  ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
3656  }
3657  if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
3658  av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
3659  if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
3660  !codec->defaults &&
3661  !av_dict_get(ost->encoder_opts, "b", NULL, 0) &&
3662  !av_dict_get(ost->encoder_opts, "ab", NULL, 0))
3663  av_dict_set(&ost->encoder_opts, "b", "128000", 0);
3664 
3665  if (ost->filter && av_buffersink_get_hw_frames_ctx(ost->filter->filter) &&
3666  ((AVHWFramesContext*)av_buffersink_get_hw_frames_ctx(ost->filter->filter)->data)->format ==
3667  av_buffersink_get_format(ost->filter->filter)) {
3668  ost->enc_ctx->hw_frames_ctx = av_buffer_ref(av_buffersink_get_hw_frames_ctx(ost->filter->filter));
3669  if (!ost->enc_ctx->hw_frames_ctx)
3670  return AVERROR(ENOMEM);
3671  } else {
3672  ret = hw_device_setup_for_encode(ost);
3673  if (ret < 0) {
3674  snprintf(error, error_len, "Device setup failed for "
3675  "encoder on output stream #%d:%d : %s",
3676  ost->file_index, ost->index, av_err2str(ret));
3677  return ret;
3678  }
3679  }
3680  if (ist && ist->dec->type == AVMEDIA_TYPE_SUBTITLE && ost->enc->type == AVMEDIA_TYPE_SUBTITLE) {
3681  int input_props = 0, output_props = 0;
3682  AVCodecDescriptor const *input_descriptor =
3683  avcodec_descriptor_get(dec->codec_id);
3684  AVCodecDescriptor const *output_descriptor =
3685  avcodec_descriptor_get(ost->enc_ctx->codec_id);
3686  if (input_descriptor)
3687  input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3688  if (output_descriptor)
3689  output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3690  if (input_props && output_props && input_props != output_props) {
3691  snprintf(error, error_len,
3692  "Subtitle encoding currently only possible from text to text "
3693  "or bitmap to bitmap");
3694  return AVERROR_INVALIDDATA;
3695  }
3696  }
3697 
3698  if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
3699  if (ret == AVERROR_EXPERIMENTAL)
3700  abort_codec_experimental(codec, 1);
3701  snprintf(error, error_len,
3702  "Error while opening encoder for output stream #%d:%d - "
3703  "maybe incorrect parameters such as bit_rate, rate, width or height",
3704  ost->file_index, ost->index);
3705  return ret;
3706  }
3707  if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
3708  !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
3709  av_buffersink_set_frame_size(ost->filter->filter,
3710  ost->enc_ctx->frame_size);
3712  if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000 &&
3713  ost->enc_ctx->codec_id != AV_CODEC_ID_CODEC2 /* don't complain about 700 bit/s modes */)
3714  av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
3715  " It takes bits/s as argument, not kbits/s\n");
3716 
3717  ret = avcodec_parameters_from_context(ost->st->codecpar, ost->enc_ctx);
3718  if (ret < 0) {
3719  av_log(NULL, AV_LOG_FATAL,
3720  "Error initializing the output stream codec context.\n");
3721  exit_program(1);
3722  }
3723  /*
3724  * FIXME: ost->st->codec should't be needed here anymore.
3725  */
3726  ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);
3727  if (ret < 0)
3728  return ret;
3729 
3730  if (ost->enc_ctx->nb_coded_side_data) {
3731  int i;
3732 
3733  for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
3734  const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
3735  uint8_t *dst_data;
3736 
3737  dst_data = av_stream_new_side_data(ost->st, sd_src->type, sd_src->size);
3738  if (!dst_data)
3739  return AVERROR(ENOMEM);
3740  memcpy(dst_data, sd_src->data, sd_src->size);
3741  }
3742  }
3743 
3744  /*
3745  * Add global input side data. For now this is naive, and copies it
3746  * from the input stream's global side data. All side data should
3747  * really be funneled over AVFrame and libavfilter, then added back to
3748  * packet side data, and then potentially using the first packet for
3749  * global side data.
3750  */
3751  if (ist) {
3752  int i;
3753  for (i = 0; i < ist->st->nb_side_data; i++) {
3754  AVPacketSideData *sd = &ist->st->side_data[i];
3755  uint8_t *dst = av_stream_new_side_data(ost->st, sd->type, sd->size);
3756  if (!dst)
3757  return AVERROR(ENOMEM);
3758  memcpy(dst, sd->data, sd->size);
3759  if (ist->autorotate && sd->type == AV_PKT_DATA_DISPLAYMATRIX)
3760  av_display_rotation_set((uint32_t *)dst, 0);
3761  }
3762  }
3763 
3764  // copy timebase while removing common factors
3765  if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
3766  ost->st->time_base = av_add_q(ost->enc_ctx->time_base, (AVRational){0, 1});
3767 
3768  // copy estimated duration as a hint to the muxer
3769  if (ost->st->duration <= 0 && ist && ist->st->duration > 0)
3770  ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
3771 
3772  ost->st->codec->codec= ost->enc_ctx->codec;
3773  } else if (ost->stream_copy) {
3774  ret = init_output_stream_streamcopy(ost);
3775  if (ret < 0)
3776  return ret;
3777  }
3778 
3779  // parse user provided disposition, and update stream values
3780  if (ost->disposition) {
3781  static const AVOption opts[] = {
3782  { "disposition" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
3783  { "default" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT }, .unit = "flags" },
3784  { "dub" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB }, .unit = "flags" },
3785  { "original" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL }, .unit = "flags" },
3786  { "comment" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT }, .unit = "flags" },
3787  { "lyrics" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS }, .unit = "flags" },
3788  { "karaoke" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE }, .unit = "flags" },
3789  { "forced" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED }, .unit = "flags" },
3790  { "hearing_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED }, .unit = "flags" },
3791  { "visual_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED }, .unit = "flags" },
3792  { "clean_effects" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS }, .unit = "flags" },
3793  { "attached_pic" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ATTACHED_PIC }, .unit = "flags" },
3794  { "captions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS }, .unit = "flags" },
3795  { "descriptions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS }, .unit = "flags" },
3796  { "dependent" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEPENDENT }, .unit = "flags" },
3797  { "metadata" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA }, .unit = "flags" },
3798  { NULL },
3799  };
3800  static const AVClass class = {
3801  .class_name = "",
3802  .item_name = av_default_item_name,
3803  .option = opts,
3804  .version = LIBAVUTIL_VERSION_INT,
3805  };
3806  const AVClass *pclass = &class;
3807 
3808  ret = av_opt_eval_flags(&pclass, &opts[0], ost->disposition, &ost->st->disposition);
3809  if (ret < 0)
3810  return ret;
3811  }
3812 
3813  /* initialize bitstream filters for the output stream
3814  * needs to be done here, because the codec id for streamcopy is not
3815  * known until now */
3816  ret = init_output_bsfs(ost);
3817  if (ret < 0)
3818  return ret;
3819 
3820  ost->initialized = 1;
3821 
3823  if (ret < 0)
3824  return ret;
3825 
3826  return ret;
3827 }
3828 
3829 static void report_new_stream(int input_index, AVPacket *pkt)
3830 {
3831  InputFile *file = input_files[input_index];
3832  AVStream *st = file->ctx->streams[pkt->stream_index];
3833 
3834  if (pkt->stream_index < file->nb_streams_warn)
3835  return;
3836  av_log(file->ctx, AV_LOG_WARNING,
3837  "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
3838  av_get_media_type_string(st->codecpar->codec_type),
3839  input_index, pkt->stream_index,
3840  pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
3841  file->nb_streams_warn = pkt->stream_index + 1;
3842 }
3843 
3844 static int transcode_init(void)
3845 {
3846  int ret = 0, i, j, k;
3847  AVFormatContext *oc;
3848  OutputStream *ost;
3849  InputStream *ist;
3850  char error[1024] = {0};
3851 
3852  for (i = 0; i < nb_filtergraphs; i++) {
3853  FilterGraph *fg = filtergraphs[i];
3854  for (j = 0; j < fg->nb_outputs; j++) {
3855  OutputFilter *ofilter = fg->outputs[j];
3856  if (!ofilter->ost || ofilter->ost->source_index >= 0)
3857  continue;
3858  if (fg->nb_inputs != 1)
3859  continue;
3860  for (k = nb_input_streams-1; k >= 0 ; k--)
3861  if (fg->inputs[0]->ist == input_streams[k])
3862  break;
3863  ofilter->ost->source_index = k;
3864  }
3865  }
3866 
3867  /* init framerate emulation */
3868  for (i = 0; i < nb_input_files; i++) {
3869  InputFile *ifile = input_files[i];
3870  if (ifile->rate_emu)
3871  for (j = 0; j < ifile->nb_streams; j++)
3872  input_streams[j + ifile->ist_index]->start = av_gettime_relative();
3873  }
3874 
3875  /* init input streams */
3876  for (i = 0; i < nb_input_streams; i++)
3877  if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
3878  for (i = 0; i < nb_output_streams; i++) {
3879  ost = output_streams[i];
3880  avcodec_close(ost->enc_ctx);
3881  }
3882  goto dump_format;
3883  }
3884 
3885  /* open each encoder */
3886  for (i = 0; i < nb_output_streams; i++) {
3887  // skip streams fed from filtergraphs until we have a frame for them
3888  if (output_streams[i]->filter)
3889  continue;
3890 
3891  ret = init_output_stream(output_streams[i], error, sizeof(error));
3892  if (ret < 0)
3893  goto dump_format;
3894  }
3895 
3896  /* discard unused programs */
3897  for (i = 0; i < nb_input_files; i++) {
3898  InputFile *ifile = input_files[i];
3899  for (j = 0; j < ifile->ctx->nb_programs; j++) {
3900  AVProgram *p = ifile->ctx->programs[j];
3901  int discard = AVDISCARD_ALL;
3902 
3903  for (k = 0; k < p->nb_stream_indexes; k++)
3904  if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
3905  discard = AVDISCARD_DEFAULT;
3906  break;
3907  }
3908  p->discard = discard;
3909  }
3910  }
3911 
3912  /* write headers for files with no streams */
3913  for (i = 0; i < nb_output_files; i++) {
3914  oc = output_files[i]->ctx;
3915  if (oc->oformat->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
3916  ret = check_init_output_file(output_files[i], i);
3917  if (ret < 0)
3918  goto dump_format;
3919  }
3920  }
3921 
3922  dump_format:
3923  /* dump the stream mapping */
3924  av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3925  for (i = 0; i < nb_input_streams; i++) {
3926  ist = input_streams[i];
3927 
3928  for (j = 0; j < ist->nb_filters; j++) {
3929  if (!filtergraph_is_simple(ist->filters[j]->graph)) {
3930  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
3931  ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
3932  ist->filters[j]->name);
3933  if (nb_filtergraphs > 1)
3934  av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
3935  av_log(NULL, AV_LOG_INFO, "\n");
3936  }
3937  }
3938  }
3939 
3940  for (i = 0; i < nb_output_streams; i++) {
3941  ost = output_streams[i];
3942 
3943  if (ost->attachment_filename) {
3944  /* an attached file */
3945  av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
3946  ost->attachment_filename, ost->file_index, ost->index);
3947  continue;
3948  }
3949 
3950  if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
3951  /* output from a complex graph */
3952  av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
3953  if (nb_filtergraphs > 1)
3954  av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
3955 
3956  av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
3957  ost->index, ost->enc ? ost->enc->name : "?");
3958  continue;
3959  }
3960 
3961  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
3963  input_streams[ost->source_index]->st->index,
3964  ost->file_index,
3965  ost->index);
3966  if (ost->sync_ist != input_streams[ost->source_index])
3967  av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
3968  ost->sync_ist->file_index,
3969  ost->sync_ist->st->index);
3970  if (ost->stream_copy)
3971  av_log(NULL, AV_LOG_INFO, " (copy)");
3972  else {
3973  const AVCodec *in_codec = input_streams[ost->source_index]->dec;
3974  const AVCodec *out_codec = ost->enc;
3975  const char *decoder_name = "?";
3976  const char *in_codec_name = "?";
3977  const char *encoder_name = "?";
3978  const char *out_codec_name = "?";
3979  const AVCodecDescriptor *desc;
3980 
3981  if (in_codec) {
3982  decoder_name = in_codec->name;
3983  desc = avcodec_descriptor_get(in_codec->id);
3984  if (desc)
3985  in_codec_name = desc->name;
3986  if (!strcmp(decoder_name, in_codec_name))
3987  decoder_name = "native";
3988  }
3989 
3990  if (out_codec) {
3991  encoder_name = out_codec->name;
3992  desc = avcodec_descriptor_get(out_codec->id);
3993  if (desc)
3994  out_codec_name = desc->name;
3995  if (!strcmp(encoder_name, out_codec_name))
3996  encoder_name = "native";
3997  }
3998 
3999  av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
4000  in_codec_name, decoder_name,
4001  out_codec_name, encoder_name);
4002  }
4003  av_log(NULL, AV_LOG_INFO, "\n");
4004  }
4005 
4006  if (ret) {
4007  av_log(NULL, AV_LOG_ERROR, "%s\n", error);
4008  return ret;
4009  }
4010 
4011  atomic_store(&transcode_init_done, 1);
4012 
4013  return 0;
4014 }
4015 
4016 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
4017 static int need_output(void)
4018 {
4019  int i;
4020 
4021  for (i = 0; i < nb_output_streams; i++) {
4022  OutputStream *ost = output_streams[i];
4023  OutputFile *of = output_files[ost->file_index];
4024  AVFormatContext *os = output_files[ost->file_index]->ctx;
4025 
4026  if (ost->finished ||
4027  (os->pb && avio_tell(os->pb) >= of->limit_filesize))
4028  continue;
4029  if (ost->frame_number >= ost->max_frames) {
4030  int j;
4031  for (j = 0; j < of->ctx->nb_streams; j++)
4033  continue;
4034  }
4035 
4036  return 1;
4037  }
4038 
4039  return 0;
4040 }
4041 
4048 {
4049  int i;
4050  int64_t opts_min = INT64_MAX;
4051  OutputStream *ost_min = NULL;
4052 
4053  for (i = 0; i < nb_output_streams; i++) {
4054  OutputStream *ost = output_streams[i];
4055  int64_t opts = ost->st->cur_dts == AV_NOPTS_VALUE ? INT64_MIN :
4056  av_rescale_q(ost->st->cur_dts, ost->st->time_base,
4057  AV_TIME_BASE_Q);
4058  if (ost->st->cur_dts == AV_NOPTS_VALUE)
4059  av_log(NULL, AV_LOG_DEBUG,
4060  "cur_dts is invalid st:%d (%d) [init:%d i_done:%d finish:%d] (this is harmless if it occurs once at the start per stream)\n",
4061  ost->st->index, ost->st->id, ost->initialized, ost->inputs_done, ost->finished);
4062 
4063  if (!ost->initialized && !ost->inputs_done)
4064  return ost;
4065 
4066  if (!ost->finished && opts < opts_min) {
4067  opts_min = opts;
4068  ost_min = ost->unavailable ? NULL : ost;
4069  }
4070  }
4071  return ost_min;
4072 }
4073 
4074 static void set_tty_echo(int on)
4075 {
4076 #if HAVE_TERMIOS_H
4077  struct termios tty;
4078  if (tcgetattr(0, &tty) == 0) {
4079  if (on) tty.c_lflag |= ECHO;
4080  else tty.c_lflag &= ~ECHO;
4081  tcsetattr(0, TCSANOW, &tty);
4082  }
4083 #endif
4084 }
4085 
4086 static int check_keyboard_interaction(int64_t cur_time)
4087 {
4088  int i, ret, key;
4089  static int64_t last_time;
4090  if (received_nb_signals)
4091  return AVERROR_EXIT;
4092  /* read_key() returns 0 on EOF */
4093  if(cur_time - last_time >= 100000 && !run_as_daemon){
4094  key = read_key();
4095  last_time = cur_time;
4096  }else
4097  key = -1;
4098  if (key == 'q')
4099  return AVERROR_EXIT;
4100  if (key == '+') av_log_set_level(av_log_get_level()+10);
4101  if (key == '-') av_log_set_level(av_log_get_level()-10);
4102  if (key == 's') qp_hist ^= 1;
4103  if (key == 'h'){
4104  if (do_hex_dump){
4105  do_hex_dump = do_pkt_dump = 0;
4106  } else if(do_pkt_dump){
4107  do_hex_dump = 1;
4108  } else
4109  do_pkt_dump = 1;
4110  av_log_set_level(AV_LOG_DEBUG);
4111  }
4112  if (key == 'c' || key == 'C'){
4113  char buf[4096], target[64], command[256], arg[256] = {0};
4114  double time;
4115  int k, n = 0;
4116  fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
4117  i = 0;
4118  set_tty_echo(1);
4119  while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
4120  if (k > 0)
4121  buf[i++] = k;
4122  buf[i] = 0;
4123  set_tty_echo(0);
4124  fprintf(stderr, "\n");
4125  if (k > 0 &&
4126  (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
4127  av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
4128  target, time, command, arg);
4129  for (i = 0; i < nb_filtergraphs; i++) {
4130  FilterGraph *fg = filtergraphs[i];
4131  if (fg->graph) {
4132  if (time < 0) {
4133  ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
4134  key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
4135  fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
4136  } else if (key == 'c') {
4137  fprintf(stderr, "Queuing commands only on filters supporting the specific command is unsupported\n");
4138  ret = AVERROR_PATCHWELCOME;
4139  } else {
4140  ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
4141  if (ret < 0)
4142  fprintf(stderr, "Queuing command failed with error %s\n", av_err2str(ret));
4143  }
4144  }
4145  }
4146  } else {
4147  av_log(NULL, AV_LOG_ERROR,
4148  "Parse error, at least 3 arguments were expected, "
4149  "only %d given in string '%s'\n", n, buf);
4150  }
4151  }
4152  if (key == 'd' || key == 'D'){
4153  int debug=0;
4154  if(key == 'D') {
4155  debug = input_streams[0]->st->codec->debug<<1;
4156  if(!debug) debug = 1;
4157  while(debug & (FF_DEBUG_DCT_COEFF
4158 #if FF_API_DEBUG_MV
4159  |FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE
4160 #endif
4161  )) //unsupported, would just crash
4162  debug += debug;
4163  }else{
4164  char buf[32];
4165  int k = 0;
4166  i = 0;
4167  set_tty_echo(1);
4168  while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
4169  if (k > 0)
4170  buf[i++] = k;
4171  buf[i] = 0;
4172  set_tty_echo(0);
4173  fprintf(stderr, "\n");
4174  if (k <= 0 || sscanf(buf, "%d", &debug)!=1)
4175  fprintf(stderr,"error parsing debug value\n");
4176  }
4177  for(i=0;i<nb_input_streams;i++) {
4178  input_streams[i]->st->codec->debug = debug;
4179  }
4180  for(i=0;i<nb_output_streams;i++) {
4181  OutputStream *ost = output_streams[i];
4182  ost->enc_ctx->debug = debug;
4183  }
4184  if(debug) av_log_set_level(AV_LOG_DEBUG);
4185  fprintf(stderr,"debug=%d\n", debug);
4186  }
4187  if (key == '?'){
4188  fprintf(stderr, "key function\n"
4189  "? show this help\n"
4190  "+ increase verbosity\n"
4191  "- decrease verbosity\n"
4192  "c Send command to first matching filter supporting it\n"
4193  "C Send/Queue command to all matching filters\n"
4194  "D cycle through available debug modes\n"
4195  "h dump packets/hex press to cycle through the 3 states\n"
4196  "q quit\n"
4197  "s Show QP histogram\n"
4198  );
4199  }
4200  return 0;
4201 }
4202 
4203 #if HAVE_THREADS
4204 static void *input_thread(void *arg)
4205 {
4206  InputFile *f = arg;
4207  unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
4208  int ret = 0;
4209 
4210  while (1) {
4211  AVPacket pkt;
4212  ret = av_read_frame(f->ctx, &pkt);
4213 
4214  if (ret == AVERROR(EAGAIN)) {
4215  av_usleep(10000);
4216  continue;
4217  }
4218  if (ret < 0) {
4219  av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
4220  break;
4221  }
4222  ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
4223  if (flags && ret == AVERROR(EAGAIN)) {
4224  flags = 0;
4225  ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, flags);
4226  av_log(f->ctx, AV_LOG_WARNING,
4227  "Thread message queue blocking; consider raising the "
4228  "thread_queue_size option (current value: %d)\n",
4229  f->thread_queue_size);
4230  }
4231  if (ret < 0) {
4232  if (ret != AVERROR_EOF)
4233  av_log(f->ctx, AV_LOG_ERROR,
4234  "Unable to send packet to main thread: %s\n",
4235  av_err2str(ret));
4236  av_packet_unref(&pkt);
4237  av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
4238  break;
4239  }
4240  }
4241 
4242  return NULL;
4243 }
4244 
4245 static void free_input_thread(int i)
4246 {
4247  InputFile *f = input_files[i];
4248  AVPacket pkt;
4249 
4250  if (!f || !f->in_thread_queue)
4251  return;
4252  av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
4253  while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
4254  av_packet_unref(&pkt);
4255 
4256  pthread_join(f->thread, NULL);
4257  f->joined = 1;
4258  av_thread_message_queue_free(&f->in_thread_queue);
4259 }
4260 
4261 static void free_input_threads(void)
4262 {
4263  int i;
4264 
4265  for (i = 0; i < nb_input_files; i++)
4266  free_input_thread(i);
4267 }
4268 
4269 static int init_input_thread(int i)
4270 {
4271  int ret;
4272  InputFile *f = input_files[i];
4273 
4274  if (nb_input_files == 1)
4275  return 0;
4276 
4277  if (f->ctx->pb ? !f->ctx->pb->seekable :
4278  strcmp(f->ctx->iformat->name, "lavfi"))
4279  f->non_blocking = 1;
4280  ret = av_thread_message_queue_alloc(&f->in_thread_queue,
4281  f->thread_queue_size, sizeof(AVPacket));
4282  if (ret < 0)
4283  return ret;
4284 
4285  if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
4286  av_log(NULL, AV_LOG_ERROR, "pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
4287  av_thread_message_queue_free(&f->in_thread_queue);
4288  return AVERROR(ret);
4289  }
4290 
4291  return 0;
4292 }
4293 
4294 static int init_input_threads(void)
4295 {
4296  int i, ret;
4297 
4298  for (i = 0; i < nb_input_files; i++) {
4299  ret = init_input_thread(i);
4300  if (ret < 0)
4301  return ret;
4302  }
4303  return 0;
4304 }
4305 
4306 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
4307 {
4308  return av_thread_message_queue_recv(f->in_thread_queue, pkt,
4309  f->non_blocking ?
4310  AV_THREAD_MESSAGE_NONBLOCK : 0);
4311 }
4312 #endif
4313 
4314 static int get_input_packet(InputFile *f, AVPacket *pkt)
4315 {
4316  if (f->rate_emu) {
4317  int i;
4318  for (i = 0; i < f->nb_streams; i++) {
4319  InputStream *ist = input_streams[f->ist_index + i];
4320  int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
4321  int64_t now = av_gettime_relative() - ist->start;
4322  if (pts > now)
4323  return AVERROR(EAGAIN);
4324  }
4325  }
4326 
4327 #if HAVE_THREADS
4328  if (nb_input_files > 1)
4329  return get_input_packet_mt(f, pkt);
4330 #endif
4331  return av_read_frame(f->ctx, pkt);
4332 }
4333 
4334 static int got_eagain(void)
4335 {
4336  int i;
4337  for (i = 0; i < nb_output_streams; i++)
4338  if (output_streams[i]->unavailable)
4339  return 1;
4340  return 0;
4341 }
4342 
4343 static void reset_eagain(void)
4344 {
4345  int i;
4346  for (i = 0; i < nb_input_files; i++)
4347  input_files[i]->eagain = 0;
4348  for (i = 0; i < nb_output_streams; i++)
4349  output_streams[i]->unavailable = 0;
4350 }
4351 
4352 // set duration to max(tmp, duration) in a proper time base and return duration's time_base
4353 static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
4354  AVRational time_base)
4355 {
4356  int ret;
4357 
4358  if (!*duration) {
4359  *duration = tmp;
4360  return tmp_time_base;
4361  }
4362 
4363  ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
4364  if (ret < 0) {
4365  *duration = tmp;
4366  return tmp_time_base;
4367  }
4368 
4369  return time_base;
4370 }
4371 
4372 static int seek_to_start(InputFile *ifile, AVFormatContext *is)
4373 {
4374  InputStream *ist;
4375  AVCodecContext *avctx;
4376  int i, ret, has_audio = 0;
4377  int64_t duration = 0;
4378 
4379  ret = avformat_seek_file(is, -1, INT64_MIN, is->start_time, is->start_time, 0);
4380  if (ret < 0)
4381  return ret;
4382 
4383  for (i = 0; i < ifile->nb_streams; i++) {
4384  ist = input_streams[ifile->ist_index + i];
4385  avctx = ist->dec_ctx;
4386 
4387  /* duration is the length of the last frame in a stream
4388  * when audio stream is present we don't care about
4389  * last video frame length because it's not defined exactly */
4390  if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
4391  has_audio = 1;
4392  }
4393 
4394  for (i = 0; i < ifile->nb_streams; i++) {
4395  ist = input_streams[ifile->ist_index + i];
4396  avctx = ist->dec_ctx;
4397 
4398  if (has_audio) {
4399  if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
4400  AVRational sample_rate = {1, avctx->sample_rate};
4401 
4402  duration = av_rescale_q(ist->nb_samples, sample_rate, ist->st->time_base);
4403  } else {
4404  continue;
4405  }
4406  } else {
4407  if (ist->framerate.num) {
4408  duration = av_rescale_q(1, av_inv_q(ist->framerate), ist->st->time_base);
4409  } else if (ist->st->avg_frame_rate.num) {
4410  duration = av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate), ist->st->time_base);
4411  } else {
4412  duration = 1;
4413  }
4414  }
4415  if (!ifile->duration)
4416  ifile->time_base = ist->st->time_base;
4417  /* the total duration of the stream, max_pts - min_pts is
4418  * the duration of the stream without the last frame */
4419  duration += ist->max_pts - ist->min_pts;
4420  ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
4421  ifile->time_base);
4422  }
4423 
4424  if (ifile->loop > 0)
4425  ifile->loop--;
4426 
4427  return ret;
4428 }
4429 
4430 /*
4431  * Return
4432  * - 0 -- one packet was read and processed
4433  * - AVERROR(EAGAIN) -- no packets were available for selected file,
4434  * this function should be called again
4435  * - AVERROR_EOF -- this function should not be called again
4436  */
4437 static int process_input(int file_index)
4438 {
4439  InputFile *ifile = input_files[file_index];
4440  AVFormatContext *is;
4441  InputStream *ist;
4442  AVPacket pkt;
4443  int ret, thread_ret, i, j;
4444  int64_t duration;
4445  int64_t pkt_dts;
4446 
4447  is = ifile->ctx;
4448  ret = get_input_packet(ifile, &pkt);
4449 
4450  if (ret == AVERROR(EAGAIN)) {
4451  ifile->eagain = 1;
4452  return ret;
4453  }
4454  if (ret < 0 && ifile->loop) {
4455  AVCodecContext *avctx;
4456  for (i = 0; i < ifile->nb_streams; i++) {
4457  ist = input_streams[ifile->ist_index + i];
4458  avctx = ist->dec_ctx;
4459  if (ist->decoding_needed) {
4460  ret = process_input_packet(ist, NULL, 1);
4461  if (ret>0)
4462  return 0;
4463  avcodec_flush_buffers(avctx);
4464  }
4465  }
4466 #if HAVE_THREADS
4467  free_input_thread(file_index);
4468 #endif
4469  ret = seek_to_start(ifile, is);
4470 #if HAVE_THREADS
4471  thread_ret = init_input_thread(file_index);
4472  if (thread_ret < 0)
4473  return thread_ret;
4474 #endif
4475  if (ret < 0)
4476  av_log(NULL, AV_LOG_WARNING, "Seek to start failed.\n");
4477  else
4478  ret = get_input_packet(ifile, &pkt);
4479  if (ret == AVERROR(EAGAIN)) {
4480  ifile->eagain = 1;
4481  return ret;
4482  }
4483  }
4484  if (ret < 0) {
4485  if (ret != AVERROR_EOF) {
4486  print_error(is->url, ret);
4487  if (exit_on_error)
4488  exit_program(1);
4489  }
4490 
4491  for (i = 0; i < ifile->nb_streams; i++) {
4492  ist = input_streams[ifile->ist_index + i];
4493  if (ist->decoding_needed) {
4494  ret = process_input_packet(ist, NULL, 0);
4495  if (ret>0)
4496  return 0;
4497  }
4498 
4499  /* mark all outputs that don't go through lavfi as finished */
4500  for (j = 0; j < nb_output_streams; j++) {
4501  OutputStream *ost = output_streams[j];
4502 
4503  if (ost->source_index == ifile->ist_index + i &&
4504  (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
4505  finish_output_stream(ost);
4506  }
4507  }
4508 
4509  ifile->eof_reached = 1;
4510  return AVERROR(EAGAIN);
4511  }
4512 
4513  reset_eagain();
4514 
4515  if (do_pkt_dump) {
4516  av_pkt_dump_log2(NULL, AV_LOG_INFO, &pkt, do_hex_dump,
4517  is->streams[pkt.stream_index]);
4518  }
4519  /* the following test is needed in case new streams appear
4520  dynamically in stream : we ignore them */
4521  if (pkt.stream_index >= ifile->nb_streams) {
4522  report_new_stream(file_index, &pkt);
4523  goto discard_packet;
4524  }
4525 
4526  ist = input_streams[ifile->ist_index + pkt.stream_index];
4527 
4528  ist->data_size += pkt.size;
4529  ist->nb_packets++;
4530 
4531  if (ist->discard)
4532  goto discard_packet;
4533 
4534  if (pkt.flags & AV_PKT_FLAG_CORRUPT) {
4535  av_log(NULL, exit_on_error ? AV_LOG_FATAL : AV_LOG_WARNING,
4536  "%s: corrupt input packet in stream %d\n", is->url, pkt.stream_index);
4537  if (exit_on_error)
4538  exit_program(1);
4539  }
4540 
4541  if (debug_ts) {
4542  av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
4543  "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",
4544  ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
4545  av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
4546  av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
4547  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
4548  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
4549  av_ts2str(input_files[ist->file_index]->ts_offset),
4550  av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
4551  }
4552 
4553  if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
4554  int64_t stime, stime2;
4555  // Correcting starttime based on the enabled streams
4556  // 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.
4557  // so we instead do it here as part of discontinuity handling
4558  if ( ist->next_dts == AV_NOPTS_VALUE
4559  && ifile->ts_offset == -is->start_time
4560  && (is->iformat->flags & AVFMT_TS_DISCONT)) {
4561  int64_t new_start_time = INT64_MAX;
4562  for (i=0; i<is->nb_streams; i++) {
4563  AVStream *st = is->streams[i];
4564  if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
4565  continue;
4566  new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
4567  }
4568  if (new_start_time > is->start_time) {
4569  av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
4570  ifile->ts_offset = -new_start_time;
4571  }
4572  }
4573 
4574  stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
4575  stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
4576  ist->wrap_correction_done = 1;
4577 
4578  if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
4579  pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
4580  ist->wrap_correction_done = 0;
4581  }
4582  if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
4583  pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
4584  ist->wrap_correction_done = 0;
4585  }
4586  }
4587 
4588  /* add the stream-global side data to the first packet */
4589  if (ist->nb_packets == 1) {
4590  for (i = 0; i < ist->st->nb_side_data; i++) {
4591  AVPacketSideData *src_sd = &ist->st->side_data[i];
4592  uint8_t *dst_data;
4593 
4594  if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
4595  continue;
4596 
4597  if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
4598  continue;
4599 
4600  dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
4601  if (!dst_data)
4602  exit_program(1);
4603 
4604  memcpy(dst_data, src_sd->data, src_sd->size);
4605  }
4606  }
4607 
4608  if (pkt.dts != AV_NOPTS_VALUE)
4609  pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
4610  if (pkt.pts != AV_NOPTS_VALUE)
4611  pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
4612 
4613  if (pkt.pts != AV_NOPTS_VALUE)
4614  pkt.pts *= ist->ts_scale;
4615  if (pkt.dts != AV_NOPTS_VALUE)
4616  pkt.dts *= ist->ts_scale;
4617 
4618  pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4619  if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
4620  ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
4621  pkt_dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
4622  && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
4623  int64_t delta = pkt_dts - ifile->last_ts;
4624  if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
4625  delta > 1LL*dts_delta_threshold*AV_TIME_BASE){
4626  ifile->ts_offset -= delta;
4627  av_log(NULL, AV_LOG_DEBUG,
4628  "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
4629  delta, ifile->ts_offset);
4630  pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
4631  if (pkt.pts != AV_NOPTS_VALUE)
4632  pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
4633  }
4634  }
4635 
4636  duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
4637  if (pkt.pts != AV_NOPTS_VALUE) {
4638  pkt.pts += duration;
4639  ist->max_pts = FFMAX(pkt.pts, ist->max_pts);
4640  ist->min_pts = FFMIN(pkt.pts, ist->min_pts);
4641  }
4642 
4643  if (pkt.dts != AV_NOPTS_VALUE)
4644  pkt.dts += duration;
4645 
4646  pkt_dts = av_rescale_q_rnd(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q, AV_ROUND_NEAR_INF|AV_ROUND_PASS_MINMAX);
4647  if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
4648  ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
4649  pkt_dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
4650  !copy_ts) {
4651  int64_t delta = pkt_dts - ist->next_dts;
4652  if (is->iformat->flags & AVFMT_TS_DISCONT) {
4653  if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
4654  delta > 1LL*dts_delta_threshold*AV_TIME_BASE ||
4655  pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {
4656  ifile->ts_offset -= delta;
4657  av_log(NULL, AV_LOG_DEBUG,
4658  "timestamp discontinuity for stream #%d:%d "
4659  "(id=%d, type=%s): %"PRId64", new offset= %"PRId64"\n",
4660  ist->file_index, ist->st->index, ist->st->id,
4661  av_get_media_type_string(ist->dec_ctx->codec_type),
4662  delta, ifile->ts_offset);
4663  pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
4664  if (pkt.pts != AV_NOPTS_VALUE)
4665  pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
4666  }
4667  } else {
4668  if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
4669  delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
4670  av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
4671  pkt.dts = AV_NOPTS_VALUE;
4672  }
4673  if (pkt.pts != AV_NOPTS_VALUE){
4674  int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
4675  delta = pkt_pts - ist->next_dts;
4676  if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
4677  delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
4678  av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
4679  pkt.pts = AV_NOPTS_VALUE;
4680  }
4681  }
4682  }
4683  }
4684 
4685  if (pkt.dts != AV_NOPTS_VALUE)
4686  ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
4687 
4688  if (debug_ts) {
4689  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",
4690  ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
4691  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
4692  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
4693  av_ts2str(input_files[ist->file_index]->ts_offset),
4694  av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
4695  }
4696 
4697  sub2video_heartbeat(ist, pkt.pts);
4698 
4699  process_input_packet(ist, &pkt, 0);
4700 
4701 discard_packet:
4702  av_packet_unref(&pkt);
4703 
4704  return 0;
4705 }
4706 
4714 static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
4715 {
4716  int i, ret;
4717  int nb_requests, nb_requests_max = 0;
4718  InputFilter *ifilter;
4719  InputStream *ist;
4720 
4721  *best_ist = NULL;
4722  ret = avfilter_graph_request_oldest(graph->graph);
4723  if (ret >= 0)
4724  return reap_filters(0);
4725 
4726  if (ret == AVERROR_EOF) {
4727  ret = reap_filters(1);
4728  for (i = 0; i < graph->nb_outputs; i++)
4729  close_output_stream(graph->outputs[i]->ost);
4730  return ret;
4731  }
4732  if (ret != AVERROR(EAGAIN))
4733  return ret;
4734 
4735  for (i = 0; i < graph->nb_inputs; i++) {
4736  ifilter = graph->inputs[i];
4737  ist = ifilter->ist;
4738  if (input_files[ist->file_index]->eagain ||
4740  continue;
4741  nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
4742  if (nb_requests > nb_requests_max) {
4743  nb_requests_max = nb_requests;
4744  *best_ist = ist;
4745  }
4746  }
4747 
4748  if (!*best_ist)
4749  for (i = 0; i < graph->nb_outputs; i++)
4750  graph->outputs[i]->ost->unavailable = 1;
4751 
4752  return 0;
4753 }
4754 
4760 static int transcode_step(void)
4761 {
4762  OutputStream *ost;
4763  InputStream *ist = NULL;
4764  int ret;
4765 
4766  ost = choose_output();
4767  if (!ost) {
4768  if (got_eagain()) {
4769  reset_eagain();
4770  av_usleep(10000);
4771  return 0;
4772  }
4773  av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
4774  return AVERROR_EOF;
4775  }
4776 
4777  if (ost->filter && !ost->filter->graph->graph) {
4779  ret = configure_filtergraph(ost->filter->graph);
4780  if (ret < 0) {
4781  av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
4782  return ret;
4783  }
4784  }
4785  }
4786 
4787  if (ost->filter && ost->filter->graph->graph) {
4788  if (!ost->initialized) {
4789  char error[1024] = {0};
4790  ret = init_output_stream(ost, error, sizeof(error));
4791  if (ret < 0) {
4792  av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
4793  ost->file_index, ost->index, error);
4794  exit_program(1);
4795  }
4796  }
4797  if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
4798  return ret;
4799  if (!ist)
4800  return 0;
4801  } else if (ost->filter) {
4802  int i;
4803  for (i = 0; i < ost->filter->graph->nb_inputs; i++) {
4804  InputFilter *ifilter = ost->filter->graph->inputs[i];
4805  if (!ifilter->ist->got_output && !input_files[ifilter->ist->file_index]->eof_reached) {
4806  ist = ifilter->ist;
4807  break;
4808  }
4809  }
4810  if (!ist) {
4811  ost->inputs_done = 1;
4812  return 0;
4813  }
4814  } else {
4815  av_assert0(ost->source_index >= 0);
4816  ist = input_streams[ost->source_index];
4817  }
4818 
4819  ret = process_input(ist->file_index);
4820  if (ret == AVERROR(EAGAIN)) {
4821  if (input_files[ist->file_index]->eagain)
4822  ost->unavailable = 1;
4823  return 0;
4824  }
4825 
4826  if (ret < 0)
4827  return ret == AVERROR_EOF ? 0 : ret;
4828 
4829  return reap_filters(0);
4830 }
4831 
4832 /*
4833  * The following code is the main loop of the file converter
4834  */
4835 static int transcode(void)
4836 {
4837  int ret, i;
4838  AVFormatContext *os;
4839  OutputStream *ost;
4840  InputStream *ist;
4841  int64_t timer_start;
4842  int64_t total_packets_written = 0;
4843 
4844  ret = transcode_init();
4845  if (ret < 0)
4846  goto fail;
4847 
4848  if (stdin_interaction) {
4849  av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
4850  }
4851 
4852  timer_start = av_gettime_relative();
4853 
4854 #if HAVE_THREADS
4855  if ((ret = init_input_threads()) < 0)
4856  goto fail;
4857 #endif
4858 
4860  int64_t cur_time= av_gettime_relative();
4861 
4862  /* if 'q' pressed, exits */
4863  if (stdin_interaction)
4864  if (check_keyboard_interaction(cur_time) < 0)
4865  break;
4866 
4867  /* check if there's any stream where output is still needed */
4868  if (!need_output()) {
4869  av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
4870  break;
4871  }
4872 
4873  ret = transcode_step();
4874  if (ret < 0 && ret != AVERROR_EOF) {
4875  av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
4876  break;
4877  }
4878 
4879  /* dump report by using the output first video and audio streams */
4880  print_report(0, timer_start, cur_time);
4881  }
4882 #if HAVE_THREADS
4883  free_input_threads();
4884 #endif
4885 
4886  /* at the end of stream, we must flush the decoder buffers */
4887  for (i = 0; i < nb_input_streams; i++) {
4888  ist = input_streams[i];
4889  if (!input_files[ist->file_index]->eof_reached) {
4890  process_input_packet(ist, NULL, 0);
4891  }
4892  }
4893  flush_encoders();
4894 
4895  term_exit();
4896 
4897  /* write the trailer if needed and close file */
4898  for (i = 0; i < nb_output_files; i++) {
4899  os = output_files[i]->ctx;
4900  if (!output_files[i]->header_written) {
4901  av_log(NULL, AV_LOG_ERROR,
4902  "Nothing was written into output file %d (%s), because "
4903  "at least one of its streams received no packets.\n",
4904  i, os->url);
4905  continue;
4906  }
4907  if ((ret = av_write_trailer(os)) < 0) {
4908  av_log(NULL, AV_LOG_ERROR, "Error writing trailer of %s: %s\n", os->url, av_err2str(ret));
4909  if (exit_on_error)
4910  exit_program(1);
4911  }
4912  }
4913 
4914  /* dump report by using the first video and audio streams */
4915  print_report(1, timer_start, av_gettime_relative());
4916 
4917  /* close each encoder */
4918  for (i = 0; i < nb_output_streams; i++) {
4919  ost = output_streams[i];
4920  if (ost->encoding_needed) {
4921  av_freep(&ost->enc_ctx->stats_in);
4922  }
4923  total_packets_written += ost->packets_written;
4924  }
4925 
4926  if (!total_packets_written && (abort_on_flags & ABORT_ON_FLAG_EMPTY_OUTPUT)) {
4927  av_log(NULL, AV_LOG_FATAL, "Empty output\n");
4928  exit_program(1);
4929  }
4930 
4931  /* close each decoder */
4932  for (i = 0; i < nb_input_streams; i++) {
4933  ist = input_streams[i];
4934  if (ist->decoding_needed) {
4935  avcodec_close(ist->dec_ctx);
4936  if (ist->hwaccel_uninit)
4937  ist->hwaccel_uninit(ist->dec_ctx);
4938  }
4939  }
4940 
4941  av_buffer_unref(&hw_device_ctx);
4943 
4944  /* finished ! */
4945  ret = 0;
4946 
4947  fail:
4948 #if HAVE_THREADS
4949  free_input_threads();
4950 #endif
4951 
4952  if (output_streams) {
4953  for (i = 0; i < nb_output_streams; i++) {
4954  ost = output_streams[i];
4955  if (ost) {
4956  if (ost->logfile) {
4957  if (fclose(ost->logfile))
4958  av_log(NULL, AV_LOG_ERROR,
4959  "Error closing logfile, loss of information possible: %s\n",
4960  av_err2str(AVERROR(errno)));
4961  ost->logfile = NULL;
4962  }
4963  av_freep(&ost->forced_kf_pts);
4964  av_freep(&ost->apad);
4965  av_freep(&ost->disposition);
4966  av_dict_free(&ost->encoder_opts);
4967  av_dict_free(&ost->sws_dict);
4968  av_dict_free(&ost->swr_opts);
4969  av_dict_free(&ost->resample_opts);
4970  }
4971  }
4972  }
4973  return ret;
4974 }
4975 
4977 {
4978  BenchmarkTimeStamps time_stamps = { av_gettime_relative() };
4979 #if HAVE_GETRUSAGE
4980  struct rusage rusage;
4981 
4982  getrusage(RUSAGE_SELF, &rusage);
4983  time_stamps.user_usec =
4984  (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
4985  time_stamps.sys_usec =
4986  (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
4987 #elif HAVE_GETPROCESSTIMES
4988  HANDLE proc;
4989  FILETIME c, e, k, u;
4990  proc = GetCurrentProcess();
4991  GetProcessTimes(proc, &c, &e, &k, &u);
4992  time_stamps.user_usec =
4993  ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
4994  time_stamps.sys_usec =
4995  ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
4996 #else
4997  time_stamps.user_usec = time_stamps.sys_usec = 0;
4998 #endif
4999  return time_stamps;
5000 }
5001 
5002 static int64_t getmaxrss(void)
5003 {
5004 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
5005  struct rusage rusage;
5006  getrusage(RUSAGE_SELF, &rusage);
5007  return (int64_t)rusage.ru_maxrss * 1024;
5008 #elif HAVE_GETPROCESSMEMORYINFO
5009  HANDLE proc;
5010  PROCESS_MEMORY_COUNTERS memcounters;
5011  proc = GetCurrentProcess();
5012  memcounters.cb = sizeof(memcounters);
5013  GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
5014  return memcounters.PeakPagefileUsage;
5015 #else
5016  return 0;
5017 #endif
5018 }
5019 
5020 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
5021 {
5022 }
5023 
5026  longjmp_value = 0;
5027  received_sigterm = 0;
5028  received_nb_signals = 0;
5029  ffmpeg_exited = 0;
5030 
5031  run_as_daemon = 0;
5032  nb_frames_dup = 0;
5033  dup_warning = 1000;
5034  nb_frames_drop = 0;
5035 
5036  want_sdp = 1;
5037 
5038  progress_avio = NULL;
5039 
5040  input_streams = NULL;
5041  nb_input_streams = 0;
5042  input_files = NULL;
5043  nb_input_files = 0;
5044 
5045  output_streams = NULL;
5046  nb_output_streams = 0;
5047  output_files = NULL;
5048  nb_output_files = 0;
5049 
5050  filtergraphs = NULL;
5051  nb_filtergraphs = 0;
5052 }
5053 
5054 void set_report_callback(void (*callback)(int, float, float, int64_t, int, double, double))
5055 {
5056  report_callback = callback;
5057 }
5058 
5059 void cancel_operation(long id)
5060 {
5061  if (id == 0) {
5062  sigterm_handler(SIGINT);
5063  } else {
5064  removeExecution(id);
5065  }
5066 }
5067 
5068 __thread OptionDef *ffmpeg_options = NULL;
5069 
5070 int ffmpeg_execute(int argc, char **argv)
5071 {
5072  char _program_name[] = "ffmpeg";
5073  program_name = (char*)&_program_name;
5074  program_birth_year = 2000;
5075 
5076  #define OFFSET(x) offsetof(OptionsContext, x)
5077  OptionDef options[] = {
5078 
5079  /* main options */
5080  { "L", OPT_EXIT, { .func_arg = show_license }, "show license" },
5081  { "h", OPT_EXIT, { .func_arg = show_help }, "show help", "topic" },
5082  { "?", OPT_EXIT, { .func_arg = show_help }, "show help", "topic" },
5083  { "help", OPT_EXIT, { .func_arg = show_help }, "show help", "topic" },
5084  { "-help", OPT_EXIT, { .func_arg = show_help }, "show help", "topic" },
5085  { "version", OPT_EXIT, { .func_arg = show_version }, "show version" },
5086  { "buildconf", OPT_EXIT, { .func_arg = show_buildconf }, "show build configuration" },
5087  { "formats", OPT_EXIT, { .func_arg = show_formats }, "show available formats" },
5088  { "muxers", OPT_EXIT, { .func_arg = show_muxers }, "show available muxers" },
5089  { "demuxers", OPT_EXIT, { .func_arg = show_demuxers }, "show available demuxers" },
5090  { "devices", OPT_EXIT, { .func_arg = show_devices }, "show available devices" },
5091  { "codecs", OPT_EXIT, { .func_arg = show_codecs }, "show available codecs" },
5092  { "decoders", OPT_EXIT, { .func_arg = show_decoders }, "show available decoders" },
5093  { "encoders", OPT_EXIT, { .func_arg = show_encoders }, "show available encoders" },
5094  { "bsfs", OPT_EXIT, { .func_arg = show_bsfs }, "show available bit stream filters" },
5095  { "protocols", OPT_EXIT, { .func_arg = show_protocols }, "show available protocols" },
5096  { "filters", OPT_EXIT, { .func_arg = show_filters }, "show available filters" },
5097  { "pix_fmts", OPT_EXIT, { .func_arg = show_pix_fmts }, "show available pixel formats" },
5098  { "layouts", OPT_EXIT, { .func_arg = show_layouts }, "show standard channel layouts" },
5099  { "sample_fmts", OPT_EXIT, { .func_arg = show_sample_fmts }, "show available audio sample formats" },
5100  { "colors", OPT_EXIT, { .func_arg = show_colors }, "show available color names" },
5101  { "loglevel", HAS_ARG, { .func_arg = opt_loglevel }, "set logging level", "loglevel" },
5102  { "v", HAS_ARG, { .func_arg = opt_loglevel }, "set logging level", "loglevel" },
5103  { "report", 0, { .func_arg = opt_report }, "generate a report" },
5104  { "max_alloc", HAS_ARG, { .func_arg = opt_max_alloc }, "set maximum size of a single allocated block", "bytes" },
5105  { "cpuflags", HAS_ARG | OPT_EXPERT, { .func_arg = opt_cpuflags }, "force specific cpu flags", "flags" },
5106  { "hide_banner", OPT_BOOL | OPT_EXPERT, {&hide_banner}, "do not show program banner", "hide_banner" },
5107 
5108  #if CONFIG_AVDEVICE
5109  { "sources" , OPT_EXIT | HAS_ARG, { .func_arg = show_sources },
5110  "list sources of the input device", "device" },
5111  { "sinks" , OPT_EXIT | HAS_ARG, { .func_arg = show_sinks },
5112  "list sinks of the output device", "device" },
5113  #endif
5114 
5115  { "f", HAS_ARG | OPT_STRING | OPT_OFFSET |
5116  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(format) },
5117  "force format", "fmt" },
5118  { "y", OPT_BOOL, { &file_overwrite },
5119  "overwrite output files" },
5120  { "n", OPT_BOOL, { &no_file_overwrite },
5121  "never overwrite output files" },
5122  { "ignore_unknown", OPT_BOOL, { &ignore_unknown_streams },
5123  "Ignore unknown stream types" },
5124  { "copy_unknown", OPT_BOOL | OPT_EXPERT, { &copy_unknown_streams },
5125  "Copy unknown stream types" },
5126  { "c", HAS_ARG | OPT_STRING | OPT_SPEC |
5127  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(codec_names) },
5128  "codec name", "codec" },
5129  { "codec", HAS_ARG | OPT_STRING | OPT_SPEC |
5130  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(codec_names) },
5131  "codec name", "codec" },
5132  { "pre", HAS_ARG | OPT_STRING | OPT_SPEC |
5133  OPT_OUTPUT, { .off = OFFSET(presets) },
5134  "preset name", "preset" },
5135  { "map", HAS_ARG | OPT_EXPERT | OPT_PERFILE |
5136  OPT_OUTPUT, { .func_arg = opt_map },
5137  "set input stream mapping",
5138  "[-]input_file_id[:stream_specifier][,sync_file_id[:stream_specifier]]" },
5139  { "map_channel", HAS_ARG | OPT_EXPERT | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_map_channel },
5140  "map an audio channel from one stream to another", "file.stream.channel[:syncfile.syncstream]" },
5141  { "map_metadata", HAS_ARG | OPT_STRING | OPT_SPEC |
5142  OPT_OUTPUT, { .off = OFFSET(metadata_map) },
5143  "set metadata information of outfile from infile",
5144  "outfile[,metadata]:infile[,metadata]" },
5145  { "map_chapters", HAS_ARG | OPT_INT | OPT_EXPERT | OPT_OFFSET |
5146  OPT_OUTPUT, { .off = OFFSET(chapters_input_file) },
5147  "set chapters mapping", "input_file_index" },
5148  { "t", HAS_ARG | OPT_TIME | OPT_OFFSET |
5149  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(recording_time) },
5150  "record or transcode \"duration\" seconds of audio/video",
5151  "duration" },
5152  { "to", HAS_ARG | OPT_TIME | OPT_OFFSET | OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(stop_time) },
5153  "record or transcode stop time", "time_stop" },
5154  { "fs", HAS_ARG | OPT_INT64 | OPT_OFFSET | OPT_OUTPUT, { .off = OFFSET(limit_filesize) },
5155  "set the limit file size in bytes", "limit_size" },
5156  { "ss", HAS_ARG | OPT_TIME | OPT_OFFSET |
5157  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(start_time) },
5158  "set the start time offset", "time_off" },
5159  { "sseof", HAS_ARG | OPT_TIME | OPT_OFFSET |
5160  OPT_INPUT, { .off = OFFSET(start_time_eof) },
5161  "set the start time offset relative to EOF", "time_off" },
5162  { "seek_timestamp", HAS_ARG | OPT_INT | OPT_OFFSET |
5163  OPT_INPUT, { .off = OFFSET(seek_timestamp) },
5164  "enable/disable seeking by timestamp with -ss" },
5165  { "accurate_seek", OPT_BOOL | OPT_OFFSET | OPT_EXPERT |
5166  OPT_INPUT, { .off = OFFSET(accurate_seek) },
5167  "enable/disable accurate seeking with -ss" },
5168  { "itsoffset", HAS_ARG | OPT_TIME | OPT_OFFSET |
5169  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(input_ts_offset) },
5170  "set the input ts offset", "time_off" },
5171  { "itsscale", HAS_ARG | OPT_DOUBLE | OPT_SPEC |
5172  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(ts_scale) },
5173  "set the input ts scale", "scale" },
5174  { "timestamp", HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_recording_timestamp },
5175  "set the recording timestamp ('now' to set the current time)", "time" },
5176  { "metadata", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(metadata) },
5177  "add metadata", "string=string" },
5178  { "program", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(program) },
5179  "add program with specified streams", "title=string:st=number..." },
5180  { "dframes", HAS_ARG | OPT_PERFILE | OPT_EXPERT |
5181  OPT_OUTPUT, { .func_arg = opt_data_frames },
5182  "set the number of data frames to output", "number" },
5183  { "benchmark", OPT_BOOL | OPT_EXPERT, { &do_benchmark },
5184  "add timings for benchmarking" },
5185  { "benchmark_all", OPT_BOOL | OPT_EXPERT, { &do_benchmark_all },
5186  "add timings for each task" },
5187  { "progress", HAS_ARG | OPT_EXPERT, { .func_arg = opt_progress },
5188  "write program-readable progress information", "url" },
5189  { "stdin", OPT_BOOL | OPT_EXPERT, { &stdin_interaction },
5190  "enable or disable interaction on standard input" },
5191  { "timelimit", HAS_ARG | OPT_EXPERT, { .func_arg = opt_timelimit },
5192  "set max runtime in seconds in CPU user time", "limit" },
5193  { "dump", OPT_BOOL | OPT_EXPERT, { &do_pkt_dump },
5194  "dump each input packet" },
5195  { "hex", OPT_BOOL | OPT_EXPERT, { &do_hex_dump },
5196  "when dumping packets, also dump the payload" },
5197  { "re", OPT_BOOL | OPT_EXPERT | OPT_OFFSET |
5198  OPT_INPUT, { .off = OFFSET(rate_emu) },
5199  "read input at native frame rate", "" },
5200  { "target", HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_target },
5201  "specify target file type (\"vcd\", \"svcd\", \"dvd\", \"dv\" or \"dv50\" "
5202  "with optional prefixes \"pal-\", \"ntsc-\" or \"film-\")", "type" },
5203  { "vsync", HAS_ARG | OPT_EXPERT, { .func_arg = opt_vsync },
5204  "video sync method", "" },
5205  { "frame_drop_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, { &frame_drop_threshold },
5206  "frame drop threshold", "" },
5207  { "async", HAS_ARG | OPT_INT | OPT_EXPERT, { &audio_sync_method },
5208  "audio sync method", "" },
5209  { "adrift_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, { &audio_drift_threshold },
5210  "audio drift threshold", "threshold" },
5211  { "copyts", OPT_BOOL | OPT_EXPERT, { &copy_ts },
5212  "copy timestamps" },
5213  { "start_at_zero", OPT_BOOL | OPT_EXPERT, { &start_at_zero },
5214  "shift input timestamps to start at 0 when using copyts" },
5215  { "copytb", HAS_ARG | OPT_INT | OPT_EXPERT, { &copy_tb },
5216  "copy input stream time base when stream copying", "mode" },
5217  { "shortest", OPT_BOOL | OPT_EXPERT | OPT_OFFSET |
5218  OPT_OUTPUT, { .off = OFFSET(shortest) },
5219  "finish encoding within shortest input" },
5220  { "bitexact", OPT_BOOL | OPT_EXPERT | OPT_OFFSET |
5221  OPT_OUTPUT | OPT_INPUT, { .off = OFFSET(bitexact) },
5222  "bitexact mode" },
5223  { "apad", OPT_STRING | HAS_ARG | OPT_SPEC |
5224  OPT_OUTPUT, { .off = OFFSET(apad) },
5225  "audio pad", "" },
5226  { "dts_delta_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, { &dts_delta_threshold },
5227  "timestamp discontinuity delta threshold", "threshold" },
5228  { "dts_error_threshold", HAS_ARG | OPT_FLOAT | OPT_EXPERT, { &dts_error_threshold },
5229  "timestamp error delta threshold", "threshold" },
5230  { "xerror", OPT_BOOL | OPT_EXPERT, { &exit_on_error },
5231  "exit on error", "error" },
5232  { "abort_on", HAS_ARG | OPT_EXPERT, { .func_arg = opt_abort_on },
5233  "abort on the specified condition flags", "flags" },
5234  { "copyinkf", OPT_BOOL | OPT_EXPERT | OPT_SPEC |
5235  OPT_OUTPUT, { .off = OFFSET(copy_initial_nonkeyframes) },
5236  "copy initial non-keyframes" },
5237  { "copypriorss", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(copy_prior_start) },
5238  "copy or discard frames before start time" },
5239  { "frames", OPT_INT64 | HAS_ARG | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(max_frames) },
5240  "set the number of frames to output", "number" },
5241  { "tag", OPT_STRING | HAS_ARG | OPT_SPEC |
5242  OPT_EXPERT | OPT_OUTPUT | OPT_INPUT, { .off = OFFSET(codec_tags) },
5243  "force codec tag/fourcc", "fourcc/tag" },
5244  { "q", HAS_ARG | OPT_EXPERT | OPT_DOUBLE |
5245  OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(qscale) },
5246  "use fixed quality scale (VBR)", "q" },
5247  { "qscale", HAS_ARG | OPT_EXPERT | OPT_PERFILE |
5248  OPT_OUTPUT, { .func_arg = opt_qscale },
5249  "use fixed quality scale (VBR)", "q" },
5250  { "profile", HAS_ARG | OPT_EXPERT | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_profile },
5251  "set profile", "profile" },
5252  { "filter", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(filters) },
5253  "set stream filtergraph", "filter_graph" },
5254  { "filter_threads", HAS_ARG | OPT_INT, { &filter_nbthreads },
5255  "number of non-complex filter threads" },
5256  { "filter_script", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(filter_scripts) },
5257  "read stream filtergraph description from a file", "filename" },
5258  { "reinit_filter", HAS_ARG | OPT_INT | OPT_SPEC | OPT_INPUT, { .off = OFFSET(reinit_filters) },
5259  "reinit filtergraph on input parameter changes", "" },
5260  { "filter_complex", HAS_ARG | OPT_EXPERT, { .func_arg = opt_filter_complex },
5261  "create a complex filtergraph", "graph_description" },
5262  { "filter_complex_threads", HAS_ARG | OPT_INT, { &filter_complex_nbthreads },
5263  "number of threads for -filter_complex" },
5264  { "lavfi", HAS_ARG | OPT_EXPERT, { .func_arg = opt_filter_complex },
5265  "create a complex filtergraph", "graph_description" },
5266  { "filter_complex_script", HAS_ARG | OPT_EXPERT, { .func_arg = opt_filter_complex_script },
5267  "read complex filtergraph description from a file", "filename" },
5268  { "stats", OPT_BOOL, { &print_stats },
5269  "print progress report during encoding", },
5270  { "attach", HAS_ARG | OPT_PERFILE | OPT_EXPERT |
5271  OPT_OUTPUT, { .func_arg = opt_attach },
5272  "add an attachment to the output file", "filename" },
5273  { "dump_attachment", HAS_ARG | OPT_STRING | OPT_SPEC |
5274  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(dump_attachment) },
5275  "extract an attachment into a file", "filename" },
5276  { "stream_loop", OPT_INT | HAS_ARG | OPT_EXPERT | OPT_INPUT |
5277  OPT_OFFSET, { .off = OFFSET(loop) }, "set number of times input stream shall be looped", "loop count" },
5278  { "debug_ts", OPT_BOOL | OPT_EXPERT, { &debug_ts },
5279  "print timestamp debugging info" },
5280  { "max_error_rate", HAS_ARG | OPT_FLOAT, { &max_error_rate },
5281  "ratio of errors (0.0: no errors, 1.0: 100% errors) above which ffmpeg returns an error instead of success.", "maximum error rate" },
5282  { "discard", OPT_STRING | HAS_ARG | OPT_SPEC |
5283  OPT_INPUT, { .off = OFFSET(discard) },
5284  "discard", "" },
5285  { "disposition", OPT_STRING | HAS_ARG | OPT_SPEC |
5286  OPT_OUTPUT, { .off = OFFSET(disposition) },
5287  "disposition", "" },
5288  { "thread_queue_size", HAS_ARG | OPT_INT | OPT_OFFSET | OPT_EXPERT | OPT_INPUT,
5289  { .off = OFFSET(thread_queue_size) },
5290  "set the maximum number of queued packets from the demuxer" },
5291  { "find_stream_info", OPT_BOOL | OPT_PERFILE | OPT_INPUT | OPT_EXPERT, { &find_stream_info },
5292  "read and decode the streams to fill missing information with heuristics" },
5293 
5294  /* video options */
5295  { "vframes", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_video_frames },
5296  "set the number of video frames to output", "number" },
5297  { "r", OPT_VIDEO | HAS_ARG | OPT_STRING | OPT_SPEC |
5298  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(frame_rates) },
5299  "set frame rate (Hz value, fraction or abbreviation)", "rate" },
5301  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(frame_sizes) },
5302  "set frame size (WxH or abbreviation)", "size" },
5303  { "aspect", OPT_VIDEO | HAS_ARG | OPT_STRING | OPT_SPEC |
5304  OPT_OUTPUT, { .off = OFFSET(frame_aspect_ratios) },
5305  "set aspect ratio (4:3, 16:9 or 1.3333, 1.7777)", "aspect" },
5306  { "pix_fmt", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING | OPT_SPEC |
5307  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(frame_pix_fmts) },
5308  "set pixel format", "format" },
5309  { "bits_per_raw_sample", OPT_VIDEO | OPT_INT | HAS_ARG, { &frame_bits_per_raw_sample },
5310  "set the number of bits per raw sample", "number" },
5311  { "intra", OPT_VIDEO | OPT_BOOL | OPT_EXPERT, { &intra_only },
5312  "deprecated use -g 1" },
5313  { "vn", OPT_VIDEO | OPT_BOOL | OPT_OFFSET | OPT_INPUT | OPT_OUTPUT,{ .off = OFFSET(video_disable) },
5314  "disable video" },
5315  { "rc_override", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING | OPT_SPEC |
5316  OPT_OUTPUT, { .off = OFFSET(rc_overrides) },
5317  "rate control override for specific intervals", "override" },
5318  { "vcodec", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_INPUT |
5319  OPT_OUTPUT, { .func_arg = opt_video_codec },
5320  "force video codec ('copy' to copy stream)", "codec" },
5321  { "sameq", OPT_VIDEO | OPT_EXPERT , { .func_arg = opt_sameq },
5322  "Removed" },
5323  { "same_quant", OPT_VIDEO | OPT_EXPERT , { .func_arg = opt_sameq },
5324  "Removed" },
5325  { "timecode", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_timecode },
5326  "set initial TimeCode value.", "hh:mm:ss[:;.]ff" },
5327  { "pass", OPT_VIDEO | HAS_ARG | OPT_SPEC | OPT_INT | OPT_OUTPUT, { .off = OFFSET(pass) },
5328  "select the pass number (1 to 3)", "n" },
5329  { "passlogfile", OPT_VIDEO | HAS_ARG | OPT_STRING | OPT_EXPERT | OPT_SPEC |
5330  OPT_OUTPUT, { .off = OFFSET(passlogfiles) },
5331  "select two pass log file name prefix", "prefix" },
5332  { "deinterlace", OPT_VIDEO | OPT_BOOL | OPT_EXPERT, { &do_deinterlace },
5333  "this option is deprecated, use the yadif filter instead" },
5334  { "psnr", OPT_VIDEO | OPT_BOOL | OPT_EXPERT, { &do_psnr },
5335  "calculate PSNR of compressed frames" },
5336  { "vstats", OPT_VIDEO | OPT_EXPERT , { .func_arg = opt_vstats },
5337  "dump video coding statistics to file" },
5338  { "vstats_file", OPT_VIDEO | HAS_ARG | OPT_EXPERT , { .func_arg = opt_vstats_file },
5339  "dump video coding statistics to file", "file" },
5340  { "vstats_version", OPT_VIDEO | OPT_INT | HAS_ARG | OPT_EXPERT , { &vstats_version },
5341  "Version of the vstats format to use."},
5342  { "vf", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_video_filters },
5343  "set video filters", "filter_graph" },
5344  { "intra_matrix", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING | OPT_SPEC |
5345  OPT_OUTPUT, { .off = OFFSET(intra_matrices) },
5346  "specify intra matrix coeffs", "matrix" },
5347  { "inter_matrix", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING | OPT_SPEC |
5348  OPT_OUTPUT, { .off = OFFSET(inter_matrices) },
5349  "specify inter matrix coeffs", "matrix" },
5350  { "chroma_intra_matrix", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_STRING | OPT_SPEC |
5351  OPT_OUTPUT, { .off = OFFSET(chroma_intra_matrices) },
5352  "specify intra matrix coeffs", "matrix" },
5353  { "top", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_INT| OPT_SPEC |
5354  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(top_field_first) },
5355  "top=1/bottom=0/auto=-1 field first", "" },
5356  { "vtag", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_PERFILE |
5357  OPT_INPUT | OPT_OUTPUT, { .func_arg = opt_old2new },
5358  "force video tag/fourcc", "fourcc/tag" },
5359  { "qphist", OPT_VIDEO | OPT_BOOL | OPT_EXPERT , { &qp_hist },
5360  "show QP histogram" },
5361  { "force_fps", OPT_VIDEO | OPT_BOOL | OPT_EXPERT | OPT_SPEC |
5362  OPT_OUTPUT, { .off = OFFSET(force_fps) },
5363  "force the selected framerate, disable the best supported framerate selection" },
5364  { "streamid", OPT_VIDEO | HAS_ARG | OPT_EXPERT | OPT_PERFILE |
5365  OPT_OUTPUT, { .func_arg = opt_streamid },
5366  "set the value of an outfile streamid", "streamIndex:value" },
5367  { "force_key_frames", OPT_VIDEO | OPT_STRING | HAS_ARG | OPT_EXPERT |
5368  OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(forced_key_frames) },
5369  "force key frames at specified timestamps", "timestamps" },
5370  { "ab", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_bitrate },
5371  "audio bitrate (please use -b:a)", "bitrate" },
5372  { "b", OPT_VIDEO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_bitrate },
5373  "video bitrate (please use -b:v)", "bitrate" },
5374  { "hwaccel", OPT_VIDEO | OPT_STRING | HAS_ARG | OPT_EXPERT |
5375  OPT_SPEC | OPT_INPUT, { .off = OFFSET(hwaccels) },
5376  "use HW accelerated decoding", "hwaccel name" },
5377  { "hwaccel_device", OPT_VIDEO | OPT_STRING | HAS_ARG | OPT_EXPERT |
5378  OPT_SPEC | OPT_INPUT, { .off = OFFSET(hwaccel_devices) },
5379  "select a device for HW acceleration", "devicename" },
5380  { "hwaccel_output_format", OPT_VIDEO | OPT_STRING | HAS_ARG | OPT_EXPERT |
5381  OPT_SPEC | OPT_INPUT, { .off = OFFSET(hwaccel_output_formats) },
5382  "select output format used with HW accelerated decoding", "format" },
5383  #if CONFIG_VIDEOTOOLBOX
5384  { "videotoolbox_pixfmt", HAS_ARG | OPT_STRING | OPT_EXPERT, { &videotoolbox_pixfmt}, "" },
5385  #endif
5386  { "hwaccels", OPT_EXIT, { .func_arg = show_hwaccels },
5387  "show available HW acceleration methods" },
5388  { "autorotate", HAS_ARG | OPT_BOOL | OPT_SPEC |
5389  OPT_EXPERT | OPT_INPUT, { .off = OFFSET(autorotate) },
5390  "automatically insert correct rotate filters" },
5391 
5392  /* audio options */
5393  { "aframes", OPT_AUDIO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_audio_frames },
5394  "set the number of audio frames to output", "number" },
5395  { "aq", OPT_AUDIO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_audio_qscale },
5396  "set audio quality (codec-specific)", "quality", },
5397  { "ar", OPT_AUDIO | HAS_ARG | OPT_INT | OPT_SPEC |
5398  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(audio_sample_rate) },
5399  "set audio sampling rate (in Hz)", "rate" },
5400  { "ac", OPT_AUDIO | HAS_ARG | OPT_INT | OPT_SPEC |
5401  OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(audio_channels) },
5402  "set number of audio channels", "channels" },
5403  { "an", OPT_AUDIO | OPT_BOOL | OPT_OFFSET | OPT_INPUT | OPT_OUTPUT,{ .off = OFFSET(audio_disable) },
5404  "disable audio" },
5405  { "acodec", OPT_AUDIO | HAS_ARG | OPT_PERFILE |
5406  OPT_INPUT | OPT_OUTPUT, { .func_arg = opt_audio_codec },
5407  "force audio codec ('copy' to copy stream)", "codec" },
5408  { "atag", OPT_AUDIO | HAS_ARG | OPT_EXPERT | OPT_PERFILE |
5409  OPT_OUTPUT, { .func_arg = opt_old2new },
5410  "force audio tag/fourcc", "fourcc/tag" },
5411  { "vol", OPT_AUDIO | HAS_ARG | OPT_INT, { &audio_volume },
5412  "change audio volume (256=normal)" , "volume" },
5413  { "sample_fmt", OPT_AUDIO | HAS_ARG | OPT_EXPERT | OPT_SPEC |
5414  OPT_STRING | OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(sample_fmts) },
5415  "set sample format", "format" },
5416  { "channel_layout", OPT_AUDIO | HAS_ARG | OPT_EXPERT | OPT_PERFILE |
5417  OPT_INPUT | OPT_OUTPUT, { .func_arg = opt_channel_layout },
5418  "set channel layout", "layout" },
5419  { "af", OPT_AUDIO | HAS_ARG | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_audio_filters },
5420  "set audio filters", "filter_graph" },
5421  { "guess_layout_max", OPT_AUDIO | HAS_ARG | OPT_INT | OPT_SPEC | OPT_EXPERT | OPT_INPUT, { .off = OFFSET(guess_layout_max) },
5422  "set the maximum number of channels to try to guess the channel layout" },
5423 
5424  /* subtitle options */
5425  { "sn", OPT_SUBTITLE | OPT_BOOL | OPT_OFFSET | OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(subtitle_disable) },
5426  "disable subtitle" },
5427  { "scodec", OPT_SUBTITLE | HAS_ARG | OPT_PERFILE | OPT_INPUT | OPT_OUTPUT, { .func_arg = opt_subtitle_codec },
5428  "force subtitle codec ('copy' to copy stream)", "codec" },
5429  { "stag", OPT_SUBTITLE | HAS_ARG | OPT_EXPERT | OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_old2new }
5430  , "force subtitle tag/fourcc", "fourcc/tag" },
5431  { "fix_sub_duration", OPT_BOOL | OPT_EXPERT | OPT_SUBTITLE | OPT_SPEC | OPT_INPUT, { .off = OFFSET(fix_sub_duration) },
5432  "fix subtitles duration" },
5433  { "canvas_size", OPT_SUBTITLE | HAS_ARG | OPT_STRING | OPT_SPEC | OPT_INPUT, { .off = OFFSET(canvas_sizes) },
5434  "set canvas size (WxH or abbreviation)", "size" },
5435 
5436  /* grab options */
5437  { "vc", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_video_channel },
5438  "deprecated, use -channel", "channel" },
5439  { "tvstd", HAS_ARG | OPT_EXPERT | OPT_VIDEO, { .func_arg = opt_video_standard },
5440  "deprecated, use -standard", "standard" },
5441  { "isync", OPT_BOOL | OPT_EXPERT, { &input_sync }, "this option is deprecated and does nothing", "" },
5442 
5443  /* muxer options */
5444  { "muxdelay", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET | OPT_OUTPUT, { .off = OFFSET(mux_max_delay) },
5445  "set the maximum demux-decode delay", "seconds" },
5446  { "muxpreload", OPT_FLOAT | HAS_ARG | OPT_EXPERT | OPT_OFFSET | OPT_OUTPUT, { .off = OFFSET(mux_preload) },
5447  "set the initial demux-decode delay", "seconds" },
5448  { "sdp_file", HAS_ARG | OPT_EXPERT | OPT_OUTPUT, { .func_arg = opt_sdp_file },
5449  "specify a file in which to print sdp information", "file" },
5450 
5451  { "time_base", HAS_ARG | OPT_STRING | OPT_EXPERT | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(time_bases) },
5452  "set the desired time base hint for output stream (1:24, 1:48000 or 0.04166, 2.0833e-5)", "ratio" },
5453  { "enc_time_base", HAS_ARG | OPT_STRING | OPT_EXPERT | OPT_SPEC | OPT_OUTPUT, { .off = OFFSET(enc_time_bases) },
5454  "set the desired time base for the encoder (1:24, 1:48000 or 0.04166, 2.0833e-5). "
5455  "two special values are defined - "
5456  "0 = use frame rate (video) or sample rate (audio),"
5457  "-1 = match source time base", "ratio" },
5458 
5459  { "bsf", HAS_ARG | OPT_STRING | OPT_SPEC | OPT_EXPERT | OPT_OUTPUT, { .off = OFFSET(bitstream_filters) },
5460  "A comma-separated list of bitstream filters", "bitstream_filters" },
5461  { "absf", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_old2new },
5462  "deprecated", "audio bitstream_filters" },
5463  { "vbsf", OPT_VIDEO | HAS_ARG | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_old2new },
5464  "deprecated", "video bitstream_filters" },
5465 
5466  { "apre", HAS_ARG | OPT_AUDIO | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_preset },
5467  "set the audio options to the indicated preset", "preset" },
5468  { "vpre", OPT_VIDEO | HAS_ARG | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_preset },
5469  "set the video options to the indicated preset", "preset" },
5470  { "spre", HAS_ARG | OPT_SUBTITLE | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_preset },
5471  "set the subtitle options to the indicated preset", "preset" },
5472  { "fpre", HAS_ARG | OPT_EXPERT| OPT_PERFILE | OPT_OUTPUT, { .func_arg = opt_preset },
5473  "set options from indicated preset file", "filename" },
5474 
5475  { "max_muxing_queue_size", HAS_ARG | OPT_INT | OPT_SPEC | OPT_EXPERT | OPT_OUTPUT, { .off = OFFSET(max_muxing_queue_size) },
5476  "maximum number of packets that can be buffered while waiting for all streams to initialize", "packets" },
5477 
5478  /* data codec support */
5479  { "dcodec", HAS_ARG | OPT_DATA | OPT_PERFILE | OPT_EXPERT | OPT_INPUT | OPT_OUTPUT, { .func_arg = opt_data_codec },
5480  "force data codec ('copy' to copy stream)", "codec" },
5481  { "dn", OPT_BOOL | OPT_VIDEO | OPT_OFFSET | OPT_INPUT | OPT_OUTPUT, { .off = OFFSET(data_disable) },
5482  "disable data" },
5483 
5484  #if CONFIG_VAAPI
5485  { "vaapi_device", HAS_ARG | OPT_EXPERT, { .func_arg = opt_vaapi_device },
5486  "set VAAPI hardware device (DRM path or X11 display name)", "device" },
5487  #endif
5488 
5489  #if CONFIG_QSV
5490  { "qsv_device", HAS_ARG | OPT_STRING | OPT_EXPERT, { &qsv_device },
5491  "set QSV hardware device (DirectX adapter index, DRM path or X11 display name)", "device"},
5492  #endif
5493 
5494  { "init_hw_device", HAS_ARG | OPT_EXPERT, { .func_arg = opt_init_hw_device },
5495  "initialise hardware device", "args" },
5496  { "filter_hw_device", HAS_ARG | OPT_EXPERT, { .func_arg = opt_filter_hw_device },
5497  "set hardware device used when filtering", "device" },
5498 
5499  { NULL, },
5500  };
5501 
5502  ffmpeg_options = options;
5503 
5504  int i, ret;
5506 
5507  int savedCode = setjmp(ex_buf__);
5508  if (savedCode == 0) {
5509 
5511 
5512  init_dynload();
5513 
5515 
5516  setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
5517 
5518  av_log_set_flags(AV_LOG_SKIP_REPEATED);
5519  parse_loglevel(argc, argv, options);
5520 
5521  if(argc>1 && !strcmp(argv[1], "-d")){
5522  run_as_daemon=1;
5523  av_log_set_callback(log_callback_null);
5524  argc--;
5525  argv++;
5526  }
5527 
5528  #if CONFIG_AVDEVICE
5529  avdevice_register_all();
5530  #endif
5531  avformat_network_init();
5532 
5533  show_banner(argc, argv, options);
5534 
5535  /* parse options and open all input/output files */
5536  ret = ffmpeg_parse_options(argc, argv);
5537  if (ret < 0)
5538  exit_program(1);
5539 
5540  if (nb_output_files <= 0 && nb_input_files == 0) {
5541  show_usage();
5542  av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
5543  exit_program(1);
5544  }
5545 
5546  /* file converter / grab */
5547  if (nb_output_files <= 0) {
5548  av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
5549  exit_program(1);
5550  }
5551 
5552  for (i = 0; i < nb_output_files; i++) {
5553  if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
5554  want_sdp = 0;
5555  }
5556 
5558  if (transcode() < 0)
5559  exit_program(1);
5560  if (do_benchmark) {
5561  int64_t utime, stime, rtime;
5563  utime = current_time.user_usec - ti.user_usec;
5564  stime = current_time.sys_usec - ti.sys_usec;
5565  rtime = current_time.real_usec - ti.real_usec;
5566  av_log(NULL, AV_LOG_INFO,
5567  "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
5568  utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
5569  }
5570  av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
5573  exit_program(69);
5574 
5576 
5577  } else {
5579  }
5580 
5581  return main_ffmpeg_return_code;
5582 }
ifilter_parameters_from_codecpar
static void ifilter_parameters_from_codecpar(InputFilter *ifilter, AVCodecParameters *par)
Definition: fftools_ffmpeg.c:2030
ffmpeg_exited
__thread volatile int ffmpeg_exited
Definition: fftools_ffmpeg.c:423
OPT_DATA
#define OPT_DATA
Definition: fftools_cmdutils.h:199
OutputStream::last_mux_dts
int64_t last_mux_dts
Definition: fftools_ffmpeg.h:480
InputStream::filter_frame
AVFrame * filter_frame
Definition: fftools_ffmpeg.h:330
InputFile::eagain
int eagain
Definition: fftools_ffmpeg.h:419
opt_sdp_file
int opt_sdp_file(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:488
speed
double speed
Definition: Statistics.m:30
OutputStream::avfilter
char * avfilter
Definition: fftools_ffmpeg.h:526
OutputStream::stream_copy
int stream_copy
Definition: fftools_ffmpeg.h:537
transcode_init_done
__thread atomic_int transcode_init_done
Definition: fftools_ffmpeg.c:422
ffmpeg_parse_options
int ffmpeg_parse_options(int argc, char **argv)
OutputStream::forced_kf_index
int forced_kf_index
Definition: fftools_ffmpeg.h:513
ENCODER_FINISHED
@ ENCODER_FINISHED
Definition: fftools_ffmpeg.h:461
InputFilter::name
uint8_t * name
Definition: fftools_ffmpeg.h:262
init_encoder_time_base
static void init_encoder_time_base(OutputStream *ost, AVRational default_time_base)
Definition: fftools_ffmpeg.c:3452
print_sdp
static void print_sdp(void)
Definition: fftools_ffmpeg.c:2933
show_decoders
int show_decoders(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1687
BenchmarkTimeStamps::real_usec
int64_t real_usec
Definition: fftools_ffmpeg.c:152
OutputStream::sync_opts
int64_t sync_opts
Definition: fftools_ffmpeg.h:475
AV_LOG_INFO
#define AV_LOG_INFO
Definition: MobileFFmpegConfig.h:66
opt_audio_frames
int opt_audio_frames(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:2945
OutputStream::filtered_frame
AVFrame * filtered_frame
Definition: fftools_ffmpeg.h:492
InputStream::sub2video::h
int h
Definition: fftools_ffmpeg.h:374
OutputStream::finished
OSTFinished finished
Definition: fftools_ffmpeg.h:535
get_format
static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
Definition: fftools_ffmpeg.c:2978
InputFile::nb_streams_warn
int nb_streams_warn
Definition: fftools_ffmpeg.h:434
get_benchmark_time_stamps
static BenchmarkTimeStamps get_benchmark_time_stamps(void)
Definition: fftools_ffmpeg.c:4976
opt_filter_complex
int opt_filter_complex(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:3163
OutputStream::rotate_override_value
double rotate_override_value
Definition: fftools_ffmpeg.h:505
OPT_EXIT
#define OPT_EXIT
Definition: fftools_cmdutils.h:198
OutputStream::frame_number
int frame_number
Definition: fftools_ffmpeg.h:471
stdin_interaction
__thread int stdin_interaction
Definition: fftools_ffmpeg_opt.c:123
OutputStream::ref_par
AVCodecParameters * ref_par
Definition: fftools_ffmpeg.h:489
parse_forced_key_frames
static void parse_forced_key_frames(char *kf, OutputStream *ost, AVCodecContext *avctx)
Definition: fftools_ffmpeg.c:3389
sub2video_push_ref
static void sub2video_push_ref(InputStream *ist, int64_t pts)
Definition: fftools_ffmpeg.c:308
program_name
__thread char * program_name
Definition: fftools_cmdutils.c:98
abort_on_flags
__thread int abort_on_flags
Definition: fftools_ffmpeg_opt.c:120
opt_audio_codec
int opt_audio_codec(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:261
opt_vsync
int opt_vsync(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:3095
InputStream::ts_scale
double ts_scale
Definition: fftools_ffmpeg.h:353
InputStream::hw_frames_ctx
AVBufferRef * hw_frames_ctx
Definition: fftools_ffmpeg.h:399
OutputStream::last_nb0_frames
int last_nb0_frames[3]
Definition: fftools_ffmpeg.h:495
opt_audio_qscale
int opt_audio_qscale(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:3157
OutputStream::filters
char * filters
filtergraph associated to the -filter option
Definition: fftools_ffmpeg.h:527
OPT_OFFSET
#define OPT_OFFSET
Definition: fftools_cmdutils.h:201
vstats_file
static FILE * vstats_file
Definition: fftools_ffmpeg.c:140
InputStream::discard
int discard
Definition: fftools_ffmpeg.h:321
OutputStream::logfile_prefix
char * logfile_prefix
Definition: fftools_ffmpeg.h:522
OPT_INPUT
#define OPT_INPUT
Definition: fftools_cmdutils.h:205
OutputStream::muxing_queue
AVFifoBuffer * muxing_queue
Definition: fftools_ffmpeg.h:568
OutputStream::rotate_overridden
int rotate_overridden
Definition: fftools_ffmpeg.h:504
want_sdp
__thread int want_sdp
Definition: fftools_ffmpeg.c:168
OutputFile::ctx
AVFormatContext * ctx
Definition: fftools_ffmpeg.h:578
OutputStream::last_dropped
int last_dropped
Definition: fftools_ffmpeg.h:494
FKF_PREV_FORCED_N
@ FKF_PREV_FORCED_N
Definition: fftools_ffmpeg.h:450
show_pix_fmts
int show_pix_fmts(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1787
handleSIGXCPU
volatile int handleSIGXCPU
Definition: MobileFFmpegConfig.m:176
fftools_ffmpeg.h
OPT_TIME
#define OPT_TIME
Definition: fftools_cmdutils.h:203
AV_LOG_WARNING
#define AV_LOG_WARNING
Definition: MobileFFmpegConfig.h:61
OutputStream::force_fps
int force_fps
Definition: fftools_ffmpeg.h:502
FilterGraph::index
int index
Definition: fftools_ffmpeg.h:306
exit_program
void exit_program(int ret)
Definition: fftools_cmdutils.c:166
FKF_N
@ FKF_N
Definition: fftools_ffmpeg.h:448
output_files
__thread OutputFile ** output_files
Definition: fftools_ffmpeg.c:182
opt_attach
int opt_attach(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:403
opt_sameq
int opt_sameq(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:240
nb_input_streams
__thread int nb_input_streams
Definition: fftools_ffmpeg.c:176
frame_drop_threshold
__thread float frame_drop_threshold
Definition: fftools_ffmpeg_opt.c:109
duration_max
static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base, AVRational time_base)
Definition: fftools_ffmpeg.c:4353
InputStream
Definition: fftools_ffmpeg.h:318
hwaccel_decode_init
int hwaccel_decode_init(AVCodecContext *avctx)
Definition: fftools_ffmpeg_hw.c:484
progress_avio
__thread AVIOContext * progress_avio
Definition: fftools_ffmpeg.c:171
show_encoders
int show_encoders(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1693
VSYNC_CFR
#define VSYNC_CFR
Definition: fftools_ffmpeg.h:74
ffmpeg_execute
int ffmpeg_execute(int argc, char **argv)
Definition: fftools_ffmpeg.c:5070
OPT_DOUBLE
#define OPT_DOUBLE
Definition: fftools_cmdutils.h:204
show_demuxers
int show_demuxers(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1407
OutputStream::is_cfr
int is_cfr
Definition: fftools_ffmpeg.h:501
check_decode_result
static void check_decode_result(InputStream *ist, int *got_output, int ret)
Definition: fftools_ffmpeg.c:2276
OutputStream::bsf_ctx
AVBSFContext ** bsf_ctx
Definition: fftools_ffmpeg.h:486
AV_LOG_FATAL
#define AV_LOG_FATAL
Definition: MobileFFmpegConfig.h:49
configure_filtergraph
int configure_filtergraph(FilterGraph *fg)
Definition: fftools_ffmpeg_filter.c:1013
find_stream_info
__thread int find_stream_info
Definition: fftools_ffmpeg_opt.c:139
transcode
static int transcode(void)
Definition: fftools_ffmpeg.c:4835
InputStream::hwaccel_device_type
enum AVHWDeviceType hwaccel_device_type
Definition: fftools_ffmpeg.h:388
audio_drift_threshold
__thread float audio_drift_threshold
Definition: fftools_ffmpeg_opt.c:102
show_muxers
int show_muxers(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1402
opt_filter_hw_device
int opt_filter_hw_device(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:531
AV_LOG_ERROR
#define AV_LOG_ERROR
Definition: MobileFFmpegConfig.h:55
opt_bitrate
int opt_bitrate(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:3037
received_nb_signals
static volatile int received_nb_signals
Definition: fftools_ffmpeg.c:421
ifilter_send_frame
static int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame)
Definition: fftools_ffmpeg.c:2306
check_output_constraints
static int check_output_constraints(InputStream *ist, OutputStream *ost)
Definition: fftools_ffmpeg.c:2162
set_report_callback
void set_report_callback(void(*callback)(int, float, float, int64_t, int, double, double))
Definition: fftools_ffmpeg.c:5054
ifilter_parameters_from_frame
int ifilter_parameters_from_frame(InputFilter *ifilter, const AVFrame *frame)
Definition: fftools_ffmpeg_filter.c:1193
cancel_operation
void cancel_operation(long id)
Definition: fftools_ffmpeg.c:5059
ex_buf__
__thread jmp_buf ex_buf__
Definition: mobileffmpeg_exception.m:23
opt_progress
int opt_progress(void *optctx, const char *opt, const char *arg)
OutputStream::audio_channels_mapped
int audio_channels_mapped
Definition: fftools_ffmpeg.h:520
dup_warning
__thread unsigned dup_warning
Definition: fftools_ffmpeg.c:164
command
NSString * command
Definition: FFmpegExecution.m:26
OutputStream::attachment_filename
const char * attachment_filename
Definition: fftools_ffmpeg.h:546
OutputStream::file_index
int file_index
Definition: fftools_ffmpeg.h:466
OPT_OUTPUT
#define OPT_OUTPUT
Definition: fftools_cmdutils.h:206
VSYNC_VSCFR
#define VSYNC_VSCFR
Definition: fftools_ffmpeg.h:76
log_callback_null
static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
Definition: fftools_ffmpeg.c:5020
InputFilter
Definition: fftools_ffmpeg.h:258
InputStream::data_size
uint64_t data_size
Definition: fftools_ffmpeg.h:403
BenchmarkTimeStamps::user_usec
int64_t user_usec
Definition: fftools_ffmpeg.c:153
debug_ts
__thread int debug_ts
Definition: fftools_ffmpeg_opt.c:118
HWACCEL_AUTO
@ HWACCEL_AUTO
Definition: fftools_ffmpeg.h:83
decode
static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
Definition: fftools_ffmpeg.c:2414
max_error_rate
__thread float max_error_rate
Definition: fftools_ffmpeg_opt.c:125
InputStream::top_field_first
int top_field_first
Definition: fftools_ffmpeg.h:357
transcode_subtitles
static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output, int *decode_failed)
Definition: fftools_ffmpeg.c:2658
BenchmarkTimeStamps::sys_usec
int64_t sys_usec
Definition: fftools_ffmpeg.c:154
do_deinterlace
__thread int do_deinterlace
Definition: fftools_ffmpeg_opt.c:110
InputStream::nb_filters
int nb_filters
Definition: fftools_ffmpeg.h:382
ffmpeg_cleanup
static void ffmpeg_cleanup(int ret)
Definition: fftools_ffmpeg.c:582
dts_error_threshold
__thread float dts_error_threshold
Definition: fftools_ffmpeg_opt.c:104
OutputStream::top_field_first
int top_field_first
Definition: fftools_ffmpeg.h:503
show_usage
void show_usage(void)
Definition: fftools_ffmpeg_opt.c:3268
InputFile::loop
int loop
Definition: fftools_ffmpeg.h:421
set_tty_echo
static void set_tty_echo(int on)
Definition: fftools_ffmpeg.c:4074
sigterm_handler
static void sigterm_handler(int sig)
Definition: fftools_ffmpeg.c:428
OutputStream::copy_prior_start
int copy_prior_start
Definition: fftools_ffmpeg.h:548
OutputStream::disposition
char * disposition
Definition: fftools_ffmpeg.h:549
show_help
int show_help(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:2019
OutputStream::source_index
int source_index
Definition: fftools_ffmpeg.h:468
OPT_VIDEO
#define OPT_VIDEO
Definition: fftools_cmdutils.h:192
InputStream::sub2video::end_pts
int64_t end_pts
Definition: fftools_ffmpeg.h:371
OutputStream::quality
int quality
Definition: fftools_ffmpeg.h:563
OutputFilter
Definition: fftools_ffmpeg.h:282
OutputStream::pict_type
int pict_type
Definition: fftools_ffmpeg.h:571
InputFilter::channel_layout
uint64_t channel_layout
Definition: fftools_ffmpeg.h:275
InputStream::subtitle
AVSubtitle subtitle
Definition: fftools_ffmpeg.h:366
OutputStream::sws_dict
AVDictionary * sws_dict
Definition: fftools_ffmpeg.h:531
OutputFile::header_written
int header_written
Definition: fftools_ffmpeg.h:587
removeExecution
void removeExecution(long executionId)
Definition: MobileFFmpegConfig.m:258
run_as_daemon
__thread int run_as_daemon
Definition: fftools_ffmpeg.c:162
OutputStream::max_muxing_queue_size
int max_muxing_queue_size
Definition: fftools_ffmpeg.h:565
OPT_INT
#define OPT_INT
Definition: fftools_cmdutils.h:194
InputStream::decoded_frame
AVFrame * decoded_frame
Definition: fftools_ffmpeg.h:329
sub2video_flush
static void sub2video_flush(InputStream *ist)
Definition: fftools_ffmpeg.c:390
show_filters
int show_filters(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1726
do_pkt_dump
__thread int do_pkt_dump
Definition: fftools_ffmpeg_opt.c:114
OutputStream::forced_keyframes_expr_const_values
double forced_keyframes_expr_const_values[FKF_NB]
Definition: fftools_ffmpeg.h:516
DECODING_FOR_OST
#define DECODING_FOR_OST
Definition: fftools_ffmpeg.h:324
opt_video_frames
int opt_video_frames(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:2939
handleSIGINT
volatile int handleSIGINT
Definition: MobileFFmpegConfig.m:174
opt_subtitle_codec
int opt_subtitle_codec(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:273
do_subtitle_out
static void do_subtitle_out(OutputFile *of, OutputStream *ost, AVSubtitle *sub)
Definition: fftools_ffmpeg.c:1072
int_cb
__thread const AVIOInterruptCB int_cb
Definition: fftools_ffmpeg.c:580
opt_streamid
int opt_streamid(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:2007
opt_timecode
int opt_timecode(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:3107
HWAccel::id
enum HWAccelID id
Definition: fftools_ffmpeg.h:93
InputStream::autorotate
int autorotate
Definition: fftools_ffmpeg.h:360
forced_keyframes_const_names
const char *const forced_keyframes_const_names[]
Definition: fftools_ffmpeg.c:142
OutputFilter::graph
struct FilterGraph * graph
Definition: fftools_ffmpeg.h:285
InputStream::sub2video::sub_queue
AVFifoBuffer * sub_queue
queue of AVSubtitle* before filter init
Definition: fftools_ffmpeg.h:372
FilterGraph::nb_inputs
int nb_inputs
Definition: fftools_ffmpeg.h:313
OFFSET
#define OFFSET(x)
show_version
int show_version(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1238
sub2video_get_blank_frame
static int sub2video_get_blank_frame(InputStream *ist)
Definition: fftools_ffmpeg.c:262
OutputStream::packets_written
uint64_t packets_written
Definition: fftools_ffmpeg.h:557
OutputFile::opts
AVDictionary * opts
Definition: fftools_ffmpeg.h:579
opt_channel_layout
int opt_channel_layout(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:3121
parse_loglevel
void parse_loglevel(int argc, char **argv, const OptionDef *options)
Definition: fftools_cmdutils.c:543
FKF_N_FORCED
@ FKF_N_FORCED
Definition: fftools_ffmpeg.h:449
OutputStream::forced_keyframes_pexpr
AVExpr * forced_keyframes_pexpr
Definition: fftools_ffmpeg.h:515
OutputStream::forced_kf_pts
int64_t * forced_kf_pts
Definition: fftools_ffmpeg.h:511
do_video_out
static void do_video_out(OutputFile *of, OutputStream *ost, AVFrame *next_picture, double sync_ipts)
Definition: fftools_ffmpeg.c:1155
HAS_ARG
#define HAS_ARG
Definition: fftools_cmdutils.h:188
intra_only
__thread int intra_only
Definition: fftools_ffmpeg_opt.c:131
ffmpeg_options
__thread OptionDef * ffmpeg_options
Definition: fftools_ffmpeg.c:5068
InputFilter::ist
struct InputStream * ist
Definition: fftools_ffmpeg.h:260
get_input_packet
static int get_input_packet(InputFile *f, AVPacket *pkt)
Definition: fftools_ffmpeg.c:4314
vstats_filename
__thread char * vstats_filename
Definition: fftools_ffmpeg_opt.c:99
InputStream::cfr_next_pts
int64_t cfr_next_pts
Definition: fftools_ffmpeg.h:349
opt_qscale
int opt_qscale(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:3053
FKF_T
@ FKF_T
Definition: fftools_ffmpeg.h:452
hwaccels
const HWAccel hwaccels[]
Definition: fftools_ffmpeg_opt.c:84
InputFilter::type
enum AVMediaType type
Definition: fftools_ffmpeg.h:263
InputStream::fix_sub_duration
int fix_sub_duration
Definition: fftools_ffmpeg.h:362
InputStream::got_output
int got_output
Definition: fftools_ffmpeg.h:364
VSYNC_AUTO
#define VSYNC_AUTO
Definition: fftools_ffmpeg.h:72
InputFilter::frame_queue
AVFifoBuffer * frame_queue
Definition: fftools_ffmpeg.h:265
show_hwaccels
int show_hwaccels(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:189
opt_profile
int opt_profile(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:3071
InputFile
Definition: fftools_ffmpeg.h:416
OutputFilter::name
uint8_t * name
Definition: fftools_ffmpeg.h:286
OPT_FLOAT
#define OPT_FLOAT
Definition: fftools_cmdutils.h:195
opt_abort_on
int opt_abort_on(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:222
FilterGraph::graph_desc
const char * graph_desc
Definition: fftools_ffmpeg.h:307
InputStream::dts
int64_t dts
dts of the last packet read for this stream (in AV_TIME_BASE units)
Definition: fftools_ffmpeg.h:336
OutputStream::encoding_needed
int encoding_needed
Definition: fftools_ffmpeg.h:470
MUXER_FINISHED
@ MUXER_FINISHED
Definition: fftools_ffmpeg.h:462
hw_device_free_all
void hw_device_free_all(void)
Definition: fftools_ffmpeg_hw.c:281
OPT_STRING
#define OPT_STRING
Definition: fftools_cmdutils.h:191
OutputFile::shortest
int shortest
Definition: fftools_ffmpeg.h:585
parse_time_or_die
int64_t parse_time_or_die(const char *context, const char *timestr, int is_duration)
Definition: fftools_cmdutils.c:198
opt_data_codec
int opt_data_codec(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:279
nb_input_files
__thread int nb_input_files
Definition: fftools_ffmpeg.c:178
handleSIGQUIT
volatile int handleSIGQUIT
Definition: MobileFFmpegConfig.m:173
do_benchmark_all
__thread int do_benchmark_all
Definition: fftools_ffmpeg_opt.c:112
InputStream::hwaccel_get_buffer
int(* hwaccel_get_buffer)(AVCodecContext *s, AVFrame *frame, int flags)
Definition: fftools_ffmpeg.h:395
opt_preset
int opt_preset(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:2977
show_colors
int show_colors(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1773
OutputFile::recording_time
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
Definition: fftools_ffmpeg.h:581
dts_delta_threshold
__thread float dts_delta_threshold
Definition: fftools_ffmpeg_opt.c:103
filter_nbthreads
__thread int filter_nbthreads
Definition: fftools_ffmpeg_opt.c:126
assert_avoptions
void assert_avoptions(AVDictionary *m)
Definition: fftools_ffmpeg.c:747
nb_output_streams
__thread int nb_output_streams
Definition: fftools_ffmpeg.c:181
ABORT_ON_FLAG_EMPTY_OUTPUT
#define ABORT_ON_FLAG_EMPTY_OUTPUT
Definition: fftools_ffmpeg.h:456
OutputStream::data_size
uint64_t data_size
Definition: fftools_ffmpeg.h:555
InputStream::sub2video::last_pts
int64_t last_pts
Definition: fftools_ffmpeg.h:370
show_bsfs
int show_bsfs(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1699
OutputStream::first_pts
int64_t first_pts
Definition: fftools_ffmpeg.h:478
OutputStream::frames_encoded
uint64_t frames_encoded
Definition: fftools_ffmpeg.h:559
term_exit
void term_exit(void)
Definition: fftools_ffmpeg.c:414
OutputStream::forced_kf_ref_pts
int64_t forced_kf_ref_pts
Definition: fftools_ffmpeg.h:510
choose_output
static OutputStream * choose_output(void)
Definition: fftools_ffmpeg.c:4047
InputFile::ctx
AVFormatContext * ctx
Definition: fftools_ffmpeg.h:417
OutputStream::logfile
FILE * logfile
Definition: fftools_ffmpeg.h:523
OSTFinished
OSTFinished
Definition: fftools_ffmpeg.h:460
InputStream::max_pts
int64_t max_pts
Definition: fftools_ffmpeg.h:345
audio_sync_method
__thread int audio_sync_method
Definition: fftools_ffmpeg_opt.c:107
FilterGraph::nb_outputs
int nb_outputs
Definition: fftools_ffmpeg.h:315
InputFilter::sample_aspect_ratio
AVRational sample_aspect_ratio
Definition: fftools_ffmpeg.h:271
hw_device_setup_for_encode
int hw_device_setup_for_encode(OutputStream *ost)
Definition: fftools_ffmpeg_hw.c:426
InputStream::samples_decoded
uint64_t samples_decoded
Definition: fftools_ffmpeg.h:408
InputFilter::graph
struct FilterGraph * graph
Definition: fftools_ffmpeg.h:261
OutputStream::resample_opts
AVDictionary * resample_opts
Definition: fftools_ffmpeg.h:533
decode_interrupt_cb
int decode_interrupt_cb(void *ctx)
Definition: fftools_ffmpeg.c:575
InputFilter::height
int height
Definition: fftools_ffmpeg.h:270
opt_init_hw_device
int opt_init_hw_device(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:516
program_birth_year
__thread int program_birth_year
Definition: fftools_cmdutils.c:99
OutputStream::filter
OutputFilter * filter
Definition: fftools_ffmpeg.h:525
nb_output_files
__thread int nb_output_files
Definition: fftools_ffmpeg.c:183
uninit_opts
void uninit_opts(void)
Definition: fftools_cmdutils.c:121
time
int time
Definition: Statistics.m:28
OutputFilter::sample_rates
int * sample_rates
Definition: fftools_ffmpeg.h:302
InputStream::sub2video::w
int w
Definition: fftools_ffmpeg.h:374
psnr
static double psnr(double d)
Definition: fftools_ffmpeg.c:1456
OutputStream::enc_timebase
AVRational enc_timebase
Definition: fftools_ffmpeg.h:483
InputFile::nb_streams
int nb_streams
Definition: fftools_ffmpeg.h:432
OPT_SUBTITLE
#define OPT_SUBTITLE
Definition: fftools_cmdutils.h:196
subtitle_out
__thread uint8_t * subtitle_out
Definition: fftools_ffmpeg.c:173
opt_target
int opt_target(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:2772
opt_loglevel
int opt_loglevel(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:913
sample_rate
sample_rate
Definition: fftools_ffmpeg_filter.c:199
FilterGraph::graph
AVFilterGraph * graph
Definition: fftools_ffmpeg.h:309
process_input
static int process_input(int file_index)
Definition: fftools_ffmpeg.c:4437
init_output_stream_streamcopy
static int init_output_stream_streamcopy(OutputStream *ost)
Definition: fftools_ffmpeg.c:3234
show_sample_fmts
int show_sample_fmts(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1849
OutputFilter::formats
int * formats
Definition: fftools_ffmpeg.h:300
init_output_stream
static int init_output_stream(OutputStream *ost, char *error, int error_len)
Definition: fftools_ffmpeg.c:3634
InputFilter::filter
AVFilterContext * filter
Definition: fftools_ffmpeg.h:259
frame_bits_per_raw_sample
__thread int frame_bits_per_raw_sample
Definition: fftools_ffmpeg_opt.c:124
InputStream::framerate
AVRational framerate
Definition: fftools_ffmpeg.h:356
register_exit
void register_exit(void(*cb)(int ret))
Definition: fftools_cmdutils.c:161
nb_frames_dup
__thread int nb_frames_dup
Definition: fftools_ffmpeg.c:163
InputStream::wrap_correction_done
int wrap_correction_done
Definition: fftools_ffmpeg.h:340
do_psnr
__thread int do_psnr
Definition: fftools_ffmpeg_opt.c:134
FilterGraph::outputs
OutputFilter ** outputs
Definition: fftools_ffmpeg.h:314
OutputStream::sync_ist
struct InputStream * sync_ist
Definition: fftools_ffmpeg.h:474
FilterGraph::inputs
InputFilter ** inputs
Definition: fftools_ffmpeg.h:312
hw_device_ctx
__thread AVBufferRef * hw_device_ctx
Definition: fftools_ffmpeg_opt.c:96
seek_to_start
static int seek_to_start(InputFile *ifile, AVFormatContext *is)
Definition: fftools_ffmpeg.c:4372
print_error
void print_error(const char *filename, int err)
Definition: fftools_cmdutils.c:1130
InputFile::ts_offset
int64_t ts_offset
Definition: fftools_ffmpeg.h:427
OutputFilter::format
int format
Definition: fftools_ffmpeg.h:295
main_ffmpeg_return_code
__thread volatile int main_ffmpeg_return_code
Definition: fftools_ffmpeg.c:424
OutputStream::index
int index
Definition: fftools_ffmpeg.h:467
term_init
void term_init(void)
Definition: fftools_ffmpeg.c:474
show_banner
void show_banner(int argc, char **argv, const OptionDef *options)
Definition: fftools_cmdutils.c:1227
close_all_output_streams
static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
Definition: fftools_ffmpeg.c:782
InputStream::st
AVStream * st
Definition: fftools_ffmpeg.h:320
InputStream::hwaccel_pix_fmt
enum AVPixelFormat hwaccel_pix_fmt
Definition: fftools_ffmpeg.h:397
opt_video_standard
int opt_video_standard(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:255
write_packet
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
Definition: fftools_ffmpeg.c:791
InputFilter::eof
int eof
Definition: fftools_ffmpeg.h:279
HWAccel
Definition: fftools_ffmpeg.h:90
OutputStream::forced_keyframes
char * forced_keyframes
Definition: fftools_ffmpeg.h:514
InputStream::dec_ctx
AVCodecContext * dec_ctx
Definition: fftools_ffmpeg.h:327
InputFile::eof_reached
int eof_reached
Definition: fftools_ffmpeg.h:418
bitrate
double bitrate
Definition: Statistics.m:29
flush_encoders
static void flush_encoders(void)
Definition: fftools_ffmpeg.c:2043
mobileffmpeg_exception.h
check_keyboard_interaction
static int check_keyboard_interaction(int64_t cur_time)
Definition: fftools_ffmpeg.c:4086
decode_audio
static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output, int *decode_failed)
Definition: fftools_ffmpeg.c:2463
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Definition: MobileFFmpegConfig.h:71
opt_video_filters
int opt_video_filters(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:3083
InputStream::next_pts
int64_t next_pts
synthetic pts for the next decode frame (in AV_TIME_BASE units)
Definition: fftools_ffmpeg.h:338
opt_data_frames
int opt_data_frames(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:2951
opt_cpuflags
int opt_cpuflags(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:901
InputStream::hwaccel_retrieve_data
int(* hwaccel_retrieve_data)(AVCodecContext *s, AVFrame *frame)
Definition: fftools_ffmpeg.h:396
send_filter_eof
static int send_filter_eof(InputStream *ist)
Definition: fftools_ffmpeg.c:2735
OutputStream::error
int64_t error[4]
Definition: fftools_ffmpeg.h:574
AV_LOG_STDERR
#define AV_LOG_STDERR
Definition: fftools_cmdutils.h:61
guess_input_channel_layout
int guess_input_channel_layout(InputStream *ist)
Definition: fftools_ffmpeg.c:2256
send_frame_to_filters
static int send_frame_to_filters(InputStream *ist, AVFrame *decoded_frame)
Definition: fftools_ffmpeg.c:2437
read_key
static int read_key(void)
Definition: fftools_ffmpeg.c:522
show_protocols
int show_protocols(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1711
transcode_init
static int transcode_init(void)
Definition: fftools_ffmpeg.c:3844
InputFile::ist_index
int ist_index
Definition: fftools_ffmpeg.h:420
InputFile::last_ts
int64_t last_ts
Definition: fftools_ffmpeg.h:428
InputStream::decoding_needed
int decoding_needed
Definition: fftools_ffmpeg.h:323
InputFilter::format
int format
Definition: fftools_ffmpeg.h:268
opt_filter_complex_script
int opt_filter_complex_script(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:3178
opt_map_channel
int opt_map_channel(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:411
OutputStream::frame_rate
AVRational frame_rate
Definition: fftools_ffmpeg.h:500
int
int
Definition: fftools_ffmpeg_filter.c:199
show_codecs
int show_codecs(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1594
decode_video
static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *duration_pts, int eof, int *decode_failed)
Definition: fftools_ffmpeg.c:2525
report_new_stream
static void report_new_stream(int input_index, AVPacket *pkt)
Definition: fftools_ffmpeg.c:3829
input_files
__thread InputFile ** input_files
Definition: fftools_ffmpeg.c:177
init_output_stream_encode
static int init_output_stream_encode(OutputStream *ost)
Definition: fftools_ffmpeg.c:3476
InputStream::saw_first_ts
int saw_first_ts
Definition: fftools_ffmpeg.h:354
close_output_stream
static void close_output_stream(OutputStream *ost)
Definition: fftools_ffmpeg.c:926
qp_hist
__thread int qp_hist
Definition: fftools_ffmpeg_opt.c:122
OutputStream::last_frame
AVFrame * last_frame
Definition: fftools_ffmpeg.h:493
InputFilter::sample_rate
int sample_rate
Definition: fftools_ffmpeg.h:273
filtergraphs
__thread FilterGraph ** filtergraphs
Definition: fftools_ffmpeg.c:185
copy_unknown_streams
__thread int copy_unknown_streams
Definition: fftools_ffmpeg_opt.c:138
InputStream::guess_layout_max
int guess_layout_max
Definition: fftools_ffmpeg.h:358
hide_banner
__thread int hide_banner
Definition: fftools_cmdutils.c:107
copy_tb
__thread int copy_tb
Definition: fftools_ffmpeg_opt.c:117
OutputStream::nb_bitstream_filters
int nb_bitstream_filters
Definition: fftools_ffmpeg.h:485
OPT_SPEC
#define OPT_SPEC
Definition: fftools_cmdutils.h:202
OPT_PERFILE
#define OPT_PERFILE
Definition: fftools_cmdutils.h:200
OutputFile::ost_index
int ost_index
Definition: fftools_ffmpeg.h:580
OptionDef
Definition: fftools_cmdutils.h:185
opt_report
int opt_report(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1098
OutputStream::filters_script
char * filters_script
filtergraph script associated to the -filter_script option
Definition: fftools_ffmpeg.h:528
remove_avoptions
void remove_avoptions(AVDictionary **a, AVDictionary *b)
Definition: fftools_ffmpeg.c:738
DECODING_FOR_FILTER
#define DECODING_FOR_FILTER
Definition: fftools_ffmpeg.h:325
InputFile::start_time
int64_t start_time
Definition: fftools_ffmpeg.h:429
opt_vstats_file
int opt_vstats_file(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:2916
check_init_output_file
static int check_init_output_file(OutputFile *of, int file_index)
Definition: fftools_ffmpeg.c:3152
OutputFile::limit_filesize
uint64_t limit_filesize
Definition: fftools_ffmpeg.h:583
OutputStream::enc
AVCodec * enc
Definition: fftools_ffmpeg.h:490
InputStream::nb_packets
uint64_t nb_packets
Definition: fftools_ffmpeg.h:405
InputStream::min_pts
int64_t min_pts
Definition: fftools_ffmpeg.h:344
InputStream::filter_in_rescale_delta_last
int64_t filter_in_rescale_delta_last
Definition: fftools_ffmpeg.h:342
OutputFilter::filter
AVFilterContext * filter
Definition: fftools_ffmpeg.h:283
process_input_packet
static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
Definition: fftools_ffmpeg.c:2751
OutputStream::st
AVStream * st
Definition: fftools_ffmpeg.h:469
decode_error_stat
__thread int64_t decode_error_stat[2]
Definition: fftools_ffmpeg.c:166
HWAccel::name
const char * name
Definition: fftools_ffmpeg.h:91
InputStream::sub2video::frame
AVFrame * frame
Definition: fftools_ffmpeg.h:373
handleSIGPIPE
volatile int handleSIGPIPE
Definition: MobileFFmpegConfig.m:177
abort_codec_experimental
static void abort_codec_experimental(AVCodec *c, int encoder)
Definition: fftools_ffmpeg.c:756
dump_attachment
void dump_attachment(AVStream *st, const char *filename)
Definition: fftools_ffmpeg_opt.c:983
video_sync_method
__thread int video_sync_method
Definition: fftools_ffmpeg_opt.c:108
AV_LOG_DEBUG
#define AV_LOG_DEBUG
Definition: MobileFFmpegConfig.h:76
do_hex_dump
__thread int do_hex_dump
Definition: fftools_ffmpeg_opt.c:113
InputStream::hwaccel_uninit
void(* hwaccel_uninit)(AVCodecContext *s)
Definition: fftools_ffmpeg.h:394
InputStream::dts_buffer
int64_t * dts_buffer
Definition: fftools_ffmpeg.h:410
sdp_filename
__thread char * sdp_filename
Definition: fftools_ffmpeg_opt.c:100
show_devices
int show_devices(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1412
OutputFile
Definition: fftools_ffmpeg.h:577
VSYNC_PASSTHROUGH
#define VSYNC_PASSTHROUGH
Definition: fftools_ffmpeg.h:73
do_audio_out
static void do_audio_out(OutputFile *of, OutputStream *ost, AVFrame *frame)
Definition: fftools_ffmpeg.c:1012
get_input_stream
static InputStream * get_input_stream(OutputStream *ost)
Definition: fftools_ffmpeg.c:3139
nb_filtergraphs
__thread int nb_filtergraphs
Definition: fftools_ffmpeg.c:186
InputStream::ret
int ret
Definition: fftools_ffmpeg.h:365
ignore_unknown_streams
__thread int ignore_unknown_streams
Definition: fftools_ffmpeg_opt.c:137
OPT_AUDIO
#define OPT_AUDIO
Definition: fftools_cmdutils.h:193
transcode_step
static int transcode_step(void)
Definition: fftools_ffmpeg.c:4760
sub2video_copy_rect
static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h, AVSubtitleRect *r)
Definition: fftools_ffmpeg.c:277
opt_old2new
int opt_old2new(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:3025
getmaxrss
static int64_t getmaxrss(void)
Definition: fftools_ffmpeg.c:5002
HWAccel::init
int(* init)(AVCodecContext *s)
Definition: fftools_ffmpeg.h:92
OPT_BOOL
#define OPT_BOOL
Definition: fftools_cmdutils.h:189
file_overwrite
__thread int file_overwrite
Definition: fftools_ffmpeg_opt.c:132
OutputStream::max_frames
int64_t max_frames
Definition: fftools_ffmpeg.h:491
BenchmarkTimeStamps
Definition: fftools_ffmpeg.c:151
reap_filters
static int reap_filters(int flush)
Definition: fftools_ffmpeg.c:1525
OutputStream::apad
char * apad
Definition: fftools_ffmpeg.h:534
init_output_bsfs
static int init_output_bsfs(OutputStream *ost)
Definition: fftools_ffmpeg.c:3198
exit_on_error
__thread int exit_on_error
Definition: fftools_ffmpeg_opt.c:119
OutputStream::frame_aspect_ratio
AVRational frame_aspect_ratio
Definition: fftools_ffmpeg.h:507
OutputStream::unavailable
int unavailable
Definition: fftools_ffmpeg.h:536
OutputStream::mux_timebase
AVRational mux_timebase
Definition: fftools_ffmpeg.h:482
hw_device_setup_for_decode
int hw_device_setup_for_decode(InputStream *ist)
Definition: fftools_ffmpeg_hw.c:310
fftools_cmdutils.h
media_type_string
#define media_type_string
Definition: fftools_cmdutils.h:605
InputStream::hwaccel_device
char * hwaccel_device
Definition: fftools_ffmpeg.h:389
InputFilter::channels
int channels
Definition: fftools_ffmpeg.h:274
do_video_stats
static void do_video_stats(OutputStream *ost, int frame_size)
Definition: fftools_ffmpeg.c:1461
FKF_PREV_FORCED_T
@ FKF_PREV_FORCED_T
Definition: fftools_ffmpeg.h:451
init_input_stream
static int init_input_stream(int ist_index, char *error, int error_len)
Definition: fftools_ffmpeg.c:3074
opt_video_codec
int opt_video_codec(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:267
InputStream::hwaccel_id
enum HWAccelID hwaccel_id
Definition: fftools_ffmpeg.h:387
cancelRequested
int cancelRequested(long executionId)
Definition: MobileFFmpegConfig.m:273
input_streams
__thread InputStream ** input_streams
Definition: fftools_ffmpeg.c:175
output_streams
__thread OutputStream ** output_streams
Definition: fftools_ffmpeg.c:180
InputStream::nb_dts_buffer
int nb_dts_buffer
Definition: fftools_ffmpeg.h:411
input_sync
__thread int input_sync
Definition: fftools_ffmpeg_opt.c:135
OutputStream::forced_kf_count
int forced_kf_count
Definition: fftools_ffmpeg.h:512
compare_int64
static int compare_int64(const void *a, const void *b)
Definition: fftools_ffmpeg.c:3146
InputStream::dec
AVCodec * dec
Definition: fftools_ffmpeg.h:328
InputStream::hwaccel_retrieved_pix_fmt
enum AVPixelFormat hwaccel_retrieved_pix_fmt
Definition: fftools_ffmpeg.h:398
VSYNC_VFR
#define VSYNC_VFR
Definition: fftools_ffmpeg.h:75
do_benchmark
__thread int do_benchmark
Definition: fftools_ffmpeg_opt.c:111
ifilter_has_all_input_formats
static int ifilter_has_all_input_formats(FilterGraph *fg)
Definition: fftools_ffmpeg.c:2295
sub2video_heartbeat
static void sub2video_heartbeat(InputStream *ist, int64_t pts)
Definition: fftools_ffmpeg.c:360
got_eagain
static int got_eagain(void)
Definition: fftools_ffmpeg.c:4334
InputStream::filters
InputFilter ** filters
Definition: fftools_ffmpeg.h:381
finish_output_stream
static void finish_output_stream(OutputStream *ost)
Definition: fftools_ffmpeg.c:1506
vstats_version
__thread int vstats_version
Definition: fftools_ffmpeg_opt.c:128
show_layouts
int show_layouts(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1820
ifilter_send_eof
static int ifilter_send_eof(InputFilter *ifilter, int64_t pts)
Definition: fftools_ffmpeg.c:2383
InputStream::nb_samples
int64_t nb_samples
Definition: fftools_ffmpeg.h:351
VSYNC_DROP
#define VSYNC_DROP
Definition: fftools_ffmpeg.h:77
size
long size
Definition: Statistics.m:27
audio_volume
__thread int audio_volume
Definition: fftools_ffmpeg_opt.c:106
videotoolbox_pixfmt
__thread char * videotoolbox_pixfmt
Definition: fftools_ffmpeg_videotoolbox.c:34
OutputStream::enc_ctx
AVCodecContext * enc_ctx
Definition: fftools_ffmpeg.h:488
InputStream::pts
int64_t pts
current pts of the decoded frame (in AV_TIME_BASE units)
Definition: fftools_ffmpeg.h:339
show_license
int show_license(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1253
term_exit_sigsafe
static void term_exit_sigsafe(void)
Definition: fftools_ffmpeg.c:406
show_buildconf
int show_buildconf(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1246
InputFile::time_base
AVRational time_base
Definition: fftools_ffmpeg.h:424
show_formats
int show_formats(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1397
InputStream::sub2video
struct InputStream::sub2video sub2video
report_callback
void(* report_callback)(int, float, float, int64_t, int, double, double)
Definition: fftools_ffmpeg.c:188
start_at_zero
__thread int start_at_zero
Definition: fftools_ffmpeg_opt.c:116
OutputStream::samples_encoded
uint64_t samples_encoded
Definition: fftools_ffmpeg.h:560
InputStream::file_index
int file_index
Definition: fftools_ffmpeg.h:319
print_report
static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
Definition: fftools_ffmpeg.c:1828
OutputFile::start_time
int64_t start_time
start time in microseconds == AV_TIME_BASE units
Definition: fftools_ffmpeg.h:582
OutputStream::audio_channels_map
int * audio_channels_map
Definition: fftools_ffmpeg.h:519
FilterGraph
Definition: fftools_ffmpeg.h:305
OutputStream
Definition: fftools_ffmpeg.h:465
AV_LOG_QUIET
#define AV_LOG_QUIET
Definition: MobileFFmpegConfig.h:37
InputStream::start
int64_t start
Definition: fftools_ffmpeg.h:332
HWACCEL_GENERIC
@ HWACCEL_GENERIC
Definition: fftools_ffmpeg.h:84
transcode_from_filter
static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
Definition: fftools_ffmpeg.c:4714
opt_map
int opt_map(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:285
forward_report
static void forward_report(int is_last_report, int64_t timer_start, int64_t cur_time)
Definition: fftools_ffmpeg.c:1747
opt_vstats
int opt_vstats(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:2923
opt_max_alloc
int opt_max_alloc(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1103
InputFilter::width
int width
Definition: fftools_ffmpeg.h:270
OutputStream::copy_initial_nonkeyframes
int copy_initial_nonkeyframes
Definition: fftools_ffmpeg.h:547
handleSIGTERM
volatile int handleSIGTERM
Definition: MobileFFmpegConfig.m:175
print_stats
__thread int print_stats
Definition: fftools_ffmpeg_opt.c:121
opt_audio_filters
int opt_audio_filters(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:3089
opt_timelimit
int opt_timelimit(void *optctx, const char *opt, const char *arg)
Definition: fftools_cmdutils.c:1117
ffmpeg_var_cleanup
void ffmpeg_var_cleanup()
Definition: fftools_ffmpeg.c:5024
reset_eagain
static void reset_eagain(void)
Definition: fftools_ffmpeg.c:4343
do_streamcopy
static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
Definition: fftools_ffmpeg.c:2179
output_packet
static void output_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int eof)
Definition: fftools_ffmpeg.c:948
InputFilter::hw_frames_ctx
AVBufferRef * hw_frames_ctx
Definition: fftools_ffmpeg.h:277
InputFile::rate_emu
int rate_emu
Definition: fftools_ffmpeg.h:435
InputStream::decoder_opts
AVDictionary * decoder_opts
Definition: fftools_ffmpeg.h:355
init_dynload
void init_dynload(void)
Definition: fftools_cmdutils.c:150
InputStream::next_dts
int64_t next_dts
Definition: fftools_ffmpeg.h:335
need_output
static int need_output(void)
Definition: fftools_ffmpeg.c:4017
InputFile::duration
int64_t duration
Definition: fftools_ffmpeg.h:422
set_encoder_id
static void set_encoder_id(OutputFile *of, OutputStream *ost)
Definition: fftools_ffmpeg.c:3348
BenchmarkTimeStamps
struct BenchmarkTimeStamps BenchmarkTimeStamps
filter_complex_nbthreads
__thread int filter_complex_nbthreads
Definition: fftools_ffmpeg_opt.c:127
opt_video_channel
int opt_video_channel(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:249
OutputStream::initialized
int initialized
Definition: fftools_ffmpeg.h:542
no_file_overwrite
__thread int no_file_overwrite
Definition: fftools_ffmpeg_opt.c:133
OutputStream::encoder_opts
AVDictionary * encoder_opts
Definition: fftools_ffmpeg.h:530
OutputStream::swr_opts
AVDictionary * swr_opts
Definition: fftools_ffmpeg.h:532
InputStream::prev_sub
struct InputStream::@2 prev_sub
update_benchmark
static void update_benchmark(const char *fmt,...)
Definition: fftools_ffmpeg.c:761
OutputFilter::ost
struct OutputStream * ost
Definition: fftools_ffmpeg.h:284
print_final_stats
static void print_final_stats(int64_t total_size)
Definition: fftools_ffmpeg.c:1629
current_time
__thread BenchmarkTimeStamps current_time
Definition: fftools_ffmpeg.c:170
OutputFilter::channel_layouts
uint64_t * channel_layouts
Definition: fftools_ffmpeg.h:301
InputFile::recording_time
int64_t recording_time
Definition: fftools_ffmpeg.h:431
OPT_EXPERT
#define OPT_EXPERT
Definition: fftools_cmdutils.h:190
InputFile::input_ts_offset
int64_t input_ts_offset
Definition: fftools_ffmpeg.h:425
InputStream::frames_decoded
uint64_t frames_decoded
Definition: fftools_ffmpeg.h:407
sub2video_update
void sub2video_update(InputStream *ist, AVSubtitle *sub)
Definition: fftools_ffmpeg.c:326
opt_recording_timestamp
int opt_recording_timestamp(void *optctx, const char *opt, const char *arg)
Definition: fftools_ffmpeg_opt.c:669
executionId
__thread volatile long executionId
Definition: FFmpegExecution.m:23
longjmp_value
__thread volatile int longjmp_value
Definition: fftools_cmdutils.c:108
InputStream::reinit_filters
int reinit_filters
Definition: fftools_ffmpeg.h:384
copy_ts
__thread int copy_ts
Definition: fftools_ffmpeg_opt.c:115
get_buffer
static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
Definition: fftools_ffmpeg.c:3064
nb_frames_drop
__thread int nb_frames_drop
Definition: fftools_ffmpeg.c:165
received_sigterm
static volatile int received_sigterm
Definition: fftools_ffmpeg.c:420
check_recording_time
static int check_recording_time(OutputStream *ost)
Definition: fftools_ffmpeg.c:999
OPT_INT64
#define OPT_INT64
Definition: fftools_cmdutils.h:197
OutputStream::inputs_done
int inputs_done
Definition: fftools_ffmpeg.h:544
filtergraph_is_simple
int filtergraph_is_simple(FilterGraph *fg)
Definition: fftools_ffmpeg_filter.c:1225