FFmpeg  1.2.12
ffmpeg.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2000-2003 Fabrice Bellard
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
26 #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"
44 #include "libswresample/swresample.h"
45 #include "libavutil/opt.h"
46 #include "libavutil/channel_layout.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"
67 # include "libavfilter/avfiltergraph.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 */
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 
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 (ist->framerate.num) {
1914  int64_t next_dts = av_rescale_q(ist->next_dts, AV_TIME_BASE_Q, av_inv_q(ist->framerate));
1915  ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), AV_TIME_BASE_Q);
1916  } else if (pkt->duration) {
1917  ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
1918  } else if(ist->st->codec->time_base.num != 0) {
1919  int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
1920  ist->next_dts += ((int64_t)AV_TIME_BASE *
1921  ist->st->codec->time_base.num * ticks) /
1922  ist->st->codec->time_base.den;
1923  }
1924  break;
1925  }
1926  ist->pts = ist->dts;
1927  ist->next_pts = ist->next_dts;
1928  }
1929  for (i = 0; pkt && i < nb_output_streams; i++) {
1930  OutputStream *ost = output_streams[i];
1931 
1932  if (!check_output_constraints(ist, ost) || ost->encoding_needed)
1933  continue;
1934 
1935  do_streamcopy(ist, ost, pkt);
1936  }
1937 
1938  return 0;
1939 }
1940 
1941 static void print_sdp(void)
1942 {
1943  char sdp[16384];
1944  int i;
1945  AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
1946 
1947  if (!avc)
1948  exit(1);
1949  for (i = 0; i < nb_output_files; i++)
1950  avc[i] = output_files[i]->ctx;
1951 
1952  av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
1953  printf("SDP:\n%s\n", sdp);
1954  fflush(stdout);
1955  av_freep(&avc);
1956 }
1957 
1958 static int init_input_stream(int ist_index, char *error, int error_len)
1959 {
1960  int ret;
1961  InputStream *ist = input_streams[ist_index];
1962 
1963  if (ist->decoding_needed) {
1964  AVCodec *codec = ist->dec;
1965  if (!codec) {
1966  snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
1967  avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
1968  return AVERROR(EINVAL);
1969  }
1970 
1971  ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !(FF_API_DEINTERLACE && do_deinterlace);
1972  if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
1975  ist->st->codec->opaque = &ist->buffer_pool;
1976  }
1977 
1978  if (!av_dict_get(ist->opts, "threads", NULL, 0))
1979  av_dict_set(&ist->opts, "threads", "auto", 0);
1980  if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
1981  if (ret == AVERROR_EXPERIMENTAL)
1982  abort_codec_experimental(codec, 0);
1983  snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
1984  ist->file_index, ist->st->index);
1985  return ret;
1986  }
1987  assert_avoptions(ist->opts);
1988  }
1989 
1990  ist->next_pts = AV_NOPTS_VALUE;
1991  ist->next_dts = AV_NOPTS_VALUE;
1992  ist->is_start = 1;
1993 
1994  return 0;
1995 }
1996 
1998 {
1999  if (ost->source_index >= 0)
2000  return input_streams[ost->source_index];
2001  return NULL;
2002 }
2003 
2004 static int compare_int64(const void *a, const void *b)
2005 {
2006  int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
2007  return va < vb ? -1 : va > vb ? +1 : 0;
2008 }
2009 
2010 static void parse_forced_key_frames(char *kf, OutputStream *ost,
2011  AVCodecContext *avctx)
2012 {
2013  char *p;
2014  int n = 1, i, size, index = 0;
2015  int64_t t, *pts;
2016 
2017  for (p = kf; *p; p++)
2018  if (*p == ',')
2019  n++;
2020  size = n;
2021  pts = av_malloc(sizeof(*pts) * size);
2022  if (!pts) {
2023  av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
2024  exit(1);
2025  }
2026 
2027  p = kf;
2028  for (i = 0; i < n; i++) {
2029  char *next = strchr(p, ',');
2030 
2031  if (next)
2032  *next++ = 0;
2033 
2034  if (!memcmp(p, "chapters", 8)) {
2035 
2036  AVFormatContext *avf = output_files[ost->file_index]->ctx;
2037  int j;
2038 
2039  if (avf->nb_chapters > INT_MAX - size ||
2040  !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
2041  sizeof(*pts)))) {
2043  "Could not allocate forced key frames array.\n");
2044  exit(1);
2045  }
2046  t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
2047  t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2048 
2049  for (j = 0; j < avf->nb_chapters; j++) {
2050  AVChapter *c = avf->chapters[j];
2051  av_assert1(index < size);
2052  pts[index++] = av_rescale_q(c->start, c->time_base,
2053  avctx->time_base) + t;
2054  }
2055 
2056  } else {
2057 
2058  t = parse_time_or_die("force_key_frames", p, 1);
2059  av_assert1(index < size);
2060  pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
2061 
2062  }
2063 
2064  p = next;
2065  }
2066 
2067  av_assert0(index == size);
2068  qsort(pts, size, sizeof(*pts), compare_int64);
2069  ost->forced_kf_count = size;
2070  ost->forced_kf_pts = pts;
2071 }
2072 
2073 static void report_new_stream(int input_index, AVPacket *pkt)
2074 {
2075  InputFile *file = input_files[input_index];
2076  AVStream *st = file->ctx->streams[pkt->stream_index];
2077 
2078  if (pkt->stream_index < file->nb_streams_warn)
2079  return;
2080  av_log(file->ctx, AV_LOG_WARNING,
2081  "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
2083  input_index, pkt->stream_index,
2084  pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
2085  file->nb_streams_warn = pkt->stream_index + 1;
2086 }
2087 
2088 static int transcode_init(void)
2089 {
2090  int ret = 0, i, j, k;
2091  AVFormatContext *oc;
2092  AVCodecContext *codec;
2093  OutputStream *ost;
2094  InputStream *ist;
2095  char error[1024] = {0};
2096  int want_sdp = 1;
2097 
2098  /* init framerate emulation */
2099  for (i = 0; i < nb_input_files; i++) {
2100  InputFile *ifile = input_files[i];
2101  if (ifile->rate_emu)
2102  for (j = 0; j < ifile->nb_streams; j++)
2103  input_streams[j + ifile->ist_index]->start = av_gettime();
2104  }
2105 
2106  /* output stream init */
2107  for (i = 0; i < nb_output_files; i++) {
2108  oc = output_files[i]->ctx;
2109  if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
2110  av_dump_format(oc, i, oc->filename, 1);
2111  av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
2112  return AVERROR(EINVAL);
2113  }
2114  }
2115 
2116  /* init complex filtergraphs */
2117  for (i = 0; i < nb_filtergraphs; i++)
2118  if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
2119  return ret;
2120 
2121  /* for each output stream, we compute the right encoding parameters */
2122  for (i = 0; i < nb_output_streams; i++) {
2123  AVCodecContext *icodec = NULL;
2124  ost = output_streams[i];
2125  oc = output_files[ost->file_index]->ctx;
2126  ist = get_input_stream(ost);
2127 
2128  if (ost->attachment_filename)
2129  continue;
2130 
2131  codec = ost->st->codec;
2132 
2133  if (ist) {
2134  icodec = ist->st->codec;
2135 
2136  ost->st->disposition = ist->st->disposition;
2137  codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
2139  }
2140 
2141  if (ost->stream_copy) {
2142  uint64_t extra_size;
2143 
2144  av_assert0(ist && !ost->filter);
2145 
2146  extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
2147 
2148  if (extra_size > INT_MAX) {
2149  return AVERROR(EINVAL);
2150  }
2151 
2152  /* if stream_copy is selected, no need to decode or encode */
2153  codec->codec_id = icodec->codec_id;
2154  codec->codec_type = icodec->codec_type;
2155 
2156  if (!codec->codec_tag) {
2157  unsigned int codec_tag;
2158  if (!oc->oformat->codec_tag ||
2159  av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
2160  !av_codec_get_tag2(oc->oformat->codec_tag, icodec->codec_id, &codec_tag))
2161  codec->codec_tag = icodec->codec_tag;
2162  }
2163 
2164  codec->bit_rate = icodec->bit_rate;
2165  codec->rc_max_rate = icodec->rc_max_rate;
2166  codec->rc_buffer_size = icodec->rc_buffer_size;
2167  codec->field_order = icodec->field_order;
2168  codec->extradata = av_mallocz(extra_size);
2169  if (!codec->extradata) {
2170  return AVERROR(ENOMEM);
2171  }
2172  memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
2173  codec->extradata_size= icodec->extradata_size;
2175 
2176  codec->time_base = ist->st->time_base;
2177  /*
2178  * Avi is a special case here because it supports variable fps but
2179  * having the fps and timebase differe significantly adds quite some
2180  * overhead
2181  */
2182  if(!strcmp(oc->oformat->name, "avi")) {
2183  if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
2184  && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
2185  && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
2186  && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
2187  || copy_tb==2){
2188  codec->time_base.num = ist->st->r_frame_rate.den;
2189  codec->time_base.den = 2*ist->st->r_frame_rate.num;
2190  codec->ticks_per_frame = 2;
2191  } else if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
2192  && av_q2d(ist->st->time_base) < 1.0/500
2193  || copy_tb==0){
2194  codec->time_base = icodec->time_base;
2195  codec->time_base.num *= icodec->ticks_per_frame;
2196  codec->time_base.den *= 2;
2197  codec->ticks_per_frame = 2;
2198  }
2199  } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
2200  && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
2201  && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
2202  && strcmp(oc->oformat->name, "f4v")
2203  ) {
2204  if( copy_tb<0 && icodec->time_base.den
2205  && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
2206  && av_q2d(ist->st->time_base) < 1.0/500
2207  || copy_tb==0){
2208  codec->time_base = icodec->time_base;
2209  codec->time_base.num *= icodec->ticks_per_frame;
2210  }
2211  }
2212  if ( codec->codec_tag == AV_RL32("tmcd")
2213  && icodec->time_base.num < icodec->time_base.den
2214  && icodec->time_base.num > 0
2215  && 121LL*icodec->time_base.num > icodec->time_base.den) {
2216  codec->time_base = icodec->time_base;
2217  }
2218 
2219  if (ist && !ost->frame_rate.num)
2220  ost->frame_rate = ist->framerate;
2221  if(ost->frame_rate.num)
2222  codec->time_base = av_inv_q(ost->frame_rate);
2223 
2224  av_reduce(&codec->time_base.num, &codec->time_base.den,
2225  codec->time_base.num, codec->time_base.den, INT_MAX);
2226 
2227  switch (codec->codec_type) {
2228  case AVMEDIA_TYPE_AUDIO:
2229  if (audio_volume != 256) {
2230  av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
2231  exit(1);
2232  }
2233  codec->channel_layout = icodec->channel_layout;
2234  codec->sample_rate = icodec->sample_rate;
2235  codec->channels = icodec->channels;
2236  codec->frame_size = icodec->frame_size;
2237  codec->audio_service_type = icodec->audio_service_type;
2238  codec->block_align = icodec->block_align;
2239  if((codec->block_align == 1 || codec->block_align == 1152 || codec->block_align == 576) && codec->codec_id == AV_CODEC_ID_MP3)
2240  codec->block_align= 0;
2241  if(codec->codec_id == AV_CODEC_ID_AC3)
2242  codec->block_align= 0;
2243  break;
2244  case AVMEDIA_TYPE_VIDEO:
2245  codec->pix_fmt = icodec->pix_fmt;
2246  codec->width = icodec->width;
2247  codec->height = icodec->height;
2248  codec->has_b_frames = icodec->has_b_frames;
2249  if (!codec->sample_aspect_ratio.num) {
2250  codec->sample_aspect_ratio =
2251  ost->st->sample_aspect_ratio =
2253  ist->st->codec->sample_aspect_ratio.num ?
2254  ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
2255  }
2256  ost->st->avg_frame_rate = ist->st->avg_frame_rate;
2257  break;
2258  case AVMEDIA_TYPE_SUBTITLE:
2259  codec->width = icodec->width;
2260  codec->height = icodec->height;
2261  break;
2262  case AVMEDIA_TYPE_DATA:
2264  break;
2265  default:
2266  abort();
2267  }
2268  } else {
2269  if (!ost->enc)
2270  ost->enc = avcodec_find_encoder(codec->codec_id);
2271  if (!ost->enc) {
2272  /* should only happen when a default codec is not present. */
2273  snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
2274  avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
2275  ret = AVERROR(EINVAL);
2276  goto dump_format;
2277  }
2278 
2279  if (ist)
2280  ist->decoding_needed++;
2281  ost->encoding_needed = 1;
2282 
2283  if (!ost->filter &&
2284  (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
2285  codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
2286  FilterGraph *fg;
2287  fg = init_simple_filtergraph(ist, ost);
2288  if (configure_filtergraph(fg)) {
2289  av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
2290  exit(1);
2291  }
2292  }
2293 
2294  if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
2295  if (ost->filter && !ost->frame_rate.num)
2297  if (ist && !ost->frame_rate.num)
2298  ost->frame_rate = ist->framerate;
2299  if (ist && !ost->frame_rate.num)
2300  ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
2301 // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
2302  if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
2304  ost->frame_rate = ost->enc->supported_framerates[idx];
2305  }
2306  }
2307 
2308  switch (codec->codec_type) {
2309  case AVMEDIA_TYPE_AUDIO:
2310  codec->sample_fmt = ost->filter->filter->inputs[0]->format;
2311  codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
2312  codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
2314  codec->time_base = (AVRational){ 1, codec->sample_rate };
2315  break;
2316  case AVMEDIA_TYPE_VIDEO:
2317  codec->time_base = av_inv_q(ost->frame_rate);
2318  if (ost->filter && !(codec->time_base.num && codec->time_base.den))
2319  codec->time_base = ost->filter->filter->inputs[0]->time_base;
2320  if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
2322  av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
2323  "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
2324  }
2325  for (j = 0; j < ost->forced_kf_count; j++)
2326  ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
2328  codec->time_base);
2329 
2330  codec->width = ost->filter->filter->inputs[0]->w;
2331  codec->height = ost->filter->filter->inputs[0]->h;
2332  codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
2333  ost->frame_aspect_ratio ? // overridden by the -aspect cli option
2334  av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
2336  codec->pix_fmt = ost->filter->filter->inputs[0]->format;
2337 
2338  if (!icodec ||
2339  codec->width != icodec->width ||
2340  codec->height != icodec->height ||
2341  codec->pix_fmt != icodec->pix_fmt) {
2343  }
2344 
2345  if (ost->forced_keyframes) {
2346  if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
2349  if (ret < 0) {
2351  "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
2352  return ret;
2353  }
2358  } else {
2360  }
2361  }
2362  break;
2363  case AVMEDIA_TYPE_SUBTITLE:
2364  codec->time_base = (AVRational){1, 1000};
2365  if (!codec->width) {
2366  codec->width = input_streams[ost->source_index]->st->codec->width;
2367  codec->height = input_streams[ost->source_index]->st->codec->height;
2368  }
2369  break;
2370  default:
2371  abort();
2372  break;
2373  }
2374  /* two pass mode */
2375  if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
2376  char logfilename[1024];
2377  FILE *f;
2378 
2379  snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
2380  ost->logfile_prefix ? ost->logfile_prefix :
2382  i);
2383  if (!strcmp(ost->enc->name, "libx264")) {
2384  av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
2385  } else {
2386  if (codec->flags & CODEC_FLAG_PASS2) {
2387  char *logbuffer;
2388  size_t logbuffer_size;
2389  if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
2390  av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
2391  logfilename);
2392  exit(1);
2393  }
2394  codec->stats_in = logbuffer;
2395  }
2396  if (codec->flags & CODEC_FLAG_PASS1) {
2397  f = fopen(logfilename, "wb");
2398  if (!f) {
2399  av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
2400  logfilename, strerror(errno));
2401  exit(1);
2402  }
2403  ost->logfile = f;
2404  }
2405  }
2406  }
2407  }
2408  }
2409 
2410  /* open each encoder */
2411  for (i = 0; i < nb_output_streams; i++) {
2412  ost = output_streams[i];
2413  if (ost->encoding_needed) {
2414  AVCodec *codec = ost->enc;
2415  AVCodecContext *dec = NULL;
2416 
2417  if ((ist = get_input_stream(ost)))
2418  dec = ist->st->codec;
2419  if (dec && dec->subtitle_header) {
2420  /* ASS code assumes this buffer is null terminated so add extra byte. */
2422  if (!ost->st->codec->subtitle_header) {
2423  ret = AVERROR(ENOMEM);
2424  goto dump_format;
2425  }
2426  memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
2428  }
2429  if (!av_dict_get(ost->opts, "threads", NULL, 0))
2430  av_dict_set(&ost->opts, "threads", "auto", 0);
2431  if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
2432  if (ret == AVERROR_EXPERIMENTAL)
2433  abort_codec_experimental(codec, 1);
2434  snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
2435  ost->file_index, ost->index);
2436  goto dump_format;
2437  }
2438  if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
2441  ost->st->codec->frame_size);
2442  assert_avoptions(ost->opts);
2443  if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
2444  av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
2445  " It takes bits/s as argument, not kbits/s\n");
2446  extra_size += ost->st->codec->extradata_size;
2447 
2448  if (ost->st->codec->me_threshold)
2449  input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
2450  } else {
2451  av_opt_set_dict(ost->st->codec, &ost->opts);
2452  }
2453  }
2454 
2455  /* init input streams */
2456  for (i = 0; i < nb_input_streams; i++)
2457  if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
2458  for (i = 0; i < nb_output_streams; i++) {
2459  ost = output_streams[i];
2460  avcodec_close(ost->st->codec);
2461  }
2462  goto dump_format;
2463  }
2464 
2465  /* discard unused programs */
2466  for (i = 0; i < nb_input_files; i++) {
2467  InputFile *ifile = input_files[i];
2468  for (j = 0; j < ifile->ctx->nb_programs; j++) {
2469  AVProgram *p = ifile->ctx->programs[j];
2470  int discard = AVDISCARD_ALL;
2471 
2472  for (k = 0; k < p->nb_stream_indexes; k++)
2473  if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
2474  discard = AVDISCARD_DEFAULT;
2475  break;
2476  }
2477  p->discard = discard;
2478  }
2479  }
2480 
2481  /* open files and write file headers */
2482  for (i = 0; i < nb_output_files; i++) {
2483  oc = output_files[i]->ctx;
2484  oc->interrupt_callback = int_cb;
2485  if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
2486  char errbuf[128];
2487  const char *errbuf_ptr = errbuf;
2488  if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
2489  errbuf_ptr = strerror(AVUNERROR(ret));
2490  snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
2491  ret = AVERROR(EINVAL);
2492  goto dump_format;
2493  }
2494 // assert_avoptions(output_files[i]->opts);
2495  if (strcmp(oc->oformat->name, "rtp")) {
2496  want_sdp = 0;
2497  }
2498  }
2499 
2500  dump_format:
2501  /* dump the file output parameters - cannot be done before in case
2502  of stream copy */
2503  for (i = 0; i < nb_output_files; i++) {
2504  av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
2505  }
2506 
2507  /* dump the stream mapping */
2508  av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
2509  for (i = 0; i < nb_input_streams; i++) {
2510  ist = input_streams[i];
2511 
2512  for (j = 0; j < ist->nb_filters; j++) {
2513  if (ist->filters[j]->graph->graph_desc) {
2514  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
2515  ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
2516  ist->filters[j]->name);
2517  if (nb_filtergraphs > 1)
2518  av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
2519  av_log(NULL, AV_LOG_INFO, "\n");
2520  }
2521  }
2522  }
2523 
2524  for (i = 0; i < nb_output_streams; i++) {
2525  ost = output_streams[i];
2526 
2527  if (ost->attachment_filename) {
2528  /* an attached file */
2529  av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
2530  ost->attachment_filename, ost->file_index, ost->index);
2531  continue;
2532  }
2533 
2534  if (ost->filter && ost->filter->graph->graph_desc) {
2535  /* output from a complex graph */
2536  av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
2537  if (nb_filtergraphs > 1)
2538  av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
2539 
2540  av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
2541  ost->index, ost->enc ? ost->enc->name : "?");
2542  continue;
2543  }
2544 
2545  av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
2546  input_streams[ost->source_index]->file_index,
2547  input_streams[ost->source_index]->st->index,
2548  ost->file_index,
2549  ost->index);
2550  if (ost->sync_ist != input_streams[ost->source_index])
2551  av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
2552  ost->sync_ist->file_index,
2553  ost->sync_ist->st->index);
2554  if (ost->stream_copy)
2555  av_log(NULL, AV_LOG_INFO, " (copy)");
2556  else
2557  av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
2558  input_streams[ost->source_index]->dec->name : "?",
2559  ost->enc ? ost->enc->name : "?");
2560  av_log(NULL, AV_LOG_INFO, "\n");
2561  }
2562 
2563  if (ret) {
2564  av_log(NULL, AV_LOG_ERROR, "%s\n", error);
2565  return ret;
2566  }
2567 
2568  if (want_sdp) {
2569  print_sdp();
2570  }
2571 
2572  return 0;
2573 }
2574 
2575 /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
2576 static int need_output(void)
2577 {
2578  int i;
2579 
2580  for (i = 0; i < nb_output_streams; i++) {
2581  OutputStream *ost = output_streams[i];
2582  OutputFile *of = output_files[ost->file_index];
2583  AVFormatContext *os = output_files[ost->file_index]->ctx;
2584 
2585  if (ost->finished ||
2586  (os->pb && avio_tell(os->pb) >= of->limit_filesize))
2587  continue;
2588  if (ost->frame_number >= ost->max_frames) {
2589  int j;
2590  for (j = 0; j < of->ctx->nb_streams; j++)
2591  close_output_stream(output_streams[of->ost_index + j]);
2592  continue;
2593  }
2594 
2595  return 1;
2596  }
2597 
2598  return 0;
2599 }
2600 
2607 {
2608  int i;
2609  int64_t opts_min = INT64_MAX;
2610  OutputStream *ost_min = NULL;
2611 
2612  for (i = 0; i < nb_output_streams; i++) {
2613  OutputStream *ost = output_streams[i];
2614  int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
2615  AV_TIME_BASE_Q);
2616  if (!ost->unavailable && !ost->finished && opts < opts_min) {
2617  opts_min = opts;
2618  ost_min = ost;
2619  }
2620  }
2621  return ost_min;
2622 }
2623 
2625 {
2626  int i, ret, key;
2627  static int64_t last_time;
2628  if (received_nb_signals)
2629  return AVERROR_EXIT;
2630  /* read_key() returns 0 on EOF */
2631  if(cur_time - last_time >= 100000 && !run_as_daemon){
2632  key = read_key();
2633  last_time = cur_time;
2634  }else
2635  key = -1;
2636  if (key == 'q')
2637  return AVERROR_EXIT;
2638  if (key == '+') av_log_set_level(av_log_get_level()+10);
2639  if (key == '-') av_log_set_level(av_log_get_level()-10);
2640  if (key == 's') qp_hist ^= 1;
2641  if (key == 'h'){
2642  if (do_hex_dump){
2643  do_hex_dump = do_pkt_dump = 0;
2644  } else if(do_pkt_dump){
2645  do_hex_dump = 1;
2646  } else
2647  do_pkt_dump = 1;
2649  }
2650  if (key == 'c' || key == 'C'){
2651  char buf[4096], target[64], command[256], arg[256] = {0};
2652  double time;
2653  int k, n = 0;
2654  fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
2655  i = 0;
2656  while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
2657  if (k > 0)
2658  buf[i++] = k;
2659  buf[i] = 0;
2660  if (k > 0 &&
2661  (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
2662  av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
2663  target, time, command, arg);
2664  for (i = 0; i < nb_filtergraphs; i++) {
2665  FilterGraph *fg = filtergraphs[i];
2666  if (fg->graph) {
2667  if (time < 0) {
2668  ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
2669  key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
2670  fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
2671  } else {
2672  ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
2673  }
2674  }
2675  }
2676  } else {
2678  "Parse error, at least 3 arguments were expected, "
2679  "only %d given in string '%s'\n", n, buf);
2680  }
2681  }
2682  if (key == 'd' || key == 'D'){
2683  int debug=0;
2684  if(key == 'D') {
2685  debug = input_streams[0]->st->codec->debug<<1;
2686  if(!debug) debug = 1;
2687  while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
2688  debug += debug;
2689  }else
2690  if(scanf("%d", &debug)!=1)
2691  fprintf(stderr,"error parsing debug value\n");
2692  for(i=0;i<nb_input_streams;i++) {
2693  input_streams[i]->st->codec->debug = debug;
2694  }
2695  for(i=0;i<nb_output_streams;i++) {
2696  OutputStream *ost = output_streams[i];
2697  ost->st->codec->debug = debug;
2698  }
2699  if(debug) av_log_set_level(AV_LOG_DEBUG);
2700  fprintf(stderr,"debug=%d\n", debug);
2701  }
2702  if (key == '?'){
2703  fprintf(stderr, "key function\n"
2704  "? show this help\n"
2705  "+ increase verbosity\n"
2706  "- decrease verbosity\n"
2707  "c Send command to filtergraph\n"
2708  "D cycle through available debug modes\n"
2709  "h dump packets/hex press to cycle through the 3 states\n"
2710  "q quit\n"
2711  "s Show QP histogram\n"
2712  );
2713  }
2714  return 0;
2715 }
2716 
2717 #if HAVE_PTHREADS
2718 static void *input_thread(void *arg)
2719 {
2720  InputFile *f = arg;
2721  int ret = 0;
2722 
2723  while (!transcoding_finished && ret >= 0) {
2724  AVPacket pkt;
2725  ret = av_read_frame(f->ctx, &pkt);
2726 
2727  if (ret == AVERROR(EAGAIN)) {
2728  av_usleep(10000);
2729  ret = 0;
2730  continue;
2731  } else if (ret < 0)
2732  break;
2733 
2735  while (!av_fifo_space(f->fifo))
2737 
2738  av_dup_packet(&pkt);
2739  av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
2740 
2742  }
2743 
2744  f->finished = 1;
2745  return NULL;
2746 }
2747 
2748 static void free_input_threads(void)
2749 {
2750  int i;
2751 
2752  if (nb_input_files == 1)
2753  return;
2754 
2756 
2757  for (i = 0; i < nb_input_files; i++) {
2758  InputFile *f = input_files[i];
2759  AVPacket pkt;
2760 
2761  if (!f->fifo || f->joined)
2762  continue;
2763 
2765  while (av_fifo_size(f->fifo)) {
2766  av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2767  av_free_packet(&pkt);
2768  }
2771 
2772  pthread_join(f->thread, NULL);
2773  f->joined = 1;
2774 
2775  while (av_fifo_size(f->fifo)) {
2776  av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
2777  av_free_packet(&pkt);
2778  }
2779  av_fifo_free(f->fifo);
2780  }
2781 }
2782 
2783 static int init_input_threads(void)
2784 {
2785  int i, ret;
2786 
2787  if (nb_input_files == 1)
2788  return 0;
2789 
2790  for (i = 0; i < nb_input_files; i++) {
2791  InputFile *f = input_files[i];
2792 
2793  if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
2794  return AVERROR(ENOMEM);
2795 
2798 
2799  if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
2800  return AVERROR(ret);
2801  }
2802  return 0;
2803 }
2804 
2806 {
2807  int ret = 0;
2808 
2810 
2811  if (av_fifo_size(f->fifo)) {
2812  av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
2814  } else {
2815  if (f->finished)
2816  ret = AVERROR_EOF;
2817  else
2818  ret = AVERROR(EAGAIN);
2819  }
2820 
2822 
2823  return ret;
2824 }
2825 #endif
2826 
2828 {
2829 #if HAVE_PTHREADS
2830  if (nb_input_files > 1)
2831  return get_input_packet_mt(f, pkt);
2832 #endif
2833  return av_read_frame(f->ctx, pkt);
2834 }
2835 
2836 static int got_eagain(void)
2837 {
2838  int i;
2839  for (i = 0; i < nb_output_streams; i++)
2840  if (output_streams[i]->unavailable)
2841  return 1;
2842  return 0;
2843 }
2844 
2845 static void reset_eagain(void)
2846 {
2847  int i;
2848  for (i = 0; i < nb_input_files; i++)
2849  input_files[i]->eagain = 0;
2850  for (i = 0; i < nb_output_streams; i++)
2851  output_streams[i]->unavailable = 0;
2852 }
2853 
2854 /*
2855  * Return
2856  * - 0 -- one packet was read and processed
2857  * - AVERROR(EAGAIN) -- no packets were available for selected file,
2858  * this function should be called again
2859  * - AVERROR_EOF -- this function should not be called again
2860  */
2861 static int process_input(int file_index)
2862 {
2863  InputFile *ifile = input_files[file_index];
2864  AVFormatContext *is;
2865  InputStream *ist;
2866  AVPacket pkt;
2867  int ret, i, j;
2868 
2869  is = ifile->ctx;
2870  ret = get_input_packet(ifile, &pkt);
2871 
2872  if (ret == AVERROR(EAGAIN)) {
2873  ifile->eagain = 1;
2874  return ret;
2875  }
2876  if (ret < 0) {
2877  if (ret != AVERROR_EOF) {
2878  print_error(is->filename, ret);
2879  if (exit_on_error)
2880  exit(1);
2881  }
2882  ifile->eof_reached = 1;
2883 
2884  for (i = 0; i < ifile->nb_streams; i++) {
2885  ist = input_streams[ifile->ist_index + i];
2886  if (ist->decoding_needed)
2887  output_packet(ist, NULL);
2888 
2889  /* mark all outputs that don't go through lavfi as finished */
2890  for (j = 0; j < nb_output_streams; j++) {
2891  OutputStream *ost = output_streams[j];
2892 
2893  if (ost->source_index == ifile->ist_index + i &&
2894  (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
2895  close_output_stream(ost);
2896  }
2897  }
2898 
2899  return AVERROR(EAGAIN);
2900  }
2901 
2902  reset_eagain();
2903 
2904  if (do_pkt_dump) {
2906  is->streams[pkt.stream_index]);
2907  }
2908  /* the following test is needed in case new streams appear
2909  dynamically in stream : we ignore them */
2910  if (pkt.stream_index >= ifile->nb_streams) {
2911  report_new_stream(file_index, &pkt);
2912  goto discard_packet;
2913  }
2914 
2915  ist = input_streams[ifile->ist_index + pkt.stream_index];
2916  if (ist->discard)
2917  goto discard_packet;
2918 
2919  if (debug_ts) {
2920  av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
2921  "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",
2925  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
2926  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
2927  av_ts2str(input_files[ist->file_index]->ts_offset),
2928  av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
2929  }
2930 
2931  if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
2932  int64_t stime, stime2;
2933  // Correcting starttime based on the enabled streams
2934  // 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.
2935  // so we instead do it here as part of discontinuity handling
2936  if ( ist->next_dts == AV_NOPTS_VALUE
2937  && ifile->ts_offset == -is->start_time
2938  && (is->iformat->flags & AVFMT_TS_DISCONT)) {
2939  int64_t new_start_time = INT64_MAX;
2940  for (i=0; i<is->nb_streams; i++) {
2941  AVStream *st = is->streams[i];
2942  if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
2943  continue;
2944  new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
2945  }
2946  if (new_start_time > is->start_time) {
2947  av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
2948  ifile->ts_offset = -new_start_time;
2949  }
2950  }
2951 
2952  stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
2953  stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
2954  ist->wrap_correction_done = 1;
2955 
2956  if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
2957  pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
2958  ist->wrap_correction_done = 0;
2959  }
2960  if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
2961  pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
2962  ist->wrap_correction_done = 0;
2963  }
2964  }
2965 
2966  if (pkt.dts != AV_NOPTS_VALUE)
2967  pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2968  if (pkt.pts != AV_NOPTS_VALUE)
2969  pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
2970 
2971  if (pkt.pts != AV_NOPTS_VALUE)
2972  pkt.pts *= ist->ts_scale;
2973  if (pkt.dts != AV_NOPTS_VALUE)
2974  pkt.dts *= ist->ts_scale;
2975 
2976  if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
2977  !copy_ts) {
2978  int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
2979  int64_t delta = pkt_dts - ist->next_dts;
2980  if (is->iformat->flags & AVFMT_TS_DISCONT) {
2981  if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
2982  (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
2984  pkt_dts+1<ist->pts){
2985  ifile->ts_offset -= delta;
2987  "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
2988  delta, ifile->ts_offset);
2989  pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2990  if (pkt.pts != AV_NOPTS_VALUE)
2991  pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
2992  }
2993  } else {
2994  if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
2996  ) {
2997  av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
2998  pkt.dts = AV_NOPTS_VALUE;
2999  }
3000  if (pkt.pts != AV_NOPTS_VALUE){
3001  int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
3002  delta = pkt_pts - ist->next_dts;
3003  if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
3005  ) {
3006  av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
3007  pkt.pts = AV_NOPTS_VALUE;
3008  }
3009  }
3010  }
3011  }
3012 
3013  if (debug_ts) {
3014  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",
3016  av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
3017  av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
3018  av_ts2str(input_files[ist->file_index]->ts_offset),
3019  av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
3020  }
3021 
3022  sub2video_heartbeat(ist, pkt.pts);
3023 
3024  ret = output_packet(ist, &pkt);
3025  if (ret < 0) {
3026  char buf[128];
3027  av_strerror(ret, buf, sizeof(buf));
3028  av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
3029  ist->file_index, ist->st->index, buf);
3030  if (exit_on_error)
3031  exit(1);
3032  }
3033 
3034 discard_packet:
3035  av_free_packet(&pkt);
3036 
3037  return 0;
3038 }
3039 
3047 static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
3048 {
3049  int i, ret;
3050  int nb_requests, nb_requests_max = 0;
3051  InputFilter *ifilter;
3052  InputStream *ist;
3053 
3054  *best_ist = NULL;
3055  ret = avfilter_graph_request_oldest(graph->graph);
3056  if (ret >= 0)
3057  return reap_filters();
3058 
3059  if (ret == AVERROR_EOF) {
3060  ret = reap_filters();
3061  for (i = 0; i < graph->nb_outputs; i++)
3062  close_output_stream(graph->outputs[i]->ost);
3063  return ret;
3064  }
3065  if (ret != AVERROR(EAGAIN))
3066  return ret;
3067 
3068  for (i = 0; i < graph->nb_inputs; i++) {
3069  ifilter = graph->inputs[i];
3070  ist = ifilter->ist;
3071  if (input_files[ist->file_index]->eagain ||
3072  input_files[ist->file_index]->eof_reached)
3073  continue;
3074  nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
3075  if (nb_requests > nb_requests_max) {
3076  nb_requests_max = nb_requests;
3077  *best_ist = ist;
3078  }
3079  }
3080 
3081  if (!*best_ist)
3082  for (i = 0; i < graph->nb_outputs; i++)
3083  graph->outputs[i]->ost->unavailable = 1;
3084 
3085  return 0;
3086 }
3087 
3093 static int transcode_step(void)
3094 {
3095  OutputStream *ost;
3096  InputStream *ist;
3097  int ret;
3098 
3099  ost = choose_output();
3100  if (!ost) {
3101  if (got_eagain()) {
3102  reset_eagain();
3103  av_usleep(10000);
3104  return 0;
3105  }
3106  av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
3107  return AVERROR_EOF;
3108  }
3109 
3110  if (ost->filter) {
3111  if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
3112  return ret;
3113  if (!ist)
3114  return 0;
3115  } else {
3116  av_assert0(ost->source_index >= 0);
3117  ist = input_streams[ost->source_index];
3118  }
3119 
3120  ret = process_input(ist->file_index);
3121  if (ret == AVERROR(EAGAIN)) {
3122  if (input_files[ist->file_index]->eagain)
3123  ost->unavailable = 1;
3124  return 0;
3125  }
3126  if (ret < 0)
3127  return ret == AVERROR_EOF ? 0 : ret;
3128 
3129  return reap_filters();
3130 }
3131 
3132 /*
3133  * The following code is the main loop of the file converter
3134  */
3135 static int transcode(void)
3136 {
3137  int ret, i;
3138  AVFormatContext *os;
3139  OutputStream *ost;
3140  InputStream *ist;
3141  int64_t timer_start;
3142 
3143  ret = transcode_init();
3144  if (ret < 0)
3145  goto fail;
3146 
3147  if (stdin_interaction) {
3148  av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
3149  }
3150 
3151  timer_start = av_gettime();
3152 
3153 #if HAVE_PTHREADS
3154  if ((ret = init_input_threads()) < 0)
3155  goto fail;
3156 #endif
3157 
3158  while (!received_sigterm) {
3159  int64_t cur_time= av_gettime();
3160 
3161  /* if 'q' pressed, exits */
3162  if (stdin_interaction)
3163  if (check_keyboard_interaction(cur_time) < 0)
3164  break;
3165 
3166  /* check if there's any stream where output is still needed */
3167  if (!need_output()) {
3168  av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
3169  break;
3170  }
3171 
3172  ret = transcode_step();
3173  if (ret < 0) {
3174  if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
3175  continue;
3176 
3177  av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
3178  break;
3179  }
3180 
3181  /* dump report by using the output first video and audio streams */
3182  print_report(0, timer_start, cur_time);
3183  }
3184 #if HAVE_PTHREADS
3186 #endif
3187 
3188  /* at the end of stream, we must flush the decoder buffers */
3189  for (i = 0; i < nb_input_streams; i++) {
3190  ist = input_streams[i];
3191  if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
3192  output_packet(ist, NULL);
3193  }
3194  }
3195  flush_encoders();
3196 
3197  term_exit();
3198 
3199  /* write the trailer if needed and close file */
3200  for (i = 0; i < nb_output_files; i++) {
3201  os = output_files[i]->ctx;
3202  av_write_trailer(os);
3203  }
3204 
3205  /* dump report by using the first video and audio streams */
3206  print_report(1, timer_start, av_gettime());
3207 
3208  /* close each encoder */
3209  for (i = 0; i < nb_output_streams; i++) {
3210  ost = output_streams[i];
3211  if (ost->encoding_needed) {
3212  av_freep(&ost->st->codec->stats_in);
3213  avcodec_close(ost->st->codec);
3214  }
3215  }
3216 
3217  /* close each decoder */
3218  for (i = 0; i < nb_input_streams; i++) {
3219  ist = input_streams[i];
3220  if (ist->decoding_needed) {
3221  avcodec_close(ist->st->codec);
3222  }
3223  }
3224 
3225  /* finished ! */
3226  ret = 0;
3227 
3228  fail:
3229 #if HAVE_PTHREADS
3231 #endif
3232 
3233  if (output_streams) {
3234  for (i = 0; i < nb_output_streams; i++) {
3235  ost = output_streams[i];
3236  if (ost) {
3237  if (ost->stream_copy)
3238  av_freep(&ost->st->codec->extradata);
3239  if (ost->logfile) {
3240  fclose(ost->logfile);
3241  ost->logfile = NULL;
3242  }
3243  av_freep(&ost->st->codec->subtitle_header);
3244  av_free(ost->forced_kf_pts);
3245  av_dict_free(&ost->opts);
3246  av_dict_free(&ost->swr_opts);
3247  av_dict_free(&ost->resample_opts);
3248  }
3249  }
3250  }
3251  return ret;
3252 }
3253 
3254 
3255 static int64_t getutime(void)
3256 {
3257 #if HAVE_GETRUSAGE
3258  struct rusage rusage;
3259 
3260  getrusage(RUSAGE_SELF, &rusage);
3261  return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
3262 #elif HAVE_GETPROCESSTIMES
3263  HANDLE proc;
3264  FILETIME c, e, k, u;
3265  proc = GetCurrentProcess();
3266  GetProcessTimes(proc, &c, &e, &k, &u);
3267  return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
3268 #else
3269  return av_gettime();
3270 #endif
3271 }
3272 
3273 static int64_t getmaxrss(void)
3274 {
3275 #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
3276  struct rusage rusage;
3277  getrusage(RUSAGE_SELF, &rusage);
3278  return (int64_t)rusage.ru_maxrss * 1024;
3279 #elif HAVE_GETPROCESSMEMORYINFO
3280  HANDLE proc;
3281  PROCESS_MEMORY_COUNTERS memcounters;
3282  proc = GetCurrentProcess();
3283  memcounters.cb = sizeof(memcounters);
3284  GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
3285  return memcounters.PeakPagefileUsage;
3286 #else
3287  return 0;
3288 #endif
3289 }
3290 
3291 static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
3292 {
3293 }
3294 
3295 int main(int argc, char **argv)
3296 {
3297  int ret;
3298  int64_t ti;
3299 
3300  atexit(exit_program);
3301 
3302  setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
3303 
3305  parse_loglevel(argc, argv, options);
3306 
3307  if(argc>1 && !strcmp(argv[1], "-d")){
3308  run_as_daemon=1;
3310  argc--;
3311  argv++;
3312  }
3313 
3315 #if CONFIG_AVDEVICE
3317 #endif
3319  av_register_all();
3321 
3322  show_banner(argc, argv, options);
3323 
3324  term_init();
3325 
3326  /* parse options and open all input/output files */
3327  ret = ffmpeg_parse_options(argc, argv);
3328  if (ret < 0)
3329  exit(1);
3330 
3331  if (nb_output_files <= 0 && nb_input_files == 0) {
3332  show_usage();
3333  av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
3334  exit(1);
3335  }
3336 
3337  /* file converter / grab */
3338  if (nb_output_files <= 0) {
3339  av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
3340  exit(1);
3341  }
3342 
3343 // if (nb_input_files == 0) {
3344 // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
3345 // exit(1);
3346 // }
3347 
3348  current_time = ti = getutime();
3349  if (transcode() < 0)
3350  exit(1);
3351  ti = getutime() - ti;
3352  if (do_benchmark) {
3353  printf("bench: utime=%0.3fs\n", ti / 1000000.0);
3354  }
3355 
3356  exit(received_nb_signals ? 255 : 0);
3357  return 0;
3358 }