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
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) {
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->nb_frames_dup;
554  nb_frames_drop = ost->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  if (is_last_report)
571  nb_frames_drop += ost->last_dropped;
572  }
573 
575  secs = FFABS64U(pts) / AV_TIME_BASE % 60;
576  mins = FFABS64U(pts) / AV_TIME_BASE / 60 % 60;
577  hours = FFABS64U(pts) / AV_TIME_BASE / 3600;
578  hours_sign = (pts < 0) ? "-" : "";
579 
580  bitrate = pts != AV_NOPTS_VALUE && pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
581  speed = pts != AV_NOPTS_VALUE && t != 0.0 ? (double)pts / AV_TIME_BASE / t : -1;
582 
583  if (total_size < 0) av_bprintf(&buf, "size=N/A time=");
584  else av_bprintf(&buf, "size=%8.0fkB time=", total_size / 1024.0);
585  if (pts == AV_NOPTS_VALUE) {
586  av_bprintf(&buf, "N/A ");
587  } else {
588  av_bprintf(&buf, "%s%02"PRId64":%02d:%02d.%02d ",
589  hours_sign, hours, mins, secs, (100 * us) / AV_TIME_BASE);
590  }
591 
592  if (bitrate < 0) {
593  av_bprintf(&buf, "bitrate=N/A");
594  av_bprintf(&buf_script, "bitrate=N/A\n");
595  }else{
596  av_bprintf(&buf, "bitrate=%6.1fkbits/s", bitrate);
597  av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
598  }
599 
600  if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
601  else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
602  if (pts == AV_NOPTS_VALUE) {
603  av_bprintf(&buf_script, "out_time_us=N/A\n");
604  av_bprintf(&buf_script, "out_time_ms=N/A\n");
605  av_bprintf(&buf_script, "out_time=N/A\n");
606  } else {
607  av_bprintf(&buf_script, "out_time_us=%"PRId64"\n", pts);
608  av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
609  av_bprintf(&buf_script, "out_time=%s%02"PRId64":%02d:%02d.%06d\n",
610  hours_sign, hours, mins, secs, us);
611  }
612 
613  if (nb_frames_dup || nb_frames_drop)
614  av_bprintf(&buf, " dup=%"PRId64" drop=%"PRId64, nb_frames_dup, nb_frames_drop);
615  av_bprintf(&buf_script, "dup_frames=%"PRId64"\n", nb_frames_dup);
616  av_bprintf(&buf_script, "drop_frames=%"PRId64"\n", nb_frames_drop);
617 
618  if (speed < 0) {
619  av_bprintf(&buf, " speed=N/A");
620  av_bprintf(&buf_script, "speed=N/A\n");
621  } else {
622  av_bprintf(&buf, " speed=%4.3gx", speed);
623  av_bprintf(&buf_script, "speed=%4.3gx\n", speed);
624  }
625 
626  if (print_stats || is_last_report) {
627  const char end = is_last_report ? '\n' : '\r';
628  if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
629  fprintf(stderr, "%s %c", buf.str, end);
630  } else
631  av_log(NULL, AV_LOG_INFO, "%s %c", buf.str, end);
632 
633  fflush(stderr);
634  }
635  av_bprint_finalize(&buf, NULL);
636 
637  if (progress_avio) {
638  av_bprintf(&buf_script, "progress=%s\n",
639  is_last_report ? "end" : "continue");
640  avio_write(progress_avio, buf_script.str,
641  FFMIN(buf_script.len, buf_script.size - 1));
643  av_bprint_finalize(&buf_script, NULL);
644  if (is_last_report) {
645  if ((ret = avio_closep(&progress_avio)) < 0)
647  "Error closing progress log, loss of information possible: %s\n", av_err2str(ret));
648  }
649  }
650 
651  first_report = 0;
652 }
653 
655 {
656  int ret = AVERROR_BUG;
657  AVSubtitle tmp = {
658  .format = src->format,
659  .start_display_time = src->start_display_time,
660  .end_display_time = src->end_display_time,
661  .num_rects = 0,
662  .rects = NULL,
663  .pts = src->pts
664  };
665 
666  if (!src->num_rects)
667  goto success;
668 
669  if (!(tmp.rects = av_calloc(src->num_rects, sizeof(*tmp.rects))))
670  return AVERROR(ENOMEM);
671 
672  for (int i = 0; i < src->num_rects; i++) {
673  AVSubtitleRect *src_rect = src->rects[i];
674  AVSubtitleRect *dst_rect;
675 
676  if (!(dst_rect = tmp.rects[i] = av_mallocz(sizeof(*tmp.rects[0])))) {
677  ret = AVERROR(ENOMEM);
678  goto cleanup;
679  }
680 
681  tmp.num_rects++;
682 
683  dst_rect->type = src_rect->type;
684  dst_rect->flags = src_rect->flags;
685 
686  dst_rect->x = src_rect->x;
687  dst_rect->y = src_rect->y;
688  dst_rect->w = src_rect->w;
689  dst_rect->h = src_rect->h;
690  dst_rect->nb_colors = src_rect->nb_colors;
691 
692  if (src_rect->text)
693  if (!(dst_rect->text = av_strdup(src_rect->text))) {
694  ret = AVERROR(ENOMEM);
695  goto cleanup;
696  }
697 
698  if (src_rect->ass)
699  if (!(dst_rect->ass = av_strdup(src_rect->ass))) {
700  ret = AVERROR(ENOMEM);
701  goto cleanup;
702  }
703 
704  for (int j = 0; j < 4; j++) {
705  // SUBTITLE_BITMAP images are special in the sense that they
706  // are like PAL8 images. first pointer to data, second to
707  // palette. This makes the size calculation match this.
708  size_t buf_size = src_rect->type == SUBTITLE_BITMAP && j == 1 ?
710  src_rect->h * src_rect->linesize[j];
711 
712  if (!src_rect->data[j])
713  continue;
714 
715  if (!(dst_rect->data[j] = av_memdup(src_rect->data[j], buf_size))) {
716  ret = AVERROR(ENOMEM);
717  goto cleanup;
718  }
719  dst_rect->linesize[j] = src_rect->linesize[j];
720  }
721  }
722 
723 success:
724  *dst = tmp;
725 
726  return 0;
727 
728 cleanup:
730 
731  return ret;
732 }
733 
734 static void subtitle_free(void *opaque, uint8_t *data)
735 {
736  AVSubtitle *sub = (AVSubtitle*)data;
737  avsubtitle_free(sub);
738  av_free(sub);
739 }
740 
742 {
743  AVBufferRef *buf;
744  AVSubtitle *sub;
745  int ret;
746 
747  if (copy) {
748  sub = av_mallocz(sizeof(*sub));
749  ret = sub ? copy_av_subtitle(sub, subtitle) : AVERROR(ENOMEM);
750  if (ret < 0) {
751  av_freep(&sub);
752  return ret;
753  }
754  } else {
755  sub = av_memdup(subtitle, sizeof(*subtitle));
756  if (!sub)
757  return AVERROR(ENOMEM);
758  memset(subtitle, 0, sizeof(*subtitle));
759  }
760 
761  buf = av_buffer_create((uint8_t*)sub, sizeof(*sub),
762  subtitle_free, NULL, 0);
763  if (!buf) {
764  avsubtitle_free(sub);
765  av_freep(&sub);
766  return AVERROR(ENOMEM);
767  }
768 
769  frame->buf[0] = buf;
770 
771  return 0;
772 }
773 
775 {
776  OutputFile *of = output_files[ost->file_index];
777  int64_t signal_pts = av_rescale_q(pkt->pts, pkt->time_base,
779 
780  if (!ost->fix_sub_duration_heartbeat || !(pkt->flags & AV_PKT_FLAG_KEY))
781  // we are only interested in heartbeats on streams configured, and
782  // only on random access points.
783  return 0;
784 
785  for (int i = 0; i < of->nb_streams; i++) {
786  OutputStream *iter_ost = of->streams[i];
787  InputStream *ist = iter_ost->ist;
788  int ret = AVERROR_BUG;
789 
790  if (iter_ost == ost || !ist || !ist->decoding_needed ||
792  // We wish to skip the stream that causes the heartbeat,
793  // output streams without an input stream, streams not decoded
794  // (as fix_sub_duration is only done for decoded subtitles) as
795  // well as non-subtitle streams.
796  continue;
797 
798  if ((ret = fix_sub_duration_heartbeat(ist, signal_pts)) < 0)
799  return ret;
800  }
801 
802  return 0;
803 }
804 
805 /* pkt = NULL means EOF (needed to flush decoder buffers) */
806 static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
807 {
809  int64_t dts_est = AV_NOPTS_VALUE;
810  int ret = 0;
811  int eof_reached = 0;
812 
813  if (ist->decoding_needed) {
814  ret = dec_packet(ist, pkt, no_eof);
815  if (ret < 0 && ret != AVERROR_EOF)
816  return ret;
817  }
818  if (ret == AVERROR_EOF || (!pkt && !ist->decoding_needed))
819  eof_reached = 1;
820 
821  if (pkt && pkt->opaque_ref) {
823  dts_est = pd->dts_est;
824  }
825 
826  if (f->recording_time != INT64_MAX) {
827  int64_t start_time = 0;
828  if (copy_ts) {
829  start_time += f->start_time != AV_NOPTS_VALUE ? f->start_time : 0;
830  start_time += start_at_zero ? 0 : f->start_time_effective;
831  }
832  if (dts_est >= f->recording_time + start_time)
833  pkt = NULL;
834  }
835 
836  for (int oidx = 0; oidx < ist->nb_outputs; oidx++) {
837  OutputStream *ost = ist->outputs[oidx];
838  if (ost->enc || (!pkt && no_eof))
839  continue;
840 
841  ret = of_streamcopy(ost, pkt, dts_est);
842  if (ret < 0)
843  return ret;
844  }
845 
846  return !eof_reached;
847 }
848 
849 static void print_stream_maps(void)
850 {
851  av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
852  for (InputStream *ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
853  for (int j = 0; j < ist->nb_filters; j++) {
854  if (!filtergraph_is_simple(ist->filters[j]->graph)) {
855  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
856  ist->file_index, ist->index, ist->dec ? ist->dec->name : "?",
857  ist->filters[j]->name);
858  if (nb_filtergraphs > 1)
859  av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
860  av_log(NULL, AV_LOG_INFO, "\n");
861  }
862  }
863  }
864 
865  for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
866  if (ost->attachment_filename) {
867  /* an attached file */
868  av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
869  ost->attachment_filename, ost->file_index, ost->index);
870  continue;
871  }
872 
873  if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
874  /* output from a complex graph */
875  av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
876  if (nb_filtergraphs > 1)
877  av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
878 
879  av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
880  ost->index, ost->enc_ctx->codec->name);
881  continue;
882  }
883 
884  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
885  ost->ist->file_index,
886  ost->ist->index,
887  ost->file_index,
888  ost->index);
889  if (ost->enc_ctx) {
890  const AVCodec *in_codec = ost->ist->dec;
891  const AVCodec *out_codec = ost->enc_ctx->codec;
892  const char *decoder_name = "?";
893  const char *in_codec_name = "?";
894  const char *encoder_name = "?";
895  const char *out_codec_name = "?";
896  const AVCodecDescriptor *desc;
897 
898  if (in_codec) {
899  decoder_name = in_codec->name;
900  desc = avcodec_descriptor_get(in_codec->id);
901  if (desc)
902  in_codec_name = desc->name;
903  if (!strcmp(decoder_name, in_codec_name))
904  decoder_name = "native";
905  }
906 
907  if (out_codec) {
908  encoder_name = out_codec->name;
909  desc = avcodec_descriptor_get(out_codec->id);
910  if (desc)
911  out_codec_name = desc->name;
912  if (!strcmp(encoder_name, out_codec_name))
913  encoder_name = "native";
914  }
915 
916  av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
917  in_codec_name, decoder_name,
918  out_codec_name, encoder_name);
919  } else
920  av_log(NULL, AV_LOG_INFO, " (copy)");
921  av_log(NULL, AV_LOG_INFO, "\n");
922  }
923 }
924 
925 /**
926  * Select the output stream to process.
927  *
928  * @retval 0 an output stream was selected
929  * @retval AVERROR(EAGAIN) need to wait until more input is available
930  * @retval AVERROR_EOF no more streams need output
931  */
932 static int choose_output(OutputStream **post)
933 {
934  int64_t opts_min = INT64_MAX;
935  OutputStream *ost_min = NULL;
936 
937  for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost)) {
938  int64_t opts;
939 
940  if (ost->filter && ost->filter->last_pts != AV_NOPTS_VALUE) {
941  opts = ost->filter->last_pts;
942  } else {
943  opts = ost->last_mux_dts == AV_NOPTS_VALUE ?
944  INT64_MIN : ost->last_mux_dts;
945  }
946 
947  if (!ost->initialized && !ost->inputs_done && !ost->finished) {
948  ost_min = ost;
949  break;
950  }
951  if (!ost->finished && opts < opts_min) {
952  opts_min = opts;
953  ost_min = ost;
954  }
955  }
956  if (!ost_min)
957  return AVERROR_EOF;
958  *post = ost_min;
959  return ost_min->unavailable ? AVERROR(EAGAIN) : 0;
960 }
961 
962 static void set_tty_echo(int on)
963 {
964 #if HAVE_TERMIOS_H
965  struct termios tty;
966  if (tcgetattr(0, &tty) == 0) {
967  if (on) tty.c_lflag |= ECHO;
968  else tty.c_lflag &= ~ECHO;
969  tcsetattr(0, TCSANOW, &tty);
970  }
971 #endif
972 }
973 
974 static int check_keyboard_interaction(int64_t cur_time)
975 {
976  int i, key;
977  static int64_t last_time;
979  return AVERROR_EXIT;
980  /* read_key() returns 0 on EOF */
981  if (cur_time - last_time >= 100000) {
982  key = read_key();
983  last_time = cur_time;
984  }else
985  key = -1;
986  if (key == 'q') {
987  av_log(NULL, AV_LOG_INFO, "\n\n[q] command received. Exiting.\n\n");
988  return AVERROR_EXIT;
989  }
990  if (key == '+') av_log_set_level(av_log_get_level()+10);
991  if (key == '-') av_log_set_level(av_log_get_level()-10);
992  if (key == 'c' || key == 'C'){
993  char buf[4096], target[64], command[256], arg[256] = {0};
994  double time;
995  int k, n = 0;
996  fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
997  i = 0;
998  set_tty_echo(1);
999  while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
1000  if (k > 0)
1001  buf[i++] = k;
1002  buf[i] = 0;
1003  set_tty_echo(0);
1004  fprintf(stderr, "\n");
1005  if (k > 0 &&
1006  (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
1007  av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
1008  target, time, command, arg);
1009  for (i = 0; i < nb_filtergraphs; i++)
1010  fg_send_command(filtergraphs[i], time, target, command, arg,
1011  key == 'C');
1012  } else {
1014  "Parse error, at least 3 arguments were expected, "
1015  "only %d given in string '%s'\n", n, buf);
1016  }
1017  }
1018  if (key == '?'){
1019  fprintf(stderr, "key function\n"
1020  "? show this help\n"
1021  "+ increase verbosity\n"
1022  "- decrease verbosity\n"
1023  "c Send command to first matching filter supporting it\n"
1024  "C Send/Queue command to all matching filters\n"
1025  "h dump packets/hex press to cycle through the 3 states\n"
1026  "q quit\n"
1027  "s Show QP histogram\n"
1028  );
1029  }
1030  return 0;
1031 }
1032 
1033 static void reset_eagain(void)
1034 {
1035  int i;
1036  for (i = 0; i < nb_input_files; i++)
1037  input_files[i]->eagain = 0;
1038  for (OutputStream *ost = ost_iter(NULL); ost; ost = ost_iter(ost))
1039  ost->unavailable = 0;
1040 }
1041 
1042 static void decode_flush(InputFile *ifile)
1043 {
1044  for (int i = 0; i < ifile->nb_streams; i++) {
1045  InputStream *ist = ifile->streams[i];
1046 
1047  if (ist->discard || !ist->decoding_needed)
1048  continue;
1049 
1050  dec_packet(ist, NULL, 1);
1051  }
1052 }
1053 
1054 /*
1055  * Return
1056  * - 0 -- one packet was read and processed
1057  * - AVERROR(EAGAIN) -- no packets were available for selected file,
1058  * this function should be called again
1059  * - AVERROR_EOF -- this function should not be called again
1060  */
1061 static int process_input(int file_index)
1062 {
1063  InputFile *ifile = input_files[file_index];
1064  InputStream *ist;
1065  AVPacket *pkt;
1066  int ret, i;
1067 
1068  ret = ifile_get_packet(ifile, &pkt);
1069 
1070  if (ret == AVERROR(EAGAIN)) {
1071  ifile->eagain = 1;
1072  return ret;
1073  }
1074  if (ret == 1) {
1075  /* the input file is looped: flush the decoders */
1076  decode_flush(ifile);
1077  return AVERROR(EAGAIN);
1078  }
1079  if (ret < 0) {
1080  if (ret != AVERROR_EOF) {
1081  av_log(ifile, AV_LOG_ERROR,
1082  "Error retrieving a packet from demuxer: %s\n", av_err2str(ret));
1083  if (exit_on_error)
1084  return ret;
1085  }
1086 
1087  for (i = 0; i < ifile->nb_streams; i++) {
1088  ist = ifile->streams[i];
1089  if (!ist->discard) {
1090  ret = process_input_packet(ist, NULL, 0);
1091  if (ret>0)
1092  return 0;
1093  else if (ret < 0)
1094  return ret;
1095  }
1096 
1097  /* mark all outputs that don't go through lavfi as finished */
1098  for (int oidx = 0; oidx < ist->nb_outputs; oidx++) {
1099  OutputStream *ost = ist->outputs[oidx];
1100  OutputFile *of = output_files[ost->file_index];
1101 
1102  ret = of_output_packet(of, ost, NULL);
1103  if (ret < 0)
1104  return ret;
1105  }
1106  }
1107 
1108  ifile->eof_reached = 1;
1109  return AVERROR(EAGAIN);
1110  }
1111 
1112  reset_eagain();
1113 
1114  ist = ifile->streams[pkt->stream_index];
1115 
1117 
1118  ret = process_input_packet(ist, pkt, 0);
1119 
1120  av_packet_free(&pkt);
1121 
1122  return ret < 0 ? ret : 0;
1123 }
1124 
1125 /**
1126  * Run a single step of transcoding.
1127  *
1128  * @return 0 for success, <0 for error
1129  */
1131 {
1132  InputStream *ist = NULL;
1133  int ret;
1134 
1135  if (ost->filter) {
1136  if ((ret = fg_transcode_step(ost->filter->graph, &ist)) < 0)
1137  return ret;
1138  if (!ist)
1139  return 0;
1140  } else {
1141  ist = ost->ist;
1142  av_assert0(ist);
1143  }
1144 
1145  ret = process_input(ist->file_index);
1146  if (ret == AVERROR(EAGAIN)) {
1147  if (input_files[ist->file_index]->eagain)
1148  ost->unavailable = 1;
1149  return 0;
1150  }
1151 
1152  if (ret < 0)
1153  return ret == AVERROR_EOF ? 0 : ret;
1154 
1155  // process_input() above might have caused output to become available
1156  // in multiple filtergraphs, so we process all of them
1157  for (int i = 0; i < nb_filtergraphs; i++) {
1158  ret = reap_filters(filtergraphs[i], 0);
1159  if (ret < 0)
1160  return ret;
1161  }
1162 
1163  return 0;
1164 }
1165 
1166 /*
1167  * The following code is the main loop of the file converter
1168  */
1169 static int transcode(int *err_rate_exceeded)
1170 {
1171  int ret = 0, i;
1172  InputStream *ist;
1173  int64_t timer_start;
1174 
1176 
1177  *err_rate_exceeded = 0;
1179 
1180  if (stdin_interaction) {
1181  av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
1182  }
1183 
1184  timer_start = av_gettime_relative();
1185 
1186  while (!received_sigterm) {
1187  OutputStream *ost;
1188  int64_t cur_time= av_gettime_relative();
1189 
1190  /* if 'q' pressed, exits */
1191  if (stdin_interaction)
1192  if (check_keyboard_interaction(cur_time) < 0)
1193  break;
1194 
1195  ret = choose_output(&ost);
1196  if (ret == AVERROR(EAGAIN)) {
1197  reset_eagain();
1198  av_usleep(10000);
1199  ret = 0;
1200  continue;
1201  } else if (ret < 0) {
1202  av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
1203  ret = 0;
1204  break;
1205  }
1206 
1207  ret = transcode_step(ost);
1208  if (ret < 0 && ret != AVERROR_EOF) {
1209  av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", av_err2str(ret));
1210  break;
1211  }
1212 
1213  /* dump report by using the output first video and audio streams */
1214  print_report(0, timer_start, cur_time);
1215  }
1216 
1217  /* at the end of stream, we must flush the decoder buffers */
1218  for (ist = ist_iter(NULL); ist; ist = ist_iter(ist)) {
1219  float err_rate;
1220 
1221  if (!input_files[ist->file_index]->eof_reached) {
1222  int err = process_input_packet(ist, NULL, 0);
1223  ret = err_merge(ret, err);
1224  }
1225 
1226  err_rate = (ist->frames_decoded || ist->decode_errors) ?
1227  ist->decode_errors / (ist->frames_decoded + ist->decode_errors) : 0.f;
1228  if (err_rate > max_error_rate) {
1229  av_log(ist, AV_LOG_FATAL, "Decode error rate %g exceeds maximum %g\n",
1230  err_rate, max_error_rate);
1231  *err_rate_exceeded = 1;
1232  } else if (err_rate)
1233  av_log(ist, AV_LOG_VERBOSE, "Decode error rate %g\n", err_rate);
1234  }
1235  ret = err_merge(ret, enc_flush());
1236 
1237  term_exit();
1238 
1239  /* write the trailer if needed */
1240  for (i = 0; i < nb_output_files; i++) {
1241  int err = of_write_trailer(output_files[i]);
1242  ret = err_merge(ret, err);
1243  }
1244 
1245  /* dump report by using the first video and audio streams */
1246  print_report(1, timer_start, av_gettime_relative());
1247 
1248  return ret;
1249 }
1250 
1252 {
1253  BenchmarkTimeStamps time_stamps = { av_gettime_relative() };
1254 #if HAVE_GETRUSAGE
1255  struct rusage rusage;
1256 
1257  getrusage(RUSAGE_SELF, &rusage);
1258  time_stamps.user_usec =
1259  (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
1260  time_stamps.sys_usec =
1261  (rusage.ru_stime.tv_sec * 1000000LL) + rusage.ru_stime.tv_usec;
1262 #elif HAVE_GETPROCESSTIMES
1263  HANDLE proc;
1264  FILETIME c, e, k, u;
1265  proc = GetCurrentProcess();
1266  GetProcessTimes(proc, &c, &e, &k, &u);
1267  time_stamps.user_usec =
1268  ((int64_t)u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
1269  time_stamps.sys_usec =
1270  ((int64_t)k.dwHighDateTime << 32 | k.dwLowDateTime) / 10;
1271 #else
1272  time_stamps.user_usec = time_stamps.sys_usec = 0;
1273 #endif
1274  return time_stamps;
1275 }
1276 
1277 static int64_t getmaxrss(void)
1278 {
1279 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
1280  struct rusage rusage;
1281  getrusage(RUSAGE_SELF, &rusage);
1282  return (int64_t)rusage.ru_maxrss * 1024;
1283 #elif HAVE_GETPROCESSMEMORYINFO
1284  HANDLE proc;
1285  PROCESS_MEMORY_COUNTERS memcounters;
1286  proc = GetCurrentProcess();
1287  memcounters.cb = sizeof(memcounters);
1288  GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
1289  return memcounters.PeakPagefileUsage;
1290 #else
1291  return 0;
1292 #endif
1293 }
1294 
1295 int main(int argc, char **argv)
1296 {
1297  int ret, err_rate_exceeded;
1299 
1300  init_dynload();
1301 
1302  setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
1303 
1305  parse_loglevel(argc, argv, options);
1306 
1307 #if CONFIG_AVDEVICE
1309 #endif
1311 
1312  show_banner(argc, argv, options);
1313 
1314  /* parse options and open all input/output files */
1315  ret = ffmpeg_parse_options(argc, argv);
1316  if (ret < 0)
1317  goto finish;
1318 
1319  if (nb_output_files <= 0 && nb_input_files == 0) {
1320  show_usage();
1321  av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
1322  ret = 1;
1323  goto finish;
1324  }
1325 
1326  if (nb_output_files <= 0) {
1327  av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
1328  ret = 1;
1329  goto finish;
1330  }
1331 
1333  ret = transcode(&err_rate_exceeded);
1334  if (ret >= 0 && do_benchmark) {
1335  int64_t utime, stime, rtime;
1337  utime = current_time.user_usec - ti.user_usec;
1338  stime = current_time.sys_usec - ti.sys_usec;
1339  rtime = current_time.real_usec - ti.real_usec;
1341  "bench: utime=%0.3fs stime=%0.3fs rtime=%0.3fs\n",
1342  utime / 1000000.0, stime / 1000000.0, rtime / 1000000.0);
1343  }
1344 
1345  ret = received_nb_signals ? 255 :
1346  err_rate_exceeded ? 69 : ret;
1347 
1348 finish:
1349  if (ret == AVERROR_EXIT)
1350  ret = 0;
1351 
1353  return ret;
1354 }
AVSubtitle
Definition: avcodec.h:2263
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:1033
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:1204
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:239
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:1834
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:744
remove_avoptions
void remove_avoptions(AVDictionary **a, AVDictionary *b)
Definition: ffmpeg.c:446
InputStream::outputs
struct OutputStream ** outputs
Definition: ffmpeg.h:372
InputStream::dec_ctx
AVCodecContext * dec_ctx
Definition: ffmpeg.h:340
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:2235
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:579
sync_queue.h
current_time
static BenchmarkTimeStamps current_time
Definition: ffmpeg.c:120
OutputStream::index
int index
Definition: ffmpeg.h:514
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:365
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:2247
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:329
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:429
OutputStream::ist
InputStream * ist
Definition: ffmpeg.h:525
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:373
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
InputFile::eof_reached
int eof_reached
Definition: ffmpeg.h:404
InputStream
Definition: ffmpeg.h:320
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:410
samplefmt.h
AVSubtitleRect::x
int x
top left corner of pict, undefined when pict is not set
Definition: avcodec.h:2236
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:103
pts
static int64_t pts
Definition: transcode_aac.c:643
us
#define us(width, name, range_min, range_max, subs,...)
Definition: cbs_h2645.c:251
trigger_fix_sub_duration_heartbeat
int trigger_fix_sub_duration_heartbeat(OutputStream *ost, const AVPacket *pkt)
Definition: ffmpeg.c:774
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:1744
avformat_network_init
int avformat_network_init(void)
Do global initialization of network libraries.
Definition: utils.c:558
InputFile
Definition: ffmpeg.h:395
AVSubtitleRect::ass
char * ass
0 terminated ASS/SSA compatible event line.
Definition: avcodec.h:2258
avsubtitle_free
void avsubtitle_free(AVSubtitle *sub)
Free all allocated data in the given subtitle struct.
Definition: avcodec.c:411
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:1042
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:2058
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:1251
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:1854
bitrate
int64_t bitrate
Definition: av1_levels.c:47
AVDictionaryEntry::key
char * key
Definition: dict.h:90
ENCODER_FINISHED
@ ENCODER_FINISHED
Definition: ffmpeg.h:481
AVSubtitleRect::y
int y
top left corner of pict, undefined when pict is not set
Definition: avcodec.h:2237
subtitle_wrap_frame
int subtitle_wrap_frame(AVFrame *frame, AVSubtitle *subtitle, int copy)
Definition: ffmpeg.c:741
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:364
limits.h
nb_streams
static int nb_streams
Definition: ffprobe.c:315
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:2251
process_input_packet
static int process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
Definition: ffmpeg.c:806
process_input
static int process_input(int file_index)
Definition: ffmpeg.c:1061
transcode
static int transcode(int *err_rate_exceeded)
Definition: ffmpeg.c:1169
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:2238
NULL
#define NULL
Definition: coverity.c:32
main
int main(int argc, char **argv)
Definition: ffmpeg.c:1295
AVRational
Rational number (pair of numerator and denominator).
Definition: rational.h:58
getmaxrss
static int64_t getmaxrss(void)
Definition: ffmpeg.c:1277
AVPALETTE_SIZE
#define AVPALETTE_SIZE
Definition: pixfmt.h:32
check_keyboard_interaction
static int check_keyboard_interaction(int64_t cur_time)
Definition: ffmpeg.c:974
DemuxPktData::dts_est
int64_t dts_est
Definition: ffmpeg.h:106
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:2246
transcode_step
static int transcode_step(OutputStream *ost)
Run a single step of transcoding.
Definition: ffmpeg.c:1130
parseutils.h
print_stream_maps
static void print_stream_maps(void)
Definition: ffmpeg.c:849
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:745
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:385
FilterGraph
Definition: ffmpeg.h:306
subtitle_free
static void subtitle_free(void *opaque, uint8_t *data)
Definition: ffmpeg.c:734
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:323
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:654
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:1738
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:2249
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:380
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:2218
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:2260
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:244
AVPacket::pts
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:367
AVSubtitleRect::nb_colors
int nb_colors
number of colors in pict, undefined when pict is not set
Definition: avcodec.h:2240
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:2239
frame
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return or at least make progress towards producing a frame
Definition: filter_design.txt:264
dec_packet
int dec_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
Submit a packet for decoding.
Definition: ffmpeg_dec.c:766
InputFile::streams
InputStream ** streams
Definition: ffmpeg.h:419
hw_device_free_all
void hw_device_free_all(void)
Definition: ffmpeg_hw.c:288
avformat.h
InputFile::eagain
int eagain
Definition: ffmpeg.h:405
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:829
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:845
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:376
InputStream::decode_errors
uint64_t decode_errors
Definition: ffmpeg.h:387
InputStream::discard
int discard
Definition: ffmpeg.h:327
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:445
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:513
InputStream::index
int index
Definition: ffmpeg.h:324
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:351
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:962
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:420
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:932
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:418
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