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