FFmpeg  4.4.9
ffmpeg.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2000-2003 Fabrice Bellard
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 /**
22  * @file
23  * multimedia converter based on the FFmpeg libraries
24  */
25 
26 #include "config.h"
27 #include <ctype.h>
28 #include <string.h>
29 #include <math.h>
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <limits.h>
33 #include <stdatomic.h>
34 #include <stdint.h>
35 
36 #if HAVE_IO_H
37 #include <io.h>
38 #endif
39 #if HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
42 
43 #include "libavformat/avformat.h"
44 #include "libavdevice/avdevice.h"
46 #include "libavutil/opt.h"
48 #include "libavutil/parseutils.h"
49 #include "libavutil/samplefmt.h"
50 #include "libavutil/fifo.h"
51 #include "libavutil/hwcontext.h"
52 #include "libavutil/internal.h"
53 #include "libavutil/intreadwrite.h"
54 #include "libavutil/dict.h"
55 #include "libavutil/display.h"
56 #include "libavutil/mathematics.h"
57 #include "libavutil/pixdesc.h"
58 #include "libavutil/avstring.h"
59 #include "libavutil/libm.h"
60 #include "libavutil/imgutils.h"
61 #include "libavutil/timestamp.h"
62 #include "libavutil/bprint.h"
63 #include "libavutil/time.h"
64 #include "libavutil/thread.h"
66 #include "libavcodec/mathops.h"
67 #include "libavformat/os_support.h"
68 
69 # include "libavfilter/avfilter.h"
70 # include "libavfilter/buffersrc.h"
71 # include "libavfilter/buffersink.h"
72 
73 #if HAVE_SYS_RESOURCE_H
74 #include <sys/time.h>
75 #include <sys/types.h>
76 #include <sys/resource.h>
77 #elif HAVE_GETPROCESSTIMES
78 #include <windows.h>
79 #endif
80 #if HAVE_GETPROCESSMEMORYINFO
81 #include <windows.h>
82 #include <psapi.h>
83 #endif
84 #if HAVE_SETCONSOLECTRLHANDLER
85 #include <windows.h>
86 #endif
87 
88 
89 #if HAVE_SYS_SELECT_H
90 #include <sys/select.h>
91 #endif
92 
93 #if HAVE_TERMIOS_H
94 #include <fcntl.h>
95 #include <sys/ioctl.h>
96 #include <sys/time.h>
97 #include <termios.h>
98 #elif HAVE_KBHIT
99 #include <conio.h>
100 #endif
101 
102 #include <time.h>
103 
104 #include "ffmpeg.h"
105 #include "cmdutils.h"
106 
107 #include "libavutil/avassert.h"
108 
109 const char program_name[] = "ffmpeg";
110 const int program_birth_year = 2000;
111 
112 static FILE *vstats_file;
113 
114 const char *const forced_keyframes_const_names[] = {
115  "n",
116  "n_forced",
117  "prev_forced_n",
118  "prev_forced_t",
119  "t",
120  NULL
121 };
122 
123 typedef struct BenchmarkTimeStamps {
128 
129 static void do_video_stats(OutputStream *ost, int frame_size);
131 static int64_t getmaxrss(void);
133 
134 static int run_as_daemon = 0;
135 static int nb_frames_dup = 0;
136 static unsigned dup_warning = 1000;
137 static int nb_frames_drop = 0;
139 static unsigned nb_output_dumped = 0;
140 
141 static int want_sdp = 1;
142 
145 
147 
152 
157 
160 
161 #if HAVE_TERMIOS_H
162 
163 /* init terminal so that we can grab keys */
164 static struct termios oldtty;
165 static int restore_tty;
166 #endif
167 
168 #if HAVE_THREADS
169 static void free_input_threads(void);
170 #endif
171 
172 /* sub2video hack:
173  Convert subtitles to video with alpha to insert them in filter graphs.
174  This is a temporary solution until libavfilter gets real subtitles support.
175  */
176 
178 {
179  int ret;
180  AVFrame *frame = ist->sub2video.frame;
181 
183  ist->sub2video.frame->width = ist->dec_ctx->width ? ist->dec_ctx->width : ist->sub2video.w;
184  ist->sub2video.frame->height = ist->dec_ctx->height ? ist->dec_ctx->height : ist->sub2video.h;
186  if ((ret = av_frame_get_buffer(frame, 0)) < 0)
187  return ret;
188  memset(frame->data[0], 0, frame->height * frame->linesize[0]);
189  return 0;
190 }
191 
192 static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
193  AVSubtitleRect *r)
194 {
195  uint32_t *pal, *dst2;
196  uint8_t *src, *src2;
197  int x, y;
198 
199  if (r->type != SUBTITLE_BITMAP) {
200  av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
201  return;
202  }
203  if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
204  av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle (%d %d %d %d) overflowing %d %d\n",
205  r->x, r->y, r->w, r->h, w, h
206  );
207  return;
208  }
209 
210  dst += r->y * dst_linesize + r->x * 4;
211  src = r->data[0];
212  pal = (uint32_t *)r->data[1];
213  for (y = 0; y < r->h; y++) {
214  dst2 = (uint32_t *)dst;
215  src2 = src;
216  for (x = 0; x < r->w; x++)
217  *(dst2++) = pal[*(src2++)];
218  dst += dst_linesize;
219  src += r->linesize[0];
220  }
221 }
222 
224 {
225  AVFrame *frame = ist->sub2video.frame;
226  int i;
227  int ret;
228 
229  av_assert1(frame->data[0]);
230  ist->sub2video.last_pts = frame->pts = pts;
231  for (i = 0; i < ist->nb_filters; i++) {
235  if (ret != AVERROR_EOF && ret < 0)
236  av_log(NULL, AV_LOG_WARNING, "Error while add the frame to buffer source(%s).\n",
237  av_err2str(ret));
238  }
239 }
240 
241 void sub2video_update(InputStream *ist, int64_t heartbeat_pts, AVSubtitle *sub)
242 {
243  AVFrame *frame = ist->sub2video.frame;
244  int8_t *dst;
245  int dst_linesize;
246  int num_rects, i;
247  int64_t pts, end_pts;
248 
249  if (!frame)
250  return;
251  if (sub) {
252  pts = av_rescale_q(sub->pts + sub->start_display_time * 1000LL,
253  AV_TIME_BASE_Q, ist->st->time_base);
254  end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000LL,
255  AV_TIME_BASE_Q, ist->st->time_base);
256  num_rects = sub->num_rects;
257  } else {
258  /* If we are initializing the system, utilize current heartbeat
259  PTS as the start time, and show until the following subpicture
260  is received. Otherwise, utilize the previous subpicture's end time
261  as the fall-back value. */
262  pts = ist->sub2video.initialize ?
263  heartbeat_pts : ist->sub2video.end_pts;
264  end_pts = INT64_MAX;
265  num_rects = 0;
266  }
267  if (sub2video_get_blank_frame(ist) < 0) {
269  "Impossible to get a blank canvas.\n");
270  return;
271  }
272  dst = frame->data [0];
273  dst_linesize = frame->linesize[0];
274  for (i = 0; i < num_rects; i++)
275  sub2video_copy_rect(dst, dst_linesize, frame->width, frame->height, sub->rects[i]);
276  sub2video_push_ref(ist, pts);
277  ist->sub2video.end_pts = end_pts;
278  ist->sub2video.initialize = 0;
279 }
280 
282 {
283  InputFile *infile = input_files[ist->file_index];
284  int i, j, nb_reqs;
285  int64_t pts2;
286 
287  /* When a frame is read from a file, examine all sub2video streams in
288  the same file and send the sub2video frame again. Otherwise, decoded
289  video frames could be accumulating in the filter graph while a filter
290  (possibly overlay) is desperately waiting for a subtitle frame. */
291  for (i = 0; i < infile->nb_streams; i++) {
292  InputStream *ist2 = input_streams[infile->ist_index + i];
293  if (!ist2->sub2video.frame)
294  continue;
295  /* subtitles seem to be usually muxed ahead of other streams;
296  if not, subtracting a larger time here is necessary */
297  pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
298  /* do not send the heartbeat frame if the subtitle is already ahead */
299  if (pts2 <= ist2->sub2video.last_pts)
300  continue;
301  if (pts2 >= ist2->sub2video.end_pts || ist2->sub2video.initialize)
302  /* if we have hit the end of the current displayed subpicture,
303  or if we need to initialize the system, update the
304  overlayed subpicture and its start/end times */
305  sub2video_update(ist2, pts2 + 1, NULL);
306  for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
307  nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
308  if (nb_reqs)
309  sub2video_push_ref(ist2, pts2);
310  }
311 }
312 
313 static void sub2video_flush(InputStream *ist)
314 {
315  int i;
316  int ret;
317 
318  if (ist->sub2video.end_pts < INT64_MAX)
319  sub2video_update(ist, INT64_MAX, NULL);
320  for (i = 0; i < ist->nb_filters; i++) {
321  ret = av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
322  if (ret != AVERROR_EOF && ret < 0)
323  av_log(NULL, AV_LOG_WARNING, "Flush the frame error.\n");
324  }
325 }
326 
327 /* end of sub2video hack */
328 
329 static void term_exit_sigsafe(void)
330 {
331 #if HAVE_TERMIOS_H
332  if(restore_tty)
333  tcsetattr (0, TCSANOW, &oldtty);
334 #endif
335 }
336 
337 void term_exit(void)
338 {
339  av_log(NULL, AV_LOG_QUIET, "%s", "");
341 }
342 
343 static volatile int received_sigterm = 0;
344 static volatile int received_nb_signals = 0;
346 static volatile int ffmpeg_exited = 0;
347 static int main_return_code = 0;
349 
350 static void
352 {
353  int ret;
354  received_sigterm = sig;
357  if(received_nb_signals > 3) {
358  ret = write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
359  strlen("Received > 3 system signals, hard exiting\n"));
360  if (ret < 0) { /* Do nothing */ };
361  exit(123);
362  }
363 }
364 
365 #if HAVE_SETCONSOLECTRLHANDLER
366 static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
367 {
368  av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
369 
370  switch (fdwCtrlType)
371  {
372  case CTRL_C_EVENT:
373  case CTRL_BREAK_EVENT:
374  sigterm_handler(SIGINT);
375  return TRUE;
376 
377  case CTRL_CLOSE_EVENT:
378  case CTRL_LOGOFF_EVENT:
379  case CTRL_SHUTDOWN_EVENT:
380  sigterm_handler(SIGTERM);
381  /* Basically, with these 3 events, when we return from this method the
382  process is hard terminated, so stall as long as we need to
383  to try and let the main thread(s) clean up and gracefully terminate
384  (we have at most 5 seconds, but should be done far before that). */
385  while (!ffmpeg_exited) {
386  Sleep(0);
387  }
388  return TRUE;
389 
390  default:
391  av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
392  return FALSE;
393  }
394 }
395 #endif
396 
397 #ifdef __linux__
398 #define SIGNAL(sig, func) \
399  do { \
400  action.sa_handler = func; \
401  sigaction(sig, &action, NULL); \
402  } while (0)
403 #else
404 #define SIGNAL(sig, func) \
405  signal(sig, func)
406 #endif
407 
408 void term_init(void)
409 {
410 #if defined __linux__
411  struct sigaction action = {0};
412  action.sa_handler = sigterm_handler;
413 
414  /* block other interrupts while processing this one */
415  sigfillset(&action.sa_mask);
416 
417  /* restart interruptible functions (i.e. don't fail with EINTR) */
418  action.sa_flags = SA_RESTART;
419 #endif
420 
421 #if HAVE_TERMIOS_H
422  /* A closed fd 0 is later reused by the first opened input file. read_key()
423  * would then read from that input instead of the terminal and corrupt the
424  * stream, so disable interaction when fd 0 is not an open descriptor.
425  */
426  if (stdin_interaction && fcntl(0, F_GETFD) == -1) {
428  "fd 0 is not an open file descriptor, stdin interaction disabled\n");
429  stdin_interaction = 0;
430  }
431 
433  struct termios tty;
434  if (tcgetattr (0, &tty) == 0) {
435  oldtty = tty;
436  restore_tty = 1;
437 
438  tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
439  |INLCR|IGNCR|ICRNL|IXON);
440  tty.c_oflag |= OPOST;
441  tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
442  tty.c_cflag &= ~(CSIZE|PARENB);
443  tty.c_cflag |= CS8;
444  tty.c_cc[VMIN] = 1;
445  tty.c_cc[VTIME] = 0;
446 
447  tcsetattr (0, TCSANOW, &tty);
448  }
449  SIGNAL(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
450  }
451 #endif
452 
453  SIGNAL(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
454  SIGNAL(SIGTERM, sigterm_handler); /* Termination (ANSI). */
455 #ifdef SIGXCPU
456  SIGNAL(SIGXCPU, sigterm_handler);
457 #endif
458 #ifdef SIGPIPE
459  signal(SIGPIPE, SIG_IGN); /* Broken pipe (POSIX). */
460 #endif
461 #if HAVE_SETCONSOLECTRLHANDLER
462  SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
463 #endif
464 }
465 
466 /* read a key without blocking */
467 static int read_key(void)
468 {
469  unsigned char ch;
470 #if HAVE_TERMIOS_H
471  int n = 1;
472  struct timeval tv;
473  fd_set rfds;
474 
475  FD_ZERO(&rfds);
476  FD_SET(0, &rfds);
477  tv.tv_sec = 0;
478  tv.tv_usec = 0;
479  n = select(1, &rfds, NULL, NULL, &tv);
480  if (n > 0) {
481  n = read(0, &ch, 1);
482  if (n == 1)
483  return ch;
484 
485  return n;
486  }
487 #elif HAVE_KBHIT
488 # if HAVE_PEEKNAMEDPIPE && HAVE_GETSTDHANDLE
489  static int is_pipe;
490  static HANDLE input_handle;
491  DWORD dw, nchars;
492  if(!input_handle){
493  input_handle = GetStdHandle(STD_INPUT_HANDLE);
494  is_pipe = !GetConsoleMode(input_handle, &dw);
495  }
496 
497  if (is_pipe) {
498  /* When running under a GUI, you will end here. */
499  if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
500  // input pipe may have been closed by the program that ran ffmpeg
501  return -1;
502  }
503  //Read it
504  if(nchars != 0) {
505  if (read(0, &ch, 1) == 1)
506  return ch;
507  return 0;
508  }else{
509  return -1;
510  }
511  }
512 # endif
513  if(kbhit())
514  return(getch());
515 #endif
516  return -1;
517 }
518 
519 static int decode_interrupt_cb(void *ctx)
520 {
522 }
523 
525 
526 static void ffmpeg_cleanup(int ret)
527 {
528  int i, j;
529 
530  if (do_benchmark) {
531  int maxrss = getmaxrss() / 1024;
532  av_log(NULL, AV_LOG_INFO, "bench: maxrss=%ikB\n", maxrss);
533  }
534 
535  for (i = 0; i < nb_filtergraphs; i++) {
536  FilterGraph *fg = filtergraphs[i];
538  for (j = 0; j < fg->nb_inputs; j++) {
539  InputFilter *ifilter = fg->inputs[j];
540  struct InputStream *ist = ifilter->ist;
541 
542  while (av_fifo_size(ifilter->frame_queue)) {
543  AVFrame *frame;
545  sizeof(frame), NULL);
547  }
548  av_fifo_freep(&ifilter->frame_queue);
549  if (ist->sub2video.sub_queue) {
550  while (av_fifo_size(ist->sub2video.sub_queue)) {
551  AVSubtitle sub;
553  &sub, sizeof(sub), NULL);
555  }
557  }
558  av_buffer_unref(&ifilter->hw_frames_ctx);
559  av_freep(&ifilter->name);
560  av_freep(&fg->inputs[j]);
561  }
562  av_freep(&fg->inputs);
563  for (j = 0; j < fg->nb_outputs; j++) {
564  OutputFilter *ofilter = fg->outputs[j];
565 
566  avfilter_inout_free(&ofilter->out_tmp);
567  av_freep(&ofilter->name);
568  av_freep(&ofilter->formats);
569  av_freep(&ofilter->channel_layouts);
570  av_freep(&ofilter->sample_rates);
571  av_freep(&fg->outputs[j]);
572  }
573  av_freep(&fg->outputs);
574  av_freep(&fg->graph_desc);
575 
577  }
579 
581 
582  /* close files */
583  for (i = 0; i < nb_output_files; i++) {
584  OutputFile *of = output_files[i];
586  if (!of)
587  continue;
588  s = of->ctx;
589  if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE))
590  avio_closep(&s->pb);
592  av_dict_free(&of->opts);
593 
595  }
596  for (i = 0; i < nb_output_streams; i++) {
598 
599  if (!ost)
600  continue;
601 
602  av_bsf_free(&ost->bsf_ctx);
603 
604  av_frame_free(&ost->filtered_frame);
605  av_frame_free(&ost->last_frame);
606  av_packet_free(&ost->pkt);
607  av_dict_free(&ost->encoder_opts);
608 
609  av_freep(&ost->forced_keyframes);
610  av_expr_free(ost->forced_keyframes_pexpr);
611  av_freep(&ost->avfilter);
612  av_freep(&ost->logfile_prefix);
613 
614  av_freep(&ost->audio_channels_map);
615  ost->audio_channels_mapped = 0;
616 
617  av_dict_free(&ost->sws_dict);
618  av_dict_free(&ost->swr_opts);
619 
620  avcodec_free_context(&ost->enc_ctx);
621  avcodec_parameters_free(&ost->ref_par);
622 
623  if (ost->muxing_queue) {
624  while (av_fifo_size(ost->muxing_queue)) {
625  AVPacket *pkt;
626  av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
628  }
629  av_fifo_freep(&ost->muxing_queue);
630  }
631 
633  }
634 #if HAVE_THREADS
635  free_input_threads();
636 #endif
637  for (i = 0; i < nb_input_files; i++) {
641  }
642  for (i = 0; i < nb_input_streams; i++) {
643  InputStream *ist = input_streams[i];
644 
647  av_packet_free(&ist->pkt);
648  av_dict_free(&ist->decoder_opts);
651  av_freep(&ist->filters);
652  av_freep(&ist->hwaccel_device);
653  av_freep(&ist->dts_buffer);
654 
656 
658  }
659 
660  if (vstats_file) {
661  if (fclose(vstats_file))
663  "Error closing vstats file, loss of information possible: %s\n",
664  av_err2str(AVERROR(errno)));
665  }
667 
672 
673  uninit_opts();
674 
676 
677  if (received_sigterm) {
678  av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
679  (int) received_sigterm);
680  } else if (ret && atomic_load(&transcode_init_done)) {
681  av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
682  }
683  term_exit();
684  ffmpeg_exited = 1;
685 }
686 
688 {
689  AVDictionaryEntry *t = NULL;
690 
691  while ((t = av_dict_get(b, "", t, AV_DICT_IGNORE_SUFFIX))) {
693  }
694 }
695 
697 {
699  if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
700  av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
701  exit_program(1);
702  }
703 }
704 
705 static void abort_codec_experimental(const AVCodec *c, int encoder)
706 {
707  exit_program(1);
708 }
709 
710 static void update_benchmark(const char *fmt, ...)
711 {
712  if (do_benchmark_all) {
714  va_list va;
715  char buf[1024];
716 
717  if (fmt) {
718  va_start(va, fmt);
719  vsnprintf(buf, sizeof(buf), fmt, va);
720  va_end(va);
722  "bench: %8" PRIu64 " user %8" PRIu64 " sys %8" PRIu64 " real %s \n",
725  t.real_usec - current_time.real_usec, buf);
726  }
727  current_time = t;
728  }
729 }
730 
732 {
733  int i;
734  for (i = 0; i < nb_output_streams; i++) {
735  OutputStream *ost2 = output_streams[i];
736  ost2->finished |= ost == ost2 ? this_stream : others;
737  }
738 }
739 
740 static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
741 {
742  AVFormatContext *s = of->ctx;
743  AVStream *st = ost->st;
744  int ret;
745 
746  /*
747  * Audio encoders may split the packets -- #frames in != #packets out.
748  * But there is no reordering, so we can limit the number of output packets
749  * by simply dropping them here.
750  * Counting encoded video frames needs to be done separately because of
751  * reordering, see do_video_out().
752  * Do not count the packet when unqueued because it has been counted when queued.
753  */
754  if (!(st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && ost->encoding_needed) && !unqueue) {
755  if (ost->frame_number >= ost->max_frames) {
757  return;
758  }
759  ost->frame_number++;
760  }
761 
762  if (!of->header_written) {
763  AVPacket *tmp_pkt;
764  /* the muxer is not initialized yet, buffer the packet */
765  if (!av_fifo_space(ost->muxing_queue)) {
766  size_t cur_size = av_fifo_size(ost->muxing_queue);
767  unsigned int are_we_over_size =
768  (ost->muxing_queue_data_size + pkt->size) > ost->muxing_queue_data_threshold;
769  size_t limit = are_we_over_size ? ost->max_muxing_queue_size : INT_MAX;
770  size_t new_size = FFMIN(2 * cur_size, limit);
771 
772  if (new_size <= cur_size) {
774  "Too many packets buffered for output stream %d:%d.\n",
775  ost->file_index, ost->st->index);
776  exit_program(1);
777  }
778  ret = av_fifo_realloc2(ost->muxing_queue, new_size);
779  if (ret < 0)
780  exit_program(1);
781  }
783  if (ret < 0)
784  exit_program(1);
785  tmp_pkt = av_packet_alloc();
786  if (!tmp_pkt)
787  exit_program(1);
788  av_packet_move_ref(tmp_pkt, pkt);
789  ost->muxing_queue_data_size += tmp_pkt->size;
790  av_fifo_generic_write(ost->muxing_queue, &tmp_pkt, sizeof(tmp_pkt), NULL);
791  return;
792  }
793 
796  pkt->pts = pkt->dts = AV_NOPTS_VALUE;
797 
799  int i;
801  NULL);
802  ost->quality = sd ? AV_RL32(sd) : -1;
803  ost->pict_type = sd ? sd[4] : AV_PICTURE_TYPE_NONE;
804 
805  for (i = 0; i<FF_ARRAY_ELEMS(ost->error); i++) {
806  if (sd && i < sd[5])
807  ost->error[i] = AV_RL64(sd + 8 + 8*i);
808  else
809  ost->error[i] = -1;
810  }
811 
812  if (ost->frame_rate.num && ost->is_cfr) {
813  if (pkt->duration > 0)
814  av_log(NULL, AV_LOG_WARNING, "Overriding packet duration by frame rate, this should not happen\n");
815  pkt->duration = av_rescale_q(1, av_inv_q(ost->frame_rate),
816  ost->mux_timebase);
817  }
818  }
819 
820  av_packet_rescale_ts(pkt, ost->mux_timebase, ost->st->time_base);
821 
822  if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS)) {
823  if (pkt->dts != AV_NOPTS_VALUE &&
824  pkt->pts != AV_NOPTS_VALUE &&
825  pkt->dts > pkt->pts) {
826  av_log(s, AV_LOG_WARNING, "Invalid DTS: %"PRId64" PTS: %"PRId64" in output stream %d:%d, replacing by guess\n",
827  pkt->dts, pkt->pts,
828  ost->file_index, ost->st->index);
829  pkt->pts =
830  pkt->dts = pkt->pts + pkt->dts + ost->last_mux_dts + 1
831  - FFMIN3(pkt->pts, pkt->dts, ost->last_mux_dts + 1)
832  - FFMAX3(pkt->pts, pkt->dts, ost->last_mux_dts + 1);
833  }
835  pkt->dts != AV_NOPTS_VALUE &&
836  !(st->codecpar->codec_id == AV_CODEC_ID_VP9 && ost->stream_copy) &&
837  ost->last_mux_dts != AV_NOPTS_VALUE) {
838  int64_t max = ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
839  if (pkt->dts < max) {
840  int loglevel = max - pkt->dts > 2 || st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG;
841  if (exit_on_error)
842  loglevel = AV_LOG_ERROR;
843  av_log(s, loglevel, "Non-monotonous DTS in output stream "
844  "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
845  ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
846  if (exit_on_error) {
847  av_log(NULL, AV_LOG_FATAL, "aborting.\n");
848  exit_program(1);
849  }
850  av_log(s, loglevel, "changing to %"PRId64". This may result "
851  "in incorrect timestamps in the output file.\n",
852  max);
853  if (pkt->pts >= pkt->dts)
854  pkt->pts = FFMAX(pkt->pts, max);
855  pkt->dts = max;
856  }
857  }
858  }
859  ost->last_mux_dts = pkt->dts;
860 
861  ost->data_size += pkt->size;
862  ost->packets_written++;
863 
865 
866  if (debug_ts) {
867  av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
868  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
869  av_get_media_type_string(ost->enc_ctx->codec_type),
872  pkt->size
873  );
874  }
875 
877  if (ret < 0) {
878  print_error("av_interleaved_write_frame()", ret);
879  main_return_code = 1;
881  }
883 }
884 
886 {
887  OutputFile *of = output_files[ost->file_index];
888 
889  ost->finished |= ENCODER_FINISHED;
890  if (of->shortest) {
891  int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, AV_TIME_BASE_Q);
892  of->recording_time = FFMIN(of->recording_time, end);
893  }
894 }
895 
896 /*
897  * Send a single packet to the output, applying any bitstream filters
898  * associated with the output stream. This may result in any number
899  * of packets actually being written, depending on what bitstream
900  * filters are applied. The supplied packet is consumed and will be
901  * blank (as if newly-allocated) when this function returns.
902  *
903  * If eof is set, instead indicate EOF to all bitstream filters and
904  * therefore flush any delayed packets to the output. A blank packet
905  * must be supplied in this case.
906  */
908  OutputStream *ost, int eof)
909 {
910  int ret = 0;
911 
912  /* apply the output bitstream filters */
913  if (ost->bsf_ctx) {
914  ret = av_bsf_send_packet(ost->bsf_ctx, eof ? NULL : pkt);
915  if (ret < 0)
916  goto finish;
917  while ((ret = av_bsf_receive_packet(ost->bsf_ctx, pkt)) >= 0)
918  write_packet(of, pkt, ost, 0);
919  if (ret == AVERROR(EAGAIN))
920  ret = 0;
921  } else if (!eof)
922  write_packet(of, pkt, ost, 0);
923 
924 finish:
925  if (ret < 0 && ret != AVERROR_EOF) {
926  av_log(NULL, AV_LOG_ERROR, "Error applying bitstream filters to an output "
927  "packet for stream #%d:%d.\n", ost->file_index, ost->index);
928  if(exit_on_error)
929  exit_program(1);
930  }
931 }
932 
934 {
935  OutputFile *of = output_files[ost->file_index];
936 
937  if (of->recording_time != INT64_MAX &&
938  av_compare_ts(ost->sync_opts - ost->first_pts, ost->enc_ctx->time_base, of->recording_time,
939  AV_TIME_BASE_Q) >= 0) {
941  return 0;
942  }
943  return 1;
944 }
945 
947  AVFrame *frame)
948 {
949  double float_pts = AV_NOPTS_VALUE; // this is identical to frame.pts but with higher precision
950  AVCodecContext *enc = ost->enc_ctx;
951  if (!frame || frame->pts == AV_NOPTS_VALUE ||
952  !enc || !ost->filter || !ost->filter->graph->graph)
953  goto early_exit;
954 
955  {
956  AVFilterContext *filter = ost->filter->filter;
957 
960  AVRational tb = enc->time_base;
961  int extra_bits = av_clip(29 - av_log2(tb.den), 0, 16);
962 
963  tb.den <<= extra_bits;
964  float_pts =
965  av_rescale_q(frame->pts, filter_tb, tb) -
967  float_pts /= 1 << extra_bits;
968  // 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
969  float_pts += FFSIGN(float_pts) * 1.0 / (1<<17);
970 
971  frame->pts =
972  av_rescale_q(frame->pts, filter_tb, enc->time_base) -
974  }
975 
976 early_exit:
977 
978  if (debug_ts) {
979  av_log(NULL, AV_LOG_INFO, "filter -> pts:%s pts_time:%s exact:%f time_base:%d/%d\n",
980  frame ? av_ts2str(frame->pts) : "NULL",
981  frame ? av_ts2timestr(frame->pts, &enc->time_base) : "NULL",
982  float_pts,
983  enc ? enc->time_base.num : -1,
984  enc ? enc->time_base.den : -1);
985  }
986 
987  return float_pts;
988 }
989 
991  char *error, int error_len);
992 
994  unsigned int fatal)
995 {
996  int ret = AVERROR_BUG;
997  char error[1024] = {0};
998 
999  if (ost->initialized)
1000  return 0;
1001 
1002  ret = init_output_stream(ost, frame, error, sizeof(error));
1003  if (ret < 0) {
1004  av_log(NULL, AV_LOG_ERROR, "Error initializing output stream %d:%d -- %s\n",
1005  ost->file_index, ost->index, error);
1006 
1007  if (fatal)
1008  exit_program(1);
1009  }
1010 
1011  return ret;
1012 }
1013 
1015  AVFrame *frame)
1016 {
1017  AVCodecContext *enc = ost->enc_ctx;
1018  AVPacket *pkt = ost->pkt;
1019  int ret;
1020 
1022 
1023  if (!check_recording_time(ost))
1024  return;
1025 
1026  if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
1027  frame->pts = ost->sync_opts;
1028  ost->sync_opts = frame->pts + frame->nb_samples;
1029  ost->samples_encoded += frame->nb_samples;
1030  ost->frames_encoded++;
1031 
1033  if (debug_ts) {
1034  av_log(NULL, AV_LOG_INFO, "encoder <- type:audio "
1035  "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1037  enc->time_base.num, enc->time_base.den);
1038  }
1039 
1040  ret = avcodec_send_frame(enc, frame);
1041  if (ret < 0)
1042  goto error;
1043 
1044  while (1) {
1046  ret = avcodec_receive_packet(enc, pkt);
1047  if (ret == AVERROR(EAGAIN))
1048  break;
1049  if (ret < 0)
1050  goto error;
1051 
1052  update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
1053 
1054  av_packet_rescale_ts(pkt, enc->time_base, ost->mux_timebase);
1055 
1056  if (debug_ts) {
1057  av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
1058  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1061  }
1062 
1063  output_packet(of, pkt, ost, 0);
1064  }
1065 
1066  return;
1067 error:
1068  av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
1069  exit_program(1);
1070 }
1071 
1072 static void do_subtitle_out(OutputFile *of,
1073  OutputStream *ost,
1074  AVSubtitle *sub)
1075 {
1076  int subtitle_out_max_size = 1024 * 1024;
1077  int subtitle_out_size, nb, i;
1078  AVCodecContext *enc;
1079  AVPacket *pkt = ost->pkt;
1080  int64_t pts;
1081 
1082  if (sub->pts == AV_NOPTS_VALUE) {
1083  av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
1084  if (exit_on_error)
1085  exit_program(1);
1086  return;
1087  }
1088 
1089  enc = ost->enc_ctx;
1090 
1091  if (!subtitle_out) {
1092  subtitle_out = av_malloc(subtitle_out_max_size);
1093  if (!subtitle_out) {
1094  av_log(NULL, AV_LOG_FATAL, "Failed to allocate subtitle_out\n");
1095  exit_program(1);
1096  }
1097  }
1098 
1099  /* Note: DVB subtitle need one packet to draw them and one other
1100  packet to clear them */
1101  /* XXX: signal it in the codec context ? */
1102  if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
1103  nb = 2;
1104  else
1105  nb = 1;
1106 
1107  /* shift timestamp to honor -ss and make check_recording_time() work with -t */
1108  pts = sub->pts;
1109  if (output_files[ost->file_index]->start_time != AV_NOPTS_VALUE)
1110  pts -= output_files[ost->file_index]->start_time;
1111  for (i = 0; i < nb; i++) {
1112  unsigned save_num_rects = sub->num_rects;
1113 
1114  ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
1115  if (!check_recording_time(ost))
1116  return;
1117 
1118  sub->pts = pts;
1119  // start_display_time is required to be 0
1120  sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
1121  sub->end_display_time -= sub->start_display_time;
1122  sub->start_display_time = 0;
1123  if (i == 1)
1124  sub->num_rects = 0;
1125 
1126  ost->frames_encoded++;
1127 
1128  subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
1129  subtitle_out_max_size, sub);
1130  if (i == 1)
1131  sub->num_rects = save_num_rects;
1132  if (subtitle_out_size < 0) {
1133  av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
1134  exit_program(1);
1135  }
1136 
1138  pkt->data = subtitle_out;
1139  pkt->size = subtitle_out_size;
1140  pkt->pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->mux_timebase);
1141  pkt->duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
1142  if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
1143  /* XXX: the pts correction is handled here. Maybe handling
1144  it in the codec would be better */
1145  if (i == 0)
1146  pkt->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
1147  else
1148  pkt->pts += av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->mux_timebase);
1149  }
1150  pkt->dts = pkt->pts;
1151  output_packet(of, pkt, ost, 0);
1152  }
1153 }
1154 
1155 static void do_video_out(OutputFile *of,
1156  OutputStream *ost,
1157  AVFrame *next_picture)
1158 {
1159  int ret, format_video_sync;
1160  AVPacket *pkt = ost->pkt;
1161  AVCodecContext *enc = ost->enc_ctx;
1162  AVRational frame_rate;
1163  int nb_frames, nb0_frames, i;
1164  double delta, delta0;
1165  double duration = 0;
1166  double sync_ipts = AV_NOPTS_VALUE;
1167  int frame_size = 0;
1168  InputStream *ist = NULL;
1169  AVFilterContext *filter = ost->filter->filter;
1170 
1171  init_output_stream_wrapper(ost, next_picture, 1);
1172  sync_ipts = adjust_frame_pts_to_encoder_tb(of, ost, next_picture);
1173 
1174  if (ost->source_index >= 0)
1175  ist = input_streams[ost->source_index];
1176 
1177  frame_rate = av_buffersink_get_frame_rate(filter);
1178  if (frame_rate.num > 0 && frame_rate.den > 0)
1179  duration = 1/(av_q2d(frame_rate) * av_q2d(enc->time_base));
1180 
1181  if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
1182  duration = FFMIN(duration, 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base)));
1183 
1184  if (!ost->filters_script &&
1185  !ost->filters &&
1186  (nb_filtergraphs == 0 || !filtergraphs[0]->graph_desc) &&
1187  next_picture &&
1188  ist &&
1189  lrintf(next_picture->pkt_duration * av_q2d(ist->st->time_base) / av_q2d(enc->time_base)) > 0) {
1190  duration = lrintf(next_picture->pkt_duration * av_q2d(ist->st->time_base) / av_q2d(enc->time_base));
1191  }
1192 
1193  if (!next_picture) {
1194  //end, flushing
1195  nb0_frames = nb_frames = mid_pred(ost->last_nb0_frames[0],
1196  ost->last_nb0_frames[1],
1197  ost->last_nb0_frames[2]);
1198  } else {
1199  delta0 = sync_ipts - ost->sync_opts; // delta0 is the "drift" between the input frame (next_picture) and where it would fall in the output.
1200  delta = delta0 + duration;
1201 
1202  /* by default, we output a single frame */
1203  nb0_frames = 0; // tracks the number of times the PREVIOUS frame should be duplicated, mostly for variable framerate (VFR)
1204  nb_frames = 1;
1205 
1206  format_video_sync = video_sync_method;
1207  if (format_video_sync == VSYNC_AUTO) {
1208  if(!strcmp(of->ctx->oformat->name, "avi")) {
1209  format_video_sync = VSYNC_VFR;
1210  } else
1211  format_video_sync = (of->ctx->oformat->flags & AVFMT_VARIABLE_FPS) ? ((of->ctx->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;
1212  if ( ist
1213  && format_video_sync == VSYNC_CFR
1214  && input_files[ist->file_index]->ctx->nb_streams == 1
1215  && input_files[ist->file_index]->input_ts_offset == 0) {
1216  format_video_sync = VSYNC_VSCFR;
1217  }
1218  if (format_video_sync == VSYNC_CFR && copy_ts) {
1219  format_video_sync = VSYNC_VSCFR;
1220  }
1221  }
1222  ost->is_cfr = (format_video_sync == VSYNC_CFR || format_video_sync == VSYNC_VSCFR);
1223 
1224  if (delta0 < 0 &&
1225  delta > 0 &&
1226  format_video_sync != VSYNC_PASSTHROUGH &&
1227  format_video_sync != VSYNC_DROP) {
1228  if (delta0 < -0.6) {
1229  av_log(NULL, AV_LOG_VERBOSE, "Past duration %f too large\n", -delta0);
1230  } else
1231  av_log(NULL, AV_LOG_DEBUG, "Clipping frame in rate conversion by %f\n", -delta0);
1232  sync_ipts = ost->sync_opts;
1233  duration += delta0;
1234  delta0 = 0;
1235  }
1236 
1237  switch (format_video_sync) {
1238  case VSYNC_VSCFR:
1239  if (ost->frame_number == 0 && delta0 >= 0.5) {
1240  av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta0));
1241  delta = duration;
1242  delta0 = 0;
1243  ost->sync_opts = llrint(sync_ipts);
1244  }
1245  case VSYNC_CFR:
1246  // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
1247  if (frame_drop_threshold && delta < frame_drop_threshold && ost->frame_number) {
1248  nb_frames = 0;
1249  } else if (delta < -1.1)
1250  nb_frames = 0;
1251  else if (delta > 1.1) {
1252  nb_frames = lrintf(delta);
1253  if (delta0 > 1.1)
1254  nb0_frames = llrintf(delta0 - 0.6);
1255  }
1256  break;
1257  case VSYNC_VFR:
1258  if (delta <= -0.6)
1259  nb_frames = 0;
1260  else if (delta > 0.6)
1261  ost->sync_opts = llrint(sync_ipts);
1262  break;
1263  case VSYNC_DROP:
1264  case VSYNC_PASSTHROUGH:
1265  ost->sync_opts = llrint(sync_ipts);
1266  break;
1267  default:
1268  av_assert0(0);
1269  }
1270  }
1271 
1272  nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
1273  nb0_frames = FFMIN(nb0_frames, nb_frames);
1274 
1275  memmove(ost->last_nb0_frames + 1,
1276  ost->last_nb0_frames,
1277  sizeof(ost->last_nb0_frames[0]) * (FF_ARRAY_ELEMS(ost->last_nb0_frames) - 1));
1278  ost->last_nb0_frames[0] = nb0_frames;
1279 
1280  if (nb0_frames == 0 && ost->last_dropped) {
1281  nb_frames_drop++;
1283  "*** dropping frame %d from stream %d at ts %"PRId64"\n",
1284  ost->frame_number, ost->st->index, ost->last_frame->pts);
1285  }
1286  if (nb_frames > (nb0_frames && ost->last_dropped) + (nb_frames > nb0_frames)) {
1287  if (nb_frames > dts_error_threshold * 30) {
1288  av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
1289  nb_frames_drop++;
1290  return;
1291  }
1292  nb_frames_dup += nb_frames - (nb0_frames && ost->last_dropped) - (nb_frames > nb0_frames);
1293  av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
1294  if (nb_frames_dup > dup_warning) {
1295  av_log(NULL, AV_LOG_WARNING, "More than %d frames duplicated\n", dup_warning);
1296  dup_warning *= 10;
1297  }
1298  }
1299  ost->last_dropped = nb_frames == nb0_frames && next_picture;
1300 
1301  /* duplicates frame if needed */
1302  for (i = 0; i < nb_frames; i++) {
1303  AVFrame *in_picture;
1304  int forced_keyframe = 0;
1305  double pts_time;
1306 
1307  if (i < nb0_frames && ost->last_frame->buf[0]) {
1308  in_picture = ost->last_frame;
1309  } else
1310  in_picture = next_picture;
1311 
1312  if (!in_picture)
1313  return;
1314 
1315  in_picture->pts = ost->sync_opts;
1316 
1317  if (!check_recording_time(ost))
1318  return;
1319 
1320  in_picture->quality = enc->global_quality;
1321  in_picture->pict_type = 0;
1322 
1323  if (ost->forced_kf_ref_pts == AV_NOPTS_VALUE &&
1324  in_picture->pts != AV_NOPTS_VALUE)
1325  ost->forced_kf_ref_pts = in_picture->pts;
1326 
1327  pts_time = in_picture->pts != AV_NOPTS_VALUE ?
1328  (in_picture->pts - ost->forced_kf_ref_pts) * av_q2d(enc->time_base) : NAN;
1329  if (ost->forced_kf_index < ost->forced_kf_count &&
1330  in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
1331  ost->forced_kf_index++;
1332  forced_keyframe = 1;
1333  } else if (ost->forced_keyframes_pexpr) {
1334  double res;
1335  ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
1336  res = av_expr_eval(ost->forced_keyframes_pexpr,
1337  ost->forced_keyframes_expr_const_values, NULL);
1338  ff_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
1339  ost->forced_keyframes_expr_const_values[FKF_N],
1340  ost->forced_keyframes_expr_const_values[FKF_N_FORCED],
1341  ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],
1342  ost->forced_keyframes_expr_const_values[FKF_T],
1343  ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],
1344  res);
1345  if (res) {
1346  forced_keyframe = 1;
1347  ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =
1348  ost->forced_keyframes_expr_const_values[FKF_N];
1349  ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =
1350  ost->forced_keyframes_expr_const_values[FKF_T];
1351  ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;
1352  }
1353 
1354  ost->forced_keyframes_expr_const_values[FKF_N] += 1;
1355  } else if ( ost->forced_keyframes
1356  && !strncmp(ost->forced_keyframes, "source", 6)
1357  && in_picture->key_frame==1
1358  && !i) {
1359  forced_keyframe = 1;
1360  }
1361 
1362  if (forced_keyframe) {
1363  in_picture->pict_type = AV_PICTURE_TYPE_I;
1364  av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
1365  }
1366 
1368  if (debug_ts) {
1369  av_log(NULL, AV_LOG_INFO, "encoder <- type:video "
1370  "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",
1371  av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),
1372  enc->time_base.num, enc->time_base.den);
1373  }
1374 
1375  ost->frames_encoded++;
1376 
1377  ret = avcodec_send_frame(enc, in_picture);
1378  if (ret < 0)
1379  goto error;
1380  // Make sure Closed Captions will not be duplicated
1382 
1383  while (1) {
1385  ret = avcodec_receive_packet(enc, pkt);
1386  update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
1387  if (ret == AVERROR(EAGAIN))
1388  break;
1389  if (ret < 0)
1390  goto error;
1391 
1392  if (debug_ts) {
1393  av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1394  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1397  }
1398 
1400  pkt->pts = ost->sync_opts;
1401 
1402  av_packet_rescale_ts(pkt, enc->time_base, ost->mux_timebase);
1403 
1404  if (debug_ts) {
1405  av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
1406  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
1407  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->mux_timebase),
1408  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->mux_timebase));
1409  }
1410 
1411  frame_size = pkt->size;
1412  output_packet(of, pkt, ost, 0);
1413 
1414  /* if two pass, output log */
1415  if (ost->logfile && enc->stats_out) {
1416  fprintf(ost->logfile, "%s", enc->stats_out);
1417  }
1418  }
1419  ost->sync_opts++;
1420  /*
1421  * For video, number of frames in == number of packets out.
1422  * But there may be reordering, so we can't throw away frames on encoder
1423  * flush, we need to limit them here, before they go into encoder.
1424  */
1425  ost->frame_number++;
1426 
1427  if (vstats_filename && frame_size)
1429  }
1430 
1431  av_frame_unref(ost->last_frame);
1432  if (next_picture)
1433  if (av_frame_ref(ost->last_frame, next_picture) < 0)
1434  goto error;
1435 
1436  return;
1437 error:
1438  av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
1439  exit_program(1);
1440 }
1441 
1442 static double psnr(double d)
1443 {
1444  return -10.0 * log10(d);
1445 }
1446 
1448 {
1449  AVCodecContext *enc;
1450  int frame_number;
1451  double ti1, bitrate, avg_bitrate;
1452 
1453  /* this is executed just the first time do_video_stats is called */
1454  if (!vstats_file) {
1455  vstats_file = fopen(vstats_filename, "w");
1456  if (!vstats_file) {
1457  perror("fopen");
1458  exit_program(1);
1459  }
1460  }
1461 
1462  enc = ost->enc_ctx;
1463  if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1464  frame_number = ost->st->nb_frames;
1465  if (vstats_version <= 1) {
1466  fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number,
1467  ost->quality / (float)FF_QP2LAMBDA);
1468  } else {
1469  fprintf(vstats_file, "out= %2d st= %2d frame= %5d q= %2.1f ", ost->file_index, ost->index, frame_number,
1470  ost->quality / (float)FF_QP2LAMBDA);
1471  }
1472 
1473  if (ost->error[0]>=0 && (enc->flags & AV_CODEC_FLAG_PSNR))
1474  fprintf(vstats_file, "PSNR= %6.2f ", psnr(ost->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1475 
1476  fprintf(vstats_file,"f_size= %6d ", frame_size);
1477  /* compute pts value */
1478  ti1 = av_stream_get_end_pts(ost->st) * av_q2d(ost->st->time_base);
1479  if (ti1 < 0.01)
1480  ti1 = 0.01;
1481 
1482  bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1483  avg_bitrate = (double)(ost->data_size * 8) / ti1 / 1000.0;
1484  fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1485  (double)ost->data_size / 1024, ti1, bitrate, avg_bitrate);
1486  fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(ost->pict_type));
1487  }
1488 }
1489 
1491 {
1492  OutputFile *of = output_files[ost->file_index];
1493  int i;
1494 
1495  ost->finished = ENCODER_FINISHED | MUXER_FINISHED;
1496 
1497  if (of->shortest) {
1498  for (i = 0; i < of->ctx->nb_streams; i++)
1500  }
1501 }
1502 
1503 /**
1504  * Get and encode new output from any of the filtergraphs, without causing
1505  * activity.
1506  *
1507  * @return 0 for success, <0 for severe errors
1508  */
1509 static int reap_filters(int flush)
1510 {
1511  AVFrame *filtered_frame = NULL;
1512  int i;
1513 
1514  /* Reap all buffers present in the buffer sinks */
1515  for (i = 0; i < nb_output_streams; i++) {
1517  OutputFile *of = output_files[ost->file_index];
1519  AVCodecContext *enc = ost->enc_ctx;
1520  int ret = 0;
1521 
1522  if (!ost->filter || !ost->filter->graph->graph)
1523  continue;
1524  filter = ost->filter->filter;
1525 
1526  /*
1527  * Unlike video, with audio the audio frame size matters.
1528  * Currently we are fully reliant on the lavfi filter chain to
1529  * do the buffering deed for us, and thus the frame size parameter
1530  * needs to be set accordingly. Where does one get the required
1531  * frame size? From the initialized AVCodecContext of an audio
1532  * encoder. Thus, if we have gotten to an audio stream, initialize
1533  * the encoder earlier than receiving the first AVFrame.
1534  */
1537 
1538  if (!ost->pkt && !(ost->pkt = av_packet_alloc())) {
1539  return AVERROR(ENOMEM);
1540  }
1541  if (!ost->filtered_frame && !(ost->filtered_frame = av_frame_alloc())) {
1542  return AVERROR(ENOMEM);
1543  }
1544  filtered_frame = ost->filtered_frame;
1545 
1546  while (1) {
1547  ret = av_buffersink_get_frame_flags(filter, filtered_frame,
1549  if (ret < 0) {
1550  if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
1552  "Error in av_buffersink_get_frame_flags(): %s\n", av_err2str(ret));
1553  } else if (flush && ret == AVERROR_EOF) {
1555  do_video_out(of, ost, NULL);
1556  }
1557  break;
1558  }
1559  if (ost->finished) {
1560  av_frame_unref(filtered_frame);
1561  continue;
1562  }
1563 
1564  switch (av_buffersink_get_type(filter)) {
1565  case AVMEDIA_TYPE_VIDEO:
1566  if (!ost->frame_aspect_ratio.num)
1567  enc->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
1568 
1569  do_video_out(of, ost, filtered_frame);
1570  break;
1571  case AVMEDIA_TYPE_AUDIO:
1572  if (!(enc->codec->capabilities & AV_CODEC_CAP_PARAM_CHANGE) &&
1573  enc->channels != filtered_frame->channels) {
1575  "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1576  break;
1577  }
1578  do_audio_out(of, ost, filtered_frame);
1579  break;
1580  default:
1581  // TODO support subtitle filters
1582  av_assert0(0);
1583  }
1584 
1585  av_frame_unref(filtered_frame);
1586  }
1587  }
1588 
1589  return 0;
1590 }
1591 
1592 static void print_final_stats(int64_t total_size)
1593 {
1594  uint64_t video_size = 0, audio_size = 0, extra_size = 0, other_size = 0;
1595  uint64_t subtitle_size = 0;
1596  uint64_t data_size = 0;
1597  float percent = -1.0;
1598  int i, j;
1599  int pass1_used = 1;
1600 
1601  for (i = 0; i < nb_output_streams; i++) {
1603  switch (ost->enc_ctx->codec_type) {
1604  case AVMEDIA_TYPE_VIDEO: video_size += ost->data_size; break;
1605  case AVMEDIA_TYPE_AUDIO: audio_size += ost->data_size; break;
1606  case AVMEDIA_TYPE_SUBTITLE: subtitle_size += ost->data_size; break;
1607  default: other_size += ost->data_size; break;
1608  }
1609  extra_size += ost->enc_ctx->extradata_size;
1610  data_size += ost->data_size;
1611  if ( (ost->enc_ctx->flags & (AV_CODEC_FLAG_PASS1 | AV_CODEC_FLAG_PASS2))
1613  pass1_used = 0;
1614  }
1615 
1616  if (data_size && total_size>0 && total_size >= data_size)
1617  percent = 100.0 * (total_size - data_size) / data_size;
1618 
1619  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: ",
1620  video_size / 1024.0,
1621  audio_size / 1024.0,
1622  subtitle_size / 1024.0,
1623  other_size / 1024.0,
1624  extra_size / 1024.0);
1625  if (percent >= 0.0)
1626  av_log(NULL, AV_LOG_INFO, "%f%%", percent);
1627  else
1628  av_log(NULL, AV_LOG_INFO, "unknown");
1629  av_log(NULL, AV_LOG_INFO, "\n");
1630 
1631  /* print verbose per-stream stats */
1632  for (i = 0; i < nb_input_files; i++) {
1633  InputFile *f = input_files[i];
1634  uint64_t total_packets = 0, total_size = 0;
1635 
1636  av_log(NULL, AV_LOG_VERBOSE, "Input file #%d (%s):\n",
1637  i, f->ctx->url);
1638 
1639  for (j = 0; j < f->nb_streams; j++) {
1640  InputStream *ist = input_streams[f->ist_index + j];
1641  enum AVMediaType type = ist->dec_ctx->codec_type;
1642 
1643  total_size += ist->data_size;
1644  total_packets += ist->nb_packets;
1645 
1646  av_log(NULL, AV_LOG_VERBOSE, " Input stream #%d:%d (%s): ",
1647  i, j, media_type_string(type));
1648  av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets read (%"PRIu64" bytes); ",
1649  ist->nb_packets, ist->data_size);
1650 
1651  if (ist->decoding_needed) {
1652  av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames decoded",
1653  ist->frames_decoded);
1654  if (type == AVMEDIA_TYPE_AUDIO)
1655  av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ist->samples_decoded);
1656  av_log(NULL, AV_LOG_VERBOSE, "; ");
1657  }
1658 
1659  av_log(NULL, AV_LOG_VERBOSE, "\n");
1660  }
1661 
1662  av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) demuxed\n",
1663  total_packets, total_size);
1664  }
1665 
1666  for (i = 0; i < nb_output_files; i++) {
1667  OutputFile *of = output_files[i];
1668  uint64_t total_packets = 0, total_size = 0;
1669 
1670  av_log(NULL, AV_LOG_VERBOSE, "Output file #%d (%s):\n",
1671  i, of->ctx->url);
1672 
1673  for (j = 0; j < of->ctx->nb_streams; j++) {
1675  enum AVMediaType type = ost->enc_ctx->codec_type;
1676 
1677  total_size += ost->data_size;
1678  total_packets += ost->packets_written;
1679 
1680  av_log(NULL, AV_LOG_VERBOSE, " Output stream #%d:%d (%s): ",
1681  i, j, media_type_string(type));
1682  if (ost->encoding_needed) {
1683  av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" frames encoded",
1684  ost->frames_encoded);
1685  if (type == AVMEDIA_TYPE_AUDIO)
1686  av_log(NULL, AV_LOG_VERBOSE, " (%"PRIu64" samples)", ost->samples_encoded);
1687  av_log(NULL, AV_LOG_VERBOSE, "; ");
1688  }
1689 
1690  av_log(NULL, AV_LOG_VERBOSE, "%"PRIu64" packets muxed (%"PRIu64" bytes); ",
1691  ost->packets_written, ost->data_size);
1692 
1693  av_log(NULL, AV_LOG_VERBOSE, "\n");
1694  }
1695 
1696  av_log(NULL, AV_LOG_VERBOSE, " Total: %"PRIu64" packets (%"PRIu64" bytes) muxed\n",
1697  total_packets, total_size);
1698  }
1699  if(video_size + data_size + audio_size + subtitle_size + extra_size == 0){
1700  av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded ");
1701  if (pass1_used) {
1702  av_log(NULL, AV_LOG_WARNING, "\n");
1703  } else {
1704  av_log(NULL, AV_LOG_WARNING, "(check -ss / -t / -frames parameters if used)\n");
1705  }
1706  }
1707 }
1708 
1709 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
1710 {
1711  AVBPrint buf, buf_script;
1712  OutputStream *ost;
1713  AVFormatContext *oc;
1714  int64_t total_size;
1715  AVCodecContext *enc;
1716  int frame_number, vid, i;
1717  double bitrate;
1718  double speed;
1719  int64_t pts = INT64_MIN + 1;
1720  static int64_t last_time = -1;
1721  static int first_report = 1;
1722  static int qp_histogram[52];
1723  int hours, mins, secs, us;
1724  const char *hours_sign;
1725  int ret;
1726  float t;
1727 
1728  if (!print_stats && !is_last_report && !progress_avio)
1729  return;
1730 
1731  if (!is_last_report) {
1732  if (last_time == -1) {
1733  last_time = cur_time;
1734  }
1735  if (((cur_time - last_time) < stats_period && !first_report) ||
1736  (first_report && nb_output_dumped < nb_output_files))
1737  return;
1738  last_time = cur_time;
1739  }
1740 
1741  t = (cur_time-timer_start) / 1000000.0;
1742 
1743 
1744  oc = output_files[0]->ctx;
1745 
1746  total_size = avio_size(oc->pb);
1747  if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
1748  total_size = avio_tell(oc->pb);
1749 
1750  vid = 0;
1752  av_bprint_init(&buf_script, 0, AV_BPRINT_SIZE_AUTOMATIC);
1753  for (i = 0; i < nb_output_streams; i++) {
1754  float q = -1;
1755  ost = output_streams[i];
1756  enc = ost->enc_ctx;
1757  if (!ost->stream_copy)
1758  q = ost->quality / (float) FF_QP2LAMBDA;
1759 
1760  if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1761  av_bprintf(&buf, "q=%2.1f ", q);
1762  av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1763  ost->file_index, ost->index, q);
1764  }
1765  if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1766  float fps;
1767 
1768  frame_number = ost->frame_number;
1769  fps = t > 1 ? frame_number / t : 0;
1770  av_bprintf(&buf, "frame=%5d fps=%3.*f q=%3.1f ",
1771  frame_number, fps < 9.95, fps, q);
1772  av_bprintf(&buf_script, "frame=%d\n", frame_number);
1773  av_bprintf(&buf_script, "fps=%.2f\n", fps);
1774  av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1775  ost->file_index, ost->index, q);
1776  if (is_last_report)
1777  av_bprintf(&buf, "L");
1778  if (qp_hist) {
1779  int j;
1780  int qp = lrintf(q);
1781  if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1782  qp_histogram[qp]++;
1783  for (j = 0; j < 32; j++)
1784  av_bprintf(&buf, "%X", av_log2(qp_histogram[j] + 1));
1785  }
1786 
1787  if ((enc->flags & AV_CODEC_FLAG_PSNR) && (ost->pict_type != AV_PICTURE_TYPE_NONE || is_last_report)) {
1788  int j;
1789  double error, error_sum = 0;
1790  double scale, scale_sum = 0;
1791  double p;
1792  char type[3] = { 'Y','U','V' };
1793  av_bprintf(&buf, "PSNR=");
1794  for (j = 0; j < 3; j++) {
1795  if (is_last_report) {
1796  error = enc->error[j];
1797  scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1798  } else {
1799  error = ost->error[j];
1800  scale = enc->width * enc->height * 255.0 * 255.0;
1801  }
1802  if (j)
1803  scale /= 4;
1804  error_sum += error;
1805  scale_sum += scale;
1806  p = psnr(error / scale);
1807  av_bprintf(&buf, "%c:%2.2f ", type[j], p);
1808  av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
1809  ost->file_index, ost->index, type[j] | 32, p);
1810  }
1811  p = psnr(error_sum / scale_sum);
1812  av_bprintf(&buf, "*:%2.2f ", psnr(error_sum / scale_sum));
1813  av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
1814  ost->file_index, ost->index, p);
1815  }
1816  vid = 1;
1817  }
1818  /* compute min output value */
1821  ost->st->time_base, AV_TIME_BASE_Q));
1822  if (copy_ts) {
1823  if (copy_ts_first_pts == AV_NOPTS_VALUE && pts > 1)
1827  }
1828  }
1829 
1830  if (is_last_report)
1831  nb_frames_drop += ost->last_dropped;
1832  }
1833 
1834  secs = FFABS(pts) / AV_TIME_BASE;
1835  us = FFABS(pts) % AV_TIME_BASE;
1836  mins = secs / 60;
1837  secs %= 60;
1838  hours = mins / 60;
1839  mins %= 60;
1840  hours_sign = (pts < 0) ? "-" : "";
1841 
1842  bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
1843  speed = t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
1844 
1845  if (total_size < 0) av_bprintf(&buf, "size=N/A time=");
1846  else av_bprintf(&buf, "size=%8.0fkB time=", total_size / 1024.0);
1847  if (pts == AV_NOPTS_VALUE) {
1848  av_bprintf(&buf, "N/A ");
1849  } else {
1850  av_bprintf(&buf, "%s%02d:%02d:%02d.%02d ",
1851  hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
1852  }
1853 
1854  if (bitrate < 0) {
1855  av_bprintf(&buf, "bitrate=N/A");
1856  av_bprintf(&buf_script, "bitrate=N/A\n");
1857  }else{
1858  av_bprintf(&buf, "bitrate=%6.1fkbits/s", bitrate);
1859  av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
1860  }
1861 
1862  if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
1863  else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
1864  if (pts == AV_NOPTS_VALUE) {
1865  av_bprintf(&buf_script, "out_time_us=N/A\n");
1866  av_bprintf(&buf_script, "out_time_ms=N/A\n");
1867  av_bprintf(&buf_script, "out_time=N/A\n");
1868  } else {
1869  av_bprintf(&buf_script, "out_time_us=%"PRId64"\n", pts);
1870  av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
1871  av_bprintf(&buf_script, "out_time=%s%02d:%02d:%02d.%06d\n",
1872  hours_sign, hours, mins, secs, us);
1873  }
1874 
1876  av_bprintf(&buf, " dup=%d drop=%d", nb_frames_dup, nb_frames_drop);
1877  av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
1878  av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
1879 
1880  if (speed < 0) {
1881  av_bprintf(&buf, " speed=N/A");
1882  av_bprintf(&buf_script, "speed=N/A\n");
1883  } else {
1884  av_bprintf(&buf, " speed=%4.3gx", speed);
1885  av_bprintf(&buf_script, "speed=%4.3gx\n", speed);
1886  }
1887 
1888  if (print_stats || is_last_report) {
1889  const char end = is_last_report ? '\n' : '\r';
1890  if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
1891  fprintf(stderr, "%s %c", buf.str, end);
1892  } else
1893  av_log(NULL, AV_LOG_INFO, "%s %c", buf.str, end);
1894 
1895  fflush(stderr);
1896  }
1897  av_bprint_finalize(&buf, NULL);
1898 
1899  if (progress_avio) {
1900  av_bprintf(&buf_script, "progress=%s\n",
1901  is_last_report ? "end" : "continue");
1902  avio_write(progress_avio, buf_script.str,
1903  FFMIN(buf_script.len, buf_script.size - 1));
1905  av_bprint_finalize(&buf_script, NULL);
1906  if (is_last_report) {
1907  if ((ret = avio_closep(&progress_avio)) < 0)
1909  "Error closing progress log, loss of information possible: %s\n", av_err2str(ret));
1910  }
1911  }
1912 
1913  first_report = 0;
1914 
1915  if (is_last_report)
1916  print_final_stats(total_size);
1917 }
1918 
1920 {
1921  // We never got any input. Set a fake format, which will
1922  // come from libavformat.
1923  ifilter->format = par->format;
1924  ifilter->sample_rate = par->sample_rate;
1925  ifilter->channels = par->channels;
1926  ifilter->channel_layout = par->channel_layout;
1927  ifilter->width = par->width;
1928  ifilter->height = par->height;
1929  ifilter->sample_aspect_ratio = par->sample_aspect_ratio;
1930 }
1931 
1932 static void flush_encoders(void)
1933 {
1934  int i, ret;
1935 
1936  for (i = 0; i < nb_output_streams; i++) {
1938  AVCodecContext *enc = ost->enc_ctx;
1939  OutputFile *of = output_files[ost->file_index];
1940 
1941  if (!ost->encoding_needed)
1942  continue;
1943 
1944  // Try to enable encoding with no input frames.
1945  // Maybe we should just let encoding fail instead.
1946  if (!ost->initialized) {
1947  FilterGraph *fg = ost->filter->graph;
1948 
1950  "Finishing stream %d:%d without any data written to it.\n",
1951  ost->file_index, ost->st->index);
1952 
1953  if (ost->filter && !fg->graph) {
1954  int x;
1955  for (x = 0; x < fg->nb_inputs; x++) {
1956  InputFilter *ifilter = fg->inputs[x];
1957  if (ifilter->format < 0)
1958  ifilter_parameters_from_codecpar(ifilter, ifilter->ist->st->codecpar);
1959  }
1960 
1962  continue;
1963 
1964  ret = configure_filtergraph(fg);
1965  if (ret < 0) {
1966  av_log(NULL, AV_LOG_ERROR, "Error configuring filter graph\n");
1967  exit_program(1);
1968  }
1969 
1971  }
1972 
1974  }
1975 
1977  continue;
1978 
1979  for (;;) {
1980  const char *desc = NULL;
1981  AVPacket *pkt = ost->pkt;
1982  int pkt_size;
1983 
1984  if (!pkt)
1985  break;
1986 
1987  switch (enc->codec_type) {
1988  case AVMEDIA_TYPE_AUDIO:
1989  desc = "audio";
1990  break;
1991  case AVMEDIA_TYPE_VIDEO:
1992  desc = "video";
1993  break;
1994  default:
1995  av_assert0(0);
1996  }
1997 
1999 
2001  while ((ret = avcodec_receive_packet(enc, pkt)) == AVERROR(EAGAIN)) {
2002  ret = avcodec_send_frame(enc, NULL);
2003  if (ret < 0) {
2004  av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
2005  desc,
2006  av_err2str(ret));
2007  exit_program(1);
2008  }
2009  }
2010 
2011  update_benchmark("flush_%s %d.%d", desc, ost->file_index, ost->index);
2012  if (ret < 0 && ret != AVERROR_EOF) {
2013  av_log(NULL, AV_LOG_FATAL, "%s encoding failed: %s\n",
2014  desc,
2015  av_err2str(ret));
2016  exit_program(1);
2017  }
2018  if (ost->logfile && enc->stats_out) {
2019  fprintf(ost->logfile, "%s", enc->stats_out);
2020  }
2021  if (ret == AVERROR_EOF) {
2022  output_packet(of, pkt, ost, 1);
2023  break;
2024  }
2025  if (ost->finished & MUXER_FINISHED) {
2027  continue;
2028  }
2029  av_packet_rescale_ts(pkt, enc->time_base, ost->mux_timebase);
2030  pkt_size = pkt->size;
2031  output_packet(of, pkt, ost, 0);
2032  if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
2033  do_video_stats(ost, pkt_size);
2034  }
2035  }
2036  }
2037 }
2038 
2039 /*
2040  * Check whether a packet from ist should be written into ost at this time
2041  */
2043 {
2044  OutputFile *of = output_files[ost->file_index];
2045  int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
2046 
2047  if (ost->source_index != ist_index)
2048  return 0;
2049 
2050  if (ost->finished)
2051  return 0;
2052 
2053  if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
2054  return 0;
2055 
2056  return 1;
2057 }
2058 
2060 {
2061  OutputFile *of = output_files[ost->file_index];
2062  InputFile *f = input_files [ist->file_index];
2063  int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
2064  int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->mux_timebase);
2065  AVPacket *opkt = ost->pkt;
2066 
2067  av_packet_unref(opkt);
2068  // EOF: flush output bitstream filters.
2069  if (!pkt) {
2070  output_packet(of, opkt, ost, 1);
2071  return;
2072  }
2073 
2074  if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
2075  !ost->copy_initial_nonkeyframes)
2076  return;
2077 
2078  if (!ost->frame_number && !ost->copy_prior_start) {
2079  int64_t comp_start = start_time;
2080  if (copy_ts && f->start_time != AV_NOPTS_VALUE)
2081  comp_start = FFMAX(start_time, f->start_time + f->ts_offset);
2082  if (pkt->pts == AV_NOPTS_VALUE ?
2083  ist->pts < comp_start :
2084  pkt->pts < av_rescale_q(comp_start, AV_TIME_BASE_Q, ist->st->time_base))
2085  return;
2086  }
2087 
2088  if (of->recording_time != INT64_MAX &&
2089  ist->pts >= of->recording_time + start_time) {
2091  return;
2092  }
2093 
2094  if (f->recording_time != INT64_MAX) {
2095  start_time = 0;
2096  if (copy_ts) {
2097  start_time += f->start_time != AV_NOPTS_VALUE ? f->start_time : 0;
2098  start_time += start_at_zero ? 0 : f->ctx->start_time;
2099  }
2100  if (ist->pts >= f->recording_time + start_time) {
2102  return;
2103  }
2104  }
2105 
2106  /* force the input stream PTS */
2107  if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
2108  ost->sync_opts++;
2109 
2110  if (av_packet_ref(opkt, pkt) < 0)
2111  exit_program(1);
2112 
2113  if (pkt->pts != AV_NOPTS_VALUE)
2114  opkt->pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->mux_timebase) - ost_tb_start_time;
2115 
2116  if (pkt->dts == AV_NOPTS_VALUE) {
2117  opkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->mux_timebase);
2118  } else if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
2120  if(!duration)
2121  duration = ist->dec_ctx->frame_size;
2122  opkt->dts = av_rescale_delta(ist->st->time_base, pkt->dts,
2123  (AVRational){1, ist->dec_ctx->sample_rate}, duration,
2124  &ist->filter_in_rescale_delta_last, ost->mux_timebase);
2125  /* dts will be set immediately afterwards to what pts is now */
2126  opkt->pts = opkt->dts - ost_tb_start_time;
2127  } else
2128  opkt->dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->mux_timebase);
2129  opkt->dts -= ost_tb_start_time;
2130 
2131  opkt->duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->mux_timebase);
2132 
2133  output_packet(of, opkt, ost, 0);
2134 }
2135 
2137 {
2138  AVCodecContext *dec = ist->dec_ctx;
2139 
2140  if (!dec->channel_layout) {
2141  char layout_name[256];
2142 
2143  if (dec->channels > ist->guess_layout_max)
2144  return 0;
2145  dec->channel_layout = av_get_default_channel_layout(dec->channels);
2146  if (!dec->channel_layout)
2147  return 0;
2148  av_get_channel_layout_string(layout_name, sizeof(layout_name),
2149  dec->channels, dec->channel_layout);
2150  av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
2151  "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
2152  }
2153  return 1;
2154 }
2155 
2156 static void check_decode_result(InputStream *ist, int *got_output, int ret)
2157 {
2158  if (*got_output || ret<0)
2159  decode_error_stat[ret<0] ++;
2160 
2161  if (ret < 0 && exit_on_error)
2162  exit_program(1);
2163 
2164  if (*got_output && ist) {
2167  "%s: corrupt decoded frame in stream %d\n", input_files[ist->file_index]->ctx->url, ist->st->index);
2168  if (exit_on_error)
2169  exit_program(1);
2170  }
2171  }
2172 }
2173 
2174 // Filters can be configured only if the formats of all inputs are known.
2176 {
2177  int i;
2178  for (i = 0; i < fg->nb_inputs; i++) {
2179  if (fg->inputs[i]->format < 0 && (fg->inputs[i]->type == AVMEDIA_TYPE_AUDIO ||
2180  fg->inputs[i]->type == AVMEDIA_TYPE_VIDEO))
2181  return 0;
2182  }
2183  return 1;
2184 }
2185 
2187 {
2188  FilterGraph *fg = ifilter->graph;
2189  int need_reinit, ret, i;
2190 
2191  /* determine if the parameters for this input changed */
2192  need_reinit = ifilter->format != frame->format;
2193 
2194  switch (ifilter->ist->st->codecpar->codec_type) {
2195  case AVMEDIA_TYPE_AUDIO:
2196  need_reinit |= ifilter->sample_rate != frame->sample_rate ||
2197  ifilter->channels != frame->channels ||
2198  ifilter->channel_layout != frame->channel_layout;
2199  break;
2200  case AVMEDIA_TYPE_VIDEO:
2201  need_reinit |= ifilter->width != frame->width ||
2202  ifilter->height != frame->height;
2203  break;
2204  }
2205 
2206  if (!ifilter->ist->reinit_filters && fg->graph)
2207  need_reinit = 0;
2208 
2209  if (!!ifilter->hw_frames_ctx != !!frame->hw_frames_ctx ||
2210  (ifilter->hw_frames_ctx && ifilter->hw_frames_ctx->data != frame->hw_frames_ctx->data))
2211  need_reinit = 1;
2212 
2213  if (need_reinit) {
2215  if (ret < 0)
2216  return ret;
2217  }
2218 
2219  /* (re)init the graph if possible, otherwise buffer the frame and return */
2220  if (need_reinit || !fg->graph) {
2221  for (i = 0; i < fg->nb_inputs; i++) {
2222  if (!ifilter_has_all_input_formats(fg)) {
2224  if (!tmp)
2225  return AVERROR(ENOMEM);
2227 
2228  if (!av_fifo_space(ifilter->frame_queue)) {
2229  ret = av_fifo_realloc2(ifilter->frame_queue, 2 * av_fifo_size(ifilter->frame_queue));
2230  if (ret < 0) {
2231  av_frame_free(&tmp);
2232  return ret;
2233  }
2234  }
2235  av_fifo_generic_write(ifilter->frame_queue, &tmp, sizeof(tmp), NULL);
2236  return 0;
2237  }
2238  }
2239 
2240  ret = reap_filters(1);
2241  if (ret < 0 && ret != AVERROR_EOF) {
2242  av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
2243  return ret;
2244  }
2245 
2246  ret = configure_filtergraph(fg);
2247  if (ret < 0) {
2248  av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
2249  return ret;
2250  }
2251  }
2252 
2254  if (ret < 0) {
2255  if (ret != AVERROR_EOF)
2256  av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
2257  return ret;
2258  }
2259 
2260  return 0;
2261 }
2262 
2264 {
2265  int ret;
2266 
2267  ifilter->eof = 1;
2268 
2269  if (ifilter->filter) {
2271  if (ret < 0)
2272  return ret;
2273  } else {
2274  // the filtergraph was never configured
2275  if (ifilter->format < 0)
2276  ifilter_parameters_from_codecpar(ifilter, ifilter->ist->st->codecpar);
2277  if (ifilter->format < 0 && (ifilter->type == AVMEDIA_TYPE_AUDIO || ifilter->type == AVMEDIA_TYPE_VIDEO)) {
2278  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);
2279  return AVERROR_INVALIDDATA;
2280  }
2281  }
2282 
2283  return 0;
2284 }
2285 
2286 // This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
2287 // There is the following difference: if you got a frame, you must call
2288 // it again with pkt=NULL. pkt==NULL is treated differently from pkt->size==0
2289 // (pkt==NULL means get more output, pkt->size==0 is a flush/drain packet)
2290 static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
2291 {
2292  int ret;
2293 
2294  *got_frame = 0;
2295 
2296  if (pkt) {
2297  ret = avcodec_send_packet(avctx, pkt);
2298  // In particular, we don't expect AVERROR(EAGAIN), because we read all
2299  // decoded frames with avcodec_receive_frame() until done.
2300  if (ret < 0 && ret != AVERROR_EOF)
2301  return ret;
2302  }
2303 
2304  ret = avcodec_receive_frame(avctx, frame);
2305  if (ret < 0 && ret != AVERROR(EAGAIN))
2306  return ret;
2307  if (ret >= 0)
2308  *got_frame = 1;
2309 
2310  return 0;
2311 }
2312 
2314 {
2315  int i, ret;
2316  AVFrame *f;
2317 
2318  av_assert1(ist->nb_filters > 0); /* ensure ret is initialized */
2319  for (i = 0; i < ist->nb_filters; i++) {
2320  if (i < ist->nb_filters - 1) {
2321  f = ist->filter_frame;
2323  if (ret < 0)
2324  break;
2325  } else
2326  f = decoded_frame;
2327  ret = ifilter_send_frame(ist->filters[i], f);
2328  if (ret == AVERROR_EOF)
2329  ret = 0; /* ignore */
2330  if (ret < 0) {
2332  "Failed to inject frame into filter network: %s\n", av_err2str(ret));
2333  break;
2334  }
2335  }
2336  return ret;
2337 }
2338 
2340  int *decode_failed)
2341 {
2343  AVCodecContext *avctx = ist->dec_ctx;
2344  int ret, err = 0;
2345  AVRational decoded_frame_tb;
2346 
2347  if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
2348  return AVERROR(ENOMEM);
2349  if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
2350  return AVERROR(ENOMEM);
2352 
2354  ret = decode(avctx, decoded_frame, got_output, pkt);
2355  update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
2356  if (ret < 0)
2357  *decode_failed = 1;
2358 
2359  if (ret >= 0 && avctx->sample_rate <= 0) {
2360  av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
2362  }
2363 
2364  if (ret != AVERROR_EOF)
2366 
2367  if (!*got_output || ret < 0)
2368  return ret;
2369 
2371  ist->frames_decoded++;
2372 
2373  /* increment next_dts to use for the case where the input stream does not
2374  have timestamps or there are multiple frames in the packet */
2376  avctx->sample_rate;
2378  avctx->sample_rate;
2379 
2380  if (decoded_frame->pts != AV_NOPTS_VALUE) {
2381  decoded_frame_tb = ist->st->time_base;
2382  } else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
2383  decoded_frame->pts = pkt->pts;
2384  decoded_frame_tb = ist->st->time_base;
2385  }else {
2386  decoded_frame->pts = ist->dts;
2387  decoded_frame_tb = AV_TIME_BASE_Q;
2388  }
2390  decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
2391  (AVRational){1, avctx->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
2392  (AVRational){1, avctx->sample_rate});
2395 
2398  return err < 0 ? err : ret;
2399 }
2400 
2401 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *duration_pts, int eof,
2402  int *decode_failed)
2403 {
2405  int i, ret = 0, err = 0;
2406  int64_t best_effort_timestamp;
2408 
2409  // With fate-indeo3-2, we're getting 0-sized packets before EOF for some
2410  // reason. This seems like a semi-critical bug. Don't trigger EOF, and
2411  // skip the packet.
2412  if (!eof && pkt && pkt->size == 0)
2413  return 0;
2414 
2415  if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
2416  return AVERROR(ENOMEM);
2417  if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
2418  return AVERROR(ENOMEM);
2420  if (ist->dts != AV_NOPTS_VALUE)
2421  dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
2422  if (pkt) {
2423  pkt->dts = dts; // ffmpeg.c probably shouldn't do this
2424  }
2425 
2426  // The old code used to set dts on the drain packet, which does not work
2427  // with the new API anymore.
2428  if (eof) {
2429  void *new = av_realloc_array(ist->dts_buffer, ist->nb_dts_buffer + 1, sizeof(ist->dts_buffer[0]));
2430  if (!new)
2431  return AVERROR(ENOMEM);
2432  ist->dts_buffer = new;
2433  ist->dts_buffer[ist->nb_dts_buffer++] = dts;
2434  }
2435 
2438  update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
2439  if (ret < 0)
2440  *decode_failed = 1;
2441 
2442  // The following line may be required in some cases where there is no parser
2443  // or the parser does not has_b_frames correctly
2444  if (ist->st->codecpar->video_delay < ist->dec_ctx->has_b_frames) {
2445  if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
2446  ist->st->codecpar->video_delay = ist->dec_ctx->has_b_frames;
2447  } else
2449  "video_delay is larger in decoder than demuxer %d > %d.\n"
2450  "If you want to help, upload a sample "
2451  "of this file to https://streams.videolan.org/upload/ "
2452  "and contact the ffmpeg-devel mailing list. (ffmpeg-devel@ffmpeg.org)\n",
2453  ist->dec_ctx->has_b_frames,
2454  ist->st->codecpar->video_delay);
2455  }
2456 
2457  if (ret != AVERROR_EOF)
2459 
2460  if (*got_output && ret >= 0) {
2461  if (ist->dec_ctx->width != decoded_frame->width ||
2462  ist->dec_ctx->height != decoded_frame->height ||
2463  ist->dec_ctx->pix_fmt != decoded_frame->format) {
2464  av_log(NULL, AV_LOG_DEBUG, "Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
2468  ist->dec_ctx->width,
2469  ist->dec_ctx->height,
2470  ist->dec_ctx->pix_fmt);
2471  }
2472  }
2473 
2474  if (!*got_output || ret < 0)
2475  return ret;
2476 
2477  if(ist->top_field_first>=0)
2479 
2480  ist->frames_decoded++;
2481 
2483  err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
2484  if (err < 0)
2485  goto fail;
2486  }
2488 
2489  best_effort_timestamp= decoded_frame->best_effort_timestamp;
2490  *duration_pts = decoded_frame->pkt_duration;
2491 
2492  if (ist->framerate.num)
2493  best_effort_timestamp = ist->cfr_next_pts++;
2494 
2495  if (eof && best_effort_timestamp == AV_NOPTS_VALUE && ist->nb_dts_buffer > 0) {
2496  best_effort_timestamp = ist->dts_buffer[0];
2497 
2498  for (i = 0; i < ist->nb_dts_buffer - 1; i++)
2499  ist->dts_buffer[i] = ist->dts_buffer[i + 1];
2500  ist->nb_dts_buffer--;
2501  }
2502 
2503  if(best_effort_timestamp != AV_NOPTS_VALUE) {
2504  int64_t ts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
2505 
2506  if (ts != AV_NOPTS_VALUE)
2507  ist->next_pts = ist->pts = ts;
2508  }
2509 
2510  if (debug_ts) {
2511  av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
2512  "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",
2513  ist->st->index, av_ts2str(decoded_frame->pts),
2515  best_effort_timestamp,
2516  av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
2518  ist->st->time_base.num, ist->st->time_base.den);
2519  }
2520 
2521  if (ist->st->sample_aspect_ratio.num)
2523 
2525 
2526 fail:
2529  return err < 0 ? err : ret;
2530 }
2531 
2533  int *decode_failed)
2534 {
2536  int free_sub = 1;
2537  int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
2538  &subtitle, got_output, pkt);
2539 
2541 
2542  if (ret < 0 || !*got_output) {
2543  *decode_failed = 1;
2544  if (!pkt->size)
2545  sub2video_flush(ist);
2546  return ret;
2547  }
2548 
2549  if (ist->fix_sub_duration) {
2550  int end = 1;
2551  if (ist->prev_sub.got_output) {
2552  end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
2553  1000, AV_TIME_BASE);
2554  if (end < ist->prev_sub.subtitle.end_display_time) {
2555  av_log(ist->dec_ctx, AV_LOG_DEBUG,
2556  "Subtitle duration reduced from %"PRId32" to %d%s\n",
2558  end <= 0 ? ", dropping it" : "");
2559  ist->prev_sub.subtitle.end_display_time = end;
2560  }
2561  }
2562  FFSWAP(int, *got_output, ist->prev_sub.got_output);
2563  FFSWAP(int, ret, ist->prev_sub.ret);
2565  if (end <= 0)
2566  goto out;
2567  }
2568 
2569  if (!*got_output)
2570  return ret;
2571 
2572  if (ist->sub2video.frame) {
2573  sub2video_update(ist, INT64_MIN, &subtitle);
2574  } else if (ist->nb_filters) {
2575  if (!ist->sub2video.sub_queue)
2576  ist->sub2video.sub_queue = av_fifo_alloc(8 * sizeof(AVSubtitle));
2577  if (!ist->sub2video.sub_queue)
2578  exit_program(1);
2579  if (!av_fifo_space(ist->sub2video.sub_queue)) {
2581  if (ret < 0)
2582  exit_program(1);
2583  }
2585  free_sub = 0;
2586  }
2587 
2588  if (!subtitle.num_rects)
2589  goto out;
2590 
2591  ist->frames_decoded++;
2592 
2593  for (i = 0; i < nb_output_streams; i++) {
2595 
2596  if (!ost->pkt && !(ost->pkt = av_packet_alloc()))
2597  exit_program(1);
2598  if (!check_output_constraints(ist, ost) || !ost->encoding_needed
2599  || ost->enc->type != AVMEDIA_TYPE_SUBTITLE)
2600  continue;
2601 
2602  do_subtitle_out(output_files[ost->file_index], ost, &subtitle);
2603  }
2604 
2605 out:
2606  if (free_sub)
2608  return ret;
2609 }
2610 
2612 {
2613  int i, ret;
2614  /* TODO keep pts also in stream time base to avoid converting back */
2617 
2618  for (i = 0; i < ist->nb_filters; i++) {
2619  ret = ifilter_send_eof(ist->filters[i], pts);
2620  if (ret < 0)
2621  return ret;
2622  }
2623  return 0;
2624 }
2625 
2626 /* pkt = NULL means EOF (needed to flush decoder buffers) */
2627 static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
2628 {
2629  int ret = 0, i;
2630  int repeating = 0;
2631  int eof_reached = 0;
2632 
2633  AVPacket *avpkt;
2634 
2635  if (!ist->pkt && !(ist->pkt = av_packet_alloc()))
2636  return AVERROR(ENOMEM);
2637  avpkt = ist->pkt;
2638 
2639  if (!ist->saw_first_ts) {
2640  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;
2641  ist->pts = 0;
2642  if (pkt && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
2643  ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
2644  ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
2645  }
2646  ist->saw_first_ts = 1;
2647  }
2648 
2649  if (ist->next_dts == AV_NOPTS_VALUE)
2650  ist->next_dts = ist->dts;
2651  if (ist->next_pts == AV_NOPTS_VALUE)
2652  ist->next_pts = ist->pts;
2653 
2654  if (pkt) {
2655  av_packet_unref(avpkt);
2656  ret = av_packet_ref(avpkt, pkt);
2657  if (ret < 0)
2658  return ret;
2659  }
2660 
2661  if (pkt && pkt->dts != AV_NOPTS_VALUE) {
2662  ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
2663  if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
2664  ist->next_pts = ist->pts = ist->dts;
2665  }
2666 
2667  // while we have more to decode or while the decoder did output something on EOF
2668  while (ist->decoding_needed) {
2669  int64_t duration_dts = 0;
2670  int64_t duration_pts = 0;
2671  int got_output = 0;
2672  int decode_failed = 0;
2673 
2674  ist->pts = ist->next_pts;
2675  ist->dts = ist->next_dts;
2676 
2677  switch (ist->dec_ctx->codec_type) {
2678  case AVMEDIA_TYPE_AUDIO:
2679  ret = decode_audio (ist, repeating ? NULL : avpkt, &got_output,
2680  &decode_failed);
2681  av_packet_unref(avpkt);
2682  break;
2683  case AVMEDIA_TYPE_VIDEO:
2684  ret = decode_video (ist, repeating ? NULL : avpkt, &got_output, &duration_pts, !pkt,
2685  &decode_failed);
2686  if (!repeating || !pkt || got_output) {
2687  if (pkt && pkt->duration) {
2688  duration_dts = av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
2689  } else if(ist->dec_ctx->framerate.num != 0 && ist->dec_ctx->framerate.den != 0) {
2691  duration_dts = ((int64_t)AV_TIME_BASE *
2692  ist->dec_ctx->framerate.den * ticks) /
2694  }
2695 
2696  if(ist->dts != AV_NOPTS_VALUE && duration_dts) {
2697  ist->next_dts += duration_dts;
2698  }else
2699  ist->next_dts = AV_NOPTS_VALUE;
2700  }
2701 
2702  if (got_output) {
2703  if (duration_pts > 0) {
2704  ist->next_pts += av_rescale_q(duration_pts, ist->st->time_base, AV_TIME_BASE_Q);
2705  } else {
2706  ist->next_pts += duration_dts;
2707  }
2708  }
2709  av_packet_unref(avpkt);
2710  break;
2711  case AVMEDIA_TYPE_SUBTITLE:
2712  if (repeating)
2713  break;
2714  ret = transcode_subtitles(ist, avpkt, &got_output, &decode_failed);
2715  if (!pkt && ret >= 0)
2716  ret = AVERROR_EOF;
2717  av_packet_unref(avpkt);
2718  break;
2719  default:
2720  return -1;
2721  }
2722 
2723  if (ret == AVERROR_EOF) {
2724  eof_reached = 1;
2725  break;
2726  }
2727 
2728  if (ret < 0) {
2729  if (decode_failed) {
2730  av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
2731  ist->file_index, ist->st->index, av_err2str(ret));
2732  } else {
2733  av_log(NULL, AV_LOG_FATAL, "Error while processing the decoded "
2734  "data for stream #%d:%d\n", ist->file_index, ist->st->index);
2735  }
2736  if (!decode_failed || exit_on_error)
2737  exit_program(1);
2738  break;
2739  }
2740 
2741  if (got_output)
2742  ist->got_output = 1;
2743 
2744  if (!got_output)
2745  break;
2746 
2747  // During draining, we might get multiple output frames in this loop.
2748  // ffmpeg.c does not drain the filter chain on configuration changes,
2749  // which means if we send multiple frames at once to the filters, and
2750  // one of those frames changes configuration, the buffered frames will
2751  // be lost. This can upset certain FATE tests.
2752  // Decode only 1 frame per call on EOF to appease these FATE tests.
2753  // The ideal solution would be to rewrite decoding to use the new
2754  // decoding API in a better way.
2755  if (!pkt)
2756  break;
2757 
2758  repeating = 1;
2759  }
2760 
2761  /* after flushing, send an EOF on all the filter inputs attached to the stream */
2762  /* except when looping we need to flush but not to send an EOF */
2763  if (!pkt && ist->decoding_needed && eof_reached && !no_eof) {
2764  int ret = send_filter_eof(ist);
2765  if (ret < 0) {
2766  av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
2767  exit_program(1);
2768  }
2769  }
2770 
2771  /* handle stream copy */
2772  if (!ist->decoding_needed && pkt) {
2773  ist->dts = ist->next_dts;
2774  switch (ist->dec_ctx->codec_type) {
2775  case AVMEDIA_TYPE_AUDIO:
2776  av_assert1(pkt->duration >= 0);
2777  if (ist->dec_ctx->sample_rate) {
2778  ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
2779  ist->dec_ctx->sample_rate;
2780  } else {
2782  }
2783  break;
2784  case AVMEDIA_TYPE_VIDEO:
2785  if (ist->framerate.num) {
2786  // TODO: Remove work-around for c99-to-c89 issue 7
2787  AVRational time_base_q = AV_TIME_BASE_Q;
2788  int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
2789  ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
2790  } else if (pkt->duration) {
2792  } else if(ist->dec_ctx->framerate.num != 0) {
2793  int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
2794  ist->next_dts += ((int64_t)AV_TIME_BASE *
2795  ist->dec_ctx->framerate.den * ticks) /
2797  }
2798  break;
2799  }
2800  ist->pts = ist->dts;
2801  ist->next_pts = ist->next_dts;
2802  }
2803  for (i = 0; i < nb_output_streams; i++) {
2805 
2806  if (!ost->pkt && !(ost->pkt = av_packet_alloc()))
2807  exit_program(1);
2808  if (!check_output_constraints(ist, ost) || ost->encoding_needed)
2809  continue;
2810 
2811  do_streamcopy(ist, ost, pkt);
2812  }
2813 
2814  return !eof_reached;
2815 }
2816 
2817 static void print_sdp(void)
2818 {
2819  char sdp[16384];
2820  int i;
2821  int j;
2822  AVIOContext *sdp_pb;
2823  AVFormatContext **avc;
2824 
2825  for (i = 0; i < nb_output_files; i++) {
2826  if (!output_files[i]->header_written)
2827  return;
2828  }
2829 
2830  avc = av_malloc_array(nb_output_files, sizeof(*avc));
2831  if (!avc)
2832  exit_program(1);
2833  for (i = 0, j = 0; i < nb_output_files; i++) {
2834  if (!strcmp(output_files[i]->ctx->oformat->name, "rtp")) {
2835  avc[j] = output_files[i]->ctx;
2836  j++;
2837  }
2838  }
2839 
2840  if (!j)
2841  goto fail;
2842 
2843  av_sdp_create(avc, j, sdp, sizeof(sdp));
2844 
2845  if (!sdp_filename) {
2846  printf("SDP:\n%s\n", sdp);
2847  fflush(stdout);
2848  } else {
2849  if (avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL) < 0) {
2850  av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
2851  } else {
2852  avio_print(sdp_pb, sdp);
2853  avio_closep(&sdp_pb);
2855  }
2856  }
2857 
2858 fail:
2859  av_freep(&avc);
2860 }
2861 
2863 {
2864  InputStream *ist = s->opaque;
2865  const enum AVPixelFormat *p;
2866  int ret;
2867 
2868  for (p = pix_fmts; *p != AV_PIX_FMT_NONE; p++) {
2870  const AVCodecHWConfig *config = NULL;
2871  int i;
2872 
2873  if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
2874  break;
2875 
2876  if (ist->hwaccel_id == HWACCEL_GENERIC ||
2877  ist->hwaccel_id == HWACCEL_AUTO) {
2878  for (i = 0;; i++) {
2879  config = avcodec_get_hw_config(s->codec, i);
2880  if (!config)
2881  break;
2882  if (!(config->methods &
2884  continue;
2885  if (config->pix_fmt == *p)
2886  break;
2887  }
2888  }
2889  if (config) {
2890  if (config->device_type != ist->hwaccel_device_type) {
2891  // Different hwaccel offered, ignore.
2892  continue;
2893  }
2894 
2896  if (ret < 0) {
2897  if (ist->hwaccel_id == HWACCEL_GENERIC) {
2899  "%s hwaccel requested for input stream #%d:%d, "
2900  "but cannot be initialized.\n",
2902  ist->file_index, ist->st->index);
2903  return AV_PIX_FMT_NONE;
2904  }
2905  continue;
2906  }
2907  } else {
2908  const HWAccel *hwaccel = NULL;
2909  int i;
2910  for (i = 0; hwaccels[i].name; i++) {
2911  if (hwaccels[i].pix_fmt == *p) {
2912  hwaccel = &hwaccels[i];
2913  break;
2914  }
2915  }
2916  if (!hwaccel) {
2917  // No hwaccel supporting this pixfmt.
2918  continue;
2919  }
2920  if (hwaccel->id != ist->hwaccel_id) {
2921  // Does not match requested hwaccel.
2922  continue;
2923  }
2924 
2925  ret = hwaccel->init(s);
2926  if (ret < 0) {
2928  "%s hwaccel requested for input stream #%d:%d, "
2929  "but cannot be initialized.\n", hwaccel->name,
2930  ist->file_index, ist->st->index);
2931  return AV_PIX_FMT_NONE;
2932  }
2933  }
2934 
2935  if (ist->hw_frames_ctx) {
2936  s->hw_frames_ctx = av_buffer_ref(ist->hw_frames_ctx);
2937  if (!s->hw_frames_ctx)
2938  return AV_PIX_FMT_NONE;
2939  }
2940 
2941  ist->hwaccel_pix_fmt = *p;
2942  break;
2943  }
2944 
2945  return *p;
2946 }
2947 
2949 {
2950  InputStream *ist = s->opaque;
2951 
2952  if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
2953  return ist->hwaccel_get_buffer(s, frame, flags);
2954 
2956 }
2957 
2958 static int init_input_stream(int ist_index, char *error, int error_len)
2959 {
2960  int ret;
2961  InputStream *ist = input_streams[ist_index];
2962 
2963  if (ist->decoding_needed) {
2964  const AVCodec *codec = ist->dec;
2965  if (!codec) {
2966  snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
2967  avcodec_get_name(ist->dec_ctx->codec_id), ist->file_index, ist->st->index);
2968  return AVERROR(EINVAL);
2969  }
2970 
2971  ist->dec_ctx->opaque = ist;
2972  ist->dec_ctx->get_format = get_format;
2973  ist->dec_ctx->get_buffer2 = get_buffer;
2974 #if LIBAVCODEC_VERSION_MAJOR < 60
2975  ist->dec_ctx->thread_safe_callbacks = 1;
2976 #endif
2977 
2978  if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
2979  (ist->decoding_needed & DECODING_FOR_OST)) {
2980  av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
2982  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");
2983  }
2984 
2985  av_dict_set(&ist->decoder_opts, "sub_text_format", "ass", AV_DICT_DONT_OVERWRITE);
2986 
2987  /* Useful for subtitles retiming by lavf (FIXME), skipping samples in
2988  * audio, and video decoders such as cuvid or mediacodec */
2989  ist->dec_ctx->pkt_timebase = ist->st->time_base;
2990 
2991  if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
2992  av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
2993  /* Attached pics are sparse, therefore we would not want to delay their decoding till EOF. */
2995  av_dict_set(&ist->decoder_opts, "threads", "1", 0);
2996 
2998  if (ret < 0) {
2999  snprintf(error, error_len, "Device setup failed for "
3000  "decoder on input stream #%d:%d : %s",
3001  ist->file_index, ist->st->index, av_err2str(ret));
3002  return ret;
3003  }
3004 
3005  if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
3006  if (ret == AVERROR_EXPERIMENTAL)
3007  abort_codec_experimental(codec, 0);
3008 
3009  snprintf(error, error_len,
3010  "Error while opening decoder for input stream "
3011  "#%d:%d : %s",
3012  ist->file_index, ist->st->index, av_err2str(ret));
3013  return ret;
3014  }
3016  }
3017 
3018  ist->next_pts = AV_NOPTS_VALUE;
3019  ist->next_dts = AV_NOPTS_VALUE;
3020 
3021  return 0;
3022 }
3023 
3025 {
3026  if (ost->source_index >= 0)
3027  return input_streams[ost->source_index];
3028  return NULL;
3029 }
3030 
3031 static int compare_int64(const void *a, const void *b)
3032 {
3033  return FFDIFFSIGN(*(const int64_t *)a, *(const int64_t *)b);
3034 }
3035 
3036 /* open the muxer when all the streams are initialized */
3038 {
3039  int ret, i;
3040 
3041  for (i = 0; i < of->ctx->nb_streams; i++) {
3043  if (!ost->initialized)
3044  return 0;
3045  }
3046 
3047  of->ctx->interrupt_callback = int_cb;
3048 
3049  ret = avformat_write_header(of->ctx, &of->opts);
3050  if (ret < 0) {
3052  "Could not write header for output file #%d "
3053  "(incorrect codec parameters ?): %s\n",
3055  return ret;
3056  }
3057  //assert_avoptions(of->opts);
3058  of->header_written = 1;
3059 
3060  av_dump_format(of->ctx, file_index, of->ctx->url, 1);
3061  nb_output_dumped++;
3062 
3063  if (sdp_filename || want_sdp)
3064  print_sdp();
3065 
3066  /* flush the muxing queues */
3067  for (i = 0; i < of->ctx->nb_streams; i++) {
3069 
3070  /* try to improve muxing time_base (only possible if nothing has been written yet) */
3071  if (!av_fifo_size(ost->muxing_queue))
3072  ost->mux_timebase = ost->st->time_base;
3073 
3074  while (av_fifo_size(ost->muxing_queue)) {
3075  AVPacket *pkt;
3076  av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
3077  ost->muxing_queue_data_size -= pkt->size;
3078  write_packet(of, pkt, ost, 1);
3079  av_packet_free(&pkt);
3080  }
3081  }
3082 
3083  return 0;
3084 }
3085 
3087 {
3088  AVBSFContext *ctx = ost->bsf_ctx;
3089  int ret;
3090 
3091  if (!ctx)
3092  return 0;
3093 
3094  ret = avcodec_parameters_copy(ctx->par_in, ost->st->codecpar);
3095  if (ret < 0)
3096  return ret;
3097 
3098  ctx->time_base_in = ost->st->time_base;
3099 
3100  ret = av_bsf_init(ctx);
3101  if (ret < 0) {
3102  av_log(NULL, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
3103  ctx->filter->name);
3104  return ret;
3105  }
3106 
3107  ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
3108  if (ret < 0)
3109  return ret;
3110  ost->st->time_base = ctx->time_base_out;
3111 
3112  return 0;
3113 }
3114 
3116 {
3117  OutputFile *of = output_files[ost->file_index];
3119  AVCodecParameters *par_dst = ost->st->codecpar;
3120  AVCodecParameters *par_src = ost->ref_par;
3121  AVRational sar;
3122  int i, ret;
3123  uint32_t codec_tag = par_dst->codec_tag;
3124 
3125  av_assert0(ist && !ost->filter);
3126 
3127  ret = avcodec_parameters_to_context(ost->enc_ctx, ist->st->codecpar);
3128  if (ret >= 0)
3129  ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
3130  if (ret < 0) {
3132  "Error setting up codec context options.\n");
3133  return ret;
3134  }
3135 
3136  ret = avcodec_parameters_from_context(par_src, ost->enc_ctx);
3137  if (ret < 0) {
3139  "Error getting reference codec parameters.\n");
3140  return ret;
3141  }
3142 
3143  if (!codec_tag) {
3144  unsigned int codec_tag_tmp;
3145  if (!of->ctx->oformat->codec_tag ||
3146  av_codec_get_id (of->ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
3147  !av_codec_get_tag2(of->ctx->oformat->codec_tag, par_src->codec_id, &codec_tag_tmp))
3148  codec_tag = par_src->codec_tag;
3149  }
3150 
3151  ret = avcodec_parameters_copy(par_dst, par_src);
3152  if (ret < 0)
3153  return ret;
3154 
3155  par_dst->codec_tag = codec_tag;
3156 
3157  if (!ost->frame_rate.num)
3158  ost->frame_rate = ist->framerate;
3159  ost->st->avg_frame_rate = ost->frame_rate;
3160 
3162  if (ret < 0)
3163  return ret;
3164 
3165  // copy timebase while removing common factors
3166  if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
3168 
3169  // copy estimated duration as a hint to the muxer
3170  if (ost->st->duration <= 0 && ist->st->duration > 0)
3171  ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
3172 
3173  // copy disposition
3174  ost->st->disposition = ist->st->disposition;
3175 
3176  if (ist->st->nb_side_data) {
3177  for (i = 0; i < ist->st->nb_side_data; i++) {
3178  const AVPacketSideData *sd_src = &ist->st->side_data[i];
3179  uint8_t *dst_data;
3180 
3181  dst_data = av_stream_new_side_data(ost->st, sd_src->type, sd_src->size);
3182  if (!dst_data)
3183  return AVERROR(ENOMEM);
3184  memcpy(dst_data, sd_src->data, sd_src->size);
3185  }
3186  }
3187 
3188  if (ost->rotate_overridden) {
3190  sizeof(int32_t) * 9);
3191  if (sd)
3192  av_display_rotation_set((int32_t *)sd, -ost->rotate_override_value);
3193  }
3194 
3195  switch (par_dst->codec_type) {
3196  case AVMEDIA_TYPE_AUDIO:
3197  if (audio_volume != 256) {
3198  av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
3199  exit_program(1);
3200  }
3201  if((par_dst->block_align == 1 || par_dst->block_align == 1152 || par_dst->block_align == 576) && par_dst->codec_id == AV_CODEC_ID_MP3)
3202  par_dst->block_align= 0;
3203  if(par_dst->codec_id == AV_CODEC_ID_AC3)
3204  par_dst->block_align= 0;
3205  break;
3206  case AVMEDIA_TYPE_VIDEO:
3207  if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
3208  sar =
3209  av_mul_q(ost->frame_aspect_ratio,
3210  (AVRational){ par_dst->height, par_dst->width });
3211  av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
3212  "with stream copy may produce invalid files\n");
3213  }
3214  else if (ist->st->sample_aspect_ratio.num)
3215  sar = ist->st->sample_aspect_ratio;
3216  else
3217  sar = par_src->sample_aspect_ratio;
3218  ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
3219  ost->st->avg_frame_rate = ist->st->avg_frame_rate;
3220  ost->st->r_frame_rate = ist->st->r_frame_rate;
3221  break;
3222  }
3223 
3224  ost->mux_timebase = ist->st->time_base;
3225 
3226  return 0;
3227 }
3228 
3230 {
3231  AVDictionaryEntry *e;
3232 
3233  uint8_t *encoder_string;
3234  int encoder_string_len;
3235  int format_flags = 0;
3236  int codec_flags = ost->enc_ctx->flags;
3237 
3238  if (av_dict_get(ost->st->metadata, "encoder", NULL, 0))
3239  return;
3240 
3241  e = av_dict_get(of->opts, "fflags", NULL, 0);
3242  if (e) {
3243  const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
3244  if (!o)
3245  return;
3246  av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
3247  }
3248  e = av_dict_get(ost->encoder_opts, "flags", NULL, 0);
3249  if (e) {
3250  const AVOption *o = av_opt_find(ost->enc_ctx, "flags", NULL, 0, 0);
3251  if (!o)
3252  return;
3253  av_opt_eval_flags(ost->enc_ctx, o, e->value, &codec_flags);
3254  }
3255 
3256  encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
3257  encoder_string = av_mallocz(encoder_string_len);
3258  if (!encoder_string)
3259  exit_program(1);
3260 
3261  if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & AV_CODEC_FLAG_BITEXACT))
3262  av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
3263  else
3264  av_strlcpy(encoder_string, "Lavc ", encoder_string_len);
3265  av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
3266  av_dict_set(&ost->st->metadata, "encoder", encoder_string,
3268 }
3269 
3271  AVCodecContext *avctx)
3272 {
3273  char *p;
3274  int n = 1, i, size, index = 0;
3275  int64_t t, *pts;
3276 
3277  for (p = kf; *p; p++)
3278  if (*p == ',')
3279  n++;
3280  size = n;
3281  pts = av_malloc_array(size, sizeof(*pts));
3282  if (!pts) {
3283  av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
3284  exit_program(1);
3285  }
3286 
3287  p = kf;
3288  for (i = 0; i < n; i++) {
3289  char *next = strchr(p, ',');
3290 
3291  if (next)
3292  *next++ = 0;
3293 
3294  if (strstr(p, "chapters") == p) {
3295 
3296  AVFormatContext *avf = output_files[ost->file_index]->ctx;
3297  int j;
3298 
3299  if (avf->nb_chapters > INT_MAX - size ||
3300  !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
3301  sizeof(*pts)))) {
3303  "Could not allocate forced key frames array.\n");
3304  exit_program(1);
3305  }
3306  t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
3307  t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3308 
3309  for (j = 0; j < avf->nb_chapters; j++) {
3310  AVChapter *c = avf->chapters[j];
3311  av_assert1(index < size);
3312  pts[index++] = av_rescale_q(c->start, c->time_base,
3313  avctx->time_base) + t;
3314  }
3315 
3316  } else {
3317 
3318  t = parse_time_or_die("force_key_frames", p, 1);
3319  av_assert1(index < size);
3320  pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
3321 
3322  }
3323 
3324  p = next;
3325  }
3326 
3327  av_assert0(index == size);
3328  qsort(pts, size, sizeof(*pts), compare_int64);
3329  ost->forced_kf_count = size;
3330  ost->forced_kf_pts = pts;
3331 }
3332 
3333 static void init_encoder_time_base(OutputStream *ost, AVRational default_time_base)
3334 {
3336  AVCodecContext *enc_ctx = ost->enc_ctx;
3337  AVFormatContext *oc;
3338 
3339  if (ost->enc_timebase.num > 0) {
3340  enc_ctx->time_base = ost->enc_timebase;
3341  return;
3342  }
3343 
3344  if (ost->enc_timebase.num < 0) {
3345  if (ist) {
3346  enc_ctx->time_base = ist->st->time_base;
3347  return;
3348  }
3349 
3350  oc = output_files[ost->file_index]->ctx;
3351  av_log(oc, AV_LOG_WARNING, "Input stream data not available, using default time base\n");
3352  }
3353 
3354  enc_ctx->time_base = default_time_base;
3355 }
3356 
3358 {
3360  AVCodecContext *enc_ctx = ost->enc_ctx;
3362  AVFormatContext *oc = output_files[ost->file_index]->ctx;
3363  int j, ret;
3364 
3365  set_encoder_id(output_files[ost->file_index], ost);
3366 
3367  // Muxers use AV_PKT_DATA_DISPLAYMATRIX to signal rotation. On the other
3368  // hand, the legacy API makes demuxers set "rotate" metadata entries,
3369  // which have to be filtered out to prevent leaking them to output files.
3370  av_dict_set(&ost->st->metadata, "rotate", NULL, 0);
3371 
3372  if (ist) {
3373  ost->st->disposition = ist->st->disposition;
3374 
3375  dec_ctx = ist->dec_ctx;
3376 
3378  } else {
3379  for (j = 0; j < oc->nb_streams; j++) {
3380  AVStream *st = oc->streams[j];
3381  if (st != ost->st && st->codecpar->codec_type == ost->st->codecpar->codec_type)
3382  break;
3383  }
3384  if (j == oc->nb_streams)
3385  if (ost->st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ||
3388  }
3389 
3390  if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
3391  if (!ost->frame_rate.num)
3392  ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
3393  if (ist && !ost->frame_rate.num)
3394  ost->frame_rate = ist->framerate;
3395  if (ist && !ost->frame_rate.num)
3396  ost->frame_rate = ist->st->r_frame_rate;
3397  if (ist && !ost->frame_rate.num && !ost->max_frame_rate.num) {
3398  ost->frame_rate = (AVRational){25, 1};
3400  "No information "
3401  "about the input framerate is available. Falling "
3402  "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
3403  "if you want a different framerate.\n",
3404  ost->file_index, ost->index);
3405  }
3406 
3407  if (ost->max_frame_rate.num &&
3408  (av_q2d(ost->frame_rate) > av_q2d(ost->max_frame_rate) ||
3409  !ost->frame_rate.den))
3410  ost->frame_rate = ost->max_frame_rate;
3411 
3412  if (ost->enc->supported_framerates && !ost->force_fps) {
3413  int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
3414  ost->frame_rate = ost->enc->supported_framerates[idx];
3415  }
3416  // reduce frame rate for mpeg4 to be within the spec limits
3417  if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
3418  av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
3419  ost->frame_rate.num, ost->frame_rate.den, 65535);
3420  }
3421  }
3422 
3423  switch (enc_ctx->codec_type) {
3424  case AVMEDIA_TYPE_AUDIO:
3425  enc_ctx->sample_fmt = av_buffersink_get_format(ost->filter->filter);
3426  if (dec_ctx)
3428  av_get_bytes_per_sample(enc_ctx->sample_fmt) << 3);
3429  enc_ctx->sample_rate = av_buffersink_get_sample_rate(ost->filter->filter);
3430  enc_ctx->channel_layout = av_buffersink_get_channel_layout(ost->filter->filter);
3431  enc_ctx->channels = av_buffersink_get_channels(ost->filter->filter);
3432 
3434  break;
3435 
3436  case AVMEDIA_TYPE_VIDEO:
3437  init_encoder_time_base(ost, av_inv_q(ost->frame_rate));
3438 
3439  if (!(enc_ctx->time_base.num && enc_ctx->time_base.den))
3440  enc_ctx->time_base = av_buffersink_get_time_base(ost->filter->filter);
3441  if ( av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
3443  av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
3444  "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
3445  }
3446 
3447  enc_ctx->width = av_buffersink_get_w(ost->filter->filter);
3448  enc_ctx->height = av_buffersink_get_h(ost->filter->filter);
3449  enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
3450  ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
3451  av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :
3452  av_buffersink_get_sample_aspect_ratio(ost->filter->filter);
3453 
3454  enc_ctx->pix_fmt = av_buffersink_get_format(ost->filter->filter);
3455  if (dec_ctx)
3457  av_pix_fmt_desc_get(enc_ctx->pix_fmt)->comp[0].depth);
3458 
3459  if (frame) {
3460  enc_ctx->color_range = frame->color_range;
3462  enc_ctx->color_trc = frame->color_trc;
3463  enc_ctx->colorspace = frame->colorspace;
3465  }
3466 
3467  enc_ctx->framerate = ost->frame_rate;
3468 
3469  ost->st->avg_frame_rate = ost->frame_rate;
3470 
3471  if (!dec_ctx ||
3472  enc_ctx->width != dec_ctx->width ||
3473  enc_ctx->height != dec_ctx->height ||
3474  enc_ctx->pix_fmt != dec_ctx->pix_fmt) {
3476  }
3477 
3478  // Field order: autodetection
3479  if (frame) {
3481  ost->top_field_first >= 0)
3482  frame->top_field_first = !!ost->top_field_first;
3483 
3484  if (frame->interlaced_frame) {
3485  if (enc_ctx->codec->id == AV_CODEC_ID_MJPEG)
3487  else
3489  } else
3490  enc_ctx->field_order = AV_FIELD_PROGRESSIVE;
3491  }
3492 
3493  // Field order: override
3494  if (ost->top_field_first == 0) {
3495  enc_ctx->field_order = AV_FIELD_BB;
3496  } else if (ost->top_field_first == 1) {
3497  enc_ctx->field_order = AV_FIELD_TT;
3498  }
3499 
3500  if (ost->forced_keyframes) {
3501  if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
3502  ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
3504  if (ret < 0) {
3506  "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
3507  return ret;
3508  }
3509  ost->forced_keyframes_expr_const_values[FKF_N] = 0;
3510  ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
3511  ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
3512  ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
3513 
3514  // Don't parse the 'forced_keyframes' in case of 'keep-source-keyframes',
3515  // parse it only for static kf timings
3516  } else if(strncmp(ost->forced_keyframes, "source", 6)) {
3517  parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx);
3518  }
3519  }
3520  break;
3521  case AVMEDIA_TYPE_SUBTITLE:
3522  enc_ctx->time_base = AV_TIME_BASE_Q;
3523  if (!enc_ctx->width) {
3524  enc_ctx->width = input_streams[ost->source_index]->st->codecpar->width;
3525  enc_ctx->height = input_streams[ost->source_index]->st->codecpar->height;
3526  }
3527  break;
3528  case AVMEDIA_TYPE_DATA:
3529  break;
3530  default:
3531  abort();
3532  break;
3533  }
3534 
3535  ost->mux_timebase = enc_ctx->time_base;
3536 
3537  return 0;
3538 }
3539 
3541  char *error, int error_len)
3542 {
3543  int ret = 0;
3544 
3545  if (ost->encoding_needed) {
3546  const AVCodec *codec = ost->enc;
3547  AVCodecContext *dec = NULL;
3548  InputStream *ist;
3549 
3551  if (ret < 0)
3552  return ret;
3553 
3554  if ((ist = get_input_stream(ost)))
3555  dec = ist->dec_ctx;
3556  if (dec && dec->subtitle_header) {
3557  /* ASS code assumes this buffer is null terminated so add extra byte. */
3558  ost->enc_ctx->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
3559  if (!ost->enc_ctx->subtitle_header)
3560  return AVERROR(ENOMEM);
3561  memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
3562  ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
3563  }
3564  if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
3565  av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
3566  if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
3567  !codec->defaults &&
3568  !av_dict_get(ost->encoder_opts, "b", NULL, 0) &&
3569  !av_dict_get(ost->encoder_opts, "ab", NULL, 0))
3570  av_dict_set(&ost->encoder_opts, "b", "128000", 0);
3571 
3573  if (ret < 0) {
3574  snprintf(error, error_len, "Device setup failed for "
3575  "encoder on output stream #%d:%d : %s",
3576  ost->file_index, ost->index, av_err2str(ret));
3577  return ret;
3578  }
3579 
3580  if (ist && ist->dec->type == AVMEDIA_TYPE_SUBTITLE && ost->enc->type == AVMEDIA_TYPE_SUBTITLE) {
3581  int input_props = 0, output_props = 0;
3582  AVCodecDescriptor const *input_descriptor =
3583  avcodec_descriptor_get(dec->codec_id);
3584  AVCodecDescriptor const *output_descriptor =
3585  avcodec_descriptor_get(ost->enc_ctx->codec_id);
3586  if (input_descriptor)
3587  input_props = input_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3588  if (output_descriptor)
3589  output_props = output_descriptor->props & (AV_CODEC_PROP_TEXT_SUB | AV_CODEC_PROP_BITMAP_SUB);
3590  if (input_props && output_props && input_props != output_props) {
3591  snprintf(error, error_len,
3592  "Subtitle encoding currently only possible from text to text "
3593  "or bitmap to bitmap");
3594  return AVERROR_INVALIDDATA;
3595  }
3596  }
3597 
3598  if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
3599  if (ret == AVERROR_EXPERIMENTAL)
3600  abort_codec_experimental(codec, 1);
3601  snprintf(error, error_len,
3602  "Error while opening encoder for output stream #%d:%d - "
3603  "maybe incorrect parameters such as bit_rate, rate, width or height",
3604  ost->file_index, ost->index);
3605  return ret;
3606  }
3607  if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
3608  !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))
3609  av_buffersink_set_frame_size(ost->filter->filter,
3610  ost->enc_ctx->frame_size);
3611  assert_avoptions(ost->encoder_opts);
3612  if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000 &&
3613  ost->enc_ctx->codec_id != AV_CODEC_ID_CODEC2 /* don't complain about 700 bit/s modes */)
3614  av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
3615  " It takes bits/s as argument, not kbits/s\n");
3616 
3618  if (ret < 0) {
3620  "Error initializing the output stream codec context.\n");
3621  exit_program(1);
3622  }
3623 
3624  if (ost->enc_ctx->nb_coded_side_data) {
3625  int i;
3626 
3627  for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
3628  const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
3629  uint8_t *dst_data;
3630 
3631  dst_data = av_stream_new_side_data(ost->st, sd_src->type, sd_src->size);
3632  if (!dst_data)
3633  return AVERROR(ENOMEM);
3634  memcpy(dst_data, sd_src->data, sd_src->size);
3635  }
3636  }
3637 
3638  /*
3639  * Add global input side data. For now this is naive, and copies it
3640  * from the input stream's global side data. All side data should
3641  * really be funneled over AVFrame and libavfilter, then added back to
3642  * packet side data, and then potentially using the first packet for
3643  * global side data.
3644  */
3645  if (ist) {
3646  int i;
3647  for (i = 0; i < ist->st->nb_side_data; i++) {
3648  AVPacketSideData *sd = &ist->st->side_data[i];
3649  if (sd->type != AV_PKT_DATA_CPB_PROPERTIES) {
3650  uint8_t *dst = av_stream_new_side_data(ost->st, sd->type, sd->size);
3651  if (!dst)
3652  return AVERROR(ENOMEM);
3653  memcpy(dst, sd->data, sd->size);
3654  if (ist->autorotate && sd->type == AV_PKT_DATA_DISPLAYMATRIX)
3655  av_display_rotation_set((int32_t *)dst, 0);
3656  }
3657  }
3658  }
3659 
3660  // copy timebase while removing common factors
3661  if (ost->st->time_base.num <= 0 || ost->st->time_base.den <= 0)
3662  ost->st->time_base = av_add_q(ost->enc_ctx->time_base, (AVRational){0, 1});
3663 
3664  // copy estimated duration as a hint to the muxer
3665  if (ost->st->duration <= 0 && ist && ist->st->duration > 0)
3666  ost->st->duration = av_rescale_q(ist->st->duration, ist->st->time_base, ost->st->time_base);
3667  } else if (ost->stream_copy) {
3669  if (ret < 0)
3670  return ret;
3671  }
3672 
3673  // parse user provided disposition, and update stream values
3674  if (ost->disposition) {
3675  static const AVOption opts[] = {
3676  { "disposition" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
3677  { "default" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT }, .unit = "flags" },
3678  { "dub" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB }, .unit = "flags" },
3679  { "original" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL }, .unit = "flags" },
3680  { "comment" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT }, .unit = "flags" },
3681  { "lyrics" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS }, .unit = "flags" },
3682  { "karaoke" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE }, .unit = "flags" },
3683  { "forced" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED }, .unit = "flags" },
3684  { "hearing_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED }, .unit = "flags" },
3685  { "visual_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED }, .unit = "flags" },
3686  { "clean_effects" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS }, .unit = "flags" },
3687  { "attached_pic" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ATTACHED_PIC }, .unit = "flags" },
3688  { "captions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS }, .unit = "flags" },
3689  { "descriptions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS }, .unit = "flags" },
3690  { "dependent" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEPENDENT }, .unit = "flags" },
3691  { "metadata" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA }, .unit = "flags" },
3692  { NULL },
3693  };
3694  static const AVClass class = {
3695  .class_name = "",
3696  .item_name = av_default_item_name,
3697  .option = opts,
3698  .version = LIBAVUTIL_VERSION_INT,
3699  };
3700  const AVClass *pclass = &class;
3701 
3702  ret = av_opt_eval_flags(&pclass, &opts[0], ost->disposition, &ost->st->disposition);
3703  if (ret < 0)
3704  return ret;
3705  }
3706 
3707  /* initialize bitstream filters for the output stream
3708  * needs to be done here, because the codec id for streamcopy is not
3709  * known until now */
3710  ret = init_output_bsfs(ost);
3711  if (ret < 0)
3712  return ret;
3713 
3714  ost->initialized = 1;
3715 
3716  ret = check_init_output_file(output_files[ost->file_index], ost->file_index);
3717  if (ret < 0)
3718  return ret;
3719 
3720  return ret;
3721 }
3722 
3723 static void report_new_stream(int input_index, AVPacket *pkt)
3724 {
3725  InputFile *file = input_files[input_index];
3726  AVStream *st = file->ctx->streams[pkt->stream_index];
3727 
3728  if (pkt->stream_index < file->nb_streams_warn)
3729  return;
3730  av_log(file->ctx, AV_LOG_WARNING,
3731  "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
3733  input_index, pkt->stream_index,
3734  pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
3735  file->nb_streams_warn = pkt->stream_index + 1;
3736 }
3737 
3738 static int transcode_init(void)
3739 {
3740  int ret = 0, i, j, k;
3741  AVFormatContext *oc;
3742  OutputStream *ost;
3743  InputStream *ist;
3744  char error[1024] = {0};
3745 
3746  for (i = 0; i < nb_filtergraphs; i++) {
3747  FilterGraph *fg = filtergraphs[i];
3748  for (j = 0; j < fg->nb_outputs; j++) {
3749  OutputFilter *ofilter = fg->outputs[j];
3750  if (!ofilter->ost || ofilter->ost->source_index >= 0)
3751  continue;
3752  if (fg->nb_inputs != 1)
3753  continue;
3754  for (k = nb_input_streams-1; k >= 0 ; k--)
3755  if (fg->inputs[0]->ist == input_streams[k])
3756  break;
3757  ofilter->ost->source_index = k;
3758  }
3759  }
3760 
3761  /* init framerate emulation */
3762  for (i = 0; i < nb_input_files; i++) {
3764  if (ifile->rate_emu)
3765  for (j = 0; j < ifile->nb_streams; j++)
3766  input_streams[j + ifile->ist_index]->start = av_gettime_relative();
3767  }
3768 
3769  /* init input streams */
3770  for (i = 0; i < nb_input_streams; i++)
3771  if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
3772  for (i = 0; i < nb_output_streams; i++) {
3773  ost = output_streams[i];
3774  avcodec_close(ost->enc_ctx);
3775  }
3776  goto dump_format;
3777  }
3778 
3779  /*
3780  * initialize stream copy and subtitle/data streams.
3781  * Encoded AVFrame based streams will get initialized as follows:
3782  * - when the first AVFrame is received in do_video_out
3783  * - just before the first AVFrame is received in either transcode_step
3784  * or reap_filters due to us requiring the filter chain buffer sink
3785  * to be configured with the correct audio frame size, which is only
3786  * known after the encoder is initialized.
3787  */
3788  for (i = 0; i < nb_output_streams; i++) {
3789  if (!output_streams[i]->stream_copy &&
3790  (output_streams[i]->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
3792  continue;
3793 
3795  if (ret < 0)
3796  goto dump_format;
3797  }
3798 
3799  /* discard unused programs */
3800  for (i = 0; i < nb_input_files; i++) {
3802  for (j = 0; j < ifile->ctx->nb_programs; j++) {
3803  AVProgram *p = ifile->ctx->programs[j];
3804  int discard = AVDISCARD_ALL;
3805 
3806  for (k = 0; k < p->nb_stream_indexes; k++)
3807  if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
3808  discard = AVDISCARD_DEFAULT;
3809  break;
3810  }
3811  p->discard = discard;
3812  }
3813  }
3814 
3815  /* write headers for files with no streams */
3816  for (i = 0; i < nb_output_files; i++) {
3817  oc = output_files[i]->ctx;
3818  if (oc->oformat->flags & AVFMT_NOSTREAMS && oc->nb_streams == 0) {
3820  if (ret < 0)
3821  goto dump_format;
3822  }
3823  }
3824 
3825  dump_format:
3826  /* dump the stream mapping */
3827  av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
3828  for (i = 0; i < nb_input_streams; i++) {
3829  ist = input_streams[i];
3830 
3831  for (j = 0; j < ist->nb_filters; j++) {
3832  if (!filtergraph_is_simple(ist->filters[j]->graph)) {
3833  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
3834  ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
3835  ist->filters[j]->name);
3836  if (nb_filtergraphs > 1)
3837  av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
3838  av_log(NULL, AV_LOG_INFO, "\n");
3839  }
3840  }
3841  }
3842 
3843  for (i = 0; i < nb_output_streams; i++) {
3844  ost = output_streams[i];
3845 
3846  if (ost->attachment_filename) {
3847  /* an attached file */
3848  av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
3849  ost->attachment_filename, ost->file_index, ost->index);
3850  continue;
3851  }
3852 
3853  if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
3854  /* output from a complex graph */
3855  av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
3856  if (nb_filtergraphs > 1)
3857  av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
3858 
3859  av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
3860  ost->index, ost->enc ? ost->enc->name : "?");
3861  continue;
3862  }
3863 
3864  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
3865  input_streams[ost->source_index]->file_index,
3866  input_streams[ost->source_index]->st->index,
3867  ost->file_index,
3868  ost->index);
3869  if (ost->sync_ist != input_streams[ost->source_index])
3870  av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
3871  ost->sync_ist->file_index,
3872  ost->sync_ist->st->index);
3873  if (ost->stream_copy)
3874  av_log(NULL, AV_LOG_INFO, " (copy)");
3875  else {
3876  const AVCodec *in_codec = input_streams[ost->source_index]->dec;
3877  const AVCodec *out_codec = ost->enc;
3878  const char *decoder_name = "?";
3879  const char *in_codec_name = "?";
3880  const char *encoder_name = "?";
3881  const char *out_codec_name = "?";
3882  const AVCodecDescriptor *desc;
3883 
3884  if (in_codec) {
3885  decoder_name = in_codec->name;
3886  desc = avcodec_descriptor_get(in_codec->id);
3887  if (desc)
3888  in_codec_name = desc->name;
3889  if (!strcmp(decoder_name, in_codec_name))
3890  decoder_name = "native";
3891  }
3892 
3893  if (out_codec) {
3894  encoder_name = out_codec->name;
3895  desc = avcodec_descriptor_get(out_codec->id);
3896  if (desc)
3897  out_codec_name = desc->name;
3898  if (!strcmp(encoder_name, out_codec_name))
3899  encoder_name = "native";
3900  }
3901 
3902  av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
3903  in_codec_name, decoder_name,
3904  out_codec_name, encoder_name);
3905  }
3906  av_log(NULL, AV_LOG_INFO, "\n");
3907  }
3908 
3909  if (ret) {
3910  av_log(NULL, AV_LOG_ERROR, "%s\n", error);
3911  return ret;
3912  }
3913 
3915 
3916  return 0;
3917 }
3918 
3919 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
3920 static int need_output(void)
3921 {
3922  int i;
3923 
3924  for (i = 0; i < nb_output_streams; i++) {
3926  OutputFile *of = output_files[ost->file_index];
3927  AVFormatContext *os = output_files[ost->file_index]->ctx;
3928 
3929  if (ost->finished ||
3930  (os->pb && avio_tell(os->pb) >= of->limit_filesize))
3931  continue;
3932  if (ost->frame_number >= ost->max_frames) {
3933  int j;
3934  for (j = 0; j < of->ctx->nb_streams; j++)
3936  continue;
3937  }
3938 
3939  return 1;
3940  }
3941 
3942  return 0;
3943 }
3944 
3945 /**
3946  * Select the output stream to process.
3947  *
3948  * @return selected output stream, or NULL if none available
3949  */
3951 {
3952  int i;
3953  int64_t opts_min = INT64_MAX;
3954  OutputStream *ost_min = NULL;
3955 
3956  for (i = 0; i < nb_output_streams; i++) {
3958  int64_t opts = ost->st->cur_dts == AV_NOPTS_VALUE ? INT64_MIN :
3959  av_rescale_q(ost->st->cur_dts, ost->st->time_base,
3960  AV_TIME_BASE_Q);
3961  if (ost->st->cur_dts == AV_NOPTS_VALUE)
3963  "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",
3964  ost->st->index, ost->st->id, ost->initialized, ost->inputs_done, ost->finished);
3965 
3966  if (!ost->initialized && !ost->inputs_done)
3967  return ost->unavailable ? NULL : ost;
3968 
3969  if (!ost->finished && opts < opts_min) {
3970  opts_min = opts;
3971  ost_min = ost->unavailable ? NULL : ost;
3972  }
3973  }
3974  return ost_min;
3975 }
3976 
3977 static void set_tty_echo(int on)
3978 {
3979 #if HAVE_TERMIOS_H
3980  struct termios tty;
3981  if (tcgetattr(0, &tty) == 0) {
3982  if (on) tty.c_lflag |= ECHO;
3983  else tty.c_lflag &= ~ECHO;
3984  tcsetattr(0, TCSANOW, &tty);
3985  }
3986 #endif
3987 }
3988 
3990 {
3991  int i, ret, key;
3992  static int64_t last_time;
3993  if (received_nb_signals)
3994  return AVERROR_EXIT;
3995  /* read_key() returns 0 on EOF */
3996  if(cur_time - last_time >= 100000 && !run_as_daemon){
3997  key = read_key();
3998  last_time = cur_time;
3999  }else
4000  key = -1;
4001  if (key == 'q')
4002  return AVERROR_EXIT;
4003  if (key == '+') av_log_set_level(av_log_get_level()+10);
4004  if (key == '-') av_log_set_level(av_log_get_level()-10);
4005  if (key == 's') qp_hist ^= 1;
4006  if (key == 'h'){
4007  if (do_hex_dump){
4008  do_hex_dump = do_pkt_dump = 0;
4009  } else if(do_pkt_dump){
4010  do_hex_dump = 1;
4011  } else
4012  do_pkt_dump = 1;
4014  }
4015  if (key == 'c' || key == 'C'){
4016  char buf[4096], target[64], command[256], arg[256] = {0};
4017  double time;
4018  int k, n = 0;
4019  fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
4020  i = 0;
4021  set_tty_echo(1);
4022  while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
4023  if (k > 0)
4024  buf[i++] = k;
4025  buf[i] = 0;
4026  set_tty_echo(0);
4027  fprintf(stderr, "\n");
4028  if (k > 0 &&
4029  (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
4030  av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
4031  target, time, command, arg);
4032  for (i = 0; i < nb_filtergraphs; i++) {
4033  FilterGraph *fg = filtergraphs[i];
4034  if (fg->graph) {
4035  if (time < 0) {
4036  ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
4037  key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
4038  fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
4039  } else if (key == 'c') {
4040  fprintf(stderr, "Queuing commands only on filters supporting the specific command is unsupported\n");
4041  ret = AVERROR_PATCHWELCOME;
4042  } else {
4043  ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
4044  if (ret < 0)
4045  fprintf(stderr, "Queuing command failed with error %s\n", av_err2str(ret));
4046  }
4047  }
4048  }
4049  } else {
4051  "Parse error, at least 3 arguments were expected, "
4052  "only %d given in string '%s'\n", n, buf);
4053  }
4054  }
4055  if (key == 'd' || key == 'D'){
4056  int debug=0;
4057  if(key == 'D') {
4058  debug = input_streams[0]->dec_ctx->debug << 1;
4059  if(!debug) debug = 1;
4060  while (debug & FF_DEBUG_DCT_COEFF) //unsupported, would just crash
4061  debug += debug;
4062  }else{
4063  char buf[32];
4064  int k = 0;
4065  i = 0;
4066  set_tty_echo(1);
4067  while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
4068  if (k > 0)
4069  buf[i++] = k;
4070  buf[i] = 0;
4071  set_tty_echo(0);
4072  fprintf(stderr, "\n");
4073  if (k <= 0 || sscanf(buf, "%d", &debug)!=1)
4074  fprintf(stderr,"error parsing debug value\n");
4075  }
4076  for(i=0;i<nb_input_streams;i++) {
4077  input_streams[i]->dec_ctx->debug = debug;
4078  }
4079  for(i=0;i<nb_output_streams;i++) {
4081  ost->enc_ctx->debug = debug;
4082  }
4083  if(debug) av_log_set_level(AV_LOG_DEBUG);
4084  fprintf(stderr,"debug=%d\n", debug);
4085  }
4086  if (key == '?'){
4087  fprintf(stderr, "key function\n"
4088  "? show this help\n"
4089  "+ increase verbosity\n"
4090  "- decrease verbosity\n"
4091  "c Send command to first matching filter supporting it\n"
4092  "C Send/Queue command to all matching filters\n"
4093  "D cycle through available debug modes\n"
4094  "h dump packets/hex press to cycle through the 3 states\n"
4095  "q quit\n"
4096  "s Show QP histogram\n"
4097  );
4098  }
4099  return 0;
4100 }
4101 
4102 #if HAVE_THREADS
4103 static void *input_thread(void *arg)
4104 {
4105  InputFile *f = arg;
4106  AVPacket *pkt = f->pkt, *queue_pkt;
4107  unsigned flags = f->non_blocking ? AV_THREAD_MESSAGE_NONBLOCK : 0;
4108  int ret = 0;
4109 
4110  while (1) {
4111  ret = av_read_frame(f->ctx, pkt);
4112 
4113  if (ret == AVERROR(EAGAIN)) {
4114  av_usleep(10000);
4115  continue;
4116  }
4117  if (ret < 0) {
4118  av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
4119  break;
4120  }
4121  queue_pkt = av_packet_alloc();
4122  if (!queue_pkt) {
4124  av_thread_message_queue_set_err_recv(f->in_thread_queue, AVERROR(ENOMEM));
4125  break;
4126  }
4127  av_packet_move_ref(queue_pkt, pkt);
4128  ret = av_thread_message_queue_send(f->in_thread_queue, &queue_pkt, flags);
4129  if (flags && ret == AVERROR(EAGAIN)) {
4130  flags = 0;
4131  ret = av_thread_message_queue_send(f->in_thread_queue, &queue_pkt, flags);
4132  av_log(f->ctx, AV_LOG_WARNING,
4133  "Thread message queue blocking; consider raising the "
4134  "thread_queue_size option (current value: %d)\n",
4135  f->thread_queue_size);
4136  }
4137  if (ret < 0) {
4138  if (ret != AVERROR_EOF)
4139  av_log(f->ctx, AV_LOG_ERROR,
4140  "Unable to send packet to main thread: %s\n",
4141  av_err2str(ret));
4142  av_packet_free(&queue_pkt);
4143  av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
4144  break;
4145  }
4146  }
4147 
4148  return NULL;
4149 }
4150 
4151 static void free_input_thread(int i)
4152 {
4153  InputFile *f = input_files[i];
4154  AVPacket *pkt;
4155 
4156  if (!f || !f->in_thread_queue)
4157  return;
4159  while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
4160  av_packet_free(&pkt);
4161 
4162  pthread_join(f->thread, NULL);
4163  f->joined = 1;
4164  av_thread_message_queue_free(&f->in_thread_queue);
4165 }
4166 
4167 static void free_input_threads(void)
4168 {
4169  int i;
4170 
4171  for (i = 0; i < nb_input_files; i++)
4172  free_input_thread(i);
4173 }
4174 
4175 static int init_input_thread(int i)
4176 {
4177  int ret;
4178  InputFile *f = input_files[i];
4179 
4180  if (f->thread_queue_size < 0)
4181  f->thread_queue_size = (nb_input_files > 1 ? 8 : 0);
4182  if (!f->thread_queue_size)
4183  return 0;
4184 
4185  if (f->ctx->pb ? !f->ctx->pb->seekable :
4186  strcmp(f->ctx->iformat->name, "lavfi"))
4187  f->non_blocking = 1;
4188  ret = av_thread_message_queue_alloc(&f->in_thread_queue,
4189  f->thread_queue_size, sizeof(f->pkt));
4190  if (ret < 0)
4191  return ret;
4192 
4193  if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
4194  av_log(NULL, AV_LOG_ERROR, "pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
4195  av_thread_message_queue_free(&f->in_thread_queue);
4196  return AVERROR(ret);
4197  }
4198 
4199  return 0;
4200 }
4201 
4202 static int init_input_threads(void)
4203 {
4204  int i, ret;
4205 
4206  for (i = 0; i < nb_input_files; i++) {
4207  ret = init_input_thread(i);
4208  if (ret < 0)
4209  return ret;
4210  }
4211  return 0;
4212 }
4213 
4214 static int get_input_packet_mt(InputFile *f, AVPacket **pkt)
4215 {
4216  return av_thread_message_queue_recv(f->in_thread_queue, pkt,
4217  f->non_blocking ?
4219 }
4220 #endif
4221 
4223 {
4224  if (f->rate_emu) {
4225  int i;
4226  for (i = 0; i < f->nb_streams; i++) {
4227  InputStream *ist = input_streams[f->ist_index + i];
4228  int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
4229  int64_t now = av_gettime_relative() - ist->start;
4230  if (pts > now)
4231  return AVERROR(EAGAIN);
4232  }
4233  }
4234 
4235 #if HAVE_THREADS
4236  if (f->thread_queue_size)
4237  return get_input_packet_mt(f, pkt);
4238 #endif
4239  *pkt = f->pkt;
4240  return av_read_frame(f->ctx, *pkt);
4241 }
4242 
4243 static int got_eagain(void)
4244 {
4245  int i;
4246  for (i = 0; i < nb_output_streams; i++)
4247  if (output_streams[i]->unavailable)
4248  return 1;
4249  return 0;
4250 }
4251 
4252 static void reset_eagain(void)
4253 {
4254  int i;
4255  for (i = 0; i < nb_input_files; i++)
4256  input_files[i]->eagain = 0;
4257  for (i = 0; i < nb_output_streams; i++)
4258  output_streams[i]->unavailable = 0;
4259 }
4260 
4261 // set duration to max(tmp, duration) in a proper time base and return duration's time_base
4263  AVRational time_base)
4264 {
4265  int ret;
4266 
4267  if (!*duration) {
4268  *duration = tmp;
4269  return tmp_time_base;
4270  }
4271 
4272  ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
4273  if (ret < 0) {
4274  *duration = tmp;
4275  return tmp_time_base;
4276  }
4277 
4278  return time_base;
4279 }
4280 
4282 {
4283  InputStream *ist;
4284  AVCodecContext *avctx;
4285  int i, ret, has_audio = 0;
4286  int64_t duration = 0;
4287 
4288  ret = avformat_seek_file(is, -1, INT64_MIN, is->start_time, is->start_time, 0);
4289  if (ret < 0)
4290  return ret;
4291 
4292  for (i = 0; i < ifile->nb_streams; i++) {
4293  ist = input_streams[ifile->ist_index + i];
4294  avctx = ist->dec_ctx;
4295 
4296  /* duration is the length of the last frame in a stream
4297  * when audio stream is present we don't care about
4298  * last video frame length because it's not defined exactly */
4299  if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
4300  has_audio = 1;
4301  }
4302 
4303  for (i = 0; i < ifile->nb_streams; i++) {
4304  ist = input_streams[ifile->ist_index + i];
4305  avctx = ist->dec_ctx;
4306 
4307  if (has_audio) {
4308  if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
4309  AVRational sample_rate = {1, avctx->sample_rate};
4310 
4312  } else {
4313  continue;
4314  }
4315  } else {
4316  if (ist->framerate.num) {
4317  duration = av_rescale_q(1, av_inv_q(ist->framerate), ist->st->time_base);
4318  } else if (ist->st->avg_frame_rate.num) {
4320  } else {
4321  duration = 1;
4322  }
4323  }
4324  if (!ifile->duration)
4325  ifile->time_base = ist->st->time_base;
4326  /* the total duration of the stream, max_pts - min_pts is
4327  * the duration of the stream without the last frame */
4328  if (ist->max_pts > ist->min_pts && ist->max_pts - (uint64_t)ist->min_pts < INT64_MAX - duration)
4329  duration += ist->max_pts - ist->min_pts;
4330  ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
4331  ifile->time_base);
4332  }
4333 
4334  if (ifile->loop > 0)
4335  ifile->loop--;
4336 
4337  return ret;
4338 }
4339 
4340 /*
4341  * Return
4342  * - 0 -- one packet was read and processed
4343  * - AVERROR(EAGAIN) -- no packets were available for selected file,
4344  * this function should be called again
4345  * - AVERROR_EOF -- this function should not be called again
4346  */
4347 static int process_input(int file_index)
4348 {
4349  InputFile *ifile = input_files[file_index];
4351  InputStream *ist;
4352  AVPacket *pkt;
4353  int ret, thread_ret, i, j;
4354  int64_t duration;
4355  int64_t pkt_dts;
4356  int disable_discontinuity_correction = copy_ts;
4357 
4358  is = ifile->ctx;
4359  ret = get_input_packet(ifile, &pkt);
4360 
4361  if (ret == AVERROR(EAGAIN)) {
4362  ifile->eagain = 1;
4363  return ret;
4364  }
4365  if (ret < 0 && ifile->loop) {
4366  AVCodecContext *avctx;
4367  for (i = 0; i < ifile->nb_streams; i++) {
4368  ist = input_streams[ifile->ist_index + i];
4369  avctx = ist->dec_ctx;
4370  if (ist->decoding_needed) {
4371  ret = process_input_packet(ist, NULL, 1);
4372  if (ret>0)
4373  return 0;
4374  avcodec_flush_buffers(avctx);
4375  }
4376  }
4377 #if HAVE_THREADS
4378  free_input_thread(file_index);
4379 #endif
4380  ret = seek_to_start(ifile, is);
4381 #if HAVE_THREADS
4382  thread_ret = init_input_thread(file_index);
4383  if (thread_ret < 0)
4384  return thread_ret;
4385 #endif
4386  if (ret < 0)
4387  av_log(NULL, AV_LOG_WARNING, "Seek to start failed.\n");
4388  else
4389  ret = get_input_packet(ifile, &pkt);
4390  if (ret == AVERROR(EAGAIN)) {
4391  ifile->eagain = 1;
4392  return ret;
4393  }
4394  }
4395  if (ret < 0) {
4396  if (ret != AVERROR_EOF) {
4397  print_error(is->url, ret);
4398  if (exit_on_error)
4399  exit_program(1);
4400  }
4401 
4402  for (i = 0; i < ifile->nb_streams; i++) {
4403  ist = input_streams[ifile->ist_index + i];
4404  if (ist->decoding_needed) {
4405  ret = process_input_packet(ist, NULL, 0);
4406  if (ret>0)
4407  return 0;
4408  }
4409 
4410  /* mark all outputs that don't go through lavfi as finished */
4411  for (j = 0; j < nb_output_streams; j++) {
4413 
4414  if (ost->source_index == ifile->ist_index + i &&
4415  (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
4417  }
4418  }
4419 
4420  ifile->eof_reached = 1;
4421  return AVERROR(EAGAIN);
4422  }
4423 
4424  reset_eagain();
4425 
4426  if (do_pkt_dump) {
4428  is->streams[pkt->stream_index]);
4429  }
4430  /* the following test is needed in case new streams appear
4431  dynamically in stream : we ignore them */
4432  if (pkt->stream_index >= ifile->nb_streams) {
4433  report_new_stream(file_index, pkt);
4434  goto discard_packet;
4435  }
4436 
4437  ist = input_streams[ifile->ist_index + pkt->stream_index];
4438 
4439  ist->data_size += pkt->size;
4440  ist->nb_packets++;
4441 
4442  if (ist->discard)
4443  goto discard_packet;
4444 
4445  if (pkt->flags & AV_PKT_FLAG_CORRUPT) {
4447  "%s: corrupt input packet in stream %d\n", is->url, pkt->stream_index);
4448  if (exit_on_error)
4449  exit_program(1);
4450  }
4451 
4452  if (debug_ts) {
4453  av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
4454  "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",
4462  }
4463 
4464  if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
4465  int64_t stime, stime2;
4466  // Correcting starttime based on the enabled streams
4467  // 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.
4468  // so we instead do it here as part of discontinuity handling
4469  if ( ist->next_dts == AV_NOPTS_VALUE
4470  && ifile->ts_offset == -is->start_time
4471  && (is->iformat->flags & AVFMT_TS_DISCONT)) {
4472  int64_t new_start_time = INT64_MAX;
4473  for (i=0; i<is->nb_streams; i++) {
4474  AVStream *st = is->streams[i];
4475  if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
4476  continue;
4477  new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
4478  }
4479  if (new_start_time > is->start_time) {
4480  av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
4481  ifile->ts_offset = -new_start_time;
4482  }
4483  }
4484 
4485  stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
4486  stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
4487  ist->wrap_correction_done = 1;
4488 
4489  if(stime2 > stime && pkt->dts != AV_NOPTS_VALUE && pkt->dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
4490  pkt->dts -= 1ULL<<ist->st->pts_wrap_bits;
4491  ist->wrap_correction_done = 0;
4492  }
4493  if(stime2 > stime && pkt->pts != AV_NOPTS_VALUE && pkt->pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
4494  pkt->pts -= 1ULL<<ist->st->pts_wrap_bits;
4495  ist->wrap_correction_done = 0;
4496  }
4497  }
4498 
4499  /* add the stream-global side data to the first packet */
4500  if (ist->nb_packets == 1) {
4501  for (i = 0; i < ist->st->nb_side_data; i++) {
4502  AVPacketSideData *src_sd = &ist->st->side_data[i];
4503  uint8_t *dst_data;
4504 
4505  if (src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
4506  continue;
4507 
4508  if (av_packet_get_side_data(pkt, src_sd->type, NULL))
4509  continue;
4510 
4511  dst_data = av_packet_new_side_data(pkt, src_sd->type, src_sd->size);
4512  if (!dst_data)
4513  exit_program(1);
4514 
4515  memcpy(dst_data, src_sd->data, src_sd->size);
4516  }
4517  }
4518 
4519  if (pkt->dts != AV_NOPTS_VALUE)
4520  pkt->dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
4521  if (pkt->pts != AV_NOPTS_VALUE)
4522  pkt->pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
4523 
4524  if (pkt->pts != AV_NOPTS_VALUE)
4525  pkt->pts *= ist->ts_scale;
4526  if (pkt->dts != AV_NOPTS_VALUE)
4527  pkt->dts *= ist->ts_scale;
4528 
4530  if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
4532  pkt_dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
4533  && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
4534  int64_t delta = pkt_dts - ifile->last_ts;
4535  if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
4537  ifile->ts_offset -= delta;
4539  "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
4540  delta, ifile->ts_offset);
4542  if (pkt->pts != AV_NOPTS_VALUE)
4544  }
4545  }
4546 
4547  duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
4548  if (pkt->pts != AV_NOPTS_VALUE) {
4549  pkt->pts += duration;
4550  ist->max_pts = FFMAX(pkt->pts, ist->max_pts);
4551  ist->min_pts = FFMIN(pkt->pts, ist->min_pts);
4552  }
4553 
4554  if (pkt->dts != AV_NOPTS_VALUE)
4555  pkt->dts += duration;
4556 
4558 
4559  if (copy_ts && pkt_dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
4560  (is->iformat->flags & AVFMT_TS_DISCONT) && ist->st->pts_wrap_bits < 60) {
4561  int64_t wrap_dts = av_rescale_q_rnd(pkt->dts + (1LL<<ist->st->pts_wrap_bits),
4562  ist->st->time_base, AV_TIME_BASE_Q,
4564  if (FFABS(wrap_dts - ist->next_dts) < FFABS(pkt_dts - ist->next_dts)/10)
4565  disable_discontinuity_correction = 0;
4566  }
4567 
4568  if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
4570  pkt_dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
4571  !disable_discontinuity_correction) {
4572  int64_t delta = pkt_dts - ist->next_dts;
4573  if (is->iformat->flags & AVFMT_TS_DISCONT) {
4574  if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
4576  pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {
4577  ifile->ts_offset -= delta;
4579  "timestamp discontinuity for stream #%d:%d "
4580  "(id=%d, type=%s): %"PRId64", new offset= %"PRId64"\n",
4581  ist->file_index, ist->st->index, ist->st->id,
4583  delta, ifile->ts_offset);
4585  if (pkt->pts != AV_NOPTS_VALUE)
4587  }
4588  } else {
4589  if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
4591  av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt->dts, ist->next_dts, pkt->stream_index);
4592  pkt->dts = AV_NOPTS_VALUE;
4593  }
4594  if (pkt->pts != AV_NOPTS_VALUE){
4595  int64_t pkt_pts = av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
4596  delta = pkt_pts - ist->next_dts;
4597  if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
4599  av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt->pts, ist->next_dts, pkt->stream_index);
4600  pkt->pts = AV_NOPTS_VALUE;
4601  }
4602  }
4603  }
4604  }
4605 
4606  if (pkt->dts != AV_NOPTS_VALUE)
4607  ifile->last_ts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
4608 
4609  if (debug_ts) {
4610  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",
4616  }
4617 
4618  sub2video_heartbeat(ist, pkt->pts);
4619 
4620  process_input_packet(ist, pkt, 0);
4621 
4622 discard_packet:
4623 #if HAVE_THREADS
4624  if (ifile->thread_queue_size)
4625  av_packet_free(&pkt);
4626  else
4627 #endif
4629 
4630  return 0;
4631 }
4632 
4633 /**
4634  * Perform a step of transcoding for the specified filter graph.
4635  *
4636  * @param[in] graph filter graph to consider
4637  * @param[out] best_ist input stream where a frame would allow to continue
4638  * @return 0 for success, <0 for error
4639  */
4640 static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
4641 {
4642  int i, ret;
4643  int nb_requests, nb_requests_max = 0;
4644  InputFilter *ifilter;
4645  InputStream *ist;
4646 
4647  *best_ist = NULL;
4648  ret = avfilter_graph_request_oldest(graph->graph);
4649  if (ret >= 0)
4650  return reap_filters(0);
4651 
4652  if (ret == AVERROR_EOF) {
4653  ret = reap_filters(1);
4654  for (i = 0; i < graph->nb_outputs; i++)
4655  close_output_stream(graph->outputs[i]->ost);
4656  return ret;
4657  }
4658  if (ret != AVERROR(EAGAIN))
4659  return ret;
4660 
4661  for (i = 0; i < graph->nb_inputs; i++) {
4662  ifilter = graph->inputs[i];
4663  ist = ifilter->ist;
4664  if (input_files[ist->file_index]->eagain ||
4666  continue;
4667  nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
4668  if (nb_requests > nb_requests_max) {
4669  nb_requests_max = nb_requests;
4670  *best_ist = ist;
4671  }
4672  }
4673 
4674  if (!*best_ist)
4675  for (i = 0; i < graph->nb_outputs; i++)
4676  graph->outputs[i]->ost->unavailable = 1;
4677 
4678  return 0;
4679 }
4680 
4681 /**
4682  * Run a single step of transcoding.
4683  *
4684  * @return 0 for success, <0 for error
4685  */
4686 static int transcode_step(void)
4687 {
4688  OutputStream *ost;
4689  InputStream *ist = NULL;
4690  int ret;
4691 
4692  ost = choose_output();
4693  if (!ost) {
4694  if (got_eagain()) {
4695  reset_eagain();
4696  av_usleep(10000);
4697  return 0;
4698  }
4699  av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
4700  return AVERROR_EOF;
4701  }
4702 
4703  if (ost->filter && !ost->filter->graph->graph) {
4704  if (ifilter_has_all_input_formats(ost->filter->graph)) {
4705  ret = configure_filtergraph(ost->filter->graph);
4706  if (ret < 0) {
4707  av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
4708  return ret;
4709  }
4710  }
4711  }
4712 
4713  if (ost->filter && ost->filter->graph->graph) {
4714  /*
4715  * Similar case to the early audio initialization in reap_filters.
4716  * Audio is special in ffmpeg.c currently as we depend on lavfi's
4717  * audio frame buffering/creation to get the output audio frame size
4718  * in samples correct. The audio frame size for the filter chain is
4719  * configured during the output stream initialization.
4720  *
4721  * Apparently avfilter_graph_request_oldest (called in
4722  * transcode_from_filter just down the line) peeks. Peeking already
4723  * puts one frame "ready to be given out", which means that any
4724  * update in filter buffer sink configuration afterwards will not
4725  * help us. And yes, even if it would be utilized,
4726  * av_buffersink_get_samples is affected, as it internally utilizes
4727  * the same early exit for peeked frames.
4728  *
4729  * In other words, if avfilter_graph_request_oldest would not make
4730  * further filter chain configuration or usage of
4731  * av_buffersink_get_samples useless (by just causing the return
4732  * of the peeked AVFrame as-is), we could get rid of this additional
4733  * early encoder initialization.
4734  */
4735  if (av_buffersink_get_type(ost->filter->filter) == AVMEDIA_TYPE_AUDIO)
4737 
4738  if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
4739  return ret;
4740  if (!ist)
4741  return 0;
4742  } else if (ost->filter) {
4743  int i;
4744  for (i = 0; i < ost->filter->graph->nb_inputs; i++) {
4745  InputFilter *ifilter = ost->filter->graph->inputs[i];
4746  if (!ifilter->ist->got_output && !input_files[ifilter->ist->file_index]->eof_reached) {
4747  ist = ifilter->ist;
4748  break;
4749  }
4750  }
4751  if (!ist) {
4752  ost->inputs_done = 1;
4753  return 0;
4754  }
4755  } else {
4756  av_assert0(ost->source_index >= 0);
4757  ist = input_streams[ost->source_index];
4758  }
4759 
4760  ret = process_input(ist->file_index);
4761  if (ret == AVERROR(EAGAIN)) {
4762  if (input_files[ist->file_index]->eagain)
4763  ost->unavailable = 1;
4764  return 0;
4765  }
4766 
4767  if (ret < 0)
4768  return ret == AVERROR_EOF ? 0 : ret;
4769 
4770  return reap_filters(0);
4771 }
4772 
4773 /*
4774  * The following code is the main loop of the file converter
4775  */
4776 static int transcode(void)
4777 {
4778  int ret, i;
4779  AVFormatContext *os;
4780  OutputStream *ost;
4781  InputStream *ist;
4782  int64_t timer_start;
4783  int64_t total_packets_written = 0;
4784 
4785  ret = transcode_init();
4786  if (ret < 0)
4787  goto fail;
4788 
4789  if (stdin_interaction) {
4790  av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
4791  }
4792 
4793  timer_start = av_gettime_relative();
4794 
4795 #if HAVE_THREADS
4796  if ((ret = init_input_threads()) < 0)
4797  goto fail;
4798 #endif
4799 
4800  while (!received_sigterm) {
4801  int64_t cur_time= av_gettime_relative();
4802 
4803  /* if 'q' pressed, exits */
4804  if (stdin_interaction)
4805  if (check_keyboard_interaction(cur_time) < 0)
4806  break;
4807 
4808  /* check if there's any stream where output is still needed */
4809  if (!need_output()) {
4810  av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
4811  break;
4812  }
4813 
4814  ret = transcode_step();
4815  if (ret < 0 && ret != AVERROR_EOF) {
4816  av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
4817  break;
4818  }
4819 
4820  /* dump report by using the output first video and audio streams */
4821  print_report(0, timer_start, cur_time);
4822  }
4823 #if HAVE_THREADS
4824  free_input_threads();
4825 #endif
4826 
4827  /* at the end of stream, we must flush the decoder buffers */
4828  for (i = 0; i < nb_input_streams; i++) {
4829  ist = input_streams[i];
4830  if (!input_files[ist->file_index]->eof_reached) {
4831  process_input_packet(ist, NULL, 0);
4832  }
4833  }
4834  flush_encoders();
4835 
4836  term_exit();
4837 
4838  /* write the trailer if needed and close file */
4839  for (i = 0; i < nb_output_files; i++) {
4840  os = output_files[i]->ctx;
4841  if (!output_files[i]->header_written) {
4843  "Nothing was written into output file %d (%s), because "
4844  "at least one of its streams received no packets.\n",
4845  i, os->url);
4846  continue;
4847  }
4848  if ((ret = av_write_trailer(os)) < 0) {
4849  av_log(NULL, AV_LOG_ERROR, "Error writing trailer of %s: %s\n", os->url, av_err2str(ret));
4850  if (exit_on_error)
4851  exit_program(1);
4852  }
4853  }
4854 
4855  /* dump report by using the first video and audio streams */
4856  print_report(1, timer_start, av_gettime_relative());
4857 
4858  /* close each encoder */
4859  for (i = 0; i < nb_output_streams; i++) {
4860  ost = output_streams[i];
4861  if (ost->encoding_needed) {
4862  av_freep(&ost->enc_ctx->stats_in);
4863  }
4864  total_packets_written += ost->packets_written;
4865  if (!ost->packets_written && (abort_on_flags & ABORT_ON_FLAG_EMPTY_OUTPUT_STREAM)) {
4866  av_log(NULL, AV_LOG_FATAL, "Empty output on stream %d.\n", i);
4867  exit_program(1);
4868  }
4869  }
4870 
4871  if (!total_packets_written && (abort_on_flags & ABORT_ON_FLAG_EMPTY_OUTPUT)) {
4872  av_log(NULL, AV_LOG_FATAL, "Empty output\n");
4873  exit_program(1);
4874  }
4875 
4876  /* close each decoder */
4877  for (i = 0; i < nb_input_streams; i++) {
4878  ist = input_streams[i];
4879  if (ist->decoding_needed) {
4880  avcodec_close(ist->dec_ctx);
4881  if (ist->hwaccel_uninit)
4882  ist->hwaccel_uninit(ist->dec_ctx);
4883  }
4884  }
4885 
4887 
4888  /* finished ! */
4889  ret = 0;
4890 
4891  fail:
4892 #if HAVE_THREADS
4893  free_input_threads();
4894 #endif
4895 
4896  if (output_streams) {
4897  for (i = 0; i < nb_output_streams; i++) {
4898  ost = output_streams[i];
4899  if (ost) {
4900  if (ost->logfile) {
4901  if (fclose(ost->logfile))
4903  "Error closing logfile, loss of information possible: %s\n",
4904  av_err2str(AVERROR(errno)));
4905  ost->logfile = NULL;
4906  }
4907  av_freep(&ost->forced_kf_pts);
4908  av_freep(&ost->apad);
4910  av_dict_free(&ost->encoder_opts);
4911  av_dict_free(&ost->sws_dict);
4912  av_dict_free(&ost->swr_opts);
4913  av_dict_free(&ost->resample_opts);
4914  }
4915  }
4916  }
4917  return ret;
4918 }
4919 
4921 {
4922  BenchmarkTimeStamps time_stamps = { av_gettime_relative() };
4923 #if HAVE_GETRUSAGE
4924  struct rusage rusage;
4925 
4926  getrusage(RUSAGE_SELF, &rusage);
4927  time_stamps.user_usec =
4928  (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
4929  time_stamps.sys_usec =
4930  (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
4931 #elif HAVE_GETPROCESSTIMES
4932  HANDLE proc;
4933  FILETIME c, e, k, u;
4934  proc = GetCurrentProcess();
4935  GetProcessTimes(proc, &c, &e, &k, &u);
4936  time_stamps.user_usec =
4937  ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
4938  time_stamps.sys_usec =
4939  ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
4940 #else
4941  time_stamps.user_usec = time_stamps.sys_usec = 0;
4942 #endif
4943  return time_stamps;
4944 }
4945 
4946 static int64_t getmaxrss(void)
4947 {
4948 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
4949  struct rusage rusage;
4950  getrusage(RUSAGE_SELF, &rusage);
4951  return (int64_t)rusage.ru_maxrss * 1024;
4952 #elif HAVE_GETPROCESSMEMORYINFO
4953  HANDLE proc;
4954  PROCESS_MEMORY_COUNTERS memcounters;
4955  proc = GetCurrentProcess();
4956  memcounters.cb = sizeof(memcounters);
4957  GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
4958  return memcounters.PeakPagefileUsage;
4959 #else
4960  return 0;
4961 #endif
4962 }
4963 
4964 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
4965 {
4966 }
4967 
4968 int main(int argc, char **argv)
4969 {
4970  int i, ret;
4972 
4973  init_dynload();
4974 
4976 
4977  setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
4978 
4980  parse_loglevel(argc, argv, options);
4981 
4982  if(argc>1 && !strcmp(argv[1], "-d")){
4983  run_as_daemon=1;
4985  argc--;
4986  argv++;
4987  }
4988 
4989 #if CONFIG_AVDEVICE
4991 #endif
4993 
4994  show_banner(argc, argv, options);
4995 
4996  /* parse options and open all input/output files */
4997  ret = ffmpeg_parse_options(argc, argv);
4998  if (ret < 0)
4999  exit_program(1);
5000 
5001  if (nb_output_files <= 0 && nb_input_files == 0) {
5002  show_usage();
5003  av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
5004  exit_program(1);
5005  }
5006 
5007  /* file converter / grab */
5008  if (nb_output_files <= 0) {
5009  av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
5010  exit_program(1);
5011  }
5012 
5013  for (i = 0; i < nb_output_files; i++) {
5014  if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
5015  want_sdp = 0;
5016  }
5017 
5019  if (transcode() < 0)
5020  exit_program(1);
5021  if (do_benchmark) {
5022  int64_t utime, stime, rtime;
5024  utime = current_time.user_usec - ti.user_usec;
5025  stime = current_time.sys_usec - ti.sys_usec;
5026  rtime = current_time.real_usec - ti.real_usec;
5028  "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
5029  utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
5030  }
5031  av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
5034  exit_program(69);
5035 
5037  return main_return_code;
5038 }
static void flush(AVCodecContext *avctx)
#define ECHO(name, type, min, max)
Definition: af_aecho.c:188
uint8_t
int32_t
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:53
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
#define FF_DEBUG_DCT_COEFF
Definition: avcodec.h:1633
Main libavdevice API header.
Main libavfilter public API header.
Main libavformat public API header.
#define AV_DISPOSITION_LYRICS
Definition: avformat.h:822
struct AVCodecParserContext * av_stream_get_parser(const AVStream *s)
Definition: utils.c:145
#define AVFMT_NOSTREAMS
Format does not require any streams.
Definition: avformat.h:467
#define AVFMT_FLAG_BITEXACT
When muxing, try to avoid writing any random/volatile data to the output.
Definition: avformat.h:1380
#define AV_DISPOSITION_HEARING_IMPAIRED
stream for hearing impaired audiences
Definition: avformat.h:831
#define AV_DISPOSITION_COMMENT
Definition: avformat.h:821
#define AVFMT_TS_DISCONT
Format allows timestamp discontinuities.
Definition: avformat.h:464
#define AVFMT_VARIABLE_FPS
Format allows variable fps.
Definition: avformat.h:465
#define AV_DISPOSITION_KARAOKE
Definition: avformat.h:823
#define AV_DISPOSITION_CAPTIONS
To specify text track kind (different from subtitles default).
Definition: avformat.h:853
#define AV_DISPOSITION_DUB
Definition: avformat.h:819
#define AV_DISPOSITION_METADATA
Definition: avformat.h:855
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition: avformat.h:458
#define AV_DISPOSITION_DEPENDENT
dependent audio stream (mix_type=0 in mpegts)
Definition: avformat.h:856
#define AVFMT_TS_NONSTRICT
Format does not require strictly increasing timestamps, but they must still be monotonic.
Definition: avformat.h:472
#define AV_DISPOSITION_CLEAN_EFFECTS
stream without voice
Definition: avformat.h:833
#define AV_DISPOSITION_FORCED
Track should be used during playback by default.
Definition: avformat.h:830
#define AV_DISPOSITION_VISUAL_IMPAIRED
stream for visual impaired audiences
Definition: avformat.h:832
#define AV_DISPOSITION_ATTACHED_PIC
The stream is stored in the file as an attached picture/"cover art" (e.g.
Definition: avformat.h:841
#define AVFMT_NOTIMESTAMPS
Format does not need / have any timestamps.
Definition: avformat.h:462
#define AV_DISPOSITION_DESCRIPTIONS
Definition: avformat.h:854
int64_t av_stream_get_end_pts(const AVStream *st)
Returns the pts of the last muxed packet + its duration.
Definition: utils.c:137
#define AV_DISPOSITION_ORIGINAL
Definition: avformat.h:820
#define AV_DISPOSITION_DEFAULT
Definition: avformat.h:818
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:349
#define avio_print(s,...)
Write strings (const char *) to the context.
Definition: avio.h:594
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:675
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:557
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:230
void avio_flush(AVIOContext *s)
Force flushing of buffered data.
Definition: aviobuf.c:252
int avio_open2(AVIOContext **s, const char *url, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options)
Create and initialize a AVIOContext for accessing the resource indicated by url.
Definition: aviobuf.c:1180
int avio_closep(AVIOContext **s)
Close the resource accessed by the AVIOContext *s, free it and set the pointer pointing to it to NULL...
Definition: aviobuf.c:1209
uint8_t * av_packet_get_side_data(const AVPacket *pkt, enum AVPacketSideDataType type, buffer_size_t *size)
Definition: avpacket.c:368
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, buffer_size_t size)
Definition: avpacket.c:343
#define AV_RL64
Definition: intreadwrite.h:173
#define AV_RL32
Definition: intreadwrite.h:146
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition: bprint.c:94
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition: bprint.c:69
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition: bprint.c:245
#define AV_BPRINT_SIZE_AUTOMATIC
memory buffer sink API for audio and video
Memory buffer source API.
static uint32_t codec_flags(enum AVCodecID codec_id)
Definition: cafenc.c:36
#define flags(name, subs,...)
Definition: cbs_av1.c:572
#define is(width, name, range_min, range_max, subs,...)
Definition: cbs_h2645.c:296
#define u(width, name, range_min, range_max)
Definition: cbs_h2645.c:274
#define us(width, name, range_min, range_max, subs,...)
Definition: cbs_h2645.c:288
#define s(width, name)
Definition: cbs_vp9.c:257
#define f(width, name)
Definition: cbs_vp9.c:255
static av_always_inline void filter(int16_t *output, ptrdiff_t out_stride, const int16_t *low, ptrdiff_t low_stride, const int16_t *high, ptrdiff_t high_stride, int len, int clip)
Definition: cfhddsp.c:27
audio channel layout utility functions
#define fail()
Definition: checkasm.h:133
void exit_program(int ret)
Wraps exit with a program-specific cleanup routine.
Definition: cmdutils.c:139
void init_dynload(void)
Initialize dynamic library loading.
Definition: cmdutils.c:117
void print_error(const char *filename, int err)
Print an error message to stderr, indicating filename and a human readable description of the error c...
Definition: cmdutils.c:1090
void parse_loglevel(int argc, char **argv, const OptionDef *options)
Find the '-loglevel' option in the command line args and apply it.
Definition: cmdutils.c:508
void show_banner(int argc, char **argv, const OptionDef *options)
Print the program banner to stderr.
Definition: cmdutils.c:1189
int64_t parse_time_or_die(const char *context, const char *timestr, int is_duration)
Parse a string specifying a time and return its corresponding value as a number of microseconds.
Definition: cmdutils.c:168
void register_exit(void(*cb)(int ret))
Register a program-specific cleanup routine.
Definition: cmdutils.c:128
void uninit_opts(void)
Uninitialize the cmdutils option system, in particular free the *_opts contexts and their contents.
Definition: cmdutils.c:87
#define media_type_string
Definition: cmdutils.h:628
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Copy the contents of src to dst.
Definition: codec_par.c:72
void avcodec_parameters_free(AVCodecParameters **ppar)
Free an AVCodecParameters instance and everything associated with it and write NULL to the supplied p...
Definition: codec_par.c:61
@ AV_FIELD_TT
Definition: codec_par.h:39
@ AV_FIELD_BB
Definition: codec_par.h:40
@ AV_FIELD_PROGRESSIVE
Definition: codec_par.h:38
@ AV_FIELD_BT
Definition: codec_par.h:42
@ AV_FIELD_TB
Definition: codec_par.h:41
#define FFMAX3(a, b, c)
Definition: common.h:104
#define FFSWAP(type, a, b)
Definition: common.h:108
#define FFMIN(a, b)
Definition: common.h:105
#define av_clip
Definition: common.h:122
#define FFMAX(a, b)
Definition: common.h:103
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition: common.h:72
#define FFDIFFSIGN(x, y)
Comparator.
Definition: common.h:101
#define FFSIGN(a)
Definition: common.h:73
#define FFMIN3(a, b, c)
Definition: common.h:106
#define NULL
Definition: coverity.c:32
long long int64_t
Definition: coverity.c:34
#define max(a, b)
Definition: cuda_runtime.h:33
static enum AVPixelFormat pix_fmt
static AVFrame * frame
Public dictionary API.
Display matrix.
static float sub(float src0, float src1)
#define atomic_store(object, desired)
Definition: stdatomic.h:85
intptr_t atomic_int
Definition: stdatomic.h:55
#define atomic_load(object)
Definition: stdatomic.h:93
#define ATOMIC_VAR_INIT(value)
Definition: stdatomic.h:31
void av_expr_free(AVExpr *e)
Free a parsed expression previously created with av_expr_parse().
Definition: eval.c:339
double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
Evaluate a previously parsed expression.
Definition: eval.c:781
int av_expr_parse(AVExpr **expr, const char *s, const char *const *const_names, const char *const *func1_names, double(*const *funcs1)(void *, double), const char *const *func2_names, double(*const *funcs2)(void *, double, double), int log_offset, void *log_ctx)
Parse an expression.
Definition: eval.c:700
const char program_name[]
program name, defined by the program for show_version().
Definition: ffmpeg.c:109
static int nb_frames_drop
Definition: ffmpeg.c:137
AVIOContext * progress_avio
Definition: ffmpeg.c:144
static int nb_frames_dup
Definition: ffmpeg.c:135
static int transcode(void)
Definition: ffmpeg.c:4776
static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output, int *decode_failed)
Definition: ffmpeg.c:2532
static void set_tty_echo(int on)
Definition: ffmpeg.c:3977
static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output, int *decode_failed)
Definition: ffmpeg.c:2339
static int check_keyboard_interaction(int64_t cur_time)
Definition: ffmpeg.c:3989
static void do_audio_out(OutputFile *of, OutputStream *ost, AVFrame *frame)
Definition: ffmpeg.c:1014
int nb_output_streams
Definition: ffmpeg.c:154
static BenchmarkTimeStamps get_benchmark_time_stamps(void)
Definition: ffmpeg.c:4920
static int need_output(void)
Definition: ffmpeg.c:3920
void term_exit(void)
Definition: ffmpeg.c:337
static volatile int received_sigterm
Definition: ffmpeg.c:343
const char *const forced_keyframes_const_names[]
Definition: ffmpeg.c:114
static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
Definition: ffmpeg.c:2290
int nb_filtergraphs
Definition: ffmpeg.c:159
static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
Definition: ffmpeg.c:2627
static void do_subtitle_out(OutputFile *of, OutputStream *ost, AVSubtitle *sub)
Definition: ffmpeg.c:1072
static int init_input_stream(int ist_index, char *error, int error_len)
Definition: ffmpeg.c:2958
static void sub2video_push_ref(InputStream *ist, int64_t pts)
Definition: ffmpeg.c:223
int guess_input_channel_layout(InputStream *ist)
Definition: ffmpeg.c:2136
static void print_sdp(void)
Definition: ffmpeg.c:2817
static int reap_filters(int flush)
Get and encode new output from any of the filtergraphs, without causing activity.
Definition: ffmpeg.c:1509
static int check_recording_time(OutputStream *ost)
Definition: ffmpeg.c:933
InputFile ** input_files
Definition: ffmpeg.c:150
static void do_video_out(OutputFile *of, OutputStream *ost, AVFrame *next_picture)
Definition: ffmpeg.c:1155
static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
Definition: ffmpeg.c:2862
static void print_final_stats(int64_t total_size)
Definition: ffmpeg.c:1592
static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
Perform a step of transcoding for the specified filter graph.
Definition: ffmpeg.c:4640
const AVIOInterruptCB int_cb
Definition: ffmpeg.c:524
int main(int argc, char **argv)
Definition: ffmpeg.c:4968
static double psnr(double d)
Definition: ffmpeg.c:1442
static int init_output_bsfs(OutputStream *ost)
Definition: ffmpeg.c:3086
static int init_output_stream_encode(OutputStream *ost, AVFrame *frame)
Definition: ffmpeg.c:3357
static int main_return_code
Definition: ffmpeg.c:347
static uint8_t * subtitle_out
Definition: ffmpeg.c:146
static int send_frame_to_filters(InputStream *ist, AVFrame *decoded_frame)
Definition: ffmpeg.c:2313
int nb_input_streams
Definition: ffmpeg.c:149
static int64_t getmaxrss(void)
Definition: ffmpeg.c:4946
static void reset_eagain(void)
Definition: ffmpeg.c:4252
int nb_input_files
Definition: ffmpeg.c:151
static void finish_output_stream(OutputStream *ost)
Definition: ffmpeg.c:1490
static void parse_forced_key_frames(char *kf, OutputStream *ost, AVCodecContext *avctx)
Definition: ffmpeg.c:3270
static OutputStream * choose_output(void)
Select the output stream to process.
Definition: ffmpeg.c:3950
FilterGraph ** filtergraphs
Definition: ffmpeg.c:158
static int compare_int64(const void *a, const void *b)
Definition: ffmpeg.c:3031
static unsigned dup_warning
Definition: ffmpeg.c:136
static int init_output_stream_wrapper(OutputStream *ost, AVFrame *frame, unsigned int fatal)
Definition: ffmpeg.c:993
static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output, int64_t *duration_pts, int eof, int *decode_failed)
Definition: ffmpeg.c:2401
static int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame)
Definition: ffmpeg.c:2186
static void check_decode_result(InputStream *ist, int *got_output, int ret)
Definition: ffmpeg.c:2156
static void sub2video_heartbeat(InputStream *ist, int64_t pts)
Definition: ffmpeg.c:281
static int process_input(int file_index)
Definition: ffmpeg.c:4347
static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
Definition: ffmpeg.c:4964
static int seek_to_start(InputFile *ifile, AVFormatContext *is)
Definition: ffmpeg.c:4281
static volatile int ffmpeg_exited
Definition: ffmpeg.c:346
static int check_output_constraints(InputStream *ist, OutputStream *ost)
Definition: ffmpeg.c:2042
int nb_output_files
Definition: ffmpeg.c:156
static void write_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int unqueue)
Definition: ffmpeg.c:740
static void set_encoder_id(OutputFile *of, OutputStream *ost)
Definition: ffmpeg.c:3229
static int64_t decode_error_stat[2]
Definition: ffmpeg.c:138
static int read_key(void)
Definition: ffmpeg.c:467
static int check_init_output_file(OutputFile *of, int file_index)
Definition: ffmpeg.c:3037
static void close_output_stream(OutputStream *ost)
Definition: ffmpeg.c:885
static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
Definition: ffmpeg.c:2948
#define SIGNAL(sig, func)
Definition: ffmpeg.c:404
void sub2video_update(InputStream *ist, int64_t heartbeat_pts, AVSubtitle *sub)
Definition: ffmpeg.c:241
static int init_output_stream(OutputStream *ost, AVFrame *frame, char *error, int error_len)
Definition: ffmpeg.c:3540
static int got_eagain(void)
Definition: ffmpeg.c:4243
static int want_sdp
Definition: ffmpeg.c:141
static int send_filter_eof(InputStream *ist)
Definition: ffmpeg.c:2611
static int decode_interrupt_cb(void *ctx)
Definition: ffmpeg.c:519
static void term_exit_sigsafe(void)
Definition: ffmpeg.c:329
static void sub2video_flush(InputStream *ist)
Definition: ffmpeg.c:313
static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h, AVSubtitleRect *r)
Definition: ffmpeg.c:192
void remove_avoptions(AVDictionary **a, AVDictionary *b)
Definition: ffmpeg.c:687
static int transcode_init(void)
Definition: ffmpeg.c:3738
static volatile int received_nb_signals
Definition: ffmpeg.c:344
InputStream ** input_streams
Definition: ffmpeg.c:148
static int64_t copy_ts_first_pts
Definition: ffmpeg.c:348
static FILE * vstats_file
Definition: ffmpeg.c:112
static void report_new_stream(int input_index, AVPacket *pkt)
Definition: ffmpeg.c:3723
static BenchmarkTimeStamps current_time
Definition: ffmpeg.c:143
static void abort_codec_experimental(const AVCodec *c, int encoder)
Definition: ffmpeg.c:705
static void update_benchmark(const char *fmt,...)
Definition: ffmpeg.c:710
static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base, AVRational time_base)
Definition: ffmpeg.c:4262
static void ffmpeg_cleanup(int ret)
Definition: ffmpeg.c:526
static double adjust_frame_pts_to_encoder_tb(OutputFile *of, OutputStream *ost, AVFrame *frame)
Definition: ffmpeg.c:946
static int transcode_step(void)
Run a single step of transcoding.
Definition: ffmpeg.c:4686
static int ifilter_has_all_input_formats(FilterGraph *fg)
Definition: ffmpeg.c:2175
static void close_all_output_streams(OutputStream *ost, OSTFinished this_stream, OSTFinished others)
Definition: ffmpeg.c:731
static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
Definition: ffmpeg.c:1709
static int init_output_stream_streamcopy(OutputStream *ost)
Definition: ffmpeg.c:3115
void term_init(void)
Definition: ffmpeg.c:408
static unsigned nb_output_dumped
Definition: ffmpeg.c:139
OutputStream ** output_streams
Definition: ffmpeg.c:153
static int get_input_packet(InputFile *f, AVPacket **pkt)
Definition: ffmpeg.c:4222
static void do_video_stats(OutputStream *ost, int frame_size)
Definition: ffmpeg.c:1447
const int program_birth_year
program birth year, defined by the program for show_banner()
Definition: ffmpeg.c:110
static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
Definition: ffmpeg.c:2059
OutputFile ** output_files
Definition: ffmpeg.c:155
static int sub2video_get_blank_frame(InputStream *ist)
Definition: ffmpeg.c:177
static void flush_encoders(void)
Definition: ffmpeg.c:1932
static void output_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int eof)
Definition: ffmpeg.c:907
static InputStream * get_input_stream(OutputStream *ost)
Definition: ffmpeg.c:3024
void assert_avoptions(AVDictionary *m)
Definition: ffmpeg.c:696
static int run_as_daemon
Definition: ffmpeg.c:134
static void init_encoder_time_base(OutputStream *ost, AVRational default_time_base)
Definition: ffmpeg.c:3333
static void ifilter_parameters_from_codecpar(InputFilter *ifilter, AVCodecParameters *par)
Definition: ffmpeg.c:1919
static int ifilter_send_eof(InputFilter *ifilter, int64_t pts)
Definition: ffmpeg.c:2263
static void sigterm_handler(int sig)
Definition: ffmpeg.c:351
static atomic_int transcode_init_done
Definition: ffmpeg.c:345
int hw_device_setup_for_encode(OutputStream *ost)
Definition: ffmpeg_hw.c:419
int debug_ts
Definition: ffmpeg_opt.c:166
@ HWACCEL_GENERIC
Definition: ffmpeg.h:61
@ HWACCEL_AUTO
Definition: ffmpeg.h:60
float max_error_rate
Definition: ffmpeg_opt.c:173
int ifilter_parameters_from_frame(InputFilter *ifilter, const AVFrame *frame)
int start_at_zero
Definition: ffmpeg_opt.c:164
int audio_volume
Definition: ffmpeg_opt.c:154
#define VSYNC_DROP
Definition: ffmpeg.h:54
char * sdp_filename
Definition: ffmpeg_opt.c:148
int print_stats
Definition: ffmpeg_opt.c:169
int stdin_interaction
Definition: ffmpeg_opt.c:171
int do_benchmark
Definition: ffmpeg_opt.c:159
int do_hex_dump
Definition: ffmpeg_opt.c:161
int frame_bits_per_raw_sample
Definition: ffmpeg_opt.c:172
float dts_error_threshold
Definition: ffmpeg_opt.c:152
int hwaccel_decode_init(AVCodecContext *avctx)
Definition: ffmpeg_hw.c:516
OSTFinished
Definition: ffmpeg.h:448
@ ENCODER_FINISHED
Definition: ffmpeg.h:449
@ MUXER_FINISHED
Definition: ffmpeg.h:450
#define VSYNC_CFR
Definition: ffmpeg.h:51
int abort_on_flags
Definition: ffmpeg_opt.c:168
float frame_drop_threshold
Definition: ffmpeg_opt.c:157
void show_usage(void)
Definition: ffmpeg_opt.c:3383
#define DECODING_FOR_FILTER
Definition: ffmpeg.h:308
int qp_hist
Definition: ffmpeg_opt.c:170
int hw_device_setup_for_decode(InputStream *ist)
Definition: ffmpeg_hw.c:303
#define VSYNC_AUTO
Definition: ffmpeg.h:49
void hw_device_free_all(void)
Definition: ffmpeg_hw.c:274
int vstats_version
Definition: ffmpeg_opt.c:176
char * vstats_filename
Definition: ffmpeg_opt.c:147
int audio_sync_method
Definition: ffmpeg_opt.c:155
int copy_tb
Definition: ffmpeg_opt.c:165
@ FKF_PREV_FORCED_N
Definition: ffmpeg.h:437
@ FKF_T
Definition: ffmpeg.h:439
@ FKF_PREV_FORCED_T
Definition: ffmpeg.h:438
@ FKF_N_FORCED
Definition: ffmpeg.h:436
@ FKF_N
Definition: ffmpeg.h:435
int ffmpeg_parse_options(int argc, char **argv)
#define ABORT_ON_FLAG_EMPTY_OUTPUT
Definition: ffmpeg.h:443
#define DECODING_FOR_OST
Definition: ffmpeg.h:307
int video_sync_method
Definition: ffmpeg_opt.c:156
float dts_delta_threshold
Definition: ffmpeg_opt.c:151
int64_t stats_period
Definition: ffmpeg_opt.c:178
int copy_ts
Definition: ffmpeg_opt.c:163
#define VSYNC_VSCFR
Definition: ffmpeg.h:53
int filtergraph_is_simple(FilterGraph *fg)
int do_benchmark_all
Definition: ffmpeg_opt.c:160
#define VSYNC_PASSTHROUGH
Definition: ffmpeg.h:50
int configure_filtergraph(FilterGraph *fg)
const HWAccel hwaccels[]
Definition: ffmpeg_opt.c:136
#define VSYNC_VFR
Definition: ffmpeg.h:52
int exit_on_error
Definition: ffmpeg_opt.c:167
#define ABORT_ON_FLAG_EMPTY_OUTPUT_STREAM
Definition: ffmpeg.h:444
int do_pkt_dump
Definition: ffmpeg_opt.c:162
const OptionDef options[]
sample_rate
static int loop
Definition: ffplay.c:341
static int64_t start_time
Definition: ffplay.c:332
a very simple circular buffer FIFO implementation
static AVCodecContext * dec_ctx
const AVOption * av_opt_find(void *obj, const char *name, const char *unit, int opt_flags, int search_flags)
Look for an option in an object.
Definition: opt.c:1671
int av_opt_set_dict(void *obj, AVDictionary **options)
Set all the options from a given dictionary on an object.
Definition: opt.c:1666
@ AV_OPT_TYPE_CONST
Definition: opt.h:234
@ AV_OPT_TYPE_FLAGS
Definition: opt.h:224
void av_get_channel_layout_string(char *buf, int buf_size, int nb_channels, uint64_t channel_layout)
Return a description of a channel layout.
int64_t av_get_default_channel_layout(int nb_channels)
Return default channel layout for a given number of channels.
void av_bsf_free(AVBSFContext **pctx)
Free a bitstream filter context and everything associated with it; write NULL into the supplied point...
Definition: bsf.c:40
int avcodec_parameters_from_context(AVCodecParameters *par, const AVCodecContext *codec)
Fill the parameters struct based on the values from the supplied codec context.
Definition: codec_par.c:90
int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition: avcodec.c:145
#define AV_CODEC_FLAG_BITEXACT
Use only bitexact stuff (except (I)DCT).
Definition: avcodec.h:333
const char * avcodec_get_name(enum AVCodecID id)
Get the name of a codec.
Definition: utils.c:497
#define AV_CODEC_FLAG_PASS2
Use internal 2pass ratecontrol in second pass mode.
Definition: avcodec.h:300
int av_bsf_init(AVBSFContext *ctx)
Prepare the filter for use, after all the parameters and options have been set.
Definition: bsf.c:148
#define AV_CODEC_CAP_VARIABLE_FRAME_SIZE
Audio encoder supports receiving a different number of samples in each call.
Definition: codec.h:129
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
Definition: codec.h:77
const AVCodecHWConfig * avcodec_get_hw_config(const AVCodec *codec, int index)
Retrieve supported hardware configurations for a codec.
Definition: utils.c:930
#define AV_CODEC_FLAG_INTERLACED_DCT
Use interlaced DCT.
Definition: avcodec.h:321
int av_bsf_receive_packet(AVBSFContext *ctx, AVPacket *pkt)
Retrieve a filtered packet.
Definition: bsf.c:227
#define AV_CODEC_FLAG_PASS1
Use internal 2pass ratecontrol in first pass mode.
Definition: avcodec.h:296
#define AV_CODEC_FLAG_INTERLACED_ME
interlaced motion estimation
Definition: avcodec.h:342
void avsubtitle_free(AVSubtitle *sub)
Free all allocated data in the given subtitle struct.
Definition: avcodec.c:557
int av_bsf_send_packet(AVBSFContext *ctx, AVPacket *pkt)
Submit a packet for filtering.
Definition: bsf.c:201
const AVCodecDescriptor * avcodec_descriptor_get(enum AVCodecID id)
Definition: codec_desc.c:3501
#define AV_CODEC_PROP_BITMAP_SUB
Subtitle codec is bitmap based Decoded AVSubtitle data can be read from the AVSubtitleRect->pict fiel...
Definition: codec_desc.h:97
#define AV_CODEC_FLAG_PSNR
error[?] variables will be set during encoding.
Definition: avcodec.h:312
int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par)
Fill the codec context based on the values from the supplied codec parameters.
Definition: codec_par.c:147
#define AV_CODEC_CAP_PARAM_CHANGE
Codec supports changed parameters at any point.
Definition: codec.h:116
#define AV_CODEC_PROP_TEXT_SUB
Subtitle codec is text based.
Definition: codec_desc.h:102
av_cold int avcodec_close(AVCodecContext *avctx)
Close a given AVCodecContext and free all the data associated with it (but not the AVCodecContext its...
Definition: avcodec.c:576
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer.
Definition: options.c:188
@ AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX
The codec supports this format via the hw_device_ctx interface.
Definition: codec.h:411
@ SUBTITLE_BITMAP
A bitmap, pict will be set.
Definition: avcodec.h:2674
@ AV_CODEC_ID_DVB_SUBTITLE
Definition: codec_id.h:524
@ AV_CODEC_ID_H264
Definition: codec_id.h:76
@ AV_CODEC_ID_CODEC2
Definition: codec_id.h:491
@ AV_CODEC_ID_AC3
Definition: codec_id.h:427
@ AV_CODEC_ID_MPEG4
Definition: codec_id.h:61
@ AV_CODEC_ID_MJPEG
Definition: codec_id.h:56
@ AV_CODEC_ID_MP3
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: codec_id.h:425
@ AV_CODEC_ID_VP9
Definition: codec_id.h:217
int avcodec_default_get_buffer2(AVCodecContext *s, AVFrame *frame, int flags)
The default callback for AVCodecContext.get_buffer2().
Definition: decode.c:1706
int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
Return decoded output data from a decoder.
Definition: decode.c:652
int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub, int *got_sub_ptr, AVPacket *avpkt)
Decode a subtitle message.
Definition: decode.c:1046
int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
Supply raw packet data as input to a decoder.
Definition: decode.c:589
int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
Read encoded data from the encoder.
Definition: encode.c:414
int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
Supply a raw video or audio frame to the encoder.
Definition: encode.c:383
@ AVDISCARD_ALL
discard all
Definition: avcodec.h:236
@ AVDISCARD_DEFAULT
discard useless packets like 0 size packets in avi
Definition: avcodec.h:231
int avcodec_encode_subtitle(AVCodecContext *avctx, uint8_t *buf, int buf_size, const AVSubtitle *sub)
Definition: encode.c:147
int av_get_audio_frame_duration(AVCodecContext *avctx, int frame_bytes)
Return audio frame duration.
Definition: utils.c:881
void avcodec_flush_buffers(AVCodecContext *avctx)
Reset the internal codec state / flush internal buffers.
Definition: avcodec.c:497
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition: avpacket.c:75
#define AV_PKT_FLAG_CORRUPT
The packet content is corrupted.
Definition: packet.h:411
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:634
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:410
int av_packet_make_refcounted(AVPacket *pkt)
Ensure the data described by a given packet is reference counted.
Definition: avpacket.c:696
void av_packet_move_ref(AVPacket *dst, AVPacket *src)
Move every field in src to dst and reset src.
Definition: avpacket.c:690
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
Definition: avpacket.c:64
int av_packet_ref(AVPacket *dst, const AVPacket *src)
Setup a new reference to the data described by a given packet.
Definition: avpacket.c:641
void av_packet_rescale_ts(AVPacket *pkt, AVRational src_tb, AVRational dst_tb)
Convert valid timing fields (timestamps / durations) in a packet from one timebase to another.
Definition: avpacket.c:737
@ AV_PKT_DATA_QUALITY_STATS
This side data contains quality related information from the encoder.
Definition: packet.h:132
@ AV_PKT_DATA_DISPLAYMATRIX
This side data contains a 3x3 transformation matrix describing an affine transformation that needs to...
Definition: packet.h:108
@ AV_PKT_DATA_CPB_PROPERTIES
This side data corresponds to the AVCPBProperties struct.
Definition: packet.h:145
void avdevice_register_all(void)
Initialize libavdevice and register all the input and output devices.
Definition: alldevices.c:66
uint8_t * av_stream_new_side_data(AVStream *stream, enum AVPacketSideDataType type, size_t size)
Allocate new information from stream.
int avformat_network_deinit(void)
Undo the initialization done by avformat_network_init.
Definition: utils.c:5067
int avformat_network_init(void)
Do global initialization of network libraries.
Definition: utils.c:5055
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:4436
int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
Seek to timestamp ts.
Definition: utils.c:2512
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition: utils.c:1741
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:4481
av_warn_unused_result int avformat_write_header(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and write the stream header to an output media file.
Definition: mux.c:506
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file ensuring correct interleaving.
Definition: mux.c:1266
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:1281
enum AVCodecID av_codec_get_id(const struct AVCodecTag *const *tags, unsigned int tag)
Get the AVCodecID for the given codec tag tag.
AVRational av_stream_get_codec_timebase(const AVStream *st)
Get the internal codec timebase from a stream.
Definition: utils.c:5849
int av_sdp_create(AVFormatContext *ac[], int n_files, char *buf, int size)
Generate an SDP for an RTP session.
Definition: sdp.c:850
void av_pkt_dump_log2(void *avcl, int level, const AVPacket *pkt, int dump_payload, const AVStream *st)
Send a nice dump of a packet to the log.
Definition: dump.c:115
int av_codec_get_tag2(const struct AVCodecTag *const *tags, enum AVCodecID id, unsigned int *tag)
Get the codec tag for the given codec id.
void av_dump_format(AVFormatContext *ic, int index, const char *url, int is_output)
Print detailed information about the input or output format, such as duration, bitrate,...
Definition: dump.c:640
int avformat_transfer_internal_stream_timing_info(const AVOutputFormat *ofmt, AVStream *ost, const AVStream *ist, enum AVTimebaseSource copy_tb)
Transfer internal timing information from one stream to another.
Definition: utils.c:5777
enum AVMediaType av_buffersink_get_type(const AVFilterContext *ctx)
int av_buffersink_get_sample_rate(const AVFilterContext *ctx)
int av_buffersink_get_format(const AVFilterContext *ctx)
AVRational av_buffersink_get_frame_rate(const AVFilterContext *ctx)
uint64_t av_buffersink_get_channel_layout(const AVFilterContext *ctx)
int av_buffersink_get_h(const AVFilterContext *ctx)
AVRational av_buffersink_get_sample_aspect_ratio(const AVFilterContext *ctx)
AVRational av_buffersink_get_time_base(const AVFilterContext *ctx)
int av_buffersink_get_w(const AVFilterContext *ctx)
int av_buffersink_get_channels(const AVFilterContext *ctx)
void av_buffersink_set_frame_size(AVFilterContext *ctx, unsigned frame_size)
Set the frame size for an audio buffer sink.
Definition: buffersink.c:198
int attribute_align_arg av_buffersink_get_frame_flags(AVFilterContext *ctx, AVFrame *frame, int flags)
Get a frame with filtered data from sink and put it in frame.
Definition: buffersink.c:140
#define AV_BUFFERSINK_FLAG_NO_REQUEST
Tell av_buffersink_get_buffer_ref() not to request a frame from its input.
Definition: buffersink.h:96
int attribute_align_arg av_buffersrc_add_frame_flags(AVFilterContext *ctx, AVFrame *frame, int flags)
Add a frame to the buffer source.
Definition: buffersrc.c:166
int av_buffersrc_close(AVFilterContext *ctx, int64_t pts, unsigned flags)
Close the buffer source after EOF.
Definition: buffersrc.c:233
int attribute_align_arg av_buffersrc_add_frame(AVFilterContext *ctx, AVFrame *frame)
Add a frame to the buffer source.
Definition: buffersrc.c:147
unsigned av_buffersrc_get_nb_failed_requests(AVFilterContext *buffer_src)
Get the number of failed requests.
Definition: buffersrc.c:265
@ AV_BUFFERSRC_FLAG_KEEP_REF
Keep a reference to the frame.
Definition: buffersrc.h:53
@ AV_BUFFERSRC_FLAG_PUSH
Immediately push the frame to the output.
Definition: buffersrc.h:46
void avfilter_inout_free(AVFilterInOut **inout)
Free the supplied list of AVFilterInOut and set *inout to NULL.
Definition: graphparser.c:212
int avfilter_graph_queue_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, int flags, double ts)
Queue a command for one or more filter instances.
void avfilter_graph_free(AVFilterGraph **graph)
Free a graph, destroy its links, and set *graph to NULL.
int avfilter_graph_send_command(AVFilterGraph *graph, const char *target, const char *cmd, const char *arg, char *res, int res_len, int flags)
Send a command to one or more filter instances.
int avfilter_graph_request_oldest(AVFilterGraph *graph)
Request a frame on the oldest sink link.
#define AVFILTER_CMD_FLAG_ONE
Stop once a filter understood the command (for target=all for example), fast filters are favored auto...
Definition: avfilter.h:706
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
Definition: buffer.c:125
AVBufferRef * av_buffer_ref(AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition: buffer.c:93
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition: dict.c:199
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key,...
Definition: dict.h:70
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
Definition: dict.h:74
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:70
#define AV_DICT_DONT_OVERWRITE
Don't overwrite existing entries.
Definition: dict.h:76
#define AV_DICT_MATCH_CASE
Only get an entry with exact-case key match.
Definition: dict.h:69
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:40
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition: avutil.h:227
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition: error.h:56
#define AVERROR_EXPERIMENTAL
Requested feature is flagged experimental. Set strict_std_compliance if you really want to use it.
Definition: error.h:72
#define AVERROR_PATCHWELCOME
Not yet implemented in FFmpeg, patches welcome.
Definition: error.h:62
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition: error.h:50
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
#define AVERROR_EOF
End of file.
Definition: error.h:55
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: error.h:119
#define AVERROR(e)
Definition: error.h:43
#define AV_FRAME_FLAG_CORRUPT
The frame data may be corrupted, e.g.
Definition: frame.h:543
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Definition: frame.c:553
void av_frame_remove_side_data(AVFrame *frame, enum AVFrameSideDataType type)
Remove and free all side data instances of the given type.
Definition: frame.c:812
AVFrame * av_frame_clone(const AVFrame *src)
Create a new frame that references the same data as src.
Definition: frame.c:540
int av_frame_get_buffer(AVFrame *frame, int align)
Allocate new buffer(s) for audio or video data.
Definition: frame.c:337
int av_frame_ref(AVFrame *dst, const AVFrame *src)
Set up a new reference to the data described by the source frame.
Definition: frame.c:443
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:203
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:190
@ AV_FRAME_DATA_A53_CC
ATSC A53 Part 4 Closed Captions.
Definition: frame.h:58
#define AV_LOG_QUIET
Print no output.
Definition: log.h:176
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:215
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:200
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition: log.h:188
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:210
#define AV_LOG_INFO
Standard information.
Definition: log.h:205
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
void av_log_set_callback(void(*callback)(void *, int, const char *, va_list))
Set the logging callback.
Definition: log.c:455
void av_log_set_level(int level)
Set the log level.
Definition: log.c:440
#define AV_LOG_SKIP_REPEATED
Skip repeated messages, this requires the user app to use av_log() instead of (f)printf as the 2 woul...
Definition: log.h:384
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:235
int av_log_get_level(void)
Get the current log level.
Definition: log.c:435
void av_log_set_flags(int arg)
Definition: log.c:445
AVRational av_add_q(AVRational b, AVRational c)
Add two rationals.
Definition: rational.c:93
AVRational av_mul_q(AVRational b, AVRational c)
Multiply two rationals.
Definition: rational.c:80
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:35
int av_find_nearest_q_idx(AVRational q, const AVRational *q_list)
Find the value in a list of rationals nearest a given reference rational.
Definition: rational.c:146
static AVRational av_make_q(int num, int den)
Create an AVRational.
Definition: rational.h:71
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition: rational.h:104
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition: rational.h:159
int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b)
Compare two timestamps each in its own time base.
Definition: mathematics.c:147
int64_t av_rescale_delta(AVRational in_tb, int64_t in_ts, AVRational fs_tb, int duration, int64_t *last, AVRational out_tb)
Rescale a timestamp while preserving known durations.
Definition: mathematics.c:168
int64_t av_rescale(int64_t a, int64_t b, int64_t c)
Rescale a 64-bit integer with rounding to nearest.
Definition: mathematics.c:129
@ AV_ROUND_PASS_MINMAX
Flag telling rescaling functions to pass INT64_MIN/MAX through unchanged, avoiding special cases for ...
Definition: mathematics.h:108
@ AV_ROUND_NEAR_INF
Round to nearest and halfway cases away from zero.
Definition: mathematics.h:84
int64_t av_rescale_q_rnd(int64_t a, AVRational bq, AVRational cq, enum AVRounding rnd)
Rescale a 64-bit integer by 2 rational numbers with specified rounding.
Definition: mathematics.c:134
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:237
void * av_realloc_array(void *ptr, size_t nmemb, size_t size)
Allocate, reallocate, or free an array.
Definition: mem.c:198
AVMediaType
Definition: avutil.h:199
const char * av_get_media_type_string(enum AVMediaType media_type)
Return a string describing the media_type enum, NULL if media_type is unknown.
Definition: utils.c:71
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:202
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:204
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
@ AVMEDIA_TYPE_DATA
Opaque data information usually continuous.
Definition: avutil.h:203
char av_get_picture_type_char(enum AVPictureType pict_type)
Return a single letter to describe the given picture type pict_type.
Definition: utils.c:83
@ AV_PICTURE_TYPE_I
Intra.
Definition: avutil.h:274
@ AV_PICTURE_TYPE_NONE
Undefined.
Definition: avutil.h:273
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:106
size_t av_strlcat(char *dst, const char *src, size_t size)
Append the string src to the string dst, but to a total length of no more than size - 1 bytes,...
Definition: avstring.c:93
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:83
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:254
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:260
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
void av_display_rotation_set(int32_t matrix[9], double angle)
Initialize a transformation matrix describing a pure counterclockwise rotation by the specified angle...
Definition: display.c:50
int av_opt_eval_flags(void *obj, const AVOption *o, const char *val, int *flags_out)
int index
Definition: gxfenc.c:89
for(j=16;j >0;--j)
const char * av_hwdevice_get_type_name(enum AVHWDeviceType type)
Get the string name of an AVHWDeviceType.
Definition: hwcontext.c:92
cl_device_type type
const char * key
misc image utilities
int i
Definition: input.c:407
#define av_log2
Definition: intmath.h:83
#define extra_bits(eb)
Definition: intrax8.c:125
const char * arg
Definition: jacosubdec.c:67
#define LIBAVCODEC_IDENT
Definition: version.h:42
void av_fifo_freep(AVFifoBuffer **f)
Free an AVFifoBuffer and reset pointer to NULL.
Definition: fifo.c:63
int av_fifo_size(const AVFifoBuffer *f)
Return the amount of data in bytes in the AVFifoBuffer, that is the amount of data you can read from ...
Definition: fifo.c:77
int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void(*func)(void *, void *, int))
Feed data from an AVFifoBuffer to a user-supplied callback.
Definition: fifo.c:213
int av_fifo_space(const AVFifoBuffer *f)
Return the amount of space in bytes in the AVFifoBuffer, that is the amount of data you can write int...
Definition: fifo.c:82
AVFifoBuffer * av_fifo_alloc(unsigned int size)
Initialize an AVFifoBuffer.
Definition: fifo.c:43
int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int(*func)(void *, void *, int))
Feed data from a user-supplied callback to an AVFifoBuffer.
Definition: fifo.c:122
int av_fifo_realloc2(AVFifoBuffer *f, unsigned int new_size)
Resize an AVFifoBuffer.
Definition: fifo.c:87
common internal API header
static enum AVPixelFormat pix_fmts[]
Definition: libkvazaar.c:309
Replacements for frequently missing libm functions.
#define llrint(x)
Definition: libm.h:394
#define llrintf(x)
Definition: libm.h:399
#define lrintf(x)
Definition: libm_mips.h:70
const char * desc
Definition: libsvtav1.c:83
uint8_t w
Definition: llviddspenc.c:39
#define NAN
Definition: mathematics.h:64
#define mid_pred
Definition: mathops.h:97
int frame_size
Definition: mxfenc.c:2206
AVOptions.
static av_always_inline int pthread_join(pthread_t thread, void **value_ptr)
Definition: os2threads.h:94
static av_always_inline int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg)
Definition: os2threads.h:80
miscellaneous OS support macros and functions.
misc parsing utilities
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition: pixdesc.c:2573
#define AV_PIX_FMT_FLAG_HWACCEL
Pixel format is an HW accelerated format.
Definition: pixdesc.h:140
AVPixelFormat
Pixel format.
Definition: pixfmt.h:64
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:65
#define AV_PIX_FMT_RGB32
Definition: pixfmt.h:372
#define tb
Definition: regdef.h:68
#define FF_ARRAY_ELEMS(a)
#define vsnprintf
Definition: snprintf.h:36
#define snprintf
Definition: snprintf.h:34
The bitstream filter state.
Definition: bsf.h:49
uint8_t * data
The data buffer.
Definition: buffer.h:92
Describe the class of an AVClass context structure.
Definition: log.h:67
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
main external API structure.
Definition: avcodec.h:536
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:746
int width
picture width / height.
Definition: avcodec.h:709
char * stats_out
pass1 encoding statistics output buffer
Definition: avcodec.h:1561
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1204
int debug
debug
Definition: avcodec.h:1627
int global_quality
Global quality for codecs which cannot change it per frame.
Definition: avcodec.h:602
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: avcodec.h:1171
AVRational pkt_timebase
Timebase in which pkt_dts/pts and AVPacket.dts/pts are.
Definition: avcodec.h:2089
enum AVPixelFormat(* get_format)(struct AVCodecContext *s, const enum AVPixelFormat *fmt)
callback to negotiate the pixelFormat
Definition: avcodec.h:788
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition: avcodec.h:1150
enum AVMediaType codec_type
Definition: avcodec.h:544
AVRational framerate
Definition: avcodec.h:2075
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
Definition: avcodec.h:915
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
Definition: avcodec.h:668
enum AVFieldOrder field_order
Field order.
Definition: avcodec.h:1193
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition: avcodec.h:826
const struct AVCodec * codec
Definition: avcodec.h:545
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition: avcodec.h:1751
enum AVColorSpace colorspace
YUV colorspace type.
Definition: avcodec.h:1164
int sample_rate
samples per second
Definition: avcodec.h:1196
attribute_deprecated int thread_safe_callbacks
Set by the client if its custom get_buffer() callback can be called synchronously from another thread...
Definition: avcodec.h:1816
void * opaque
Private data of the user, can be used to carry app specific stuff.
Definition: avcodec.h:578
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition: avcodec.h:1157
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avcodec.h:659
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:616
int channels
number of audio channels
Definition: avcodec.h:1197
enum AVChromaLocation chroma_sample_location
This defines the location of chroma samples.
Definition: avcodec.h:1178
uint64_t error[AV_NUM_DATA_POINTERS]
error
Definition: avcodec.h:1703
enum AVCodecID codec_id
Definition: avcodec.h:546
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:1247
int frame_size
Number of samples per channel in an audio frame.
Definition: avcodec.h:1216
int(* get_buffer2)(struct AVCodecContext *s, AVFrame *frame, int flags)
This callback is called at the beginning of each frame to get data buffer(s) for it.
Definition: avcodec.h:1355
This struct describes the properties of a single codec described by an AVCodecID.
Definition: codec_desc.h:38
int props
Codec properties, a combination of AV_CODEC_PROP_* flags.
Definition: codec_desc.h:54
enum AVHWDeviceType device_type
The device type associated with the configuration.
Definition: codec.h:464
int methods
Bit set of AV_CODEC_HW_CONFIG_METHOD_* flags, describing the possible setup methods which can be used...
Definition: codec.h:457
enum AVPixelFormat pix_fmt
For decoders, a hardware pixel format which that decoder may be able to decode to if suitable hardwar...
Definition: codec.h:452
This struct describes the properties of an encoded stream.
Definition: codec_par.h:52
uint64_t channel_layout
Audio only.
Definition: codec_par.h:162
int channels
Audio only.
Definition: codec_par.h:166
int width
Video only.
Definition: codec_par.h:126
enum AVMediaType codec_type
General type of the encoded data.
Definition: codec_par.h:56
int block_align
Audio only.
Definition: codec_par.h:177
AVRational sample_aspect_ratio
Video only.
Definition: codec_par.h:136
int video_delay
Video only.
Definition: codec_par.h:155
uint32_t codec_tag
Additional information about the codec (corresponds to the AVI FOURCC).
Definition: codec_par.h:64
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition: codec_par.h:60
int sample_rate
Audio only.
Definition: codec_par.h:170
int repeat_pict
This field is used for proper frame duration computation in lavf.
Definition: avcodec.h:3399
AVCodec.
Definition: codec.h:197
enum AVCodecID id
Definition: codec.h:211
const AVCodecDefault * defaults
Private codec-specific defaults.
Definition: codec.h:266
enum AVMediaType type
Definition: codec.h:210
const char * name
Name of the codec implementation.
Definition: codec.h:204
int capabilities
Codec capabilities.
Definition: codec.h:216
int depth
Number of bits in the component.
Definition: pixdesc.h:58
char * key
Definition: dict.h:82
char * value
Definition: dict.h:83
An instance of a filter.
Definition: avfilter.h:341
Format I/O context.
Definition: avformat.h:1232
unsigned int nb_streams
Number of elements in AVFormatContext.streams.
Definition: avformat.h:1288
AVIOContext * pb
I/O context.
Definition: avformat.h:1274
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition: avformat.h:1512
char * url
input or output URL.
Definition: avformat.h:1328
unsigned int nb_chapters
Number of chapters in AVChapter array.
Definition: avformat.h:1463
ff_const59 struct AVOutputFormat * oformat
The output container format.
Definition: avformat.h:1251
AVChapter ** chapters
Definition: avformat.h:1464
AVStream ** streams
A list of all streams in the file.
Definition: avformat.h:1300
This structure describes decoded (raw) audio or video data.
Definition: frame.h:318
int nb_samples
number of audio samples (per channel) described by this frame
Definition: frame.h:384
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:411
int64_t best_effort_timestamp
frame timestamp estimated using various heuristics, in stream time base
Definition: frame.h:582
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:332
enum AVChromaLocation chroma_location
Definition: frame.h:575
int width
Definition: frame.h:376
AVBufferRef * hw_frames_ctx
For hwaccel-format frames, this should be a reference to the AVHWFramesContext describing the frame.
Definition: frame.h:657
int key_frame
1 -> keyframe, 0-> not
Definition: frame.h:396
int64_t pkt_duration
duration of the corresponding packet, expressed in AVStream->time_base units, 0 if unknown.
Definition: frame.h:597
int decode_error_flags
decode error flags of the frame, set to a combination of FF_DECODE_ERROR_xxx flags if the decoder pro...
Definition: frame.h:613
int height
Definition: frame.h:376
int flags
Frame flags, a combination of AV_FRAME_FLAGS.
Definition: frame.h:555
int channels
number of audio channels, only used for audio.
Definition: frame.h:624
enum AVColorPrimaries color_primaries
Definition: frame.h:564
uint64_t channel_layout
Channel layout of the audio data.
Definition: frame.h:495
AVRational sample_aspect_ratio
Sample aspect ratio for the video frame, 0/1 if unknown/unspecified.
Definition: frame.h:406
int top_field_first
If the content is interlaced, is top field displayed first.
Definition: frame.h:470
int quality
quality (between 1 (good) and FF_LAMBDA_MAX (bad))
Definition: frame.h:441
int interlaced_frame
The content of the picture is interlaced.
Definition: frame.h:465
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: frame.h:562
enum AVColorSpace colorspace
YUV colorspace type.
Definition: frame.h:573
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:349
enum AVColorTransferCharacteristic color_trc
Definition: frame.h:566
int sample_rate
Sample rate of the audio data.
Definition: frame.h:490
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames,...
Definition: frame.h:391
enum AVPictureType pict_type
Picture type of the frame.
Definition: frame.h:401
Bytestream IO Context.
Definition: avio.h:161
Callback for checking whether to abort blocking functions.
Definition: avio.h:58
AVOption.
Definition: opt.h:248
int flags
can use flags: AVFMT_NOFILE, AVFMT_NEEDNUMBER, AVFMT_GLOBALHEADER, AVFMT_NOTIMESTAMPS,...
Definition: avformat.h:510
const char * name
Definition: avformat.h:491
const struct AVCodecTag *const * codec_tag
List of supported codec_id-codec_tag pairs, ordered by "better choice first".
Definition: avformat.h:516
uint8_t * data
Definition: packet.h:307
enum AVPacketSideDataType type
Definition: packet.h:313
size_t size
Definition: packet.h:311
This structure stores compressed data.
Definition: packet.h:346
int stream_index
Definition: packet.h:371
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:375
int size
Definition: packet.h:370
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:387
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:362
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition: packet.h:368
uint8_t * data
Definition: packet.h:369
int64_t pos
byte position in stream, -1 if unknown
Definition: packet.h:389
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Definition: pixdesc.h:81
AVComponentDescriptor comp[4]
Parameters that describe how pixels are packed.
Definition: pixdesc.h:117
New fields can be added to the end with minor version bumps.
Definition: avformat.h:1150
unsigned int nb_stream_indexes
Definition: avformat.h:1155
unsigned int * stream_index
Definition: avformat.h:1154
enum AVDiscard discard
selects which program to discard and which to feed to the caller
Definition: avformat.h:1153
Rational number (pair of numerator and denominator).
Definition: rational.h:58
int num
Numerator.
Definition: rational.h:59
int den
Denominator.
Definition: rational.h:60
Stream structure.
Definition: avformat.h:873
AVPacketSideData * side_data
An array of side data that applies to the whole stream (i.e.
Definition: avformat.h:975
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition: avformat.h:1038
int64_t first_dts
Timestamp corresponding to the last dts sync point.
Definition: avformat.h:1065
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown)
Definition: avformat.h:935
int64_t nb_frames
number of frames in this stream if known or 0
Definition: avformat.h:924
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:928
int64_t duration
Decoding: duration of the stream, in stream time base.
Definition: avformat.h:922
AVDictionary * metadata
Definition: avformat.h:937
int id
Format-specific stream ID.
Definition: avformat.h:880
int index
stream index in AVFormatContext
Definition: avformat.h:874
int pts_wrap_bits
number of bits in pts (used for wrapping control)
Definition: avformat.h:1055
int64_t start_time
Decoding: pts of the first frame of the stream in presentation order, in stream time base.
Definition: avformat.h:912
AVRational avg_frame_rate
Average framerate.
Definition: avformat.h:946
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avformat.h:902
int nb_side_data
The number of elements in the AVStream.side_data array.
Definition: avformat.h:979
int64_t cur_dts
Definition: avformat.h:1066
AVRational r_frame_rate
Real base framerate of the stream.
Definition: avformat.h:1015
int disposition
AV_DISPOSITION_* bit field.
Definition: avformat.h:926
uint32_t end_display_time
Definition: avcodec.h:2729
unsigned num_rects
Definition: avcodec.h:2730
int64_t pts
Same as packet pts, in AV_TIME_BASE.
Definition: avcodec.h:2732
int64_t sys_usec
Definition: ffmpeg.c:126
int64_t real_usec
Definition: ffmpeg.c:124
int64_t user_usec
Definition: ffmpeg.c:125
int index
Definition: ffmpeg.h:289
int nb_outputs
Definition: ffmpeg.h:298
OutputFilter ** outputs
Definition: ffmpeg.h:297
int nb_inputs
Definition: ffmpeg.h:296
const char * graph_desc
Definition: ffmpeg.h:290
AVFilterGraph * graph
Definition: ffmpeg.h:292
InputFilter ** inputs
Definition: ffmpeg.h:295
Definition: ffmpeg.h:66
enum HWAccelID id
Definition: ffmpeg.h:69
int(* init)(AVCodecContext *s)
Definition: ffmpeg.h:68
const char * name
Definition: ffmpeg.h:67
int eagain
Definition: ffmpeg.h:404
int64_t ts_offset
Definition: ffmpeg.h:412
AVFormatContext * ctx
Definition: ffmpeg.h:402
int64_t input_ts_offset
Definition: ffmpeg.h:410
int eof_reached
Definition: ffmpeg.h:403
int nb_streams_warn
Definition: ffmpeg.h:419
int ist_index
Definition: ffmpeg.h:405
int nb_streams
Definition: ffmpeg.h:417
AVBufferRef * hw_frames_ctx
Definition: ffmpeg.h:260
uint8_t * name
Definition: ffmpeg.h:245
int sample_rate
Definition: ffmpeg.h:256
int height
Definition: ffmpeg.h:253
struct InputStream * ist
Definition: ffmpeg.h:243
AVFilterContext * filter
Definition: ffmpeg.h:242
enum AVMediaType type
Definition: ffmpeg.h:246
AVFifoBuffer * frame_queue
Definition: ffmpeg.h:248
uint64_t channel_layout
Definition: ffmpeg.h:258
struct FilterGraph * graph
Definition: ffmpeg.h:244
AVRational sample_aspect_ratio
Definition: ffmpeg.h:254
int eof
Definition: ffmpeg.h:262
int channels
Definition: ffmpeg.h:257
int format
Definition: ffmpeg.h:251
int width
Definition: ffmpeg.h:253
unsigned int initialize
marks if sub2video_update should force an initialization
Definition: ffmpeg.h:359
AVFifoBuffer * sub_queue
queue of AVSubtitle* before filter init
Definition: ffmpeg.h:356
enum AVPixelFormat hwaccel_pix_fmt
Definition: ffmpeg.h:382
int saw_first_ts
Definition: ffmpeg.h:338
double ts_scale
Definition: ffmpeg.h:337
AVFrame * decoded_frame
Definition: ffmpeg.h:312
int64_t * dts_buffer
Definition: ffmpeg.h:395
int64_t dts
dts of the last packet read for this stream (in AV_TIME_BASE units)
Definition: ffmpeg.h:320
int fix_sub_duration
Definition: ffmpeg.h:346
int64_t cfr_next_pts
Definition: ffmpeg.h:333
int got_output
Definition: ffmpeg.h:348
void(* hwaccel_uninit)(AVCodecContext *s)
Definition: ffmpeg.h:379
int nb_dts_buffer
Definition: ffmpeg.h:396
AVCodecContext * dec_ctx
Definition: ffmpeg.h:310
int64_t pts
current pts of the decoded frame (in AV_TIME_BASE units)
Definition: ffmpeg.h:323
AVBufferRef * hw_frames_ctx
Definition: ffmpeg.h:384
struct InputStream::@2 prev_sub
int64_t start
Definition: ffmpeg.h:316
int ret
Definition: ffmpeg.h:349
enum HWAccelID hwaccel_id
Definition: ffmpeg.h:372
uint64_t data_size
Definition: ffmpeg.h:388
int(* hwaccel_get_buffer)(AVCodecContext *s, AVFrame *frame, int flags)
Definition: ffmpeg.h:380
int nb_filters
Definition: ffmpeg.h:367
int64_t filter_in_rescale_delta_last
Definition: ffmpeg.h:326
int64_t next_dts
Definition: ffmpeg.h:319
int reinit_filters
Definition: ffmpeg.h:369
int wrap_correction_done
Definition: ffmpeg.h:324
int64_t max_pts
Definition: ffmpeg.h:329
enum AVPixelFormat hwaccel_retrieved_pix_fmt
Definition: ffmpeg.h:383
int guess_layout_max
Definition: ffmpeg.h:342
AVPacket * pkt
Definition: ffmpeg.h:314
AVFrame * filter_frame
Definition: ffmpeg.h:313
uint64_t samples_decoded
Definition: ffmpeg.h:393
int64_t next_pts
synthetic pts for the next decode frame (in AV_TIME_BASE units)
Definition: ffmpeg.h:322
int top_field_first
Definition: ffmpeg.h:341
int autorotate
Definition: ffmpeg.h:344
int discard
Definition: ffmpeg.h:304
uint64_t frames_decoded
Definition: ffmpeg.h:392
int decoding_needed
Definition: ffmpeg.h:306
struct InputStream::sub2video sub2video
AVStream * st
Definition: ffmpeg.h:303
int file_index
Definition: ffmpeg.h:302
InputFilter ** filters
Definition: ffmpeg.h:366
int(* hwaccel_retrieve_data)(AVCodecContext *s, AVFrame *frame)
Definition: ffmpeg.h:381
uint64_t nb_packets
Definition: ffmpeg.h:390
AVSubtitle subtitle
Definition: ffmpeg.h:350
char * hwaccel_device
Definition: ffmpeg.h:374
AVDictionary * decoder_opts
Definition: ffmpeg.h:339
int64_t min_pts
Definition: ffmpeg.h:328
const AVCodec * dec
Definition: ffmpeg.h:311
enum AVHWDeviceType hwaccel_device_type
Definition: ffmpeg.h:373
int64_t nb_samples
Definition: ffmpeg.h:335
AVRational framerate
Definition: ffmpeg.h:340
AVFormatContext * ctx
Definition: ffmpeg.h:577
int header_written
Definition: ffmpeg.h:586
int64_t start_time
start time in microseconds == AV_TIME_BASE units
Definition: ffmpeg.h:581
AVDictionary * opts
Definition: ffmpeg.h:578
int64_t limit_filesize
Definition: ffmpeg.h:582
int ost_index
Definition: ffmpeg.h:579
int shortest
Definition: ffmpeg.h:584
int64_t recording_time
desired length of the resulting file in microseconds == AV_TIME_BASE units
Definition: ffmpeg.h:580
AVFilterInOut * out_tmp
Definition: ffmpeg.h:272
struct OutputStream * ost
Definition: ffmpeg.h:267
uint64_t * channel_layouts
Definition: ffmpeg.h:284
uint8_t * name
Definition: ffmpeg.h:269
int * sample_rates
Definition: ffmpeg.h:285
int * formats
Definition: ffmpeg.h:283
int source_index
Definition: ffmpeg.h:456
OSTFinished finished
Definition: ffmpeg.h:525
int unavailable
Definition: ffmpeg.h:526
AVCodecContext * enc_ctx
Definition: ffmpeg.h:475
uint8_t level
Definition: svq3.c:206
libswresample public header
#define av_malloc_array(a, b)
#define ff_dlog(a,...)
#define av_realloc_f(p, o, n)
#define av_freep(p)
#define av_malloc(s)
#define av_log(a,...)
static void error(const char *err)
static uint8_t tmp[11]
Definition: aes_ctr.c:27
#define src
Definition: vp8dsp.c:255
int64_t bitrate
Definition: h264_levels.c:131
FILE * out
Definition: movenc.c:54
int64_t duration
Definition: movenc.c:64
AVPacket * pkt
Definition: movenc.c:59
AVFormatContext * ctx
Definition: movenc.c:48
static void finish(void)
Definition: movenc.c:342
AVDictionary * opts
Definition: movenc.c:50
void av_thread_message_queue_set_err_send(AVThreadMessageQueue *mq, int err)
Set the sending error code.
int av_thread_message_queue_recv(AVThreadMessageQueue *mq, void *msg, unsigned flags)
Receive a message from the queue.
int av_thread_message_queue_alloc(AVThreadMessageQueue **mq, unsigned nelem, unsigned elsize)
Allocate a new message queue.
Definition: threadmessage.c:40
void av_thread_message_queue_set_err_recv(AVThreadMessageQueue *mq, int err)
Set the receiving error code.
int av_thread_message_queue_send(AVThreadMessageQueue *mq, void *msg, unsigned flags)
Send a message on the queue.
void av_thread_message_queue_free(AVThreadMessageQueue **mq)
Free a message queue.
Definition: threadmessage.c:91
@ AV_THREAD_MESSAGE_NONBLOCK
Perform non-blocking operation.
Definition: threadmessage.h:31
int av_usleep(unsigned usec)
Sleep for a period of time.
Definition: time.c:84
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition: time.c:56
timestamp utils, mostly useful for debugging/logging purposes
#define av_ts2str(ts)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:54
#define av_ts2timestr(ts, tb)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: timestamp.h:76
static int64_t pts
int size
static AVStream * ost
const char * b
Definition: vf_curves.c:119
const char * r
Definition: vf_curves.c:117
static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
Definition: vf_drawtext.c:883
float delta
static double c[64]