FFmpeg
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 
28 #include <errno.h>
29 #include <limits.h>
30 #include <stdatomic.h>
31 #include <stdint.h>
32 #include <stdlib.h>
33 #include <string.h>
34 #include <time.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 #if HAVE_SYS_RESOURCE_H
44 #include <sys/time.h>
45 #include <sys/types.h>
46 #include <sys/resource.h>
47 #elif HAVE_GETPROCESSTIMES
48 #include <windows.h>
49 #endif
50 #if HAVE_GETPROCESSMEMORYINFO
51 #include <windows.h>
52 #include <psapi.h>
53 #endif
54 #if HAVE_SETCONSOLECTRLHANDLER
55 #include <windows.h>
56 #endif
57 
58 #if HAVE_SYS_SELECT_H
59 #include <sys/select.h>
60 #endif
61 
62 #if HAVE_TERMIOS_H
63 #include <fcntl.h>
64 #include <sys/ioctl.h>
65 #include <sys/time.h>
66 #include <termios.h>
67 #elif HAVE_KBHIT
68 #include <conio.h>
69 #endif
70 
71 #include "libavutil/avassert.h"
72 #include "libavutil/avstring.h"
73 #include "libavutil/bprint.h"
75 #include "libavutil/dict.h"
76 #include "libavutil/display.h"
77 #include "libavutil/fifo.h"
78 #include "libavutil/hwcontext.h"
79 #include "libavutil/imgutils.h"
80 #include "libavutil/intreadwrite.h"
81 #include "libavutil/libm.h"
82 #include "libavutil/mathematics.h"
83 #include "libavutil/opt.h"
84 #include "libavutil/parseutils.h"
85 #include "libavutil/pixdesc.h"
86 #include "libavutil/samplefmt.h"
87 #include "libavutil/thread.h"
89 #include "libavutil/time.h"
90 #include "libavutil/timestamp.h"
91 
92 #include "libavcodec/version.h"
93 
94 #include "libavformat/avformat.h"
95 
96 #include "libavdevice/avdevice.h"
97 
99 
100 #include "cmdutils.h"
101 #include "ffmpeg.h"
102 #include "sync_queue.h"
103 
104 const char program_name[] = "ffmpeg";
105 const int program_birth_year = 2000;
106 
108 
109 typedef struct BenchmarkTimeStamps {
110  int64_t real_usec;
111  int64_t user_usec;
112  int64_t sys_usec;
114 
116 static int64_t getmaxrss(void);
117 
118 unsigned nb_output_dumped = 0;
119 
122 
125 
128 
131 
132 #if HAVE_TERMIOS_H
133 
134 /* init terminal so that we can grab keys */
135 static struct termios oldtty;
136 static int restore_tty;
137 #endif
138 
139 /* sub2video hack:
140  Convert subtitles to video with alpha to insert them in filter graphs.
141  This is a temporary solution until libavfilter gets real subtitles support.
142  */
143 
144 static void sub2video_heartbeat(InputFile *infile, int64_t pts, AVRational tb)
145 {
146  /* When a frame is read from a file, examine all sub2video streams in
147  the same file and send the sub2video frame again. Otherwise, decoded
148  video frames could be accumulating in the filter graph while a filter
149  (possibly overlay) is desperately waiting for a subtitle frame. */
150  for (int i = 0; i < infile->nb_streams; i++) {
151  InputStream *ist = infile->streams[i];
152 
154  continue;
155 
156  for (int j = 0; j < ist->nb_filters; j++)
158  }
159 }
160 
161 /* end of sub2video hack */
162 
163 static void term_exit_sigsafe(void)
164 {
165 #if HAVE_TERMIOS_H
166  if(restore_tty)
167  tcsetattr (0, TCSANOW, &oldtty);
168 #endif
169 }
170 
171 void term_exit(void)
172 {
173  av_log(NULL, AV_LOG_QUIET, "%s", "");
175 }
176 
177 static volatile int received_sigterm = 0;
178 static volatile int received_nb_signals = 0;
180 static volatile int ffmpeg_exited = 0;
182 
183 static void
185 {
186  int ret;
187  received_sigterm = sig;
190  if(received_nb_signals > 3) {
191  ret = write(2/*STDERR_FILENO*/, "Received > 3 system signals, hard exiting\n",
192  strlen("Received > 3 system signals, hard exiting\n"));
193  if (ret < 0) { /* Do nothing */ };
194  exit(123);
195  }
196 }
197 
198 #if HAVE_SETCONSOLECTRLHANDLER
199 static BOOL WINAPI CtrlHandler(DWORD fdwCtrlType)
200 {
201  av_log(NULL, AV_LOG_DEBUG, "\nReceived windows signal %ld\n", fdwCtrlType);
202 
203  switch (fdwCtrlType)
204  {
205  case CTRL_C_EVENT:
206  case CTRL_BREAK_EVENT:
207  sigterm_handler(SIGINT);
208  return TRUE;
209 
210  case CTRL_CLOSE_EVENT:
211  case CTRL_LOGOFF_EVENT:
212  case CTRL_SHUTDOWN_EVENT:
213  sigterm_handler(SIGTERM);
214  /* Basically, with these 3 events, when we return from this method the
215  process is hard terminated, so stall as long as we need to
216  to try and let the main thread(s) clean up and gracefully terminate
217  (we have at most 5 seconds, but should be done far before that). */
218  while (!ffmpeg_exited) {
219  Sleep(0);
220  }
221  return TRUE;
222 
223  default:
224  av_log(NULL, AV_LOG_ERROR, "Received unknown windows signal %ld\n", fdwCtrlType);
225  return FALSE;
226  }
227 }
228 #endif
229 
230 #ifdef __linux__
231 #define SIGNAL(sig, func) \
232  do { \
233  action.sa_handler = func; \
234  sigaction(sig, &action, NULL); \
235  } while (0)
236 #else
237 #define SIGNAL(sig, func) \
238  signal(sig, func)
239 #endif
240 
241 void term_init(void)
242 {
243 #if defined __linux__
244  struct sigaction action = {0};
245  action.sa_handler = sigterm_handler;
246 
247  /* block other interrupts while processing this one */
248  sigfillset(&action.sa_mask);
249 
250  /* restart interruptible functions (i.e. don't fail with EINTR) */
251  action.sa_flags = SA_RESTART;
252 #endif
253 
254 #if HAVE_TERMIOS_H
255  if (stdin_interaction) {
256  struct termios tty;
257  if (tcgetattr (0, &tty) == 0) {
258  oldtty = tty;
259  restore_tty = 1;
260 
261  tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
262  |INLCR|IGNCR|ICRNL|IXON);
263  tty.c_oflag |= OPOST;
264  tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
265  tty.c_cflag &= ~(CSIZE|PARENB);
266  tty.c_cflag |= CS8;
267  tty.c_cc[VMIN] = 1;
268  tty.c_cc[VTIME] = 0;
269 
270  tcsetattr (0, TCSANOW, &tty);
271  }
272  SIGNAL(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
273  }
274 #endif
275 
276  SIGNAL(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
277  SIGNAL(SIGTERM, sigterm_handler); /* Termination (ANSI). */
278 #ifdef SIGXCPU
279  SIGNAL(SIGXCPU, sigterm_handler);
280 #endif
281 #ifdef SIGPIPE
282  signal(SIGPIPE, SIG_IGN); /* Broken pipe (POSIX). */
283 #endif
284 #if HAVE_SETCONSOLECTRLHANDLER
285  SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
286 #endif
287 }
288 
289 /* read a key without blocking */
290 static int read_key(void)
291 {
292  unsigned char ch;
293 #if HAVE_TERMIOS_H
294  int n = 1;
295  struct timeval tv;
296  fd_set rfds;
297 
298  FD_ZERO(&rfds);
299  FD_SET(0, &rfds);
300  tv.tv_sec = 0;
301  tv.tv_usec = 0;
302  n = select(1, &rfds, NULL, NULL, &tv);
303  if (n > 0) {
304  n = read(0, &ch, 1);
305  if (n == 1)
306  return ch;
307 
308  return n;
309  }
310 #elif HAVE_KBHIT
311 # if HAVE_PEEKNAMEDPIPE && HAVE_GETSTDHANDLE
312  static int is_pipe;
313  static HANDLE input_handle;
314  DWORD dw, nchars;
315  if(!input_handle){
316  input_handle = GetStdHandle(STD_INPUT_HANDLE);
317  is_pipe = !GetConsoleMode(input_handle, &dw);
318  }
319 
320  if (is_pipe) {
321  /* When running under a GUI, you will end here. */
322  if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
323  // input pipe may have been closed by the program that ran ffmpeg
324  return -1;
325  }
326  //Read it
327  if(nchars != 0) {
328  read(0, &ch, 1);
329  return ch;
330  }else{
331  return -1;
332  }
333  }
334 # endif
335  if(kbhit())
336  return(getch());
337 #endif
338  return -1;
339 }
340 
341 static int decode_interrupt_cb(void *ctx)
342 {
344 }
345 
347 
348 static void ffmpeg_cleanup(int ret)
349 {
350  int i;
351 
352  if (do_benchmark) {
353  int maxrss = getmaxrss() / 1024;
354  av_log(NULL, AV_LOG_INFO, "bench: maxrss=%ikB\n", maxrss);
355  }
356 
357  for (i = 0; i < nb_filtergraphs; i++)
360 
361  for (i = 0; i < nb_output_files; i++)
363 
364  for (i = 0; i < nb_input_files; i++)
366 
367  if (vstats_file) {
368  if (fclose(vstats_file))
370  "Error closing vstats file, loss of information possible: %s\n",
371  av_err2str(AVERROR(errno)));
372  }
375 
377 
379 
382 
383  uninit_opts();
384 
386 
387  if (received_sigterm) {
388  av_log(NULL, AV_LOG_INFO, "Exiting normally, received signal %d.\n",
389  (int) received_sigterm);
390  } else if (ret && atomic_load(&transcode_init_done)) {
391  av_log(NULL, AV_LOG_INFO, "Conversion failed!\n");
392  }
393  term_exit();
394  ffmpeg_exited = 1;
395 }
396 
398 {
399  int of_idx = prev ? prev->file_index : 0;
400  int ost_idx = prev ? prev->index + 1 : 0;
401 
402  for (; of_idx < nb_output_files; of_idx++) {
403  OutputFile *of = output_files[of_idx];
404  if (ost_idx < of->nb_streams)
405  return of->streams[ost_idx];
406 
407  ost_idx = 0;
408  }
409 
410  return NULL;
411 }
412 
414 {
415  int if_idx = prev ? prev->file_index : 0;
416  int ist_idx = prev ? prev->index + 1 : 0;
417 
418  for (; if_idx < nb_input_files; if_idx++) {
419  InputFile *f = input_files[if_idx];
420  if (ist_idx < f->nb_streams)
421  return f->streams[ist_idx];
422 
423  ist_idx = 0;
424  }
425 
426  return NULL;
427 }
428 
430 {
431  if (!frame->opaque_ref) {
432  FrameData *fd;
433 
434  frame->opaque_ref = av_buffer_allocz(sizeof(*fd));
435  if (!frame->opaque_ref)
436  return NULL;
437  fd = (FrameData*)frame->opaque_ref->data;
438 
439  fd->dec.frame_num = UINT64_MAX;
440  fd->dec.pts = AV_NOPTS_VALUE;
441  }
442 
443  return (FrameData*)frame->opaque_ref->data;
444 }
445 
447 {
448  const AVDictionaryEntry *t = NULL;
449 
450  while ((t = av_dict_iterate(b, t))) {
452  }
453 }
454 
456 {
457  const AVDictionaryEntry *t;
458  if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
459  av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
461  }
462 
463  return 0;
464 }
465 
466 void update_benchmark(const char *fmt, ...)
467 {
468  if (do_benchmark_all) {
470  va_list va;
471  char buf[1024];
472 
473  if (fmt) {
474  va_start(va, fmt);
475  vsnprintf(buf, sizeof(buf), fmt, va);
476  va_end(va);
478  "bench: %8" PRIu64 " user %8" PRIu64 " sys %8" PRIu64 " real %s \n",
481  t.real_usec - current_time.real_usec, buf);
482  }
483  current_time = t;
484  }
485 }
486 
488 {
489  OutputFile *of = output_files[ost->file_index];
490  ost->finished |= ENCODER_FINISHED;
491 
492  if (ost->sq_idx_encode >= 0)
493  sq_send(of->sq_encode, ost->sq_idx_encode, SQFRAME(NULL));
494 }
495 
496 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
497 {
498  AVBPrint buf, buf_script;
499  int64_t total_size = of_filesize(output_files[0]);
500  int vid;
501  double bitrate;
502  double speed;
503  int64_t pts = AV_NOPTS_VALUE;
504  static int64_t last_time = -1;
505  static int first_report = 1;
506  uint64_t nb_frames_dup = 0, nb_frames_drop = 0;
507  int mins, secs, us;
508  int64_t hours;
509  const char *hours_sign;
510  int ret;
511  float t;
512 
513  if (!print_stats && !is_last_report && !progress_avio)
514  return;
515 
516  if (!is_last_report) {
517  if (last_time == -1) {
518  last_time = cur_time;
519  }
520  if (((cur_time - last_time) < stats_period && !first_report) ||
521  (first_report && nb_output_dumped < nb_output_files))
522  return;
523  last_time = cur_time;
524  }
525 
526  t = (cur_time-timer_start) / 1000000.0;
527 
528  vid = 0;
530  av_bprint_init(&buf_script, 0, AV_BPRINT_SIZE_AUTOMATIC);
531  for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
532  const float q = ost->enc ? ost->quality / (float) FF_QP2LAMBDA : -1;
533 
534  if (vid && ost->type == AVMEDIA_TYPE_VIDEO) {
535  av_bprintf(&buf, "q=%2.1f ", q);
536  av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
537  ost->file_index, ost->index, q);
538  }
539  if (!vid && ost->type == AVMEDIA_TYPE_VIDEO && ost->filter) {
540  float fps;
541  uint64_t frame_number = atomic_load(&ost->packets_written);
542 
543  fps = t > 1 ? frame_number / t : 0;
544  av_bprintf(&buf, "frame=%5"PRId64" fps=%3.*f q=%3.1f ",
545  frame_number, fps < 9.95, fps, q);
546  av_bprintf(&buf_script, "frame=%"PRId64"\n", frame_number);
547  av_bprintf(&buf_script, "fps=%.2f\n", fps);
548  av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
549  ost->file_index, ost->index, q);
550  if (is_last_report)
551  av_bprintf(&buf, "L");
552 
553  nb_frames_dup = ost->filter->nb_frames_dup;
554  nb_frames_drop = ost->filter->nb_frames_drop;
555 
556  vid = 1;
557  }
558  /* compute min output value */
559  if (ost->last_mux_dts != AV_NOPTS_VALUE) {
560  if (pts == AV_NOPTS_VALUE || ost->last_mux_dts > pts)
561  pts = ost->last_mux_dts;
562  if (copy_ts) {
563  if (copy_ts_first_pts == AV_NOPTS_VALUE && pts > 1)
567  }
568  }
569  }
570 
572  secs = FFABS64U(pts) / AV_TIME_BASE % 60;
573  mins = FFABS64U(pts) / AV_TIME_BASE / 60 % 60;
574  hours = FFABS64U(pts) / AV_TIME_BASE / 3600;
575  hours_sign = (pts < 0) ? "-" : "";
576 
577  bitrate = pts != AV_NOPTS_VALUE && pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
578  speed = pts != AV_NOPTS_VALUE && t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
579 
580  if (total_size < 0) av_bprintf(&buf, "size=N/A time=");
581  else av_bprintf(&buf, "size=%8.0fkB time=", total_size / 1024.0);
582  if (pts == AV_NOPTS_VALUE) {
583  av_bprintf(&buf, "N/A ");
584  } else {
585  av_bprintf(&buf, "%s%02"PRId64":%02d:%02d.%02d ",
586  hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
587  }
588 
589  if (bitrate < 0) {
590  av_bprintf(&buf, "bitrate=N/A");
591  av_bprintf(&buf_script, "bitrate=N/A\n");
592  }else{
593  av_bprintf(&buf, "bitrate=%6.1fkbits/s", bitrate);
594  av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
595  }
596 
597  if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
598  else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
599  if (pts == AV_NOPTS_VALUE) {
600  av_bprintf(&buf_script, "out_time_us=N/A\n");
601  av_bprintf(&buf_script, "out_time_ms=N/A\n");
602  av_bprintf(&buf_script, "out_time=N/A\n");
603  } else {
604  av_bprintf(&buf_script, "out_time_us=%"PRId64"\n", pts);
605  av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
606  av_bprintf(&buf_script, "out_time=%s%02"PRId64":%02d:%02d.%06d\n",
607  hours_sign, hours, mins, secs, us);
608  }
609 
610  if (nb_frames_dup || nb_frames_drop)
611  av_bprintf(&buf, " dup=%"PRId64" drop=%"PRId64, nb_frames_dup, nb_frames_drop);
612  av_bprintf(&buf_script, "dup_frames=%"PRId64"\n", nb_frames_dup);
613  av_bprintf(&buf_script, "drop_frames=%"PRId64"\n", nb_frames_drop);
614 
615  if (speed < 0) {
616  av_bprintf(&buf, " speed=N/A");
617  av_bprintf(&buf_script, "speed=N/A\n");
618  } else {
619  av_bprintf(&buf, " speed=%4.3gx", speed);
620  av_bprintf(&buf_script, "speed=%4.3gx\n", speed);
621  }
622 
623  if (print_stats || is_last_report) {
624  const char end = is_last_report ? '\n' : '\r';
625  if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
626  fprintf(stderr, "%s %c", buf.str, end);
627  } else
628  av_log(NULL, AV_LOG_INFO, "%s %c", buf.str, end);
629 
630  fflush(stderr);
631  }
632  av_bprint_finalize(&buf, NULL);
633 
634  if (progress_avio) {
635  av_bprintf(&buf_script, "progress=%s\n",
636  is_last_report ? "end" : "continue");
637  avio_write(progress_avio, buf_script.str,
638  FFMIN(buf_script.len, buf_script.size - 1));
640  av_bprint_finalize(&buf_script, NULL);
641  if (is_last_report) {
642  if ((ret = avio_closep(&progress_avio)) < 0)
644  "Error closing progress log, loss of information possible: %s\n", av_err2str(ret));
645  }
646  }
647 
648  first_report = 0;
649 }
650 
652 {
653  int ret = AVERROR_BUG;
654  AVSubtitle tmp = {
655  .format = src->format,
656  .start_display_time = src->start_display_time,
657  .end_display_time = src->end_display_time,
658  .num_rects = 0,
659  .rects = NULL,
660  .pts = src->pts
661  };
662 
663  if (!src->num_rects)
664  goto success;
665 
666  if (!(tmp.rects = av_calloc(src->num_rects, sizeof(*tmp.rects))))
667  return AVERROR(ENOMEM);
668 
669  for (int i = 0; i < src->num_rects; i++) {
670  AVSubtitleRect *src_rect = src->rects[i];
671  AVSubtitleRect *dst_rect;
672 
673  if (!(dst_rect = tmp.rects[i] = av_mallocz(sizeof(*tmp.rects[0])))) {
674  ret = AVERROR(ENOMEM);
675  goto cleanup;
676  }
677 
678  tmp.num_rects++;
679 
680  dst_rect->type = src_rect->type;
681  dst_rect->flags = src_rect->flags;
682 
683  dst_rect->x = src_rect->x;
684  dst_rect->y = src_rect->y;
685  dst_rect->w = src_rect->w;
686  dst_rect->h = src_rect->h;
687  dst_rect->nb_colors = src_rect->nb_colors;
688 
689  if (src_rect->text)
690  if (!(dst_rect->text = av_strdup(src_rect->text))) {
691  ret = AVERROR(ENOMEM);
692  goto cleanup;
693  }
694 
695  if (src_rect->ass)
696  if (!(dst_rect->ass = av_strdup(src_rect->ass))) {
697  ret = AVERROR(ENOMEM);
698  goto cleanup;
699  }
700 
701  for (int j = 0; j < 4; j++) {
702  // SUBTITLE_BITMAP images are special in the sense that they
703  // are like PAL8 images. first pointer to data, second to
704  // palette. This makes the size calculation match this.
705  size_t buf_size = src_rect->type == SUBTITLE_BITMAP && j == 1 ?
707  src_rect->h * src_rect->linesize[j];
708 
709  if (!src_rect->data[j])
710  continue;
711 
712  if (!(dst_rect->data[j] = av_memdup(src_rect->data[j], buf_size))) {
713  ret = AVERROR(ENOMEM);
714  goto cleanup;
715  }
716  dst_rect->linesize[j] = src_rect->linesize[j];
717  }
718  }
719 
720 success:
721  *dst = tmp;
722 
723  return 0;
724 
725 cleanup:
727 
728  return ret;
729 }
730 
731 static void subtitle_free(void *opaque, uint8_t *data)
732 {
733  AVSubtitle *sub = (AVSubtitle*)data;
734  avsubtitle_free(sub);
735  av_free(sub);
736 }
737 
739 {
740  AVBufferRef *buf;
741  AVSubtitle *sub;
742  int ret;
743 
744  if (copy) {
745  sub = av_mallocz(sizeof(*sub));
746  ret = sub ? copy_av_subtitle(sub, subtitle) : AVERROR(ENOMEM);
747  if (ret < 0) {
748  av_freep(&sub);
749  return ret;
750  }
751  } else {
752  sub = av_memdup(subtitle, sizeof(*subtitle));
753  if (!sub)
754  return AVERROR(ENOMEM);
755  memset(subtitle, 0, sizeof(*subtitle));
756  }
757 
758  buf = av_buffer_create((uint8_t*)sub, sizeof(*sub),
759  subtitle_free, NULL, 0);
760  if (!buf) {
761  avsubtitle_free(sub);
762  av_freep(&sub);
763  return AVERROR(ENOMEM);
764  }
765 
766  frame->buf[0] = buf;
767 
768  return 0;
769 }
770 
772 {
773  OutputFile *of = output_files[ost->file_index];
774  int64_t signal_pts = av_rescale_q(pkt->pts, pkt->time_base,
776 
777  if (!ost->fix_sub_duration_heartbeat || !(pkt->flags & AV_PKT_FLAG_KEY))
778  // we are only interested in heartbeats on streams configured, and
779  // only on random access points.
780  return 0;
781 
782  for (int i = 0; i < of->nb_streams; i++) {
783  OutputStream *iter_ost = of->streams[i];
784  InputStream *ist = iter_ost->ist;
785  int ret = AVERROR_BUG;
786 
787  if (iter_ost == ost || !ist || !ist->decoding_needed ||
789  // We wish to skip the stream that causes the heartbeat,
790  // output streams without an input stream, streams not decoded
791  // (as fix_sub_duration is only done for decoded subtitles) as
792  // well as non-subtitle streams.
793  continue;
794 
795  if ((ret = fix_sub_duration_heartbeat(ist, signal_pts)) < 0)
796  return ret;
797  }
798 
799  return 0;
800 }
801 
802 /* pkt = NULL means EOF (needed to flush decoder buffers) */
803 static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
804 {
806  int64_t dts_est = AV_NOPTS_VALUE;
807  int ret = 0;
808  int eof_reached = 0;
809 
810  if (ist->decoding_needed) {
811  ret = dec_packet(ist, pkt, no_eof);
812  if (ret < 0 && ret != AVERROR_EOF)
813  return ret;
814  }
815  if (ret == AVERROR_EOF || (!pkt && !ist->decoding_needed))
816  eof_reached = 1;
817 
818  if (pkt && pkt->opaque_ref) {
820  dts_est = pd->dts_est;
821  }
822 
823  if (f->recording_time != INT64_MAX) {
824  int64_t start_time = 0;
825  if (copy_ts) {
826  start_time += f->start_time != AV_NOPTS_VALUE ? f->start_time : 0;
827  start_time += start_at_zero ? 0 : f->start_time_effective;
828  }
829  if (dts_est >= f->recording_time + start_time)
830  pkt = NULL;
831  }
832 
833  for (int oidx = 0; oidx < ist->nb_outputs; oidx++) {
834  OutputStream *ost = ist->outputs[oidx];
835  if (ost->enc || (!pkt && no_eof))
836  continue;
837 
838  ret = of_streamcopy(ost, pkt, dts_est);
839  if (ret < 0)
840  return ret;
841  }
842 
843  return !eof_reached;
844 }
845 
846 static void print_stream_maps(void)
847 {
848  av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
849  for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
850  for (int j = 0; j < ist->nb_filters; j++) {
851  if (!filtergraph_is_simple(ist->filters[j]->graph)) {
852  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
853  ist->file_index, ist->index, ist->dec ? ist->dec->name : "?",
854  ist->filters[j]->name);
855  if (nb_filtergraphs > 1)
856  av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
857  av_log(NULL, AV_LOG_INFO, "\n");
858  }
859  }
860  }
861 
862  for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
863  if (ost->attachment_filename) {
864  /* an attached file */
865  av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
866  ost->attachment_filename, ost->file_index, ost->index);
867  continue;
868  }
869 
870  if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
871  /* output from a complex graph */
872  av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
873  if (nb_filtergraphs > 1)
874  av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
875 
876  av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
877  ost->index, ost->enc_ctx->codec->name);
878  continue;
879  }
880 
881  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
882  ost->ist->file_index,
883  ost->ist->index,
884  ost->file_index,
885  ost->index);
886  if (ost->enc_ctx) {
887  const AVCodec *in_codec = ost->ist->dec;
888  const AVCodec *out_codec = ost->enc_ctx->codec;
889  const char *decoder_name = "?";
890  const char *in_codec_name = "?";
891  const char *encoder_name = "?";
892  const char *out_codec_name = "?";
893  const AVCodecDescriptor *desc;
894 
895  if (in_codec) {
896  decoder_name = in_codec->name;
897  desc = avcodec_descriptor_get(in_codec->id);
898  if (desc)
899  in_codec_name = desc->name;
900  if (!strcmp(decoder_name, in_codec_name))
901  decoder_name = "native";
902  }
903 
904  if (out_codec) {
905  encoder_name = out_codec->name;
906  desc = avcodec_descriptor_get(out_codec->id);
907  if (desc)
908  out_codec_name = desc->name;
909  if (!strcmp(encoder_name, out_codec_name))
910  encoder_name = "native";
911  }
912 
913  av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
914  in_codec_name, decoder_name,
915  out_codec_name, encoder_name);
916  } else
917  av_log(NULL, AV_LOG_INFO, " (copy)");
918  av_log(NULL, AV_LOG_INFO, "\n");
919  }
920 }
921 
922 /**
923  * Select the output stream to process.
924  *
925  * @retval 0 an output stream was selected
926  * @retval AVERROR(EAGAIN) need to wait until more input is available
927  * @retval AVERROR_EOF no more streams need output
928  */
929 static int choose_output(OutputStream **post)
930 {
931  int64_t opts_min = INT64_MAX;
932  OutputStream *ost_min = NULL;
933 
934  for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
935  int64_t opts;
936 
937  if (ost->filter && ost->filter->last_pts != AV_NOPTS_VALUE) {
938  opts = ost->filter->last_pts;
939  } else {
940  opts = ost->last_mux_dts == AV_NOPTS_VALUE ?
941  INT64_MIN : ost->last_mux_dts;
942  }
943 
944  if (!ost->initialized && !ost->finished) {
945  ost_min = ost;
946  break;
947  }
948  if (!ost->finished && opts < opts_min) {
949  opts_min = opts;
950  ost_min = ost;
951  }
952  }
953  if (!ost_min)
954  return AVERROR_EOF;
955  *post = ost_min;
956  return ost_min->unavailable ? AVERROR(EAGAIN) : 0;
957 }
958 
959 static void set_tty_echo(int on)
960 {
961 #if HAVE_TERMIOS_H
962  struct termios tty;
963  if (tcgetattr(0, &tty) == 0) {
964  if (on) tty.c_lflag |= ECHO;
965  else tty.c_lflag &= ~ECHO;
966  tcsetattr(0, TCSANOW, &tty);
967  }
968 #endif
969 }
970 
971 static int check_keyboard_interaction(int64_t cur_time)
972 {
973  int i, key;
974  static int64_t last_time;
976  return AVERROR_EXIT;
977  /* read_key() returns 0 on EOF */
978  if (cur_time - last_time >= 100000) {
979  key = read_key();
980  last_time = cur_time;
981  }else
982  key = -1;
983  if (key == 'q') {
984  av_log(NULL, AV_LOG_INFO, "\n\n[q] command received. Exiting.\n\n");
985  return AVERROR_EXIT;
986  }
987  if (key == '+') av_log_set_level(av_log_get_level()+10);
988  if (key == '-') av_log_set_level(av_log_get_level()-10);
989  if (key == 'c' || key == 'C'){
990  char buf[4096], target[64], command[256], arg[256] = {0};
991  double time;
992  int k, n = 0;
993  fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
994  i = 0;
995  set_tty_echo(1);
996  while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
997  if (k > 0)
998  buf[i++] = k;
999  buf[i] = 0;
1000  set_tty_echo(0);
1001  fprintf(stderr, "\n");
1002  if (k > 0 &&
1003  (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
1004  av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
1005  target, time, command, arg);
1006  for (i = 0; i < nb_filtergraphs; i++)
1007  fg_send_command(filtergraphs[i], time, target, command, arg,
1008  key == 'C');
1009  } else {
1011  "Parse error, at least 3 arguments were expected, "
1012  "only %d given in string '%s'\n", n, buf);
1013  }
1014  }
1015  if (key == '?'){
1016  fprintf(stderr, "key function\n"
1017  "? show this help\n"
1018  "+ increase verbosity\n"
1019  "- decrease verbosity\n"
1020  "c Send command to first matching filter supporting it\n"
1021  "C Send/Queue command to all matching filters\n"
1022  "h dump packets/hex press to cycle through the 3 states\n"
1023  "q quit\n"
1024  "s Show QP histogram\n"
1025  );
1026  }
1027  return 0;
1028 }
1029 
1030 static void reset_eagain(void)
1031 {
1032  int i;
1033  for (i = 0; i < nb_input_files; i++)
1034  input_files[i]->eagain = 0;
1035  for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost))
1036  ost->unavailable = 0;
1037 }
1038 
1039 static void decode_flush(InputFile *ifile)
1040 {
1041  for (int i = 0; i < ifile->nb_streams; i++) {
1042  InputStream *ist = ifile->streams[i];
1043 
1044  if (ist->discard || !ist->decoding_needed)
1045  continue;
1046 
1047  dec_packet(ist, NULL, 1);
1048  }
1049 }
1050 
1051 /*
1052  * Return
1053  * - 0 -- one packet was read and processed
1054  * - AVERROR(EAGAIN) -- no packets were available for selected file,
1055  * this function should be called again
1056  * - AVERROR_EOF -- this function should not be called again
1057  */
1058 static int process_input(int file_index)
1059 {
1060  InputFile *ifile = input_files[file_index];
1061  InputStream *ist;
1062  AVPacket *pkt;
1063  int ret, i;
1064 
1065  ret = ifile_get_packet(ifile, &pkt);
1066 
1067  if (ret == AVERROR(EAGAIN)) {
1068  ifile->eagain = 1;
1069  return ret;
1070  }
1071  if (ret == 1) {
1072  /* the input file is looped: flush the decoders */
1073  decode_flush(ifile);
1074  return AVERROR(EAGAIN);
1075  }
1076  if (ret < 0) {
1077  if (ret != AVERROR_EOF) {
1078  av_log(ifile, AV_LOG_ERROR,
1079  "Error retrieving a packet from demuxer: %s\n", av_err2str(ret));
1080  if (exit_on_error)
1081  return ret;
1082  }
1083 
1084  for (i = 0; i < ifile->nb_streams; i++) {
1085  ist = ifile->streams[i];
1086  if (!ist->discard) {
1087  ret = process_input_packet(ist, NULL, 0);
1088  if (ret>0)
1089  return 0;
1090  else if (ret < 0)
1091  return ret;
1092  }
1093 
1094  /* mark all outputs that don't go through lavfi as finished */
1095  for (int oidx = 0; oidx < ist->nb_outputs; oidx++) {
1096  OutputStream *ost = ist->outputs[oidx];
1097  OutputFile *of = output_files[ost->file_index];
1098 
1099  ret = of_output_packet(of, ost, NULL);
1100  if (ret < 0)
1101  return ret;
1102  }
1103  }
1104 
1105  ifile->eof_reached = 1;
1106  return AVERROR(EAGAIN);
1107  }
1108 
1109  reset_eagain();
1110 
1111  ist = ifile->streams[pkt->stream_index];
1112 
1114 
1115  ret = process_input_packet(ist, pkt, 0);
1116 
1117  av_packet_free(&pkt);
1118 
1119  return ret < 0 ? ret : 0;
1120 }
1121 
1122 /**
1123  * Run a single step of transcoding.
1124  *
1125  * @return 0 for success, <0 for error
1126  */
1128 {
1129  InputStream *ist = NULL;
1130  int ret;
1131 
1132  if (ost->filter) {
1133  if ((ret = fg_transcode_step(ost->filter->graph, &ist)) < 0)
1134  return ret;
1135  if (!ist)
1136  return 0;
1137  } else {
1138  ist = ost->ist;
1139  av_assert0(ist);
1140  }
1141 
1142  ret = process_input(ist->file_index);
1143  if (ret == AVERROR(EAGAIN)) {
1144  if (input_files[ist->file_index]->eagain)
1145  ost->unavailable = 1;
1146  return 0;
1147  }
1148 
1149  if (ret < 0)
1150  return ret == AVERROR_EOF ? 0 : ret;
1151 
1152  // process_input() above might have caused output to become available
1153  // in multiple filtergraphs, so we process all of them
1154  for (int i = 0; i < nb_filtergraphs; i++) {
1155  ret = reap_filters(filtergraphs[i], 0);
1156  if (ret < 0)
1157  return ret;
1158  }
1159 
1160  return 0;
1161 }
1162 
1163 /*
1164  * The following code is the main loop of the file converter
1165  */
1166 static int transcode(int *err_rate_exceeded)
1167 {
1168  int ret = 0, i;
1169  InputStream *ist;
1170  int64_t timer_start;
1171 
1173 
1174  *err_rate_exceeded = 0;
1176 
1177  if (stdin_interaction) {
1178  av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
1179  }
1180 
1181  timer_start = av_gettime_relative();
1182 
1183  while (!received_sigterm) {
1184  OutputStream *ost;
1185  int64_t cur_time= av_gettime_relative();
1186 
1187  /* if 'q' pressed, exits */
1188  if (stdin_interaction)
1189  if (check_keyboard_interaction(cur_time) < 0)
1190  break;
1191 
1192  ret = choose_output(&ost);
1193  if (ret == AVERROR(EAGAIN)) {
1194  reset_eagain();
1195  av_usleep(10000);
1196  ret = 0;
1197  continue;
1198  } else if (ret < 0) {
1199  av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
1200  ret = 0;
1201  break;
1202  }
1203 
1204  ret = transcode_step(ost);
1205  if (ret < 0 && ret != AVERROR_EOF) {
1206  av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
1207  break;
1208  }
1209 
1210  /* dump report by using the output first video and audio streams */
1211  print_report(0, timer_start, cur_time);
1212  }
1213 
1214  /* at the end of stream, we must flush the decoder buffers */
1215  for (ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
1216  float err_rate;
1217 
1218  if (!input_files[ist->file_index]->eof_reached) {
1219  int err = process_input_packet(ist, NULL, 0);
1220  ret = err_merge(ret, err);
1221  }
1222 
1223  err_rate = (ist->frames_decoded || ist->decode_errors) ?
1224  ist->decode_errors / (ist->frames_decoded + ist->decode_errors) : 0.f;
1225  if (err_rate > max_error_rate) {
1226  av_log(ist, AV_LOG_FATAL, "Decode error rate %g exceeds maximum %g\n",
1227  err_rate, max_error_rate);
1228  *err_rate_exceeded = 1;
1229  } else if (err_rate)
1230  av_log(ist, AV_LOG_VERBOSE, "Decode error rate %g\n", err_rate);
1231  }
1232  ret = err_merge(ret, enc_flush());
1233 
1234  term_exit();
1235 
1236  /* write the trailer if needed */
1237  for (i = 0; i < nb_output_files; i++) {
1238  int err = of_write_trailer(output_files[i]);
1239  ret = err_merge(ret, err);
1240  }
1241 
1242  /* dump report by using the first video and audio streams */
1243  print_report(1, timer_start, av_gettime_relative());
1244 
1245  return ret;
1246 }
1247 
1249 {
1250  BenchmarkTimeStamps time_stamps = { av_gettime_relative() };
1251 #if HAVE_GETRUSAGE
1252  struct rusage rusage;
1253 
1254  getrusage(RUSAGE_SELF, &rusage);
1255  time_stamps.user_usec =
1256  (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
1257  time_stamps.sys_usec =
1258  (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
1259 #elif HAVE_GETPROCESSTIMES
1260  HANDLE proc;
1261  FILETIME c, e, k, u;
1262  proc = GetCurrentProcess();
1263  GetProcessTimes(proc, &c, &e, &k, &u);
1264  time_stamps.user_usec =
1265  ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
1266  time_stamps.sys_usec =
1267  ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
1268 #else
1269  time_stamps.user_usec = time_stamps.sys_usec = 0;
1270 #endif
1271  return time_stamps;
1272 }
1273 
1274 static int64_t getmaxrss(void)
1275 {
1276 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
1277  struct rusage rusage;
1278  getrusage(RUSAGE_SELF, &rusage);
1279  return (int64_t)rusage.ru_maxrss * 1024;
1280 #elif HAVE_GETPROCESSMEMORYINFO
1281  HANDLE proc;
1282  PROCESS_MEMORY_COUNTERS memcounters;
1283  proc = GetCurrentProcess();
1284  memcounters.cb = sizeof(memcounters);
1285  GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
1286  return memcounters.PeakPagefileUsage;
1287 #else
1288  return 0;
1289 #endif
1290 }
1291 
1292 int main(int argc, char **argv)
1293 {
1294  int ret, err_rate_exceeded;
1296 
1297  init_dynload();
1298 
1299  setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
1300 
1302  parse_loglevel(argc, argv, options);
1303 
1304 #if CONFIG_AVDEVICE
1306 #endif
1308 
1309  show_banner(argc, argv, options);
1310 
1311  /* parse options and open all input/output files */
1312  ret = ffmpeg_parse_options(argc, argv);
1313  if (ret < 0)
1314  goto finish;
1315 
1316  if (nb_output_files <= 0 && nb_input_files == 0) {
1317  show_usage();
1318  av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
1319  ret = 1;
1320  goto finish;
1321  }
1322 
1323  if (nb_output_files <= 0) {
1324  av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
1325  ret = 1;
1326  goto finish;
1327  }
1328 
1330  ret = transcode(&err_rate_exceeded);
1331  if (ret >= 0 && do_benchmark) {
1332  int64_t utime, stime, rtime;
1334  utime = current_time.user_usec - ti.user_usec;
1335  stime = current_time.sys_usec - ti.sys_usec;
1336  rtime = current_time.real_usec - ti.real_usec;
1338  "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
1339  utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
1340  }
1341 
1342  ret = received_nb_signals ? 255 :
1343  err_rate_exceeded ? 69 : ret;
1344 
1345 finish:
1346  if (ret == AVERROR_EXIT)
1347  ret = 0;
1348 
1350  return ret;
1351 }
AVSubtitle
Definition: avcodec.h:2269
AVCodec
AVCodec.
Definition: codec.h:187
AVMEDIA_TYPE_SUBTITLE
@ AVMEDIA_TYPE_SUBTITLE
Definition: avutil.h:204
av_gettime_relative
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition: time.c:56
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:186
of_streamcopy
int of_streamcopy(OutputStream *ost, const AVPacket *pkt, int64_t dts)
Definition: ffmpeg_mux.c:406
atomic_store
#define atomic_store(object, desired)
Definition: stdatomic.h:85
reset_eagain
static void reset_eagain(void)
Definition: ffmpeg.c:1030
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
nb_input_files
int nb_input_files
Definition: ffmpeg.c:124
opt.h
ffmpeg_exited
static volatile int ffmpeg_exited
Definition: ffmpeg.c:180
libm.h
FrameData
Definition: ffmpeg.h:636
close_output_stream
void close_output_stream(OutputStream *ost)
Definition: ffmpeg.c:487
enc_flush
int enc_flush(void)
Definition: ffmpeg_enc.c:863
av_bprint_init
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition: bprint.c:69
u
#define u(width, name, range_min, range_max)
Definition: cbs_h2645.c:250
AV_LOG_QUIET
#define AV_LOG_QUIET
Print no output.
Definition: log.h:162
reap_filters
int reap_filters(FilterGraph *fg, int flush)
Get and encode new output from specified filtergraph, without causing activity.
Definition: ffmpeg_filter.c:2228
thread.h
AVERROR_EOF
#define AVERROR_EOF
End of file.
Definition: error.h:57
AVBufferRef::data
uint8_t * data
The data buffer.
Definition: buffer.h:90
fg_free
void fg_free(FilterGraph **pfg)
Definition: ffmpeg_filter.c:800
remove_avoptions
void remove_avoptions(AVDictionary **a, AVDictionary *b)
Definition: ffmpeg.c:446
InputStream::outputs
struct OutputStream ** outputs
Definition: ffmpeg.h:376
InputStream::dec_ctx
AVCodecContext * dec_ctx
Definition: ffmpeg.h:344
AV_TIME_BASE_Q
#define AV_TIME_BASE_Q
Internal time base represented as fractional value.
Definition: avutil.h:264
BenchmarkTimeStamps::user_usec
int64_t user_usec
Definition: ffmpeg.c:111
AVSubtitleRect
Definition: avcodec.h:2241
ist_iter
InputStream * ist_iter(InputStream *prev)
Definition: ffmpeg.c:413
SQFRAME
#define SQFRAME(frame)
Definition: sync_queue.h:38
ffmpeg_parse_options
int ffmpeg_parse_options(int argc, char **argv)
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:340
tmp
static uint8_t tmp[11]
Definition: aes_ctr.c:28
pixdesc.h
cleanup
static av_cold void cleanup(FlashSV2Context *s)
Definition: flashsv2enc.c:130
of_filesize
int64_t of_filesize(OutputFile *of)
Definition: ffmpeg_mux.c:947
OutputStream::unavailable
int unavailable
Definition: ffmpeg.h:581
sync_queue.h
current_time
static BenchmarkTimeStamps current_time
Definition: ffmpeg.c:120
OutputStream::index
int index
Definition: ffmpeg.h:520
ATOMIC_VAR_INIT
#define ATOMIC_VAR_INIT(value)
Definition: stdatomic.h:31
b
#define b
Definition: input.c:41
nb_output_dumped
unsigned nb_output_dumped
Definition: ffmpeg.c:118
data
const char data[16]
Definition: mxf.c:148
InputStream::nb_filters
int nb_filters
Definition: ffmpeg.h:369
atomic_int
intptr_t atomic_int
Definition: stdatomic.h:55
AV_DICT_IGNORE_SUFFIX
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key,...
Definition: dict.h:75
version.h
AVSubtitleRect::linesize
int linesize[4]
Definition: avcodec.h:2253
ffmpeg.h
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:196
BenchmarkTimeStamps::sys_usec
int64_t sys_usec
Definition: ffmpeg.c:112
progress_avio
AVIOContext * progress_avio
Definition: ffmpeg.c:121
show_usage
void show_usage(void)
Definition: ffmpeg_opt.c:1248
mathematics.h
AVDictionary
Definition: dict.c:34
program_birth_year
const int program_birth_year
program birth year, defined by the program for show_banner()
Definition: ffmpeg.c:105
InputStream::decoding_needed
int decoding_needed
Definition: ffmpeg.h:333
AVFrame::buf
AVBufferRef * buf[AV_NUM_DATA_POINTERS]
AVBuffer references backing the data for this frame.
Definition: frame.h:590
ost
static AVStream * ost
Definition: vaapi_transcode.c:42
AV_PKT_FLAG_KEY
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:546
OutputStream::ist
InputStream * ist
Definition: ffmpeg.h:531
av_packet_free
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
Definition: avpacket.c:74
term_exit_sigsafe
static void term_exit_sigsafe(void)
Definition: ffmpeg.c:163
ECHO
#define ECHO(name, type, min, max)
Definition: af_aecho.c:157
AVIOInterruptCB
Callback for checking whether to abort blocking functions.
Definition: avio.h:59
InputStream::nb_outputs
int nb_outputs
Definition: ffmpeg.h:377
FrameData::frame_num
uint64_t frame_num
Definition: ffmpeg.h:639
OutputFile::nb_streams
int nb_streams
Definition: ffmpeg.h:624
av_memdup
void * av_memdup(const void *p, size_t size)
Duplicate a buffer with av_malloc().
Definition: mem.c:302
AVFrame::opaque_ref
AVBufferRef * opaque_ref
Frame owner's private data.
Definition: frame.h:768
InputFile::eof_reached
int eof_reached
Definition: ffmpeg.h:408
InputStream
Definition: ffmpeg.h:324
filter_nbthreads
char * filter_nbthreads
Definition: ffmpeg_opt.c:87
stats_period
int64_t stats_period
Definition: ffmpeg_opt.c:91
fifo.h
finish
static void finish(void)
Definition: movenc.c:342
AVPacket::opaque_ref
AVBufferRef * opaque_ref
AVBufferRef for free use by the API user.
Definition: packet.h:527
samplefmt.h
AVSubtitleRect::x
int x
top left corner of pict, undefined when pict is not set
Definition: avcodec.h:2242
AVERROR_OPTION_NOT_FOUND
#define AVERROR_OPTION_NOT_FOUND
Option not found.
Definition: error.h:63
AV_BPRINT_SIZE_AUTOMATIC
#define AV_BPRINT_SIZE_AUTOMATIC
update_benchmark
void update_benchmark(const char *fmt,...)
Definition: ffmpeg.c:466
DemuxPktData
Definition: ffmpeg.h:104
pts
static int64_t pts
Definition: transcode_aac.c:643
us
#define us(width, name, range_min, range_max, subs,...)
Definition: cbs_h2645.c:262
trigger_fix_sub_duration_heartbeat
int trigger_fix_sub_duration_heartbeat(OutputStream *ost, const AVPacket *pkt)
Definition: ffmpeg.c:771
fg_send_command
void fg_send_command(FilterGraph *fg, double time, const char *target, const char *command, const char *arg, int all_filters)
Definition: ffmpeg_filter.c:1818
avformat_network_init
int avformat_network_init(void)
Do global initialization of network libraries.
Definition: utils.c:558
InputFile
Definition: ffmpeg.h:399
AVSubtitleRect::ass
char * ass
0 terminated ASS/SSA compatible event line.
Definition: avcodec.h:2264
avsubtitle_free
void avsubtitle_free(AVSubtitle *sub)
Free all allocated data in the given subtitle struct.
Definition: avcodec.c:413
ffmpeg_cleanup
static void ffmpeg_cleanup(int ret)
Definition: ffmpeg.c:348
avassert.h
pkt
AVPacket * pkt
Definition: movenc.c:59
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:180
decode_flush
static void decode_flush(InputFile *ifile)
Definition: ffmpeg.c:1039
BenchmarkTimeStamps::real_usec
int64_t real_usec
Definition: ffmpeg.c:110
av_dict_get
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:62
fg_transcode_step
int fg_transcode_step(FilterGraph *graph, InputStream **best_ist)
Perform a step of transcoding for the specified filter graph.
Definition: ffmpeg_filter.c:2452
float
float
Definition: af_crystalizer.c:121
of_free
void of_free(OutputFile **pof)
Definition: ffmpeg_mux.c:920
AVCodecDescriptor
This struct describes the properties of a single codec described by an AVCodecID.
Definition: codec_desc.h:38
intreadwrite.h
get_benchmark_time_stamps
static BenchmarkTimeStamps get_benchmark_time_stamps(void)
Definition: ffmpeg.c:1248
vstats_filename
char * vstats_filename
Definition: ffmpeg_opt.c:65
copy_ts_first_pts
static int64_t copy_ts_first_pts
Definition: ffmpeg.c:181
ifilter_sub2video_heartbeat
void ifilter_sub2video_heartbeat(InputFilter *ifilter, int64_t pts, AVRational tb)
Definition: ffmpeg_filter.c:2248
bitrate
int64_t bitrate
Definition: av1_levels.c:47
AVDictionaryEntry::key
char * key
Definition: dict.h:90
ENCODER_FINISHED
@ ENCODER_FINISHED
Definition: ffmpeg.h:485
AVSubtitleRect::y
int y
top left corner of pict, undefined when pict is not set
Definition: avcodec.h:2243
subtitle_wrap_frame
int subtitle_wrap_frame(AVFrame *frame, AVSubtitle *subtitle, int copy)
Definition: ffmpeg.c:738
av_assert0
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:40
term_init
void term_init(void)
Definition: ffmpeg.c:241
AV_LOG_DEBUG
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:201
ctx
AVFormatContext * ctx
Definition: movenc.c:48
InputStream::filters
InputFilter ** filters
Definition: ffmpeg.h:368
limits.h
nb_streams
static int nb_streams
Definition: ffprobe.c:328
av_rescale_q
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
max_error_rate
float max_error_rate
Definition: ffmpeg_opt.c:86
on
s EdgeDetect Foobar g libavfilter vf_edgedetect c libavfilter vf_foobar c edit libavfilter and add an entry for foobar following the pattern of the other filters edit libavfilter allfilters and add an entry for foobar following the pattern of the other filters configure make j< whatever > ffmpeg ffmpeg i you should get a foobar png with Lena edge detected That s your new playground is ready Some little details about what s going on
Definition: writing_filters.txt:34
term_exit
void term_exit(void)
Definition: ffmpeg.c:171
key
const char * key
Definition: hwcontext_opencl.c:174
av_usleep
int av_usleep(unsigned usec)
Sleep for a period of time.
Definition: time.c:84
atomic_load
#define atomic_load(object)
Definition: stdatomic.h:93
AVSubtitleRect::text
char * text
0 terminated plain UTF-8 text
Definition: avcodec.h:2257
process_input_packet
static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
Definition: ffmpeg.c:803
process_input
static int process_input(int file_index)
Definition: ffmpeg.c:1058
transcode
static int transcode(int *err_rate_exceeded)
Definition: ffmpeg.c:1166
frame
static AVFrame * frame
Definition: demux_decode.c:54
arg
const char * arg
Definition: jacosubdec.c:67
of_enc_stats_close
void of_enc_stats_close(void)
Definition: ffmpeg_mux_init.c:235
avio_flush
void avio_flush(AVIOContext *s)
Force flushing of buffered data.
Definition: aviobuf.c:270
av_log_get_level
int av_log_get_level(void)
Get the current log level.
Definition: log.c:437
init_dynload
void init_dynload(void)
Initialize dynamic library loading.
Definition: cmdutils.c:77
opts
AVDictionary * opts
Definition: movenc.c:50
AVSubtitleRect::w
int w
width of pict, undefined when pict is not set
Definition: avcodec.h:2244
NULL
#define NULL
Definition: coverity.c:32
main
int main(int argc, char **argv)
Definition: ffmpeg.c:1292
AVRational
Rational number (pair of numerator and denominator).
Definition: rational.h:58
getmaxrss
static int64_t getmaxrss(void)
Definition: ffmpeg.c:1274
AVPALETTE_SIZE
#define AVPALETTE_SIZE
Definition: pixfmt.h:32
check_keyboard_interaction
static int check_keyboard_interaction(int64_t cur_time)
Definition: ffmpeg.c:971
DemuxPktData::dts_est
int64_t dts_est
Definition: ffmpeg.h:107
av_log_set_flags
void av_log_set_flags(int arg)
Definition: log.c:447
AVSubtitleRect::data
uint8_t * data[4]
data+linesize for the bitmap of this subtitle.
Definition: avcodec.h:2252
transcode_step
static int transcode_step(OutputStream *ost)
Run a single step of transcoding.
Definition: ffmpeg.c:1127
parseutils.h
print_stream_maps
static void print_stream_maps(void)
Definition: ffmpeg.c:846
vstats_file
FILE * vstats_file
Definition: ffmpeg.c:107
ifile_get_packet
int ifile_get_packet(InputFile *f, AVPacket **pkt)
Get next input packet from the demuxer.
Definition: ffmpeg_demux.c:723
ost_iter
OutputStream * ost_iter(OutputStream *prev)
Definition: ffmpeg.c:397
double
double
Definition: af_crystalizer.c:131
time.h
sub2video_heartbeat
static void sub2video_heartbeat(InputFile *infile, int64_t pts, AVRational tb)
Definition: ffmpeg.c:144
received_nb_signals
static volatile int received_nb_signals
Definition: ffmpeg.c:178
do_benchmark_all
int do_benchmark_all
Definition: ffmpeg_opt.c:75
swresample.h
c
Undefined Behavior In the C some operations are like signed integer dereferencing freed accessing outside allocated Undefined Behavior must not occur in a C it is not safe even if the output of undefined operations is unused The unsafety may seem nit picking but Optimizing compilers have in fact optimized code on the assumption that no undefined Behavior occurs Optimizing code based on wrong assumptions can and has in some cases lead to effects beyond the output of computations The signed integer overflow problem in speed critical code Code which is highly optimized and works with signed integers sometimes has the problem that often the output of the computation does not c
Definition: undefined.txt:32
av_buffer_create
AVBufferRef * av_buffer_create(uint8_t *data, size_t size, void(*free)(void *opaque, uint8_t *data), void *opaque, int flags)
Create an AVBuffer from an existing array.
Definition: buffer.c:55
input_files
InputFile ** input_files
Definition: ffmpeg.c:123
OutputFile::streams
OutputStream ** streams
Definition: ffmpeg.h:623
InputStream::frames_decoded
uint64_t frames_decoded
Definition: ffmpeg.h:389
FilterGraph
Definition: ffmpeg.h:310
subtitle_free
static void subtitle_free(void *opaque, uint8_t *data)
Definition: ffmpeg.c:731
print_stats
int print_stats
Definition: ffmpeg_opt.c:84
decode_interrupt_cb
static int decode_interrupt_cb(void *ctx)
Definition: ffmpeg.c:341
options
const OptionDef options[]
f
f
Definition: af_crystalizer.c:121
AVIOContext
Bytestream IO Context.
Definition: avio.h:166
copy
static void copy(const float *p1, float *p2, const int length)
Definition: vf_vaguedenoiser.c:185
av_bprint_finalize
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition: bprint.c:240
threadmessage.h
InputStream::file_index
int file_index
Definition: ffmpeg.h:327
output_files
OutputFile ** output_files
Definition: ffmpeg.c:126
SIGNAL
#define SIGNAL(sig, func)
Definition: ffmpeg.c:237
FrameData::dec
struct FrameData::@3 dec
av_err2str
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: error.h:121
copy_av_subtitle
int copy_av_subtitle(AVSubtitle *dst, const AVSubtitle *src)
Definition: ffmpeg.c:651
received_sigterm
static volatile int received_sigterm
Definition: ffmpeg.c:177
start_time
static int64_t start_time
Definition: ffplay.c:328
filtergraph_is_simple
int filtergraph_is_simple(const FilterGraph *fg)
Definition: ffmpeg_filter.c:1812
sq_send
int sq_send(SyncQueue *sq, unsigned int stream_idx, SyncQueueFrame frame)
Submit a frame for the stream with index stream_idx.
Definition: sync_queue.c:343
uninit_opts
void uninit_opts(void)
Uninitialize the cmdutils option system, in particular free the *_opts contexts and their contents.
Definition: cmdutils.c:64
copy_ts
int copy_ts
Definition: ffmpeg_opt.c:78
AV_NOPTS_VALUE
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
check_avoptions
int check_avoptions(AVDictionary *m)
Definition: ffmpeg.c:455
frame_data
FrameData * frame_data(AVFrame *frame)
Get our axiliary frame data attached to the frame, allocating it if needed.
Definition: ffmpeg.c:429
avdevice.h
AVSubtitleRect::type
enum AVSubtitleType type
Definition: avcodec.h:2255
show_banner
void show_banner(int argc, char **argv, const OptionDef *options)
Print the program banner to stderr.
Definition: opt_common.c:237
fix_sub_duration_heartbeat
int fix_sub_duration_heartbeat(InputStream *ist, int64_t signal_pts)
Definition: ffmpeg_dec.c:454
avio_write
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition: aviobuf.c:248
a
The reader does not expect b to be semantically here and if the code is changed by maybe adding a a division or other the signedness will almost certainly be mistaken To avoid this confusion a new type was SUINT is the C unsigned type but it holds a signed int to use the same example SUINT a
Definition: undefined.txt:41
FrameData::pts
int64_t pts
Definition: ffmpeg.h:641
AVPacket::flags
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:497
do_benchmark
int do_benchmark
Definition: ffmpeg_opt.c:74
OutputFile::sq_encode
SyncQueue * sq_encode
Definition: ffmpeg.h:626
SUBTITLE_BITMAP
@ SUBTITLE_BITMAP
A bitmap, pict will be set.
Definition: avcodec.h:2224
AV_LOG_INFO
#define AV_LOG_INFO
Standard information.
Definition: log.h:191
AVCodec::id
enum AVCodecID id
Definition: codec.h:201
AVSubtitleRect::flags
int flags
Definition: avcodec.h:2266
avio_closep
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:1304
of_output_packet
int of_output_packet(OutputFile *of, OutputStream *ost, AVPacket *pkt)
Definition: ffmpeg_mux.c:349
av_log_set_level
void av_log_set_level(int level)
Set the log level.
Definition: log.c:442
bprint.h
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:255
AVPacket::pts
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:484
AVSubtitleRect::nb_colors
int nb_colors
number of colors in pict, undefined when pict is not set
Definition: avcodec.h:2246
AV_TIME_BASE
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:254
display.h
vsnprintf
#define vsnprintf
Definition: snprintf.h:36
exit_on_error
int exit_on_error
Definition: ffmpeg_opt.c:82
sigterm_handler
static void sigterm_handler(int sig)
Definition: ffmpeg.c:184
FFMIN
#define FFMIN(a, b)
Definition: macros.h:49
tb
#define tb
Definition: regdef.h:68
av_mallocz
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:254
AVCodec::name
const char * name
Name of the codec implementation.
Definition: codec.h:194
filtergraphs
FilterGraph ** filtergraphs
Definition: ffmpeg.c:129
int_cb
const AVIOInterruptCB int_cb
Definition: ffmpeg.c:346
av_calloc
void * av_calloc(size_t nmemb, size_t size)
Definition: mem.c:262
nb_output_files
int nb_output_files
Definition: ffmpeg.c:127
parse_loglevel
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:474
av_buffer_allocz
AVBufferRef * av_buffer_allocz(size_t size)
Same as av_buffer_alloc(), except the returned buffer will be initialized to zero.
Definition: buffer.c:93
ret
ret
Definition: filter_design.txt:187
AV_LOG_FATAL
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition: log.h:174
AVSubtitleRect::h
int h
height of pict, undefined when pict is not set
Definition: avcodec.h:2245
dec_packet
int dec_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
Submit a packet for decoding.
Definition: ffmpeg_dec.c:772
InputFile::streams
InputStream ** streams
Definition: ffmpeg.h:423
hw_device_free_all
void hw_device_free_all(void)
Definition: ffmpeg_hw.c:288
avformat.h
InputFile::eagain
int eagain
Definition: ffmpeg.h:409
av_bprintf
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition: bprint.c:99
dict.h
AV_LOG_SKIP_REPEATED
#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:370
AV_DICT_MATCH_CASE
#define AV_DICT_MATCH_CASE
Only get an entry with exact-case key match.
Definition: dict.h:74
ifile_close
void ifile_close(InputFile **f)
Definition: ffmpeg_demux.c:807
avformat_network_deinit
int avformat_network_deinit(void)
Undo the initialization done by avformat_network_init.
Definition: utils.c:570
AVStream::index
int index
stream index in AVFormatContext
Definition: avformat.h:847
transcode_init_done
static atomic_int transcode_init_done
Definition: ffmpeg.c:179
BenchmarkTimeStamps
Definition: ffmpeg.c:109
channel_layout.h
program_name
const char program_name[]
program name, defined by the program for show_version().
Definition: ffmpeg.c:104
AVPacket::stream_index
int stream_index
Definition: packet.h:493
InputStream::decode_errors
uint64_t decode_errors
Definition: ffmpeg.h:391
InputStream::discard
int discard
Definition: ffmpeg.h:331
print_report
static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
Definition: ffmpeg.c:496
AVCodecContext::codec_type
enum AVMediaType codec_type
Definition: avcodec.h:449
av_strdup
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:270
desc
const char * desc
Definition: libsvtav1.c:83
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
start_at_zero
int start_at_zero
Definition: ffmpeg_opt.c:79
AVBufferRef
A reference to a data buffer.
Definition: buffer.h:82
OutputStream::file_index
int file_index
Definition: ffmpeg.h:519
InputStream::index
int index
Definition: ffmpeg.h:328
av_free
#define av_free(p)
Definition: tableprint_vlc.h:33
AVDictionaryEntry
Definition: dict.h:89
stdin_interaction
int stdin_interaction
Definition: ffmpeg_opt.c:85
AVPacket
This structure stores compressed data.
Definition: packet.h:468
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:34
av_dict_set
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:88
src
INIT_CLIP pixel * src
Definition: h264pred_template.c:418
cmdutils.h
nb_filtergraphs
int nb_filtergraphs
Definition: ffmpeg.c:130
imgutils.h
timestamp.h
OutputStream
Definition: mux.c:53
hwcontext.h
AVERROR_BUG
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition: error.h:52
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
FFABS64U
#define FFABS64U(a)
Definition: common.h:83
AVERROR_EXIT
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition: error.h:58
err_merge
static int err_merge(int err0, int err1)
Merge two return codes - return one of the error codes if at least one of them was negative,...
Definition: ffmpeg.h:889
avcodec_descriptor_get
const AVCodecDescriptor * avcodec_descriptor_get(enum AVCodecID id)
Definition: codec_desc.c:3722
set_tty_echo
static void set_tty_echo(int on)
Definition: ffmpeg.c:959
avstring.h
FF_QP2LAMBDA
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition: avutil.h:227
InputFile::nb_streams
int nb_streams
Definition: ffmpeg.h:424
read_key
static int read_key(void)
Definition: ffmpeg.c:290
of_write_trailer
int of_write_trailer(OutputFile *of)
Definition: ffmpeg_mux.c:799
choose_output
static int choose_output(OutputStream **post)
Select the output stream to process.
Definition: ffmpeg.c:929
av_dict_iterate
const AVDictionaryEntry * av_dict_iterate(const AVDictionary *m, const AVDictionaryEntry *prev)
Iterate over a dictionary.
Definition: dict.c:44
read
static uint32_t BS_FUNC() read(BSCTX *bc, unsigned int n)
Return n bits from the buffer, n has to be in the 0-32 range.
Definition: bitstream_template.h:231
AVPacket::time_base
AVRational time_base
Time base of the packet's timestamps.
Definition: packet.h:535
OutputFile
Definition: ffmpeg.h:615
avdevice_register_all
void avdevice_register_all(void)
Initialize libavdevice and register all the input and output devices.
Definition: alldevices.c:65