FFmpeg
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
ffmpeg.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2000-2003 Fabrice Bellard
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 /**
22  * @file
23  * multimedia converter based on the FFmpeg libraries
24  */
25 
26 #include "config.h"
27 #include <ctype.h>
28 #include <string.h>
29 #include <math.h>
30 #include <stdlib.h>
31 #include <errno.h>
32 #include <limits.h>
33 #if HAVE_ISATTY
34 #if HAVE_IO_H
35 #include <io.h>
36 #endif
37 #if HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #endif
41 #include "libavformat/avformat.h"
42 #include "libavdevice/avdevice.h"
43 #include "libswscale/swscale.h"
45 #include "libavutil/opt.h"
47 #include "libavutil/parseutils.h"
48 #include "libavutil/samplefmt.h"
49 #include "libavutil/colorspace.h"
50 #include "libavutil/fifo.h"
51 #include "libavutil/intreadwrite.h"
52 #include "libavutil/dict.h"
53 #include "libavutil/mathematics.h"
54 #include "libavutil/pixdesc.h"
55 #include "libavutil/avstring.h"
56 #include "libavutil/libm.h"
57 #include "libavutil/imgutils.h"
58 #include "libavutil/timestamp.h"
59 #include "libavutil/bprint.h"
60 #include "libavutil/time.h"
61 #include "libavformat/os_support.h"
62 
63 #include "libavformat/ffm.h" // not public API
64 
65 # include "libavfilter/avcodec.h"
66 # include "libavfilter/avfilter.h"
68 # include "libavfilter/buffersrc.h"
69 # include "libavfilter/buffersink.h"
70 
71 #if HAVE_SYS_RESOURCE_H
72 #include <sys/time.h>
73 #include <sys/types.h>
74 #include <sys/resource.h>
75 #elif HAVE_GETPROCESSTIMES
76 #include <windows.h>
77 #endif
78 #if HAVE_GETPROCESSMEMORYINFO
79 #include <windows.h>
80 #include <psapi.h>
81 #endif
82 
83 #if HAVE_SYS_SELECT_H
84 #include <sys/select.h>
85 #endif
86 
87 #if HAVE_TERMIOS_H
88 #include <fcntl.h>
89 #include <sys/ioctl.h>
90 #include <sys/time.h>
91 #include <termios.h>
92 #elif HAVE_KBHIT
93 #include <conio.h>
94 #endif
95 
96 #if HAVE_PTHREADS
97 #include <pthread.h>
98 #endif
99 
100 #include <time.h>
101 
102 #include "ffmpeg.h"
103 #include "cmdutils.h"
104 
105 #include "libavutil/avassert.h"
106 
107 const char program_name[] = "ffmpeg";
108 const int program_birth_year = 2000;
109 
110 static FILE *vstats_file;
111 
112 const char *const forced_keyframes_const_names[] = {
113  "n",
114  "n_forced",
115  "prev_forced_n",
116  "prev_forced_t",
117  "t",
118  NULL
119 };
120 
121 static void do_video_stats(OutputStream *ost, int frame_size);
122 static int64_t getutime(void);
123 static int64_t getmaxrss(void);
124 
125 static int run_as_daemon = 0;
126 static int64_t video_size = 0;
127 static int64_t audio_size = 0;
128 static int64_t subtitle_size = 0;
129 static int64_t extra_size = 0;
130 static int nb_frames_dup = 0;
131 static int nb_frames_drop = 0;
132 
133 static int current_time;
135 
137 
138 #if HAVE_PTHREADS
139 /* signal to input threads that they should exit; set by the main thread */
140 static int transcoding_finished;
141 #endif
142 
143 #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
144 
149 
154 
157 
158 #if HAVE_TERMIOS_H
159 
160 /* init terminal so that we can grab keys */
161 static struct termios oldtty;
162 static int restore_tty;
163 #endif
164 
165 static void free_input_threads(void);
166 
167 
168 /* sub2video hack:
169  Convert subtitles to video with alpha to insert them in filter graphs.
170  This is a temporary solution until libavfilter gets real subtitles support.
171  */
172 
173 
174 
175 static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
176  AVSubtitleRect *r)
177 {
178  uint32_t *pal, *dst2;
179  uint8_t *src, *src2;
180  int x, y;
181 
182  if (r->type != SUBTITLE_BITMAP) {
183  av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
184  return;
185  }
186  if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
187  av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");
188  return;
189  }
190 
191  dst += r->y * dst_linesize + r->x * 4;
192  src = r->pict.data[0];
193  pal = (uint32_t *)r->pict.data[1];
194  for (y = 0; y < r->h; y++) {
195  dst2 = (uint32_t *)dst;
196  src2 = src;
197  for (x = 0; x < r->w; x++)
198  *(dst2++) = pal[*(src2++)];
199  dst += dst_linesize;
200  src += r->pict.linesize[0];
201  }
202 }
203 
204 static void sub2video_push_ref(InputStream *ist, int64_t pts)
205 {
206  AVFilterBufferRef *ref = ist->sub2video.ref;
207  int i;
208 
209  ist->sub2video.last_pts = ref->pts = pts;
210  for (i = 0; i < ist->nb_filters; i++)
212  avfilter_ref_buffer(ref, ~0),
216 }
217 
218 static void sub2video_update(InputStream *ist, AVSubtitle *sub)
219 {
220  int w = ist->sub2video.w, h = ist->sub2video.h;
221  AVFilterBufferRef *ref = ist->sub2video.ref;
222  int8_t *dst;
223  int dst_linesize;
224  int num_rects, i;
225  int64_t pts, end_pts;
226 
227  if (!ref)
228  return;
229  if (sub) {
230  pts = av_rescale_q(sub->pts + sub->start_display_time * 1000,
231  AV_TIME_BASE_Q, ist->st->time_base);
232  end_pts = av_rescale_q(sub->pts + sub->end_display_time * 1000,
233  AV_TIME_BASE_Q, ist->st->time_base);
234  num_rects = sub->num_rects;
235  } else {
236  pts = ist->sub2video.end_pts;
237  end_pts = INT64_MAX;
238  num_rects = 0;
239  }
240  dst = ref->data [0];
241  dst_linesize = ref->linesize[0];
242  memset(dst, 0, h * dst_linesize);
243  for (i = 0; i < num_rects; i++)
244  sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);
245  sub2video_push_ref(ist, pts);
246  ist->sub2video.end_pts = end_pts;
247 }
248 
249 static void sub2video_heartbeat(InputStream *ist, int64_t pts)
250 {
251  InputFile *infile = input_files[ist->file_index];
252  int i, j, nb_reqs;
253  int64_t pts2;
254 
255  /* When a frame is read from a file, examine all sub2video streams in
256  the same file and send the sub2video frame again. Otherwise, decoded
257  video frames could be accumulating in the filter graph while a filter
258  (possibly overlay) is desperately waiting for a subtitle frame. */
259  for (i = 0; i < infile->nb_streams; i++) {
260  InputStream *ist2 = input_streams[infile->ist_index + i];
261  if (!ist2->sub2video.ref)
262  continue;
263  /* subtitles seem to be usually muxed ahead of other streams;
264  if not, substracting a larger time here is necessary */
265  pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
266  /* do not send the heartbeat frame if the subtitle is already ahead */
267  if (pts2 <= ist2->sub2video.last_pts)
268  continue;
269  if (pts2 >= ist2->sub2video.end_pts)
270  sub2video_update(ist2, NULL);
271  for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
272  nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
273  if (nb_reqs)
274  sub2video_push_ref(ist2, pts2);
275  }
276 }
277 
278 static void sub2video_flush(InputStream *ist)
279 {
280  int i;
281 
282  for (i = 0; i < ist->nb_filters; i++)
283  av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
284 }
285 
286 /* end of sub2video hack */
287 
288 void term_exit(void)
289 {
290  av_log(NULL, AV_LOG_QUIET, "%s", "");
291 #if HAVE_TERMIOS_H
292  if(restore_tty)
293  tcsetattr (0, TCSANOW, &oldtty);
294 #endif
295 }
296 
297 static volatile int received_sigterm = 0;
298 static volatile int received_nb_signals = 0;
299 
300 static void
302 {
303  received_sigterm = sig;
305  term_exit();
306  if(received_nb_signals > 3)
307  exit(123);
308 }
309 
310 void term_init(void)
311 {
312 #if HAVE_TERMIOS_H
313  if(!run_as_daemon){
314  struct termios tty;
315  int istty = 1;
316 #if HAVE_ISATTY
317  istty = isatty(0) && isatty(2);
318 #endif
319  if (istty && tcgetattr (0, &tty) == 0) {
320  oldtty = tty;
321  restore_tty = 1;
322  atexit(term_exit);
323 
324  tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
325  |INLCR|IGNCR|ICRNL|IXON);
326  tty.c_oflag |= OPOST;
327  tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
328  tty.c_cflag &= ~(CSIZE|PARENB);
329  tty.c_cflag |= CS8;
330  tty.c_cc[VMIN] = 1;
331  tty.c_cc[VTIME] = 0;
332 
333  tcsetattr (0, TCSANOW, &tty);
334  }
335  signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
336  }
337 #endif
339 
340  signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
341  signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
342 #ifdef SIGXCPU
343  signal(SIGXCPU, sigterm_handler);
344 #endif
345 }
346 
347 /* read a key without blocking */
348 static int read_key(void)
349 {
350  unsigned char ch;
351 #if HAVE_TERMIOS_H
352  int n = 1;
353  struct timeval tv;
354  fd_set rfds;
355 
356  FD_ZERO(&rfds);
357  FD_SET(0, &rfds);
358  tv.tv_sec = 0;
359  tv.tv_usec = 0;
360  n = select(1, &rfds, NULL, NULL, &tv);
361  if (n > 0) {
362  n = read(0, &ch, 1);
363  if (n == 1)
364  return ch;
365 
366  return n;
367  }
368 #elif HAVE_KBHIT
369 # if HAVE_PEEKNAMEDPIPE
370  static int is_pipe;
371  static HANDLE input_handle;
372  DWORD dw, nchars;
373  if(!input_handle){
374  input_handle = GetStdHandle(STD_INPUT_HANDLE);
375  is_pipe = !GetConsoleMode(input_handle, &dw);
376  }
377 
378  if (stdin->_cnt > 0) {
379  read(0, &ch, 1);
380  return ch;
381  }
382  if (is_pipe) {
383  /* When running under a GUI, you will end here. */
384  if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL)) {
385  // input pipe may have been closed by the program that ran ffmpeg
386  return -1;
387  }
388  //Read it
389  if(nchars != 0) {
390  read(0, &ch, 1);
391  return ch;
392  }else{
393  return -1;
394  }
395  }
396 # endif
397  if(kbhit())
398  return(getch());
399 #endif
400  return -1;
401 }
402 
403 static int decode_interrupt_cb(void *ctx)
404 {
405  return received_nb_signals > 1;
406 }
407 
409 
410 static void exit_program(void)
411 {
412  int i, j;
413 
414  if (do_benchmark) {
415  int maxrss = getmaxrss() / 1024;
416  printf("bench: maxrss=%ikB\n", maxrss);
417  }
418 
419  for (i = 0; i < nb_filtergraphs; i++) {
420  avfilter_graph_free(&filtergraphs[i]->graph);
421  for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
422  av_freep(&filtergraphs[i]->inputs[j]->name);
423  av_freep(&filtergraphs[i]->inputs[j]);
424  }
425  av_freep(&filtergraphs[i]->inputs);
426  for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
427  av_freep(&filtergraphs[i]->outputs[j]->name);
428  av_freep(&filtergraphs[i]->outputs[j]);
429  }
430  av_freep(&filtergraphs[i]->outputs);
431  av_freep(&filtergraphs[i]);
432  }
433  av_freep(&filtergraphs);
434 
436 
437  /* close files */
438  for (i = 0; i < nb_output_files; i++) {
439  AVFormatContext *s = output_files[i]->ctx;
440  if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
441  avio_close(s->pb);
443  av_dict_free(&output_files[i]->opts);
444  av_freep(&output_files[i]);
445  }
446  for (i = 0; i < nb_output_streams; i++) {
447  AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
448  while (bsfc) {
449  AVBitStreamFilterContext *next = bsfc->next;
451  bsfc = next;
452  }
453  output_streams[i]->bitstream_filters = NULL;
454  avcodec_free_frame(&output_streams[i]->filtered_frame);
455 
456  av_freep(&output_streams[i]->forced_keyframes);
457  av_expr_free(output_streams[i]->forced_keyframes_pexpr);
458  av_freep(&output_streams[i]->avfilter);
459  av_freep(&output_streams[i]->logfile_prefix);
460  av_freep(&output_streams[i]);
461  }
462 #if HAVE_PTHREADS
464 #endif
465  for (i = 0; i < nb_input_files; i++) {
466  avformat_close_input(&input_files[i]->ctx);
467  av_freep(&input_files[i]);
468  }
469  for (i = 0; i < nb_input_streams; i++) {
470  avcodec_free_frame(&input_streams[i]->decoded_frame);
471  av_dict_free(&input_streams[i]->opts);
472  free_buffer_pool(&input_streams[i]->buffer_pool);
473  avsubtitle_free(&input_streams[i]->prev_sub.subtitle);
474  avfilter_unref_bufferp(&input_streams[i]->sub2video.ref);
475  av_freep(&input_streams[i]->filters);
476  av_freep(&input_streams[i]);
477  }
478 
479  if (vstats_file)
480  fclose(vstats_file);
482 
483  av_freep(&input_streams);
484  av_freep(&input_files);
485  av_freep(&output_streams);
486  av_freep(&output_files);
487 
488  uninit_opts();
489 
490  avfilter_uninit();
492 
493  if (received_sigterm) {
494  av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
495  (int) received_sigterm);
496  }
497 }
498 
500 {
502  if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
503  av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
504  exit(1);
505  }
506 }
507 
508 static void abort_codec_experimental(AVCodec *c, int encoder)
509 {
510  exit(1);
511 }
512 
513 static void update_benchmark(const char *fmt, ...)
514 {
515  if (do_benchmark_all) {
516  int64_t t = getutime();
517  va_list va;
518  char buf[1024];
519 
520  if (fmt) {
521  va_start(va, fmt);
522  vsnprintf(buf, sizeof(buf), fmt, va);
523  va_end(va);
524  printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
525  }
526  current_time = t;
527  }
528 }
529 
531 {
533  AVCodecContext *avctx = ost->st->codec;
534  int ret;
535 
538  pkt->pts = pkt->dts = AV_NOPTS_VALUE;
539 
540  if ((avctx->codec_type == AVMEDIA_TYPE_AUDIO || avctx->codec_type == AVMEDIA_TYPE_VIDEO) && pkt->dts != AV_NOPTS_VALUE) {
541  int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
542  if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE && max > pkt->dts) {
543  av_log(s, max - pkt->dts > 2 || avctx->codec_type == AVMEDIA_TYPE_VIDEO ? AV_LOG_WARNING : AV_LOG_DEBUG,
544  "st:%d PTS: %"PRId64" DTS: %"PRId64" < %"PRId64" invalid, clipping\n", pkt->stream_index, pkt->pts, pkt->dts, max);
545  if(pkt->pts >= pkt->dts)
546  pkt->pts = FFMAX(pkt->pts, max);
547  pkt->dts = max;
548  }
549  }
550 
551  /*
552  * Audio encoders may split the packets -- #frames in != #packets out.
553  * But there is no reordering, so we can limit the number of output packets
554  * by simply dropping them here.
555  * Counting encoded video frames needs to be done separately because of
556  * reordering, see do_video_out()
557  */
558  if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
559  if (ost->frame_number >= ost->max_frames) {
560  av_free_packet(pkt);
561  return;
562  }
563  ost->frame_number++;
564  }
565 
566  while (bsfc) {
567  AVPacket new_pkt = *pkt;
568  int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
569  &new_pkt.data, &new_pkt.size,
570  pkt->data, pkt->size,
571  pkt->flags & AV_PKT_FLAG_KEY);
572  if(a == 0 && new_pkt.data != pkt->data && new_pkt.destruct) {
573  uint8_t *t = av_malloc(new_pkt.size + FF_INPUT_BUFFER_PADDING_SIZE); //the new should be a subset of the old so cannot overflow
574  if(t) {
575  memcpy(t, new_pkt.data, new_pkt.size);
576  memset(t + new_pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);
577  new_pkt.data = t;
578  a = 1;
579  } else
580  a = AVERROR(ENOMEM);
581  }
582  if (a > 0) {
583  av_free_packet(pkt);
584  new_pkt.destruct = av_destruct_packet;
585  } else if (a < 0) {
586  av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
587  bsfc->filter->name, pkt->stream_index,
588  avctx->codec ? avctx->codec->name : "copy");
589  print_error("", a);
590  if (exit_on_error)
591  exit(1);
592  }
593  *pkt = new_pkt;
594 
595  bsfc = bsfc->next;
596  }
597 
598  pkt->stream_index = ost->index;
599 
600  if (debug_ts) {
601  av_log(NULL, AV_LOG_INFO, "muxer <- type:%s "
602  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s size:%d\n",
604  av_ts2str(pkt->pts), av_ts2timestr(pkt->pts, &ost->st->time_base),
605  av_ts2str(pkt->dts), av_ts2timestr(pkt->dts, &ost->st->time_base),
606  pkt->size
607  );
608  }
609 
610  ret = av_interleaved_write_frame(s, pkt);
611  if (ret < 0) {
612  print_error("av_interleaved_write_frame()", ret);
613  exit(1);
614  }
615 }
616 
618 {
619  OutputFile *of = output_files[ost->file_index];
620 
621  ost->finished = 1;
622  if (of->shortest) {
623  int64_t end = av_rescale_q(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, AV_TIME_BASE_Q);
624  of->recording_time = FFMIN(of->recording_time, end);
625  }
626 }
627 
629 {
630  OutputFile *of = output_files[ost->file_index];
631 
632  if (of->recording_time != INT64_MAX &&
634  AV_TIME_BASE_Q) >= 0) {
635  close_output_stream(ost);
636  return 0;
637  }
638  return 1;
639 }
640 
642  AVFrame *frame)
643 {
644  AVCodecContext *enc = ost->st->codec;
645  AVPacket pkt;
646  int got_packet = 0;
647 
648  av_init_packet(&pkt);
649  pkt.data = NULL;
650  pkt.size = 0;
651 
652  if (!check_recording_time(ost))
653  return;
654 
655  if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
656  frame->pts = ost->sync_opts;
657  ost->sync_opts = frame->pts + frame->nb_samples;
658 
659  av_assert0(pkt.size || !pkt.data);
661  if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
662  av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
663  exit(1);
664  }
665  update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
666 
667  if (got_packet) {
668  if (pkt.pts != AV_NOPTS_VALUE)
669  pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
670  if (pkt.dts != AV_NOPTS_VALUE)
671  pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
672  if (pkt.duration > 0)
673  pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
674 
675  if (debug_ts) {
676  av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
677  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
678  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
679  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
680  }
681 
682  audio_size += pkt.size;
683  write_frame(s, &pkt, ost);
684 
685  av_free_packet(&pkt);
686  }
687 }
688 
689 #if FF_API_DEINTERLACE
690 static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
691 {
692  AVCodecContext *dec;
693  AVPicture *picture2;
694  AVPicture picture_tmp;
695  uint8_t *buf = 0;
696 
697  dec = ist->st->codec;
698 
699  /* deinterlace : must be done before any resize */
701  int size;
702 
703  /* create temporary picture */
704  size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
705  if (size < 0)
706  return;
707  buf = av_malloc(size);
708  if (!buf)
709  return;
710 
711  picture2 = &picture_tmp;
712  avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
713 
714  if (avpicture_deinterlace(picture2, picture,
715  dec->pix_fmt, dec->width, dec->height) < 0) {
716  /* if error, do not deinterlace */
717  av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
718  av_free(buf);
719  buf = NULL;
720  picture2 = picture;
721  }
722  } else {
723  picture2 = picture;
724  }
725 
726  if (picture != picture2)
727  *picture = *picture2;
728  *bufp = buf;
729 }
730 #endif
731 
733  OutputStream *ost,
734  InputStream *ist,
735  AVSubtitle *sub)
736 {
737  int subtitle_out_max_size = 1024 * 1024;
738  int subtitle_out_size, nb, i;
739  AVCodecContext *enc;
740  AVPacket pkt;
741  int64_t pts;
742 
743  if (sub->pts == AV_NOPTS_VALUE) {
744  av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
745  if (exit_on_error)
746  exit(1);
747  return;
748  }
749 
750  enc = ost->st->codec;
751 
752  if (!subtitle_out) {
753  subtitle_out = av_malloc(subtitle_out_max_size);
754  }
755 
756  /* Note: DVB subtitle need one packet to draw them and one other
757  packet to clear them */
758  /* XXX: signal it in the codec context ? */
760  nb = 2;
761  else
762  nb = 1;
763 
764  /* shift timestamp to honor -ss and make check_recording_time() work with -t */
765  pts = sub->pts - output_files[ost->file_index]->start_time;
766  for (i = 0; i < nb; i++) {
767  ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
768  if (!check_recording_time(ost))
769  return;
770 
771  sub->pts = pts;
772  // start_display_time is required to be 0
773  sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
775  sub->start_display_time = 0;
776  if (i == 1)
777  sub->num_rects = 0;
778  subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
779  subtitle_out_max_size, sub);
780  if (subtitle_out_size < 0) {
781  av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
782  exit(1);
783  }
784 
785  av_init_packet(&pkt);
786  pkt.data = subtitle_out;
787  pkt.size = subtitle_out_size;
788  pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
789  pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
790  if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
791  /* XXX: the pts correction is handled here. Maybe handling
792  it in the codec would be better */
793  if (i == 0)
794  pkt.pts += 90 * sub->start_display_time;
795  else
796  pkt.pts += 90 * sub->end_display_time;
797  }
799  write_frame(s, &pkt, ost);
800  }
801 }
802 
804  OutputStream *ost,
805  AVFrame *in_picture)
806 {
807  int ret, format_video_sync;
808  AVPacket pkt;
809  AVCodecContext *enc = ost->st->codec;
810  int nb_frames, i;
811  double sync_ipts, delta;
812  double duration = 0;
813  int frame_size = 0;
814  InputStream *ist = NULL;
815 
816  if (ost->source_index >= 0)
817  ist = input_streams[ost->source_index];
818 
819  if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
820  duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
821 
822  sync_ipts = in_picture->pts;
823  delta = sync_ipts - ost->sync_opts + duration;
824 
825  /* by default, we output a single frame */
826  nb_frames = 1;
827 
828  format_video_sync = video_sync_method;
829  if (format_video_sync == VSYNC_AUTO)
831 
832  switch (format_video_sync) {
833  case VSYNC_CFR:
834  // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
835  if (delta < -1.1)
836  nb_frames = 0;
837  else if (delta > 1.1)
838  nb_frames = lrintf(delta);
839  break;
840  case VSYNC_VFR:
841  if (delta <= -0.6)
842  nb_frames = 0;
843  else if (delta > 0.6)
844  ost->sync_opts = lrint(sync_ipts);
845  break;
846  case VSYNC_DROP:
847  case VSYNC_PASSTHROUGH:
848  ost->sync_opts = lrint(sync_ipts);
849  break;
850  default:
851  av_assert0(0);
852  }
853 
854  nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
855  if (nb_frames == 0) {
856  nb_frames_drop++;
857  av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
858  return;
859  } else if (nb_frames > 1) {
860  if (nb_frames > dts_error_threshold * 30) {
861  av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);
862  nb_frames_drop++;
863  return;
864  }
865  nb_frames_dup += nb_frames - 1;
866  av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
867  }
868 
869  /* duplicates frame if needed */
870  for (i = 0; i < nb_frames; i++) {
871  av_init_packet(&pkt);
872  pkt.data = NULL;
873  pkt.size = 0;
874 
875  in_picture->pts = ost->sync_opts;
876 
877  if (!check_recording_time(ost))
878  return;
879 
880  if (s->oformat->flags & AVFMT_RAWPICTURE &&
881  enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
882  /* raw pictures are written as AVPicture structure to
883  avoid any copies. We support temporarily the older
884  method. */
885  enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
886  enc->coded_frame->top_field_first = in_picture->top_field_first;
887  if (enc->coded_frame->interlaced_frame)
889  else
891  pkt.data = (uint8_t *)in_picture;
892  pkt.size = sizeof(AVPicture);
893  pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
894  pkt.flags |= AV_PKT_FLAG_KEY;
895 
896  video_size += pkt.size;
897  write_frame(s, &pkt, ost);
898  } else {
899  int got_packet, forced_keyframe = 0;
900  AVFrame big_picture;
901  double pts_time;
902 
903  big_picture = *in_picture;
904  /* better than nothing: use input picture interlaced
905  settings */
906  big_picture.interlaced_frame = in_picture->interlaced_frame;
908  if (ost->top_field_first == -1)
909  big_picture.top_field_first = in_picture->top_field_first;
910  else
911  big_picture.top_field_first = !!ost->top_field_first;
912  }
913 
914  if (big_picture.interlaced_frame) {
915  if (enc->codec->id == AV_CODEC_ID_MJPEG)
916  enc->field_order = big_picture.top_field_first ? AV_FIELD_TT:AV_FIELD_BB;
917  else
918  enc->field_order = big_picture.top_field_first ? AV_FIELD_TB:AV_FIELD_BT;
919  } else
921 
922  big_picture.quality = ost->st->codec->global_quality;
923  if (!enc->me_threshold)
924  big_picture.pict_type = 0;
925 
926  pts_time = big_picture.pts != AV_NOPTS_VALUE ?
927  big_picture.pts * av_q2d(enc->time_base) : NAN;
928  if (ost->forced_kf_index < ost->forced_kf_count &&
929  big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
930  ost->forced_kf_index++;
931  forced_keyframe = 1;
932  } else if (ost->forced_keyframes_pexpr) {
933  double res;
934  ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;
937  av_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",
943  res);
944  if (res) {
945  forced_keyframe = 1;
951  }
952 
954  }
955  if (forced_keyframe) {
956  big_picture.pict_type = AV_PICTURE_TYPE_I;
957  av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);
958  }
959 
961  ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
962  update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
963  if (ret < 0) {
964  av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
965  exit(1);
966  }
967 
968  if (got_packet) {
969  if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
970  pkt.pts = ost->sync_opts;
971 
972  if (pkt.pts != AV_NOPTS_VALUE)
973  pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
974  if (pkt.dts != AV_NOPTS_VALUE)
975  pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
976 
977  if (debug_ts) {
978  av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
979  "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
980  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
981  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
982  }
983 
984  frame_size = pkt.size;
985  video_size += pkt.size;
986  write_frame(s, &pkt, ost);
987  av_free_packet(&pkt);
988 
989  /* if two pass, output log */
990  if (ost->logfile && enc->stats_out) {
991  fprintf(ost->logfile, "%s", enc->stats_out);
992  }
993  }
994  }
995  ost->sync_opts++;
996  /*
997  * For video, number of frames in == number of packets out.
998  * But there may be reordering, so we can't throw away frames on encoder
999  * flush, we need to limit them here, before they go into encoder.
1000  */
1001  ost->frame_number++;
1002  }
1003 
1004  if (vstats_filename && frame_size)
1005  do_video_stats(ost, frame_size);
1006 }
1007 
1008 static double psnr(double d)
1009 {
1010  return -10.0 * log(d) / log(10.0);
1011 }
1012 
1014 {
1015  AVCodecContext *enc;
1016  int frame_number;
1017  double ti1, bitrate, avg_bitrate;
1018 
1019  /* this is executed just the first time do_video_stats is called */
1020  if (!vstats_file) {
1021  vstats_file = fopen(vstats_filename, "w");
1022  if (!vstats_file) {
1023  perror("fopen");
1024  exit(1);
1025  }
1026  }
1027 
1028  enc = ost->st->codec;
1029  if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1030  frame_number = ost->st->nb_frames;
1031  fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
1032  if (enc->flags&CODEC_FLAG_PSNR)
1033  fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
1034 
1035  fprintf(vstats_file,"f_size= %6d ", frame_size);
1036  /* compute pts value */
1037  ti1 = ost->st->pts.val * av_q2d(enc->time_base);
1038  if (ti1 < 0.01)
1039  ti1 = 0.01;
1040 
1041  bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
1042  avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
1043  fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
1044  (double)video_size / 1024, ti1, bitrate, avg_bitrate);
1045  fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
1046  }
1047 }
1048 
1049 /**
1050  * Get and encode new output from any of the filtergraphs, without causing
1051  * activity.
1052  *
1053  * @return 0 for success, <0 for severe errors
1054  */
1055 static int reap_filters(void)
1056 {
1057  AVFilterBufferRef *picref;
1058  AVFrame *filtered_frame = NULL;
1059  int i;
1060  int64_t frame_pts;
1061 
1062  /* Reap all buffers present in the buffer sinks */
1063  for (i = 0; i < nb_output_streams; i++) {
1064  OutputStream *ost = output_streams[i];
1065  OutputFile *of = output_files[ost->file_index];
1066  int ret = 0;
1067 
1068  if (!ost->filter)
1069  continue;
1070 
1071  if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
1072  return AVERROR(ENOMEM);
1073  } else
1075  filtered_frame = ost->filtered_frame;
1076 
1077  while (1) {
1078  ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
1080  if (ret < 0) {
1081  if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
1082  char buf[256];
1083  av_strerror(ret, buf, sizeof(buf));
1085  "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
1086  }
1087  break;
1088  }
1089  frame_pts = AV_NOPTS_VALUE;
1090  if (picref->pts != AV_NOPTS_VALUE) {
1091  filtered_frame->pts = frame_pts = av_rescale_q(picref->pts,
1092  ost->filter->filter->inputs[0]->time_base,
1093  ost->st->codec->time_base) -
1096  ost->st->codec->time_base);
1097 
1098  if (of->start_time && filtered_frame->pts < 0) {
1099  avfilter_unref_buffer(picref);
1100  continue;
1101  }
1102  }
1103  //if (ost->source_index >= 0)
1104  // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
1105 
1106 
1107  switch (ost->filter->filter->inputs[0]->type) {
1108  case AVMEDIA_TYPE_VIDEO:
1109  avfilter_copy_buf_props(filtered_frame, picref);
1110  filtered_frame->pts = frame_pts;
1111  if (!ost->frame_aspect_ratio)
1113 
1114  do_video_out(of->ctx, ost, filtered_frame);
1115  break;
1116  case AVMEDIA_TYPE_AUDIO:
1117  avfilter_copy_buf_props(filtered_frame, picref);
1118  filtered_frame->pts = frame_pts;
1119  if (!(ost->st->codec->codec->capabilities & CODEC_CAP_PARAM_CHANGE) &&
1120  ost->st->codec->channels != av_frame_get_channels(filtered_frame)) {
1122  "Audio filter graph output is not normalized and encoder does not support parameter changes\n");
1123  break;
1124  }
1125  do_audio_out(of->ctx, ost, filtered_frame);
1126  break;
1127  default:
1128  // TODO support subtitle filters
1129  av_assert0(0);
1130  }
1131 
1132  avfilter_unref_buffer(picref);
1133  }
1134  }
1135 
1136  return 0;
1137 }
1138 
1139 static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
1140 {
1141  char buf[1024];
1142  AVBPrint buf_script;
1143  OutputStream *ost;
1144  AVFormatContext *oc;
1145  int64_t total_size;
1146  AVCodecContext *enc;
1147  int frame_number, vid, i;
1148  double bitrate;
1149  int64_t pts = INT64_MIN;
1150  static int64_t last_time = -1;
1151  static int qp_histogram[52];
1152  int hours, mins, secs, us;
1153 
1154  if (!print_stats && !is_last_report && !progress_avio)
1155  return;
1156 
1157  if (!is_last_report) {
1158  if (last_time == -1) {
1159  last_time = cur_time;
1160  return;
1161  }
1162  if ((cur_time - last_time) < 500000)
1163  return;
1164  last_time = cur_time;
1165  }
1166 
1167 
1168  oc = output_files[0]->ctx;
1169 
1170  total_size = avio_size(oc->pb);
1171  if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
1172  total_size = avio_tell(oc->pb);
1173 
1174  buf[0] = '\0';
1175  vid = 0;
1176  av_bprint_init(&buf_script, 0, 1);
1177  for (i = 0; i < nb_output_streams; i++) {
1178  float q = -1;
1179  ost = output_streams[i];
1180  enc = ost->st->codec;
1181  if (!ost->stream_copy && enc->coded_frame)
1182  q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
1183  if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1184  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
1185  av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1186  ost->file_index, ost->index, q);
1187  }
1188  if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
1189  float fps, t = (cur_time-timer_start) / 1000000.0;
1190 
1191  frame_number = ost->frame_number;
1192  fps = t > 1 ? frame_number / t : 0;
1193  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
1194  frame_number, fps < 9.95, fps, q);
1195  av_bprintf(&buf_script, "frame=%d\n", frame_number);
1196  av_bprintf(&buf_script, "fps=%.1f\n", fps);
1197  av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
1198  ost->file_index, ost->index, q);
1199  if (is_last_report)
1200  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
1201  if (qp_hist) {
1202  int j;
1203  int qp = lrintf(q);
1204  if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
1205  qp_histogram[qp]++;
1206  for (j = 0; j < 32; j++)
1207  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
1208  }
1209  if ((enc->flags&CODEC_FLAG_PSNR) && (enc->coded_frame || is_last_report)) {
1210  int j;
1211  double error, error_sum = 0;
1212  double scale, scale_sum = 0;
1213  double p;
1214  char type[3] = { 'Y','U','V' };
1215  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
1216  for (j = 0; j < 3; j++) {
1217  if (is_last_report) {
1218  error = enc->error[j];
1219  scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
1220  } else {
1221  error = enc->coded_frame->error[j];
1222  scale = enc->width * enc->height * 255.0 * 255.0;
1223  }
1224  if (j)
1225  scale /= 4;
1226  error_sum += error;
1227  scale_sum += scale;
1228  p = psnr(error / scale);
1229  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
1230  av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
1231  ost->file_index, ost->index, type[j] | 32, p);
1232  }
1233  p = psnr(error_sum / scale_sum);
1234  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
1235  av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
1236  ost->file_index, ost->index, p);
1237  }
1238  vid = 1;
1239  }
1240  /* compute min output value */
1241  if ((is_last_report || !ost->finished) && ost->st->pts.val != AV_NOPTS_VALUE)
1242  pts = FFMAX(pts, av_rescale_q(ost->st->pts.val,
1243  ost->st->time_base, AV_TIME_BASE_Q));
1244  }
1245 
1246  secs = pts / AV_TIME_BASE;
1247  us = pts % AV_TIME_BASE;
1248  mins = secs / 60;
1249  secs %= 60;
1250  hours = mins / 60;
1251  mins %= 60;
1252 
1253  bitrate = pts && total_size >= 0 ? total_size * 8 / (pts / 1000.0) : -1;
1254 
1255  if (total_size < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1256  "size=N/A time=");
1257  else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1258  "size=%8.0fkB time=", total_size / 1024.0);
1259  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1260  "%02d:%02d:%02d.%02d ", hours, mins, secs,
1261  (100 * us) / AV_TIME_BASE);
1262  if (bitrate < 0) snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1263  "bitrate=N/A");
1264  else snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
1265  "bitrate=%6.1fkbits/s", bitrate);
1266  if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
1267  else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
1268  av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
1269  av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
1270  hours, mins, secs, us);
1271 
1273  snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
1275  av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
1276  av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
1277 
1278  if (print_stats || is_last_report) {
1279  if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
1280  fprintf(stderr, "%s \r", buf);
1281  } else
1282  av_log(NULL, AV_LOG_INFO, "%s \r", buf);
1283 
1284  fflush(stderr);
1285  }
1286 
1287  if (progress_avio) {
1288  av_bprintf(&buf_script, "progress=%s\n",
1289  is_last_report ? "end" : "continue");
1290  avio_write(progress_avio, buf_script.str,
1291  FFMIN(buf_script.len, buf_script.size - 1));
1292  avio_flush(progress_avio);
1293  av_bprint_finalize(&buf_script, NULL);
1294  if (is_last_report) {
1295  avio_close(progress_avio);
1296  progress_avio = NULL;
1297  }
1298  }
1299 
1300  if (is_last_report) {
1301  int64_t raw= audio_size + video_size + subtitle_size + extra_size;
1302  av_log(NULL, AV_LOG_INFO, "\n");
1303  av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
1304  video_size / 1024.0,
1305  audio_size / 1024.0,
1306  subtitle_size / 1024.0,
1307  extra_size / 1024.0,
1308  100.0 * (total_size - raw) / raw
1309  );
1310  if(video_size + audio_size + subtitle_size + extra_size == 0){
1311  av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
1312  }
1313  }
1314 }
1315 
1316 static void flush_encoders(void)
1317 {
1318  int i, ret;
1319 
1320  for (i = 0; i < nb_output_streams; i++) {
1321  OutputStream *ost = output_streams[i];
1322  AVCodecContext *enc = ost->st->codec;
1323  AVFormatContext *os = output_files[ost->file_index]->ctx;
1324  int stop_encoding = 0;
1325 
1326  if (!ost->encoding_needed)
1327  continue;
1328 
1329  if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
1330  continue;
1332  continue;
1333 
1334  for (;;) {
1335  int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
1336  const char *desc;
1337  int64_t *size;
1338 
1339  switch (ost->st->codec->codec_type) {
1340  case AVMEDIA_TYPE_AUDIO:
1341  encode = avcodec_encode_audio2;
1342  desc = "Audio";
1343  size = &audio_size;
1344  break;
1345  case AVMEDIA_TYPE_VIDEO:
1346  encode = avcodec_encode_video2;
1347  desc = "Video";
1348  size = &video_size;
1349  break;
1350  default:
1351  stop_encoding = 1;
1352  }
1353 
1354  if (encode) {
1355  AVPacket pkt;
1356  int got_packet;
1357  av_init_packet(&pkt);
1358  pkt.data = NULL;
1359  pkt.size = 0;
1360 
1362  ret = encode(enc, &pkt, NULL, &got_packet);
1363  update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
1364  if (ret < 0) {
1365  av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
1366  exit(1);
1367  }
1368  *size += pkt.size;
1369  if (ost->logfile && enc->stats_out) {
1370  fprintf(ost->logfile, "%s", enc->stats_out);
1371  }
1372  if (!got_packet) {
1373  stop_encoding = 1;
1374  break;
1375  }
1376  if (pkt.pts != AV_NOPTS_VALUE)
1377  pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
1378  if (pkt.dts != AV_NOPTS_VALUE)
1379  pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
1380  if (pkt.duration > 0)
1381  pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
1382  write_frame(os, &pkt, ost);
1384  do_video_stats(ost, pkt.size);
1385  }
1386  }
1387 
1388  if (stop_encoding)
1389  break;
1390  }
1391  }
1392 }
1393 
1394 /*
1395  * Check whether a packet from ist should be written into ost at this time
1396  */
1398 {
1399  OutputFile *of = output_files[ost->file_index];
1400  int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
1401 
1402  if (ost->source_index != ist_index)
1403  return 0;
1404 
1405  if (of->start_time && ist->pts < of->start_time)
1406  return 0;
1407 
1408  return 1;
1409 }
1410 
1411 static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
1412 {
1413  OutputFile *of = output_files[ost->file_index];
1414  int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
1415  AVPicture pict;
1416  AVPacket opkt;
1417 
1418  av_init_packet(&opkt);
1419 
1420  if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
1422  return;
1423 
1424  if (!ost->frame_number && ist->pts < of->start_time &&
1425  !ost->copy_prior_start)
1426  return;
1427 
1428  if (of->recording_time != INT64_MAX &&
1429  ist->pts >= of->recording_time + of->start_time) {
1430  close_output_stream(ost);
1431  return;
1432  }
1433 
1434  /* force the input stream PTS */
1435  if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
1436  audio_size += pkt->size;
1437  else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
1438  video_size += pkt->size;
1439  ost->sync_opts++;
1440  } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
1441  subtitle_size += pkt->size;
1442  }
1443 
1444  if (pkt->pts != AV_NOPTS_VALUE)
1445  opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
1446  else
1447  opkt.pts = AV_NOPTS_VALUE;
1448 
1449  if (pkt->dts == AV_NOPTS_VALUE)
1450  opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
1451  else
1452  opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
1453  opkt.dts -= ost_tb_start_time;
1454 
1455  if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
1456  int duration = av_get_audio_frame_duration(ist->st->codec, pkt->size);
1457  if(!duration)
1458  duration = ist->st->codec->frame_size;
1459  opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
1461  ost->st->time_base) - ost_tb_start_time;
1462  }
1463 
1464  opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
1465  opkt.flags = pkt->flags;
1466 
1467  // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
1468  if ( ost->st->codec->codec_id != AV_CODEC_ID_H264
1469  && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
1470  && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
1471  && ost->st->codec->codec_id != AV_CODEC_ID_VC1
1472  ) {
1473  if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
1474  opkt.destruct = av_destruct_packet;
1475  } else {
1476  opkt.data = pkt->data;
1477  opkt.size = pkt->size;
1478  }
1479 
1480  if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
1481  /* store AVPicture in AVPacket, as expected by the output format */
1482  avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
1483  opkt.data = (uint8_t *)&pict;
1484  opkt.size = sizeof(AVPicture);
1485  opkt.flags |= AV_PKT_FLAG_KEY;
1486  }
1487 
1488  write_frame(of->ctx, &opkt, ost);
1489  ost->st->codec->frame_number++;
1490 }
1491 
1492 static void rate_emu_sleep(InputStream *ist)
1493 {
1494  if (input_files[ist->file_index]->rate_emu) {
1495  int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
1496  int64_t now = av_gettime() - ist->start;
1497  if (pts > now)
1498  av_usleep(pts - now);
1499  }
1500 }
1501 
1503 {
1504  AVCodecContext *dec = ist->st->codec;
1505 
1506  if (!dec->channel_layout) {
1507  char layout_name[256];
1508 
1509  if (dec->channels > ist->guess_layout_max)
1510  return 0;
1512  if (!dec->channel_layout)
1513  return 0;
1514  av_get_channel_layout_string(layout_name, sizeof(layout_name),
1515  dec->channels, dec->channel_layout);
1516  av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
1517  "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
1518  }
1519  return 1;
1520 }
1521 
1522 static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
1523 {
1524  AVFrame *decoded_frame;
1525  AVCodecContext *avctx = ist->st->codec;
1526  int i, ret, resample_changed;
1527  AVRational decoded_frame_tb;
1528 
1529  if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1530  return AVERROR(ENOMEM);
1531  decoded_frame = ist->decoded_frame;
1532 
1534  ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
1535  update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
1536 
1537  if (ret >= 0 && avctx->sample_rate <= 0) {
1538  av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
1539  ret = AVERROR_INVALIDDATA;
1540  }
1541 
1542  if (!*got_output || ret < 0) {
1543  if (!pkt->size) {
1544  for (i = 0; i < ist->nb_filters; i++)
1545  av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
1546  }
1547  return ret;
1548  }
1549 
1550 #if 1
1551  /* increment next_dts to use for the case where the input stream does not
1552  have timestamps or there are multiple frames in the packet */
1553  ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1554  avctx->sample_rate;
1555  ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
1556  avctx->sample_rate;
1557 #endif
1558 
1559  rate_emu_sleep(ist);
1560 
1561  resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
1562  ist->resample_channels != avctx->channels ||
1563  ist->resample_channel_layout != decoded_frame->channel_layout ||
1564  ist->resample_sample_rate != decoded_frame->sample_rate;
1565  if (resample_changed) {
1566  char layout1[64], layout2[64];
1567 
1568  if (!guess_input_channel_layout(ist)) {
1569  av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
1570  "layout for Input Stream #%d.%d\n", ist->file_index,
1571  ist->st->index);
1572  exit(1);
1573  }
1574  decoded_frame->channel_layout = avctx->channel_layout;
1575 
1576  av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
1578  av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
1579  decoded_frame->channel_layout);
1580 
1582  "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",
1583  ist->file_index, ist->st->index,
1585  ist->resample_channels, layout1,
1586  decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
1587  avctx->channels, layout2);
1588 
1589  ist->resample_sample_fmt = decoded_frame->format;
1590  ist->resample_sample_rate = decoded_frame->sample_rate;
1591  ist->resample_channel_layout = decoded_frame->channel_layout;
1592  ist->resample_channels = avctx->channels;
1593 
1594  for (i = 0; i < nb_filtergraphs; i++)
1595  if (ist_in_filtergraph(filtergraphs[i], ist)) {
1596  FilterGraph *fg = filtergraphs[i];
1597  int j;
1598  if (configure_filtergraph(fg) < 0) {
1599  av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1600  exit(1);
1601  }
1602  for (j = 0; j < fg->nb_outputs; j++) {
1603  OutputStream *ost = fg->outputs[j]->ost;
1604  if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
1607  ost->st->codec->frame_size);
1608  }
1609  }
1610  }
1611 
1612  /* if the decoder provides a pts, use it instead of the last packet pts.
1613  the decoder could be delaying output by a packet or more. */
1614  if (decoded_frame->pts != AV_NOPTS_VALUE) {
1615  ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
1616  decoded_frame_tb = avctx->time_base;
1617  } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
1618  decoded_frame->pts = decoded_frame->pkt_pts;
1619  pkt->pts = AV_NOPTS_VALUE;
1620  decoded_frame_tb = ist->st->time_base;
1621  } else if (pkt->pts != AV_NOPTS_VALUE) {
1622  decoded_frame->pts = pkt->pts;
1623  pkt->pts = AV_NOPTS_VALUE;
1624  decoded_frame_tb = ist->st->time_base;
1625  }else {
1626  decoded_frame->pts = ist->dts;
1627  decoded_frame_tb = AV_TIME_BASE_Q;
1628  }
1629  if (decoded_frame->pts != AV_NOPTS_VALUE)
1630  decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
1631  (AVRational){1, ist->st->codec->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
1632  (AVRational){1, ist->st->codec->sample_rate});
1633  for (i = 0; i < ist->nb_filters; i++)
1634  av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame,
1636 
1637  decoded_frame->pts = AV_NOPTS_VALUE;
1638 
1639  return ret;
1640 }
1641 
1642 static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
1643 {
1644  AVFrame *decoded_frame;
1645  void *buffer_to_free = NULL;
1646  int i, ret = 0, resample_changed;
1647  int64_t best_effort_timestamp;
1648  AVRational *frame_sample_aspect;
1649 
1650  if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
1651  return AVERROR(ENOMEM);
1652  decoded_frame = ist->decoded_frame;
1653  pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
1654 
1656  ret = avcodec_decode_video2(ist->st->codec,
1657  decoded_frame, got_output, pkt);
1658  update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
1659  if (!*got_output || ret < 0) {
1660  if (!pkt->size) {
1661  for (i = 0; i < ist->nb_filters; i++)
1662  av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
1663  }
1664  return ret;
1665  }
1666 
1667  if(ist->top_field_first>=0)
1668  decoded_frame->top_field_first = ist->top_field_first;
1669 
1670  best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
1671  if(best_effort_timestamp != AV_NOPTS_VALUE)
1672  ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
1673 
1674  if (debug_ts) {
1675  av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
1676  "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
1677  ist->st->index, av_ts2str(decoded_frame->pts),
1678  av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
1679  best_effort_timestamp,
1680  av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
1681  decoded_frame->key_frame, decoded_frame->pict_type);
1682  }
1683 
1684  pkt->size = 0;
1685 #if FF_API_DEINTERLACE
1686  pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
1687 #endif
1688 
1689  rate_emu_sleep(ist);
1690 
1691  if (ist->st->sample_aspect_ratio.num)
1692  decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
1693 
1694  resample_changed = ist->resample_width != decoded_frame->width ||
1695  ist->resample_height != decoded_frame->height ||
1696  ist->resample_pix_fmt != decoded_frame->format;
1697  if (resample_changed) {
1699  "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
1700  ist->file_index, ist->st->index,
1702  decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
1703 
1704  ist->resample_width = decoded_frame->width;
1705  ist->resample_height = decoded_frame->height;
1706  ist->resample_pix_fmt = decoded_frame->format;
1707 
1708  for (i = 0; i < nb_filtergraphs; i++) {
1709  if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
1710  configure_filtergraph(filtergraphs[i]) < 0) {
1711  av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
1712  exit(1);
1713  }
1714  }
1715  }
1716 
1717  frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
1718  for (i = 0; i < ist->nb_filters; i++) {
1719  int changed = ist->st->codec->width != ist->filters[i]->filter->outputs[0]->w
1720  || ist->st->codec->height != ist->filters[i]->filter->outputs[0]->h
1721  || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
1722 
1723  if (!frame_sample_aspect->num)
1724  *frame_sample_aspect = ist->st->sample_aspect_ratio;
1725  if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
1726  FrameBuffer *buf = decoded_frame->opaque;
1728  decoded_frame->data, decoded_frame->linesize,
1730  ist->st->codec->width, ist->st->codec->height,
1731  ist->st->codec->pix_fmt);
1732 
1733  avfilter_copy_frame_props(fb, decoded_frame);
1734  fb->buf->priv = buf;
1736 
1737  av_assert0(buf->refcount>0);
1738  buf->refcount++;
1739  av_buffersrc_add_ref(ist->filters[i]->filter, fb,
1743  } else
1744  if(av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, AV_BUFFERSRC_FLAG_PUSH)<0) {
1745  av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
1746  exit(1);
1747  }
1748 
1749  }
1750 
1751  av_free(buffer_to_free);
1752  return ret;
1753 }
1754 
1755 static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
1756 {
1757  AVSubtitle subtitle;
1758  int i, ret = avcodec_decode_subtitle2(ist->st->codec,
1759  &subtitle, got_output, pkt);
1760  if (ret < 0 || !*got_output) {
1761  if (!pkt->size)
1762  sub2video_flush(ist);
1763  return ret;
1764  }
1765 
1766  if (ist->fix_sub_duration) {
1767  if (ist->prev_sub.got_output) {
1768  int end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
1769  1000, AV_TIME_BASE);
1770  if (end < ist->prev_sub.subtitle.end_display_time) {
1771  av_log(ist->st->codec, AV_LOG_DEBUG,
1772  "Subtitle duration reduced from %d to %d\n",
1773  ist->prev_sub.subtitle.end_display_time, end);
1775  }
1776  }
1777  FFSWAP(int, *got_output, ist->prev_sub.got_output);
1778  FFSWAP(int, ret, ist->prev_sub.ret);
1779  FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
1780  }
1781 
1782  sub2video_update(ist, &subtitle);
1783 
1784  if (!*got_output || !subtitle.num_rects)
1785  return ret;
1786 
1787  rate_emu_sleep(ist);
1788 
1789  for (i = 0; i < nb_output_streams; i++) {
1790  OutputStream *ost = output_streams[i];
1791 
1792  if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
1793  continue;
1794 
1795  do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
1796  }
1797 
1798  avsubtitle_free(&subtitle);
1799  return ret;
1800 }
1801 
1802 /* pkt = NULL means EOF (needed to flush decoder buffers) */
1803 static int output_packet(InputStream *ist, const AVPacket *pkt)
1804 {
1805  int ret = 0, i;
1806  int got_output;
1807 
1808  AVPacket avpkt;
1809  if (!ist->saw_first_ts) {
1810  ist->dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
1811  ist->pts = 0;
1812  if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
1813  ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
1814  ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
1815  }
1816  ist->saw_first_ts = 1;
1817  }
1818 
1819  if (ist->next_dts == AV_NOPTS_VALUE)
1820  ist->next_dts = ist->dts;
1821  if (ist->next_pts == AV_NOPTS_VALUE)
1822  ist->next_pts = ist->pts;
1823 
1824  if (pkt == NULL) {
1825  /* EOF handling */
1826  av_init_packet(&avpkt);
1827  avpkt.data = NULL;
1828  avpkt.size = 0;
1829  goto handle_eof;
1830  } else {
1831  avpkt = *pkt;
1832  }
1833 
1834  if (pkt->dts != AV_NOPTS_VALUE) {
1835  ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
1836  if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
1837  ist->next_pts = ist->pts = ist->dts;
1838  }
1839 
1840  // while we have more to decode or while the decoder did output something on EOF
1841  while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
1842  int duration;
1843  handle_eof:
1844 
1845  ist->pts = ist->next_pts;
1846  ist->dts = ist->next_dts;
1847 
1848  if (avpkt.size && avpkt.size != pkt->size) {
1850  "Multiple frames in a packet from stream %d\n", pkt->stream_index);
1851  ist->showed_multi_packet_warning = 1;
1852  }
1853 
1854  switch (ist->st->codec->codec_type) {
1855  case AVMEDIA_TYPE_AUDIO:
1856  ret = decode_audio (ist, &avpkt, &got_output);
1857  break;
1858  case AVMEDIA_TYPE_VIDEO:
1859  ret = decode_video (ist, &avpkt, &got_output);
1860  if (avpkt.duration) {
1861  duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
1862  } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
1863  int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
1864  duration = ((int64_t)AV_TIME_BASE *
1865  ist->st->codec->time_base.num * ticks) /
1866  ist->st->codec->time_base.den;
1867  } else
1868  duration = 0;
1869 
1870  if(ist->dts != AV_NOPTS_VALUE && duration) {
1871  ist->next_dts += duration;
1872  }else
1873  ist->next_dts = AV_NOPTS_VALUE;
1874 
1875  if (got_output)
1876  ist->next_pts += duration; //FIXME the duration is not correct in some cases
1877  break;
1878  case AVMEDIA_TYPE_SUBTITLE:
1879  ret = transcode_subtitles(ist, &avpkt, &got_output);
1880  break;
1881  default:
1882  return -1;
1883  }
1884 
1885  if (ret < 0)
1886  return ret;
1887 
1888  avpkt.dts=
1889  avpkt.pts= AV_NOPTS_VALUE;
1890 
1891  // touch data and size only if not EOF
1892  if (pkt) {
1893  if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
1894  ret = avpkt.size;
1895  avpkt.data += ret;
1896  avpkt.size -= ret;
1897  }
1898  if (!got_output) {
1899  continue;
1900  }
1901  }
1902 
1903  /* handle stream copy */
1904  if (!ist->decoding_needed) {
1905  rate_emu_sleep(ist);
1906  ist->dts = ist->next_dts;
1907  switch (ist->st->codec->codec_type) {
1908  case AVMEDIA_TYPE_AUDIO:
1909  ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
1910  ist->st->codec->sample_rate;
1911  break;
1912  case AVMEDIA_TYPE_VIDEO:
1913  if (pkt->duration) {
1914  ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1915  } else if(ist->st->codec->time_base.num != 0) {
1916  int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
1917  ist->next_dts += ((int64_t)AV_TIME_BASE *
1918  ist->st->codec->time_base.num * ticks) /
1919  ist->st->codec->time_base.den;
1920  }
1921  break;
1922  }
1923  ist->pts = ist->dts;
1924  ist->next_pts = ist->next_dts;
1925  }
1926  for (i = 0; pkt && i < nb_output_streams; i++) {
1927  OutputStream *ost = output_streams[i];
1928 
1929  if (!check_output_constraints(ist, ost) || ost->encoding_needed)
1930  continue;
1931 
1932  do_streamcopy(ist, ost, pkt);
1933  }
1934 
1935  return 0;
1936 }
1937 
1938 static void print_sdp(void)
1939 {
1940  char sdp[16384];
1941  int i;
1942  AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
1943 
1944  if (!avc)
1945  exit(1);
1946  for (i = 0; i < nb_output_files; i++)
1947  avc[i] = output_files[i]->ctx;
1948 
1949  av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
1950  printf("SDP:\n%s\n", sdp);
1951  fflush(stdout);
1952  av_freep(&avc);
1953 }
1954 
1955 static int init_input_stream(int ist_index, char *error, int error_len)
1956 {
1957  int ret;
1958  InputStream *ist = input_streams[ist_index];
1959 
1960  if (ist->decoding_needed) {
1961  AVCodec *codec = ist->dec;
1962  if (!codec) {
1963  snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
1964  avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
1965  return AVERROR(EINVAL);
1966  }
1967 
1968  ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !(FF_API_DEINTERLACE && do_deinterlace);
1969  if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
1972  ist->st->codec->opaque = &ist->buffer_pool;
1973  }
1974 
1975  if (!av_dict_get(ist->opts, "threads", NULL, 0))
1976  av_dict_set(&ist->opts, "threads", "auto", 0);
1977  if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
1978  if (ret == AVERROR_EXPERIMENTAL)
1979  abort_codec_experimental(codec, 0);
1980  snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
1981  ist->file_index, ist->st->index);
1982  return ret;
1983  }
1984  assert_avoptions(ist->opts);
1985  }
1986 
1987  ist->next_pts = AV_NOPTS_VALUE;
1988  ist->next_dts = AV_NOPTS_VALUE;
1989  ist->is_start = 1;
1990 
1991  return 0;
1992 }
1993 
1995 {
1996  if (ost->source_index >= 0)
1997  return input_streams[ost->source_index];
1998  return NULL;
1999 }
2000 
2001 static int compare_int64(const void *a, const void *b)
2002 {
2003  int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
2004  return va < vb ? -1 : va > vb ? +1 : 0;
2005 }
2006 
2007 static void parse_forced_key_frames(char *kf, OutputStream *ost,
2008  AVCodecContext *avctx)
2009 {
2010  char *p;
2011  int n = 1, i, size, index = 0;
2012  int64_t t, *pts;
2013 
2014  for (p = kf; *p; p++)
2015  if (*p == ',')
2016  n++;
2017  size = n;
2018  pts = av_malloc(sizeof(*pts) * size);
2019  if (!pts) {
2020  av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
2021  exit(1);
2022  }
2023 
2024  p = kf;
2025  for (i = 0; i < n; i++) {
2026  char *next = strchr(p, ',');
2027 
2028  if (next)
2029  *next++ = 0;
2030 
2031  if (!memcmp(p, "chapters", 8)) {
2032 
2033  AVFormatContext *avf = output_files[ost->file_index]->ctx;
2034  int j;
2035 
2036  if (avf->nb_chapters > INT_MAX - size ||
2037  !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
2038  sizeof(*pts)))) {
2040  "Could not allocate forced key frames array.\n");
2041  exit(1);
2042  }
2043  t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
2044  t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2045 
2046  for (j = 0; j < avf->nb_chapters; j++) {
2047  AVChapter *c = avf->chapters[j];
2048  av_assert1(index < size);
2049  pts[index++] = av_rescale_q(c->start, c->time_base,
2050  avctx->time_base) + t;
2051  }
2052 
2053  } else {
2054 
2055  t = parse_time_or_die("force_key_frames", p, 1);
2056  av_assert1(index < size);
2057  pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2058 
2059  }
2060 
2061  p = next;
2062  }
2063 
2064  av_assert0(index == size);
2065  qsort(pts, size, sizeof(*pts), compare_int64);
2066  ost->forced_kf_count = size;
2067  ost->forced_kf_pts = pts;
2068 }
2069 
2070 static void report_new_stream(int input_index, AVPacket *pkt)
2071 {
2072  InputFile *file = input_files[input_index];
2073  AVStream *st = file->ctx->streams[pkt->stream_index];
2074 
2075  if (pkt->stream_index < file->nb_streams_warn)
2076  return;
2077  av_log(file->ctx, AV_LOG_WARNING,
2078  "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
2080  input_index, pkt->stream_index,
2081  pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
2082  file->nb_streams_warn = pkt->stream_index + 1;
2083 }
2084 
2085 static int transcode_init(void)
2086 {
2087  int ret = 0, i, j, k;
2088  AVFormatContext *oc;
2089  AVCodecContext *codec;
2090  OutputStream *ost;
2091  InputStream *ist;
2092  char error[1024];
2093  int want_sdp = 1;
2094 
2095  /* init framerate emulation */
2096  for (i = 0; i < nb_input_files; i++) {
2097  InputFile *ifile = input_files[i];
2098  if (ifile->rate_emu)
2099  for (j = 0; j < ifile->nb_streams; j++)
2100  input_streams[j + ifile->ist_index]->start = av_gettime();
2101  }
2102 
2103  /* output stream init */
2104  for (i = 0; i < nb_output_files; i++) {
2105  oc = output_files[i]->ctx;
2106  if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2107  av_dump_format(oc, i, oc->filename, 1);
2108  av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2109  return AVERROR(EINVAL);
2110  }
2111  }
2112 
2113  /* init complex filtergraphs */
2114  for (i = 0; i < nb_filtergraphs; i++)
2115  if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2116  return ret;
2117 
2118  /* for each output stream, we compute the right encoding parameters */
2119  for (i = 0; i < nb_output_streams; i++) {
2120  AVCodecContext *icodec = NULL;
2121  ost = output_streams[i];
2122  oc = output_files[ost->file_index]->ctx;
2123  ist = get_input_stream(ost);
2124 
2125  if (ost->attachment_filename)
2126  continue;
2127 
2128  codec = ost->st->codec;
2129 
2130  if (ist) {
2131  icodec = ist->st->codec;
2132 
2133  ost->st->disposition = ist->st->disposition;
2134  codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2136  }
2137 
2138  if (ost->stream_copy) {
2139  uint64_t extra_size;
2140 
2141  av_assert0(ist && !ost->filter);
2142 
2143  extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2144 
2145  if (extra_size > INT_MAX) {
2146  return AVERROR(EINVAL);
2147  }
2148 
2149  /* if stream_copy is selected, no need to decode or encode */
2150  codec->codec_id = icodec->codec_id;
2151  codec->codec_type = icodec->codec_type;
2152 
2153  if (!codec->codec_tag) {
2154  unsigned int codec_tag;
2155  if (!oc->oformat->codec_tag ||
2156  av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2157  !av_codec_get_tag2(oc->oformat->codec_tag, icodec->codec_id, &codec_tag))
2158  codec->codec_tag = icodec->codec_tag;
2159  }
2160 
2161  codec->bit_rate = icodec->bit_rate;
2162  codec->rc_max_rate = icodec->rc_max_rate;
2163  codec->rc_buffer_size = icodec->rc_buffer_size;
2164  codec->field_order = icodec->field_order;
2165  codec->extradata = av_mallocz(extra_size);
2166  if (!codec->extradata) {
2167  return AVERROR(ENOMEM);
2168  }
2169  memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2170  codec->extradata_size= icodec->extradata_size;
2172 
2173  codec->time_base = ist->st->time_base;
2174  /*
2175  * Avi is a special case here because it supports variable fps but
2176  * having the fps and timebase differe significantly adds quite some
2177  * overhead
2178  */
2179  if(!strcmp(oc->oformat->name, "avi")) {
2180  if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
2181  && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
2182  && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
2183  && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
2184  || copy_tb==2){
2185  codec->time_base.num = ist->st->r_frame_rate.den;
2186  codec->time_base.den = 2*ist->st->r_frame_rate.num;
2187  codec->ticks_per_frame = 2;
2188  } else if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2189  && av_q2d(ist->st->time_base) < 1.0/500
2190  || copy_tb==0){
2191  codec->time_base = icodec->time_base;
2192  codec->time_base.num *= icodec->ticks_per_frame;
2193  codec->time_base.den *= 2;
2194  codec->ticks_per_frame = 2;
2195  }
2196  } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2197  && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2198  && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
2199  && strcmp(oc->oformat->name, "f4v")
2200  ) {
2201  if( copy_tb<0 && icodec->time_base.den
2202  && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
2203  && av_q2d(ist->st->time_base) < 1.0/500
2204  || copy_tb==0){
2205  codec->time_base = icodec->time_base;
2206  codec->time_base.num *= icodec->ticks_per_frame;
2207  }
2208  }
2209  if ( codec->codec_tag == AV_RL32("tmcd")
2210  && icodec->time_base.num < icodec->time_base.den
2211  && icodec->time_base.num > 0
2212  && 121LL*icodec->time_base.num > icodec->time_base.den) {
2213  codec->time_base = icodec->time_base;
2214  }
2215 
2216  if(ost->frame_rate.num)
2217  codec->time_base = av_inv_q(ost->frame_rate);
2218 
2219  av_reduce(&codec->time_base.num, &codec->time_base.den,
2220  codec->time_base.num, codec->time_base.den, INT_MAX);
2221 
2222  switch (codec->codec_type) {
2223  case AVMEDIA_TYPE_AUDIO:
2224  if (audio_volume != 256) {
2225  av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2226  exit(1);
2227  }
2228  codec->channel_layout = icodec->channel_layout;
2229  codec->sample_rate = icodec->sample_rate;
2230  codec->channels = icodec->channels;
2231  codec->frame_size = icodec->frame_size;
2232  codec->audio_service_type = icodec->audio_service_type;
2233  codec->block_align = icodec->block_align;
2234  if((codec->block_align == 1 || codec->block_align == 1152 || codec->block_align == 576) && codec->codec_id == AV_CODEC_ID_MP3)
2235  codec->block_align= 0;
2236  if(codec->codec_id == AV_CODEC_ID_AC3)
2237  codec->block_align= 0;
2238  break;
2239  case AVMEDIA_TYPE_VIDEO:
2240  codec->pix_fmt = icodec->pix_fmt;
2241  codec->width = icodec->width;
2242  codec->height = icodec->height;
2243  codec->has_b_frames = icodec->has_b_frames;
2244  if (!codec->sample_aspect_ratio.num) {
2245  codec->sample_aspect_ratio =
2246  ost->st->sample_aspect_ratio =
2248  ist->st->codec->sample_aspect_ratio.num ?
2249  ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2250  }
2251  ost->st->avg_frame_rate = ist->st->avg_frame_rate;
2252  break;
2253  case AVMEDIA_TYPE_SUBTITLE:
2254  codec->width = icodec->width;
2255  codec->height = icodec->height;
2256  break;
2257  case AVMEDIA_TYPE_DATA:
2259  break;
2260  default:
2261  abort();
2262  }
2263  } else {
2264  if (!ost->enc)
2265  ost->enc = avcodec_find_encoder(codec->codec_id);
2266  if (!ost->enc) {
2267  /* should only happen when a default codec is not present. */
2268  snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
2269  avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
2270  ret = AVERROR(EINVAL);
2271  goto dump_format;
2272  }
2273 
2274  if (ist)
2275  ist->decoding_needed++;
2276  ost->encoding_needed = 1;
2277 
2278  if (!ost->filter &&
2279  (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2280  codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
2281  FilterGraph *fg;
2282  fg = init_simple_filtergraph(ist, ost);
2283  if (configure_filtergraph(fg)) {
2284  av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2285  exit(1);
2286  }
2287  }
2288 
2289  if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2290  if (ost->filter && !ost->frame_rate.num)
2292  if (ist && !ost->frame_rate.num)
2293  ost->frame_rate = ist->framerate;
2294  if (ist && !ost->frame_rate.num)
2295  ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
2296 // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
2297  if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2299  ost->frame_rate = ost->enc->supported_framerates[idx];
2300  }
2301  }
2302 
2303  switch (codec->codec_type) {
2304  case AVMEDIA_TYPE_AUDIO:
2305  codec->sample_fmt = ost->filter->filter->inputs[0]->format;
2306  codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
2307  codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2309  codec->time_base = (AVRational){ 1, codec->sample_rate };
2310  break;
2311  case AVMEDIA_TYPE_VIDEO:
2312  codec->time_base = av_inv_q(ost->frame_rate);
2313  if (ost->filter && !(codec->time_base.num && codec->time_base.den))
2314  codec->time_base = ost->filter->filter->inputs[0]->time_base;
2315  if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
2317  av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
2318  "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
2319  }
2320  for (j = 0; j < ost->forced_kf_count; j++)
2321  ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
2323  codec->time_base);
2324 
2325  codec->width = ost->filter->filter->inputs[0]->w;
2326  codec->height = ost->filter->filter->inputs[0]->h;
2327  codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
2328  ost->frame_aspect_ratio ? // overridden by the -aspect cli option
2329  av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
2331  codec->pix_fmt = ost->filter->filter->inputs[0]->format;
2332 
2333  if (!icodec ||
2334  codec->width != icodec->width ||
2335  codec->height != icodec->height ||
2336  codec->pix_fmt != icodec->pix_fmt) {
2338  }
2339 
2340  if (ost->forced_keyframes) {
2341  if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
2344  if (ret < 0) {
2346  "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
2347  return ret;
2348  }
2353  } else {
2355  }
2356  }
2357  break;
2358  case AVMEDIA_TYPE_SUBTITLE:
2359  codec->time_base = (AVRational){1, 1000};
2360  if (!codec->width) {
2361  codec->width = input_streams[ost->source_index]->st->codec->width;
2362  codec->height = input_streams[ost->source_index]->st->codec->height;
2363  }
2364  break;
2365  default:
2366  abort();
2367  break;
2368  }
2369  /* two pass mode */
2370  if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
2371  char logfilename[1024];
2372  FILE *f;
2373 
2374  snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2375  ost->logfile_prefix ? ost->logfile_prefix :
2377  i);
2378  if (!strcmp(ost->enc->name, "libx264")) {
2379  av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2380  } else {
2381  if (codec->flags & CODEC_FLAG_PASS2) {
2382  char *logbuffer;
2383  size_t logbuffer_size;
2384  if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2385  av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2386  logfilename);
2387  exit(1);
2388  }
2389  codec->stats_in = logbuffer;
2390  }
2391  if (codec->flags & CODEC_FLAG_PASS1) {
2392  f = fopen(logfilename, "wb");
2393  if (!f) {
2394  av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2395  logfilename, strerror(errno));
2396  exit(1);
2397  }
2398  ost->logfile = f;
2399  }
2400  }
2401  }
2402  }
2403  }
2404 
2405  /* open each encoder */
2406  for (i = 0; i < nb_output_streams; i++) {
2407  ost = output_streams[i];
2408  if (ost->encoding_needed) {
2409  AVCodec *codec = ost->enc;
2410  AVCodecContext *dec = NULL;
2411 
2412  if ((ist = get_input_stream(ost)))
2413  dec = ist->st->codec;
2414  if (dec && dec->subtitle_header) {
2415  /* ASS code assumes this buffer is null terminated so add extra byte. */
2417  if (!ost->st->codec->subtitle_header) {
2418  ret = AVERROR(ENOMEM);
2419  goto dump_format;
2420  }
2421  memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2423  }
2424  if (!av_dict_get(ost->opts, "threads", NULL, 0))
2425  av_dict_set(&ost->opts, "threads", "auto", 0);
2426  if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
2427  if (ret == AVERROR_EXPERIMENTAL)
2428  abort_codec_experimental(codec, 1);
2429  snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2430  ost->file_index, ost->index);
2431  goto dump_format;
2432  }
2433  if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
2436  ost->st->codec->frame_size);
2437  assert_avoptions(ost->opts);
2438  if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2439  av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2440  " It takes bits/s as argument, not kbits/s\n");
2441  extra_size += ost->st->codec->extradata_size;
2442 
2443  if (ost->st->codec->me_threshold)
2444  input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
2445  } else {
2446  av_opt_set_dict(ost->st->codec, &ost->opts);
2447  }
2448  }
2449 
2450  /* init input streams */
2451  for (i = 0; i < nb_input_streams; i++)
2452  if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
2453  for (i = 0; i < nb_output_streams; i++) {
2454  ost = output_streams[i];
2455  avcodec_close(ost->st->codec);
2456  }
2457  goto dump_format;
2458  }
2459 
2460  /* discard unused programs */
2461  for (i = 0; i < nb_input_files; i++) {
2462  InputFile *ifile = input_files[i];
2463  for (j = 0; j < ifile->ctx->nb_programs; j++) {
2464  AVProgram *p = ifile->ctx->programs[j];
2465  int discard = AVDISCARD_ALL;
2466 
2467  for (k = 0; k < p->nb_stream_indexes; k++)
2468  if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2469  discard = AVDISCARD_DEFAULT;
2470  break;
2471  }
2472  p->discard = discard;
2473  }
2474  }
2475 
2476  /* open files and write file headers */
2477  for (i = 0; i < nb_output_files; i++) {
2478  oc = output_files[i]->ctx;
2479  oc->interrupt_callback = int_cb;
2480  if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
2481  char errbuf[128];
2482  const char *errbuf_ptr = errbuf;
2483  if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
2484  errbuf_ptr = strerror(AVUNERROR(ret));
2485  snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
2486  ret = AVERROR(EINVAL);
2487  goto dump_format;
2488  }
2489 // assert_avoptions(output_files[i]->opts);
2490  if (strcmp(oc->oformat->name, "rtp")) {
2491  want_sdp = 0;
2492  }
2493  }
2494 
2495  dump_format:
2496  /* dump the file output parameters - cannot be done before in case
2497  of stream copy */
2498  for (i = 0; i < nb_output_files; i++) {
2499  av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
2500  }
2501 
2502  /* dump the stream mapping */
2503  av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2504  for (i = 0; i < nb_input_streams; i++) {
2505  ist = input_streams[i];
2506 
2507  for (j = 0; j < ist->nb_filters; j++) {
2508  if (ist->filters[j]->graph->graph_desc) {
2509  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
2510  ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2511  ist->filters[j]->name);
2512  if (nb_filtergraphs > 1)
2513  av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2514  av_log(NULL, AV_LOG_INFO, "\n");
2515  }
2516  }
2517  }
2518 
2519  for (i = 0; i < nb_output_streams; i++) {
2520  ost = output_streams[i];
2521 
2522  if (ost->attachment_filename) {
2523  /* an attached file */
2524  av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2525  ost->attachment_filename, ost->file_index, ost->index);
2526  continue;
2527  }
2528 
2529  if (ost->filter && ost->filter->graph->graph_desc) {
2530  /* output from a complex graph */
2531  av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
2532  if (nb_filtergraphs > 1)
2533  av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2534 
2535  av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2536  ost->index, ost->enc ? ost->enc->name : "?");
2537  continue;
2538  }
2539 
2540  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2541  input_streams[ost->source_index]->file_index,
2542  input_streams[ost->source_index]->st->index,
2543  ost->file_index,
2544  ost->index);
2545  if (ost->sync_ist != input_streams[ost->source_index])
2546  av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2547  ost->sync_ist->file_index,
2548  ost->sync_ist->st->index);
2549  if (ost->stream_copy)
2550  av_log(NULL, AV_LOG_INFO, " (copy)");
2551  else
2552  av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
2553  input_streams[ost->source_index]->dec->name : "?",
2554  ost->enc ? ost->enc->name : "?");
2555  av_log(NULL, AV_LOG_INFO, "\n");
2556  }
2557 
2558  if (ret) {
2559  av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2560  return ret;
2561  }
2562 
2563  if (want_sdp) {
2564  print_sdp();
2565  }
2566 
2567  return 0;
2568 }
2569 
2570 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
2571 static int need_output(void)
2572 {
2573  int i;
2574 
2575  for (i = 0; i < nb_output_streams; i++) {
2576  OutputStream *ost = output_streams[i];
2577  OutputFile *of = output_files[ost->file_index];
2578  AVFormatContext *os = output_files[ost->file_index]->ctx;
2579 
2580  if (ost->finished ||
2581  (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2582  continue;
2583  if (ost->frame_number >= ost->max_frames) {
2584  int j;
2585  for (j = 0; j < of->ctx->nb_streams; j++)
2586  close_output_stream(output_streams[of->ost_index + j]);
2587  continue;
2588  }
2589 
2590  return 1;
2591  }
2592 
2593  return 0;
2594 }
2595 
2596 /**
2597  * Select the output stream to process.
2598  *
2599  * @return selected output stream, or NULL if none available
2600  */
2602 {
2603  int i;
2604  int64_t opts_min = INT64_MAX;
2605  OutputStream *ost_min = NULL;
2606 
2607  for (i = 0; i < nb_output_streams; i++) {
2608  OutputStream *ost = output_streams[i];
2609  int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
2610  AV_TIME_BASE_Q);
2611  if (!ost->unavailable && !ost->finished && opts < opts_min) {
2612  opts_min = opts;
2613  ost_min = ost;
2614  }
2615  }
2616  return ost_min;
2617 }
2618 
2620 {
2621  int i, ret, key;
2622  static int64_t last_time;
2623  if (received_nb_signals)
2624  return AVERROR_EXIT;
2625  /* read_key() returns 0 on EOF */
2626  if(cur_time - last_time >= 100000 && !run_as_daemon){
2627  key = read_key();
2628  last_time = cur_time;
2629  }else
2630  key = -1;
2631  if (key == 'q')
2632  return AVERROR_EXIT;
2633  if (key == '+') av_log_set_level(av_log_get_level()+10);
2634  if (key == '-') av_log_set_level(av_log_get_level()-10);
2635  if (key == 's') qp_hist ^= 1;
2636  if (key == 'h'){
2637  if (do_hex_dump){
2638  do_hex_dump = do_pkt_dump = 0;
2639  } else if(do_pkt_dump){
2640  do_hex_dump = 1;
2641  } else
2642  do_pkt_dump = 1;
2644  }
2645  if (key == 'c' || key == 'C'){
2646  char buf[4096], target[64], command[256], arg[256] = {0};
2647  double time;
2648  int k, n = 0;
2649  fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
2650  i = 0;
2651  while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
2652  if (k > 0)
2653  buf[i++] = k;
2654  buf[i] = 0;
2655  if (k > 0 &&
2656  (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
2657  av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
2658  target, time, command, arg);
2659  for (i = 0; i < nb_filtergraphs; i++) {
2660  FilterGraph *fg = filtergraphs[i];
2661  if (fg->graph) {
2662  if (time < 0) {
2663  ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
2664  key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
2665  fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
2666  } else {
2667  ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
2668  }
2669  }
2670  }
2671  } else {
2673  "Parse error, at least 3 arguments were expected, "
2674  "only %d given in string '%s'\n", n, buf);
2675  }
2676  }
2677  if (key == 'd' || key == 'D'){
2678  int debug=0;
2679  if(key == 'D') {
2680  debug = input_streams[0]->st->codec->debug<<1;
2681  if(!debug) debug = 1;
2682  while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
2683  debug += debug;
2684  }else
2685  if(scanf("%d", &debug)!=1)
2686  fprintf(stderr,"error parsing debug value\n");
2687  for(i=0;i<nb_input_streams;i++) {
2688  input_streams[i]->st->codec->debug = debug;
2689  }
2690  for(i=0;i<nb_output_streams;i++) {
2691  OutputStream *ost = output_streams[i];
2692  ost->st->codec->debug = debug;
2693  }
2694  if(debug) av_log_set_level(AV_LOG_DEBUG);
2695  fprintf(stderr,"debug=%d\n", debug);
2696  }
2697  if (key == '?'){
2698  fprintf(stderr, "key function\n"
2699  "? show this help\n"
2700  "+ increase verbosity\n"
2701  "- decrease verbosity\n"
2702  "c Send command to filtergraph\n"
2703  "D cycle through available debug modes\n"
2704  "h dump packets/hex press to cycle through the 3 states\n"
2705  "q quit\n"
2706  "s Show QP histogram\n"
2707  );
2708  }
2709  return 0;
2710 }
2711 
2712 #if HAVE_PTHREADS
2713 static void *input_thread(void *arg)
2714 {
2715  InputFile *f = arg;
2716  int ret = 0;
2717 
2718  while (!transcoding_finished && ret >= 0) {
2719  AVPacket pkt;
2720  ret = av_read_frame(f->ctx, &pkt);
2721 
2722  if (ret == AVERROR(EAGAIN)) {
2723  av_usleep(10000);
2724  ret = 0;
2725  continue;
2726  } else if (ret < 0)
2727  break;
2728 
2729  pthread_mutex_lock(&f->fifo_lock);
2730  while (!av_fifo_space(f->fifo))
2731  pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
2732 
2733  av_dup_packet(&pkt);
2734  av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2735 
2736  pthread_mutex_unlock(&f->fifo_lock);
2737  }
2738 
2739  f->finished = 1;
2740  return NULL;
2741 }
2742 
2743 static void free_input_threads(void)
2744 {
2745  int i;
2746 
2747  if (nb_input_files == 1)
2748  return;
2749 
2750  transcoding_finished = 1;
2751 
2752  for (i = 0; i < nb_input_files; i++) {
2753  InputFile *f = input_files[i];
2754  AVPacket pkt;
2755 
2756  if (!f->fifo || f->joined)
2757  continue;
2758 
2759  pthread_mutex_lock(&f->fifo_lock);
2760  while (av_fifo_size(f->fifo)) {
2761  av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2762  av_free_packet(&pkt);
2763  }
2764  pthread_cond_signal(&f->fifo_cond);
2765  pthread_mutex_unlock(&f->fifo_lock);
2766 
2767  pthread_join(f->thread, NULL);
2768  f->joined = 1;
2769 
2770  while (av_fifo_size(f->fifo)) {
2771  av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2772  av_free_packet(&pkt);
2773  }
2774  av_fifo_free(f->fifo);
2775  }
2776 }
2777 
2778 static int init_input_threads(void)
2779 {
2780  int i, ret;
2781 
2782  if (nb_input_files == 1)
2783  return 0;
2784 
2785  for (i = 0; i < nb_input_files; i++) {
2786  InputFile *f = input_files[i];
2787 
2788  if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2789  return AVERROR(ENOMEM);
2790 
2791  pthread_mutex_init(&f->fifo_lock, NULL);
2792  pthread_cond_init (&f->fifo_cond, NULL);
2793 
2794  if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2795  return AVERROR(ret);
2796  }
2797  return 0;
2798 }
2799 
2800 static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
2801 {
2802  int ret = 0;
2803 
2804  pthread_mutex_lock(&f->fifo_lock);
2805 
2806  if (av_fifo_size(f->fifo)) {
2807  av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2808  pthread_cond_signal(&f->fifo_cond);
2809  } else {
2810  if (f->finished)
2811  ret = AVERROR_EOF;
2812  else
2813  ret = AVERROR(EAGAIN);
2814  }
2815 
2816  pthread_mutex_unlock(&f->fifo_lock);
2817 
2818  return ret;
2819 }
2820 #endif
2821 
2823 {
2824 #if HAVE_PTHREADS
2825  if (nb_input_files > 1)
2826  return get_input_packet_mt(f, pkt);
2827 #endif
2828  return av_read_frame(f->ctx, pkt);
2829 }
2830 
2831 static int got_eagain(void)
2832 {
2833  int i;
2834  for (i = 0; i < nb_output_streams; i++)
2835  if (output_streams[i]->unavailable)
2836  return 1;
2837  return 0;
2838 }
2839 
2840 static void reset_eagain(void)
2841 {
2842  int i;
2843  for (i = 0; i < nb_input_files; i++)
2844  input_files[i]->eagain = 0;
2845  for (i = 0; i < nb_output_streams; i++)
2846  output_streams[i]->unavailable = 0;
2847 }
2848 
2849 /*
2850  * Return
2851  * - 0 -- one packet was read and processed
2852  * - AVERROR(EAGAIN) -- no packets were available for selected file,
2853  * this function should be called again
2854  * - AVERROR_EOF -- this function should not be called again
2855  */
2856 static int process_input(int file_index)
2857 {
2858  InputFile *ifile = input_files[file_index];
2859  AVFormatContext *is;
2860  InputStream *ist;
2861  AVPacket pkt;
2862  int ret, i, j;
2863 
2864  is = ifile->ctx;
2865  ret = get_input_packet(ifile, &pkt);
2866 
2867  if (ret == AVERROR(EAGAIN)) {
2868  ifile->eagain = 1;
2869  return ret;
2870  }
2871  if (ret < 0) {
2872  if (ret != AVERROR_EOF) {
2873  print_error(is->filename, ret);
2874  if (exit_on_error)
2875  exit(1);
2876  }
2877  ifile->eof_reached = 1;
2878 
2879  for (i = 0; i < ifile->nb_streams; i++) {
2880  ist = input_streams[ifile->ist_index + i];
2881  if (ist->decoding_needed)
2882  output_packet(ist, NULL);
2883 
2884  /* mark all outputs that don't go through lavfi as finished */
2885  for (j = 0; j < nb_output_streams; j++) {
2886  OutputStream *ost = output_streams[j];
2887 
2888  if (ost->source_index == ifile->ist_index + i &&
2889  (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
2890  close_output_stream(ost);
2891  }
2892  }
2893 
2894  return AVERROR(EAGAIN);
2895  }
2896 
2897  reset_eagain();
2898 
2899  if (do_pkt_dump) {
2901  is->streams[pkt.stream_index]);
2902  }
2903  /* the following test is needed in case new streams appear
2904  dynamically in stream : we ignore them */
2905  if (pkt.stream_index >= ifile->nb_streams) {
2906  report_new_stream(file_index, &pkt);
2907  goto discard_packet;
2908  }
2909 
2910  ist = input_streams[ifile->ist_index + pkt.stream_index];
2911  if (ist->discard)
2912  goto discard_packet;
2913 
2914  if (debug_ts) {
2915  av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
2916  "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
2920  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
2921  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
2922  av_ts2str(input_files[ist->file_index]->ts_offset),
2923  av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
2924  }
2925 
2926  if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
2927  int64_t stime, stime2;
2928  // Correcting starttime based on the enabled streams
2929  // FIXME this ideally should be done before the first use of starttime but we do not know which are the enabled streams at that point.
2930  // so we instead do it here as part of discontinuity handling
2931  if ( ist->next_dts == AV_NOPTS_VALUE
2932  && ifile->ts_offset == -is->start_time
2933  && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2934  int64_t new_start_time = INT64_MAX;
2935  for (i=0; i<is->nb_streams; i++) {
2936  AVStream *st = is->streams[i];
2937  if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
2938  continue;
2939  new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
2940  }
2941  if (new_start_time > is->start_time) {
2942  av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
2943  ifile->ts_offset = -new_start_time;
2944  }
2945  }
2946 
2947  stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
2948  stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
2949  ist->wrap_correction_done = 1;
2950 
2951  if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
2952  pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
2953  ist->wrap_correction_done = 0;
2954  }
2955  if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
2956  pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
2957  ist->wrap_correction_done = 0;
2958  }
2959  }
2960 
2961  if (pkt.dts != AV_NOPTS_VALUE)
2962  pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2963  if (pkt.pts != AV_NOPTS_VALUE)
2964  pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2965 
2966  if (pkt.pts != AV_NOPTS_VALUE)
2967  pkt.pts *= ist->ts_scale;
2968  if (pkt.dts != AV_NOPTS_VALUE)
2969  pkt.dts *= ist->ts_scale;
2970 
2971  if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
2972  !copy_ts) {
2973  int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2974  int64_t delta = pkt_dts - ist->next_dts;
2975  if (is->iformat->flags & AVFMT_TS_DISCONT) {
2976  if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
2977  (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
2979  pkt_dts+1<ist->pts){
2980  ifile->ts_offset -= delta;
2982  "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2983  delta, ifile->ts_offset);
2984  pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2985  if (pkt.pts != AV_NOPTS_VALUE)
2986  pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2987  }
2988  } else {
2989  if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
2991  ) {
2992  av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
2993  pkt.dts = AV_NOPTS_VALUE;
2994  }
2995  if (pkt.pts != AV_NOPTS_VALUE){
2996  int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
2997  delta = pkt_pts - ist->next_dts;
2998  if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3000  ) {
3001  av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3002  pkt.pts = AV_NOPTS_VALUE;
3003  }
3004  }
3005  }
3006  }
3007 
3008  if (debug_ts) {
3009  av_log(NULL, AV_LOG_INFO, "demuxer+ffmpeg -> ist_index:%d type:%s pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%s off_time:%s\n",
3011  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3012  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3013  av_ts2str(input_files[ist->file_index]->ts_offset),
3014  av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3015  }
3016 
3017  sub2video_heartbeat(ist, pkt.pts);
3018 
3019  ret = output_packet(ist, &pkt);
3020  if (ret < 0) {
3021  char buf[128];
3022  av_strerror(ret, buf, sizeof(buf));
3023  av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
3024  ist->file_index, ist->st->index, buf);
3025  if (exit_on_error)
3026  exit(1);
3027  }
3028 
3029 discard_packet:
3030  av_free_packet(&pkt);
3031 
3032  return 0;
3033 }
3034 
3035 /**
3036  * Perform a step of transcoding for the specified filter graph.
3037  *
3038  * @param[in] graph filter graph to consider
3039  * @param[out] best_ist input stream where a frame would allow to continue
3040  * @return 0 for success, <0 for error
3041  */
3042 static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
3043 {
3044  int i, ret;
3045  int nb_requests, nb_requests_max = 0;
3046  InputFilter *ifilter;
3047  InputStream *ist;
3048 
3049  *best_ist = NULL;
3050  ret = avfilter_graph_request_oldest(graph->graph);
3051  if (ret >= 0)
3052  return reap_filters();
3053 
3054  if (ret == AVERROR_EOF) {
3055  ret = reap_filters();
3056  for (i = 0; i < graph->nb_outputs; i++)
3057  close_output_stream(graph->outputs[i]->ost);
3058  return ret;
3059  }
3060  if (ret != AVERROR(EAGAIN))
3061  return ret;
3062 
3063  for (i = 0; i < graph->nb_inputs; i++) {
3064  ifilter = graph->inputs[i];
3065  ist = ifilter->ist;
3066  if (input_files[ist->file_index]->eagain ||
3067  input_files[ist->file_index]->eof_reached)
3068  continue;
3069  nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
3070  if (nb_requests > nb_requests_max) {
3071  nb_requests_max = nb_requests;
3072  *best_ist = ist;
3073  }
3074  }
3075 
3076  if (!*best_ist)
3077  for (i = 0; i < graph->nb_outputs; i++)
3078  graph->outputs[i]->ost->unavailable = 1;
3079 
3080  return 0;
3081 }
3082 
3083 /**
3084  * Run a single step of transcoding.
3085  *
3086  * @return 0 for success, <0 for error
3087  */
3088 static int transcode_step(void)
3089 {
3090  OutputStream *ost;
3091  InputStream *ist;
3092  int ret;
3093 
3094  ost = choose_output();
3095  if (!ost) {
3096  if (got_eagain()) {
3097  reset_eagain();
3098  av_usleep(10000);
3099  return 0;
3100  }
3101  av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
3102  return AVERROR_EOF;
3103  }
3104 
3105  if (ost->filter) {
3106  if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
3107  return ret;
3108  if (!ist)
3109  return 0;
3110  } else {
3111  av_assert0(ost->source_index >= 0);
3112  ist = input_streams[ost->source_index];
3113  }
3114 
3115  ret = process_input(ist->file_index);
3116  if (ret == AVERROR(EAGAIN)) {
3117  if (input_files[ist->file_index]->eagain)
3118  ost->unavailable = 1;
3119  return 0;
3120  }
3121  if (ret < 0)
3122  return ret == AVERROR_EOF ? 0 : ret;
3123 
3124  return reap_filters();
3125 }
3126 
3127 /*
3128  * The following code is the main loop of the file converter
3129  */
3130 static int transcode(void)
3131 {
3132  int ret, i;
3133  AVFormatContext *os;
3134  OutputStream *ost;
3135  InputStream *ist;
3136  int64_t timer_start;
3137 
3138  ret = transcode_init();
3139  if (ret < 0)
3140  goto fail;
3141 
3142  if (stdin_interaction) {
3143  av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3144  }
3145 
3146  timer_start = av_gettime();
3147 
3148 #if HAVE_PTHREADS
3149  if ((ret = init_input_threads()) < 0)
3150  goto fail;
3151 #endif
3152 
3153  while (!received_sigterm) {
3154  int64_t cur_time= av_gettime();
3155 
3156  /* if 'q' pressed, exits */
3157  if (stdin_interaction)
3158  if (check_keyboard_interaction(cur_time) < 0)
3159  break;
3160 
3161  /* check if there's any stream where output is still needed */
3162  if (!need_output()) {
3163  av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
3164  break;
3165  }
3166 
3167  ret = transcode_step();
3168  if (ret < 0) {
3169  if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
3170  continue;
3171 
3172  av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
3173  break;
3174  }
3175 
3176  /* dump report by using the output first video and audio streams */
3177  print_report(0, timer_start, cur_time);
3178  }
3179 #if HAVE_PTHREADS
3181 #endif
3182 
3183  /* at the end of stream, we must flush the decoder buffers */
3184  for (i = 0; i < nb_input_streams; i++) {
3185  ist = input_streams[i];
3186  if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3187  output_packet(ist, NULL);
3188  }
3189  }
3190  flush_encoders();
3191 
3192  term_exit();
3193 
3194  /* write the trailer if needed and close file */
3195  for (i = 0; i < nb_output_files; i++) {
3196  os = output_files[i]->ctx;
3197  av_write_trailer(os);
3198  }
3199 
3200  /* dump report by using the first video and audio streams */
3201  print_report(1, timer_start, av_gettime());
3202 
3203  /* close each encoder */
3204  for (i = 0; i < nb_output_streams; i++) {
3205  ost = output_streams[i];
3206  if (ost->encoding_needed) {
3207  av_freep(&ost->st->codec->stats_in);
3208  avcodec_close(ost->st->codec);
3209  }
3210  }
3211 
3212  /* close each decoder */
3213  for (i = 0; i < nb_input_streams; i++) {
3214  ist = input_streams[i];
3215  if (ist->decoding_needed) {
3216  avcodec_close(ist->st->codec);
3217  }
3218  }
3219 
3220  /* finished ! */
3221  ret = 0;
3222 
3223  fail:
3224 #if HAVE_PTHREADS
3226 #endif
3227 
3228  if (output_streams) {
3229  for (i = 0; i < nb_output_streams; i++) {
3230  ost = output_streams[i];
3231  if (ost) {
3232  if (ost->stream_copy)
3233  av_freep(&ost->st->codec->extradata);
3234  if (ost->logfile) {
3235  fclose(ost->logfile);
3236  ost->logfile = NULL;
3237  }
3238  av_freep(&ost->st->codec->subtitle_header);
3239  av_free(ost->forced_kf_pts);
3240  av_dict_free(&ost->opts);
3241  av_dict_free(&ost->swr_opts);
3242  av_dict_free(&ost->resample_opts);
3243  }
3244  }
3245  }
3246  return ret;
3247 }
3248 
3249 
3250 static int64_t getutime(void)
3251 {
3252 #if HAVE_GETRUSAGE
3253  struct rusage rusage;
3254 
3255  getrusage(RUSAGE_SELF, &rusage);
3256  return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3257 #elif HAVE_GETPROCESSTIMES
3258  HANDLE proc;
3259  FILETIME c, e, k, u;
3260  proc = GetCurrentProcess();
3261  GetProcessTimes(proc, &c, &e, &k, &u);
3262  return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3263 #else
3264  return av_gettime();
3265 #endif
3266 }
3267 
3268 static int64_t getmaxrss(void)
3269 {
3270 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3271  struct rusage rusage;
3272  getrusage(RUSAGE_SELF, &rusage);
3273  return (int64_t)rusage.ru_maxrss * 1024;
3274 #elif HAVE_GETPROCESSMEMORYINFO
3275  HANDLE proc;
3276  PROCESS_MEMORY_COUNTERS memcounters;
3277  proc = GetCurrentProcess();
3278  memcounters.cb = sizeof(memcounters);
3279  GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
3280  return memcounters.PeakPagefileUsage;
3281 #else
3282  return 0;
3283 #endif
3284 }
3285 
3286 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
3287 {
3288 }
3289 
3290 int main(int argc, char **argv)
3291 {
3292  int ret;
3293  int64_t ti;
3294 
3295  atexit(exit_program);
3296 
3297  setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
3298 
3300  parse_loglevel(argc, argv, options);
3301 
3302  if(argc>1 && !strcmp(argv[1], "-d")){
3303  run_as_daemon=1;
3305  argc--;
3306  argv++;
3307  }
3308 
3310 #if CONFIG_AVDEVICE
3312 #endif
3314  av_register_all();
3316 
3317  show_banner(argc, argv, options);
3318 
3319  term_init();
3320 
3321  /* parse options and open all input/output files */
3322  ret = ffmpeg_parse_options(argc, argv);
3323  if (ret < 0)
3324  exit(1);
3325 
3326  if (nb_output_files <= 0 && nb_input_files == 0) {
3327  show_usage();
3328  av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
3329  exit(1);
3330  }
3331 
3332  /* file converter / grab */
3333  if (nb_output_files <= 0) {
3334  av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
3335  exit(1);
3336  }
3337 
3338 // if (nb_input_files == 0) {
3339 // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
3340 // exit(1);
3341 // }
3342 
3343  current_time = ti = getutime();
3344  if (transcode() < 0)
3345  exit(1);
3346  ti = getutime() - ti;
3347  if (do_benchmark) {
3348  printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3349  }
3350 
3351  exit(received_nb_signals ? 255 : 0);
3352  return 0;
3353 }