You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3267 lines
113KB

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