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.

3265 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. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  1258. if (!dec->channel_layout)
  1259. return 0;
  1260. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  1261. dec->channels, dec->channel_layout);
  1262. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  1263. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  1264. }
  1265. return 1;
  1266. }
  1267. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  1268. {
  1269. AVFrame *decoded_frame;
  1270. AVCodecContext *avctx = ist->st->codec;
  1271. int i, ret, resample_changed;
  1272. AVRational decoded_frame_tb;
  1273. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  1274. return AVERROR(ENOMEM);
  1275. decoded_frame = ist->decoded_frame;
  1276. update_benchmark(NULL);
  1277. ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
  1278. update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
  1279. if (ret >= 0 && avctx->sample_rate <= 0) {
  1280. av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
  1281. ret = AVERROR_INVALIDDATA;
  1282. }
  1283. if (!*got_output || ret < 0) {
  1284. if (!pkt->size) {
  1285. for (i = 0; i < ist->nb_filters; i++)
  1286. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1287. }
  1288. return ret;
  1289. }
  1290. #if 1
  1291. /* increment next_dts to use for the case where the input stream does not
  1292. have timestamps or there are multiple frames in the packet */
  1293. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1294. avctx->sample_rate;
  1295. ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1296. avctx->sample_rate;
  1297. #endif
  1298. rate_emu_sleep(ist);
  1299. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  1300. ist->resample_channels != avctx->channels ||
  1301. ist->resample_channel_layout != decoded_frame->channel_layout ||
  1302. ist->resample_sample_rate != decoded_frame->sample_rate;
  1303. if (resample_changed) {
  1304. char layout1[64], layout2[64];
  1305. if (!guess_input_channel_layout(ist)) {
  1306. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  1307. "layout for Input Stream #%d.%d\n", ist->file_index,
  1308. ist->st->index);
  1309. exit(1);
  1310. }
  1311. decoded_frame->channel_layout = avctx->channel_layout;
  1312. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  1313. ist->resample_channel_layout);
  1314. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  1315. decoded_frame->channel_layout);
  1316. av_log(NULL, AV_LOG_INFO,
  1317. "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",
  1318. ist->file_index, ist->st->index,
  1319. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  1320. ist->resample_channels, layout1,
  1321. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  1322. avctx->channels, layout2);
  1323. ist->resample_sample_fmt = decoded_frame->format;
  1324. ist->resample_sample_rate = decoded_frame->sample_rate;
  1325. ist->resample_channel_layout = decoded_frame->channel_layout;
  1326. ist->resample_channels = avctx->channels;
  1327. for (i = 0; i < nb_filtergraphs; i++)
  1328. if (ist_in_filtergraph(filtergraphs[i], ist)) {
  1329. FilterGraph *fg = filtergraphs[i];
  1330. int j;
  1331. if (configure_filtergraph(fg) < 0) {
  1332. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1333. exit(1);
  1334. }
  1335. for (j = 0; j < fg->nb_outputs; j++) {
  1336. OutputStream *ost = fg->outputs[j]->ost;
  1337. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  1338. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  1339. av_buffersink_set_frame_size(ost->filter->filter,
  1340. ost->st->codec->frame_size);
  1341. }
  1342. }
  1343. }
  1344. /* if the decoder provides a pts, use it instead of the last packet pts.
  1345. the decoder could be delaying output by a packet or more. */
  1346. if (decoded_frame->pts != AV_NOPTS_VALUE) {
  1347. ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
  1348. decoded_frame_tb = avctx->time_base;
  1349. } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
  1350. decoded_frame->pts = decoded_frame->pkt_pts;
  1351. pkt->pts = AV_NOPTS_VALUE;
  1352. decoded_frame_tb = ist->st->time_base;
  1353. } else if (pkt->pts != AV_NOPTS_VALUE) {
  1354. decoded_frame->pts = pkt->pts;
  1355. pkt->pts = AV_NOPTS_VALUE;
  1356. decoded_frame_tb = ist->st->time_base;
  1357. }else {
  1358. decoded_frame->pts = ist->dts;
  1359. decoded_frame_tb = AV_TIME_BASE_Q;
  1360. }
  1361. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1362. decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
  1363. (AVRational){1, ist->st->codec->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
  1364. (AVRational){1, ist->st->codec->sample_rate});
  1365. for (i = 0; i < ist->nb_filters; i++)
  1366. av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame,
  1367. AV_BUFFERSRC_FLAG_PUSH);
  1368. decoded_frame->pts = AV_NOPTS_VALUE;
  1369. return ret;
  1370. }
  1371. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  1372. {
  1373. AVFrame *decoded_frame;
  1374. void *buffer_to_free = NULL;
  1375. int i, ret = 0, resample_changed;
  1376. int64_t best_effort_timestamp;
  1377. AVRational *frame_sample_aspect;
  1378. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  1379. return AVERROR(ENOMEM);
  1380. decoded_frame = ist->decoded_frame;
  1381. pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  1382. update_benchmark(NULL);
  1383. ret = avcodec_decode_video2(ist->st->codec,
  1384. decoded_frame, got_output, pkt);
  1385. update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
  1386. if (!*got_output || ret < 0) {
  1387. if (!pkt->size) {
  1388. for (i = 0; i < ist->nb_filters; i++)
  1389. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1390. }
  1391. return ret;
  1392. }
  1393. if(ist->top_field_first>=0)
  1394. decoded_frame->top_field_first = ist->top_field_first;
  1395. best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
  1396. if(best_effort_timestamp != AV_NOPTS_VALUE)
  1397. ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
  1398. if (debug_ts) {
  1399. av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
  1400. "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
  1401. ist->st->index, av_ts2str(decoded_frame->pts),
  1402. av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
  1403. best_effort_timestamp,
  1404. av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
  1405. decoded_frame->key_frame, decoded_frame->pict_type);
  1406. }
  1407. pkt->size = 0;
  1408. pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
  1409. rate_emu_sleep(ist);
  1410. if (ist->st->sample_aspect_ratio.num)
  1411. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1412. resample_changed = ist->resample_width != decoded_frame->width ||
  1413. ist->resample_height != decoded_frame->height ||
  1414. ist->resample_pix_fmt != decoded_frame->format;
  1415. if (resample_changed) {
  1416. av_log(NULL, AV_LOG_INFO,
  1417. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1418. ist->file_index, ist->st->index,
  1419. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1420. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1421. ist->resample_width = decoded_frame->width;
  1422. ist->resample_height = decoded_frame->height;
  1423. ist->resample_pix_fmt = decoded_frame->format;
  1424. for (i = 0; i < nb_filtergraphs; i++) {
  1425. if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
  1426. configure_filtergraph(filtergraphs[i]) < 0) {
  1427. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1428. exit(1);
  1429. }
  1430. }
  1431. }
  1432. frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
  1433. for (i = 0; i < ist->nb_filters; i++) {
  1434. int changed = ist->st->codec->width != ist->filters[i]->filter->outputs[0]->w
  1435. || ist->st->codec->height != ist->filters[i]->filter->outputs[0]->h
  1436. || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
  1437. if (!frame_sample_aspect->num)
  1438. *frame_sample_aspect = ist->st->sample_aspect_ratio;
  1439. if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
  1440. FrameBuffer *buf = decoded_frame->opaque;
  1441. AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
  1442. decoded_frame->data, decoded_frame->linesize,
  1443. AV_PERM_READ | AV_PERM_PRESERVE,
  1444. ist->st->codec->width, ist->st->codec->height,
  1445. ist->st->codec->pix_fmt);
  1446. avfilter_copy_frame_props(fb, decoded_frame);
  1447. fb->buf->priv = buf;
  1448. fb->buf->free = filter_release_buffer;
  1449. av_assert0(buf->refcount>0);
  1450. buf->refcount++;
  1451. av_buffersrc_add_ref(ist->filters[i]->filter, fb,
  1452. AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
  1453. AV_BUFFERSRC_FLAG_NO_COPY |
  1454. AV_BUFFERSRC_FLAG_PUSH);
  1455. } else
  1456. if(av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, AV_BUFFERSRC_FLAG_PUSH)<0) {
  1457. av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
  1458. exit(1);
  1459. }
  1460. }
  1461. av_free(buffer_to_free);
  1462. return ret;
  1463. }
  1464. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1465. {
  1466. AVSubtitle subtitle;
  1467. int i, ret = avcodec_decode_subtitle2(ist->st->codec,
  1468. &subtitle, got_output, pkt);
  1469. if (ret < 0 || !*got_output) {
  1470. if (!pkt->size)
  1471. sub2video_flush(ist);
  1472. return ret;
  1473. }
  1474. if (ist->fix_sub_duration) {
  1475. if (ist->prev_sub.got_output) {
  1476. int end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
  1477. 1000, AV_TIME_BASE);
  1478. if (end < ist->prev_sub.subtitle.end_display_time) {
  1479. av_log(ist->st->codec, AV_LOG_DEBUG,
  1480. "Subtitle duration reduced from %d to %d\n",
  1481. ist->prev_sub.subtitle.end_display_time, end);
  1482. ist->prev_sub.subtitle.end_display_time = end;
  1483. }
  1484. }
  1485. FFSWAP(int, *got_output, ist->prev_sub.got_output);
  1486. FFSWAP(int, ret, ist->prev_sub.ret);
  1487. FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
  1488. }
  1489. sub2video_update(ist, &subtitle);
  1490. if (!*got_output || !subtitle.num_rects)
  1491. return ret;
  1492. rate_emu_sleep(ist);
  1493. for (i = 0; i < nb_output_streams; i++) {
  1494. OutputStream *ost = output_streams[i];
  1495. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1496. continue;
  1497. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
  1498. }
  1499. avsubtitle_free(&subtitle);
  1500. return ret;
  1501. }
  1502. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1503. static int output_packet(InputStream *ist, const AVPacket *pkt)
  1504. {
  1505. int ret = 0, i;
  1506. int got_output;
  1507. AVPacket avpkt;
  1508. if (!ist->saw_first_ts) {
  1509. 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;
  1510. ist->pts = 0;
  1511. if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
  1512. ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
  1513. ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
  1514. }
  1515. ist->saw_first_ts = 1;
  1516. }
  1517. if (ist->next_dts == AV_NOPTS_VALUE)
  1518. ist->next_dts = ist->dts;
  1519. if (ist->next_pts == AV_NOPTS_VALUE)
  1520. ist->next_pts = ist->pts;
  1521. if (pkt == NULL) {
  1522. /* EOF handling */
  1523. av_init_packet(&avpkt);
  1524. avpkt.data = NULL;
  1525. avpkt.size = 0;
  1526. goto handle_eof;
  1527. } else {
  1528. avpkt = *pkt;
  1529. }
  1530. if (pkt->dts != AV_NOPTS_VALUE) {
  1531. ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1532. if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
  1533. ist->next_pts = ist->pts = ist->dts;
  1534. }
  1535. // while we have more to decode or while the decoder did output something on EOF
  1536. while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
  1537. int duration;
  1538. handle_eof:
  1539. ist->pts = ist->next_pts;
  1540. ist->dts = ist->next_dts;
  1541. if (avpkt.size && avpkt.size != pkt->size) {
  1542. av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
  1543. "Multiple frames in a packet from stream %d\n", pkt->stream_index);
  1544. ist->showed_multi_packet_warning = 1;
  1545. }
  1546. switch (ist->st->codec->codec_type) {
  1547. case AVMEDIA_TYPE_AUDIO:
  1548. ret = decode_audio (ist, &avpkt, &got_output);
  1549. break;
  1550. case AVMEDIA_TYPE_VIDEO:
  1551. ret = decode_video (ist, &avpkt, &got_output);
  1552. if (avpkt.duration) {
  1553. duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
  1554. } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
  1555. int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
  1556. duration = ((int64_t)AV_TIME_BASE *
  1557. ist->st->codec->time_base.num * ticks) /
  1558. ist->st->codec->time_base.den;
  1559. } else
  1560. duration = 0;
  1561. if(ist->dts != AV_NOPTS_VALUE && duration) {
  1562. ist->next_dts += duration;
  1563. }else
  1564. ist->next_dts = AV_NOPTS_VALUE;
  1565. if (got_output)
  1566. ist->next_pts += duration; //FIXME the duration is not correct in some cases
  1567. break;
  1568. case AVMEDIA_TYPE_SUBTITLE:
  1569. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1570. break;
  1571. default:
  1572. return -1;
  1573. }
  1574. if (ret < 0)
  1575. return ret;
  1576. avpkt.dts=
  1577. avpkt.pts= AV_NOPTS_VALUE;
  1578. // touch data and size only if not EOF
  1579. if (pkt) {
  1580. if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  1581. ret = avpkt.size;
  1582. avpkt.data += ret;
  1583. avpkt.size -= ret;
  1584. }
  1585. if (!got_output) {
  1586. continue;
  1587. }
  1588. }
  1589. /* handle stream copy */
  1590. if (!ist->decoding_needed) {
  1591. rate_emu_sleep(ist);
  1592. ist->dts = ist->next_dts;
  1593. switch (ist->st->codec->codec_type) {
  1594. case AVMEDIA_TYPE_AUDIO:
  1595. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
  1596. ist->st->codec->sample_rate;
  1597. break;
  1598. case AVMEDIA_TYPE_VIDEO:
  1599. if (pkt->duration) {
  1600. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1601. } else if(ist->st->codec->time_base.num != 0) {
  1602. int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
  1603. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1604. ist->st->codec->time_base.num * ticks) /
  1605. ist->st->codec->time_base.den;
  1606. }
  1607. break;
  1608. }
  1609. ist->pts = ist->dts;
  1610. ist->next_pts = ist->next_dts;
  1611. }
  1612. for (i = 0; pkt && i < nb_output_streams; i++) {
  1613. OutputStream *ost = output_streams[i];
  1614. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1615. continue;
  1616. do_streamcopy(ist, ost, pkt);
  1617. }
  1618. return 0;
  1619. }
  1620. static void print_sdp(void)
  1621. {
  1622. char sdp[16384];
  1623. int i;
  1624. AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
  1625. if (!avc)
  1626. exit(1);
  1627. for (i = 0; i < nb_output_files; i++)
  1628. avc[i] = output_files[i]->ctx;
  1629. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1630. printf("SDP:\n%s\n", sdp);
  1631. fflush(stdout);
  1632. av_freep(&avc);
  1633. }
  1634. static int init_input_stream(int ist_index, char *error, int error_len)
  1635. {
  1636. int ret;
  1637. InputStream *ist = input_streams[ist_index];
  1638. if (ist->decoding_needed) {
  1639. AVCodec *codec = ist->dec;
  1640. if (!codec) {
  1641. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
  1642. avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
  1643. return AVERROR(EINVAL);
  1644. }
  1645. ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !do_deinterlace;
  1646. if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
  1647. ist->st->codec->get_buffer = codec_get_buffer;
  1648. ist->st->codec->release_buffer = codec_release_buffer;
  1649. ist->st->codec->opaque = &ist->buffer_pool;
  1650. }
  1651. if (!av_dict_get(ist->opts, "threads", NULL, 0))
  1652. av_dict_set(&ist->opts, "threads", "auto", 0);
  1653. if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
  1654. if (ret == AVERROR_EXPERIMENTAL)
  1655. abort_codec_experimental(codec, 0);
  1656. snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
  1657. ist->file_index, ist->st->index);
  1658. return ret;
  1659. }
  1660. assert_avoptions(ist->opts);
  1661. }
  1662. ist->next_pts = AV_NOPTS_VALUE;
  1663. ist->next_dts = AV_NOPTS_VALUE;
  1664. ist->is_start = 1;
  1665. return 0;
  1666. }
  1667. static InputStream *get_input_stream(OutputStream *ost)
  1668. {
  1669. if (ost->source_index >= 0)
  1670. return input_streams[ost->source_index];
  1671. return NULL;
  1672. }
  1673. static int compare_int64(const void *a, const void *b)
  1674. {
  1675. int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
  1676. return va < vb ? -1 : va > vb ? +1 : 0;
  1677. }
  1678. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1679. AVCodecContext *avctx)
  1680. {
  1681. char *p;
  1682. int n = 1, i, size, index = 0;
  1683. int64_t t, *pts;
  1684. for (p = kf; *p; p++)
  1685. if (*p == ',')
  1686. n++;
  1687. size = n;
  1688. pts = av_malloc(sizeof(*pts) * size);
  1689. if (!pts) {
  1690. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1691. exit(1);
  1692. }
  1693. p = kf;
  1694. for (i = 0; i < n; i++) {
  1695. char *next = strchr(p, ',');
  1696. if (next)
  1697. *next++ = 0;
  1698. if (!memcmp(p, "chapters", 8)) {
  1699. AVFormatContext *avf = output_files[ost->file_index]->ctx;
  1700. int j;
  1701. if (avf->nb_chapters > INT_MAX - size ||
  1702. !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
  1703. sizeof(*pts)))) {
  1704. av_log(NULL, AV_LOG_FATAL,
  1705. "Could not allocate forced key frames array.\n");
  1706. exit(1);
  1707. }
  1708. t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
  1709. t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1710. for (j = 0; j < avf->nb_chapters; j++) {
  1711. AVChapter *c = avf->chapters[j];
  1712. av_assert1(index < size);
  1713. pts[index++] = av_rescale_q(c->start, c->time_base,
  1714. avctx->time_base) + t;
  1715. }
  1716. } else {
  1717. t = parse_time_or_die("force_key_frames", p, 1);
  1718. av_assert1(index < size);
  1719. pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1720. }
  1721. p = next;
  1722. }
  1723. av_assert0(index == size);
  1724. qsort(pts, size, sizeof(*pts), compare_int64);
  1725. ost->forced_kf_count = size;
  1726. ost->forced_kf_pts = pts;
  1727. }
  1728. static void report_new_stream(int input_index, AVPacket *pkt)
  1729. {
  1730. InputFile *file = input_files[input_index];
  1731. AVStream *st = file->ctx->streams[pkt->stream_index];
  1732. if (pkt->stream_index < file->nb_streams_warn)
  1733. return;
  1734. av_log(file->ctx, AV_LOG_WARNING,
  1735. "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
  1736. av_get_media_type_string(st->codec->codec_type),
  1737. input_index, pkt->stream_index,
  1738. pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
  1739. file->nb_streams_warn = pkt->stream_index + 1;
  1740. }
  1741. static int transcode_init(void)
  1742. {
  1743. int ret = 0, i, j, k;
  1744. AVFormatContext *oc;
  1745. AVCodecContext *codec;
  1746. OutputStream *ost;
  1747. InputStream *ist;
  1748. char error[1024];
  1749. int want_sdp = 1;
  1750. /* init framerate emulation */
  1751. for (i = 0; i < nb_input_files; i++) {
  1752. InputFile *ifile = input_files[i];
  1753. if (ifile->rate_emu)
  1754. for (j = 0; j < ifile->nb_streams; j++)
  1755. input_streams[j + ifile->ist_index]->start = av_gettime();
  1756. }
  1757. /* output stream init */
  1758. for (i = 0; i < nb_output_files; i++) {
  1759. oc = output_files[i]->ctx;
  1760. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  1761. av_dump_format(oc, i, oc->filename, 1);
  1762. av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
  1763. return AVERROR(EINVAL);
  1764. }
  1765. }
  1766. /* init complex filtergraphs */
  1767. for (i = 0; i < nb_filtergraphs; i++)
  1768. if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
  1769. return ret;
  1770. /* for each output stream, we compute the right encoding parameters */
  1771. for (i = 0; i < nb_output_streams; i++) {
  1772. AVCodecContext *icodec = NULL;
  1773. ost = output_streams[i];
  1774. oc = output_files[ost->file_index]->ctx;
  1775. ist = get_input_stream(ost);
  1776. if (ost->attachment_filename)
  1777. continue;
  1778. codec = ost->st->codec;
  1779. if (ist) {
  1780. icodec = ist->st->codec;
  1781. ost->st->disposition = ist->st->disposition;
  1782. codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
  1783. codec->chroma_sample_location = icodec->chroma_sample_location;
  1784. }
  1785. if (ost->stream_copy) {
  1786. uint64_t extra_size;
  1787. av_assert0(ist && !ost->filter);
  1788. extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
  1789. if (extra_size > INT_MAX) {
  1790. return AVERROR(EINVAL);
  1791. }
  1792. /* if stream_copy is selected, no need to decode or encode */
  1793. codec->codec_id = icodec->codec_id;
  1794. codec->codec_type = icodec->codec_type;
  1795. if (!codec->codec_tag) {
  1796. unsigned int codec_tag;
  1797. if (!oc->oformat->codec_tag ||
  1798. av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
  1799. !av_codec_get_tag2(oc->oformat->codec_tag, icodec->codec_id, &codec_tag))
  1800. codec->codec_tag = icodec->codec_tag;
  1801. }
  1802. codec->bit_rate = icodec->bit_rate;
  1803. codec->rc_max_rate = icodec->rc_max_rate;
  1804. codec->rc_buffer_size = icodec->rc_buffer_size;
  1805. codec->field_order = icodec->field_order;
  1806. codec->extradata = av_mallocz(extra_size);
  1807. if (!codec->extradata) {
  1808. return AVERROR(ENOMEM);
  1809. }
  1810. memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
  1811. codec->extradata_size= icodec->extradata_size;
  1812. codec->bits_per_coded_sample = icodec->bits_per_coded_sample;
  1813. codec->time_base = ist->st->time_base;
  1814. /*
  1815. * Avi is a special case here because it supports variable fps but
  1816. * having the fps and timebase differe significantly adds quite some
  1817. * overhead
  1818. */
  1819. if(!strcmp(oc->oformat->name, "avi")) {
  1820. if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
  1821. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
  1822. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
  1823. && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
  1824. || copy_tb==2){
  1825. codec->time_base.num = ist->st->r_frame_rate.den;
  1826. codec->time_base.den = 2*ist->st->r_frame_rate.num;
  1827. codec->ticks_per_frame = 2;
  1828. } else if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
  1829. && av_q2d(ist->st->time_base) < 1.0/500
  1830. || copy_tb==0){
  1831. codec->time_base = icodec->time_base;
  1832. codec->time_base.num *= icodec->ticks_per_frame;
  1833. codec->time_base.den *= 2;
  1834. codec->ticks_per_frame = 2;
  1835. }
  1836. } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
  1837. && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
  1838. && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
  1839. && strcmp(oc->oformat->name, "f4v")
  1840. ) {
  1841. if( copy_tb<0 && icodec->time_base.den
  1842. && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
  1843. && av_q2d(ist->st->time_base) < 1.0/500
  1844. || copy_tb==0){
  1845. codec->time_base = icodec->time_base;
  1846. codec->time_base.num *= icodec->ticks_per_frame;
  1847. }
  1848. }
  1849. if ( codec->codec_tag == AV_RL32("tmcd")
  1850. && icodec->time_base.num < icodec->time_base.den
  1851. && icodec->time_base.num > 0
  1852. && 121LL*icodec->time_base.num > icodec->time_base.den) {
  1853. codec->time_base = icodec->time_base;
  1854. }
  1855. if(ost->frame_rate.num)
  1856. codec->time_base = av_inv_q(ost->frame_rate);
  1857. av_reduce(&codec->time_base.num, &codec->time_base.den,
  1858. codec->time_base.num, codec->time_base.den, INT_MAX);
  1859. switch (codec->codec_type) {
  1860. case AVMEDIA_TYPE_AUDIO:
  1861. if (audio_volume != 256) {
  1862. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  1863. exit(1);
  1864. }
  1865. codec->channel_layout = icodec->channel_layout;
  1866. codec->sample_rate = icodec->sample_rate;
  1867. codec->channels = icodec->channels;
  1868. codec->frame_size = icodec->frame_size;
  1869. codec->audio_service_type = icodec->audio_service_type;
  1870. codec->block_align = icodec->block_align;
  1871. if((codec->block_align == 1 || codec->block_align == 1152) && codec->codec_id == AV_CODEC_ID_MP3)
  1872. codec->block_align= 0;
  1873. if(codec->codec_id == AV_CODEC_ID_AC3)
  1874. codec->block_align= 0;
  1875. break;
  1876. case AVMEDIA_TYPE_VIDEO:
  1877. codec->pix_fmt = icodec->pix_fmt;
  1878. codec->width = icodec->width;
  1879. codec->height = icodec->height;
  1880. codec->has_b_frames = icodec->has_b_frames;
  1881. if (!codec->sample_aspect_ratio.num) {
  1882. codec->sample_aspect_ratio =
  1883. ost->st->sample_aspect_ratio =
  1884. ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
  1885. ist->st->codec->sample_aspect_ratio.num ?
  1886. ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
  1887. }
  1888. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
  1889. break;
  1890. case AVMEDIA_TYPE_SUBTITLE:
  1891. codec->width = icodec->width;
  1892. codec->height = icodec->height;
  1893. break;
  1894. case AVMEDIA_TYPE_DATA:
  1895. case AVMEDIA_TYPE_ATTACHMENT:
  1896. break;
  1897. default:
  1898. abort();
  1899. }
  1900. } else {
  1901. if (!ost->enc)
  1902. ost->enc = avcodec_find_encoder(codec->codec_id);
  1903. if (!ost->enc) {
  1904. /* should only happen when a default codec is not present. */
  1905. snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
  1906. avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
  1907. ret = AVERROR(EINVAL);
  1908. goto dump_format;
  1909. }
  1910. if (ist)
  1911. ist->decoding_needed++;
  1912. ost->encoding_needed = 1;
  1913. if (!ost->filter &&
  1914. (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  1915. codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
  1916. FilterGraph *fg;
  1917. fg = init_simple_filtergraph(ist, ost);
  1918. if (configure_filtergraph(fg)) {
  1919. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  1920. exit(1);
  1921. }
  1922. }
  1923. if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1924. if (ost->filter && !ost->frame_rate.num)
  1925. ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
  1926. if (ist && !ost->frame_rate.num)
  1927. ost->frame_rate = ist->framerate;
  1928. if (ist && !ost->frame_rate.num)
  1929. ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
  1930. // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
  1931. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  1932. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  1933. ost->frame_rate = ost->enc->supported_framerates[idx];
  1934. }
  1935. }
  1936. switch (codec->codec_type) {
  1937. case AVMEDIA_TYPE_AUDIO:
  1938. codec->sample_fmt = ost->filter->filter->inputs[0]->format;
  1939. codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  1940. codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  1941. codec->channels = av_get_channel_layout_nb_channels(codec->channel_layout);
  1942. codec->time_base = (AVRational){ 1, codec->sample_rate };
  1943. break;
  1944. case AVMEDIA_TYPE_VIDEO:
  1945. codec->time_base = av_inv_q(ost->frame_rate);
  1946. if (ost->filter && !(codec->time_base.num && codec->time_base.den))
  1947. codec->time_base = ost->filter->filter->inputs[0]->time_base;
  1948. if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
  1949. && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
  1950. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
  1951. "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
  1952. }
  1953. for (j = 0; j < ost->forced_kf_count; j++)
  1954. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
  1955. AV_TIME_BASE_Q,
  1956. codec->time_base);
  1957. codec->width = ost->filter->filter->inputs[0]->w;
  1958. codec->height = ost->filter->filter->inputs[0]->h;
  1959. codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  1960. ost->frame_aspect_ratio ? // overridden by the -aspect cli option
  1961. av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
  1962. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  1963. codec->pix_fmt = ost->filter->filter->inputs[0]->format;
  1964. if (!icodec ||
  1965. codec->width != icodec->width ||
  1966. codec->height != icodec->height ||
  1967. codec->pix_fmt != icodec->pix_fmt) {
  1968. codec->bits_per_raw_sample = frame_bits_per_raw_sample;
  1969. }
  1970. if (ost->forced_keyframes)
  1971. parse_forced_key_frames(ost->forced_keyframes, ost,
  1972. ost->st->codec);
  1973. break;
  1974. case AVMEDIA_TYPE_SUBTITLE:
  1975. codec->time_base = (AVRational){1, 1000};
  1976. if (!codec->width) {
  1977. codec->width = input_streams[ost->source_index]->st->codec->width;
  1978. codec->height = input_streams[ost->source_index]->st->codec->height;
  1979. }
  1980. break;
  1981. default:
  1982. abort();
  1983. break;
  1984. }
  1985. /* two pass mode */
  1986. if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
  1987. char logfilename[1024];
  1988. FILE *f;
  1989. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  1990. ost->logfile_prefix ? ost->logfile_prefix :
  1991. DEFAULT_PASS_LOGFILENAME_PREFIX,
  1992. i);
  1993. if (!strcmp(ost->enc->name, "libx264")) {
  1994. av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  1995. } else {
  1996. if (codec->flags & CODEC_FLAG_PASS2) {
  1997. char *logbuffer;
  1998. size_t logbuffer_size;
  1999. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
  2000. av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  2001. logfilename);
  2002. exit(1);
  2003. }
  2004. codec->stats_in = logbuffer;
  2005. }
  2006. if (codec->flags & CODEC_FLAG_PASS1) {
  2007. f = fopen(logfilename, "wb");
  2008. if (!f) {
  2009. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
  2010. logfilename, strerror(errno));
  2011. exit(1);
  2012. }
  2013. ost->logfile = f;
  2014. }
  2015. }
  2016. }
  2017. }
  2018. }
  2019. /* open each encoder */
  2020. for (i = 0; i < nb_output_streams; i++) {
  2021. ost = output_streams[i];
  2022. if (ost->encoding_needed) {
  2023. AVCodec *codec = ost->enc;
  2024. AVCodecContext *dec = NULL;
  2025. if ((ist = get_input_stream(ost)))
  2026. dec = ist->st->codec;
  2027. if (dec && dec->subtitle_header) {
  2028. /* ASS code assumes this buffer is null terminated so add extra byte. */
  2029. ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
  2030. if (!ost->st->codec->subtitle_header) {
  2031. ret = AVERROR(ENOMEM);
  2032. goto dump_format;
  2033. }
  2034. memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  2035. ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
  2036. }
  2037. if (!av_dict_get(ost->opts, "threads", NULL, 0))
  2038. av_dict_set(&ost->opts, "threads", "auto", 0);
  2039. if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
  2040. if (ret == AVERROR_EXPERIMENTAL)
  2041. abort_codec_experimental(codec, 1);
  2042. snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
  2043. ost->file_index, ost->index);
  2044. goto dump_format;
  2045. }
  2046. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  2047. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  2048. av_buffersink_set_frame_size(ost->filter->filter,
  2049. ost->st->codec->frame_size);
  2050. assert_avoptions(ost->opts);
  2051. if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
  2052. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  2053. " It takes bits/s as argument, not kbits/s\n");
  2054. extra_size += ost->st->codec->extradata_size;
  2055. if (ost->st->codec->me_threshold)
  2056. input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
  2057. }
  2058. }
  2059. /* init input streams */
  2060. for (i = 0; i < nb_input_streams; i++)
  2061. if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
  2062. goto dump_format;
  2063. /* discard unused programs */
  2064. for (i = 0; i < nb_input_files; i++) {
  2065. InputFile *ifile = input_files[i];
  2066. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  2067. AVProgram *p = ifile->ctx->programs[j];
  2068. int discard = AVDISCARD_ALL;
  2069. for (k = 0; k < p->nb_stream_indexes; k++)
  2070. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  2071. discard = AVDISCARD_DEFAULT;
  2072. break;
  2073. }
  2074. p->discard = discard;
  2075. }
  2076. }
  2077. /* open files and write file headers */
  2078. for (i = 0; i < nb_output_files; i++) {
  2079. oc = output_files[i]->ctx;
  2080. oc->interrupt_callback = int_cb;
  2081. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  2082. char errbuf[128];
  2083. const char *errbuf_ptr = errbuf;
  2084. if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
  2085. errbuf_ptr = strerror(AVUNERROR(ret));
  2086. snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
  2087. ret = AVERROR(EINVAL);
  2088. goto dump_format;
  2089. }
  2090. // assert_avoptions(output_files[i]->opts);
  2091. if (strcmp(oc->oformat->name, "rtp")) {
  2092. want_sdp = 0;
  2093. }
  2094. }
  2095. dump_format:
  2096. /* dump the file output parameters - cannot be done before in case
  2097. of stream copy */
  2098. for (i = 0; i < nb_output_files; i++) {
  2099. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  2100. }
  2101. /* dump the stream mapping */
  2102. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  2103. for (i = 0; i < nb_input_streams; i++) {
  2104. ist = input_streams[i];
  2105. for (j = 0; j < ist->nb_filters; j++) {
  2106. if (ist->filters[j]->graph->graph_desc) {
  2107. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  2108. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  2109. ist->filters[j]->name);
  2110. if (nb_filtergraphs > 1)
  2111. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  2112. av_log(NULL, AV_LOG_INFO, "\n");
  2113. }
  2114. }
  2115. }
  2116. for (i = 0; i < nb_output_streams; i++) {
  2117. ost = output_streams[i];
  2118. if (ost->attachment_filename) {
  2119. /* an attached file */
  2120. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  2121. ost->attachment_filename, ost->file_index, ost->index);
  2122. continue;
  2123. }
  2124. if (ost->filter && ost->filter->graph->graph_desc) {
  2125. /* output from a complex graph */
  2126. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  2127. if (nb_filtergraphs > 1)
  2128. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  2129. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  2130. ost->index, ost->enc ? ost->enc->name : "?");
  2131. continue;
  2132. }
  2133. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  2134. input_streams[ost->source_index]->file_index,
  2135. input_streams[ost->source_index]->st->index,
  2136. ost->file_index,
  2137. ost->index);
  2138. if (ost->sync_ist != input_streams[ost->source_index])
  2139. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  2140. ost->sync_ist->file_index,
  2141. ost->sync_ist->st->index);
  2142. if (ost->stream_copy)
  2143. av_log(NULL, AV_LOG_INFO, " (copy)");
  2144. else
  2145. av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
  2146. input_streams[ost->source_index]->dec->name : "?",
  2147. ost->enc ? ost->enc->name : "?");
  2148. av_log(NULL, AV_LOG_INFO, "\n");
  2149. }
  2150. if (ret) {
  2151. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  2152. return ret;
  2153. }
  2154. if (want_sdp) {
  2155. print_sdp();
  2156. }
  2157. return 0;
  2158. }
  2159. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  2160. static int need_output(void)
  2161. {
  2162. int i;
  2163. for (i = 0; i < nb_output_streams; i++) {
  2164. OutputStream *ost = output_streams[i];
  2165. OutputFile *of = output_files[ost->file_index];
  2166. AVFormatContext *os = output_files[ost->file_index]->ctx;
  2167. if (ost->finished ||
  2168. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  2169. continue;
  2170. if (ost->frame_number >= ost->max_frames) {
  2171. int j;
  2172. for (j = 0; j < of->ctx->nb_streams; j++)
  2173. close_output_stream(output_streams[of->ost_index + j]);
  2174. continue;
  2175. }
  2176. return 1;
  2177. }
  2178. return 0;
  2179. }
  2180. /**
  2181. * Select the output stream to process.
  2182. *
  2183. * @return selected output stream, or NULL if none available
  2184. */
  2185. static OutputStream *choose_output(void)
  2186. {
  2187. int i;
  2188. int64_t opts_min = INT64_MAX;
  2189. OutputStream *ost_min = NULL;
  2190. for (i = 0; i < nb_output_streams; i++) {
  2191. OutputStream *ost = output_streams[i];
  2192. int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
  2193. AV_TIME_BASE_Q);
  2194. if (!ost->unavailable && !ost->finished && opts < opts_min) {
  2195. opts_min = opts;
  2196. ost_min = ost;
  2197. }
  2198. }
  2199. return ost_min;
  2200. }
  2201. static int check_keyboard_interaction(int64_t cur_time)
  2202. {
  2203. int i, ret, key;
  2204. static int64_t last_time;
  2205. if (received_nb_signals)
  2206. return AVERROR_EXIT;
  2207. /* read_key() returns 0 on EOF */
  2208. if(cur_time - last_time >= 100000 && !run_as_daemon){
  2209. key = read_key();
  2210. last_time = cur_time;
  2211. }else
  2212. key = -1;
  2213. if (key == 'q')
  2214. return AVERROR_EXIT;
  2215. if (key == '+') av_log_set_level(av_log_get_level()+10);
  2216. if (key == '-') av_log_set_level(av_log_get_level()-10);
  2217. if (key == 's') qp_hist ^= 1;
  2218. if (key == 'h'){
  2219. if (do_hex_dump){
  2220. do_hex_dump = do_pkt_dump = 0;
  2221. } else if(do_pkt_dump){
  2222. do_hex_dump = 1;
  2223. } else
  2224. do_pkt_dump = 1;
  2225. av_log_set_level(AV_LOG_DEBUG);
  2226. }
  2227. if (key == 'c' || key == 'C'){
  2228. char buf[4096], target[64], command[256], arg[256] = {0};
  2229. double time;
  2230. int k, n = 0;
  2231. fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
  2232. i = 0;
  2233. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  2234. if (k > 0)
  2235. buf[i++] = k;
  2236. buf[i] = 0;
  2237. if (k > 0 &&
  2238. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  2239. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  2240. target, time, command, arg);
  2241. for (i = 0; i < nb_filtergraphs; i++) {
  2242. FilterGraph *fg = filtergraphs[i];
  2243. if (fg->graph) {
  2244. if (time < 0) {
  2245. ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
  2246. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
  2247. fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
  2248. } else {
  2249. ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
  2250. }
  2251. }
  2252. }
  2253. } else {
  2254. av_log(NULL, AV_LOG_ERROR,
  2255. "Parse error, at least 3 arguments were expected, "
  2256. "only %d given in string '%s'\n", n, buf);
  2257. }
  2258. }
  2259. if (key == 'd' || key == 'D'){
  2260. int debug=0;
  2261. if(key == 'D') {
  2262. debug = input_streams[0]->st->codec->debug<<1;
  2263. if(!debug) debug = 1;
  2264. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
  2265. debug += debug;
  2266. }else
  2267. if(scanf("%d", &debug)!=1)
  2268. fprintf(stderr,"error parsing debug value\n");
  2269. for(i=0;i<nb_input_streams;i++) {
  2270. input_streams[i]->st->codec->debug = debug;
  2271. }
  2272. for(i=0;i<nb_output_streams;i++) {
  2273. OutputStream *ost = output_streams[i];
  2274. ost->st->codec->debug = debug;
  2275. }
  2276. if(debug) av_log_set_level(AV_LOG_DEBUG);
  2277. fprintf(stderr,"debug=%d\n", debug);
  2278. }
  2279. if (key == '?'){
  2280. fprintf(stderr, "key function\n"
  2281. "? show this help\n"
  2282. "+ increase verbosity\n"
  2283. "- decrease verbosity\n"
  2284. "c Send command to filtergraph\n"
  2285. "D cycle through available debug modes\n"
  2286. "h dump packets/hex press to cycle through the 3 states\n"
  2287. "q quit\n"
  2288. "s Show QP histogram\n"
  2289. );
  2290. }
  2291. return 0;
  2292. }
  2293. #if HAVE_PTHREADS
  2294. static void *input_thread(void *arg)
  2295. {
  2296. InputFile *f = arg;
  2297. int ret = 0;
  2298. while (!transcoding_finished && ret >= 0) {
  2299. AVPacket pkt;
  2300. ret = av_read_frame(f->ctx, &pkt);
  2301. if (ret == AVERROR(EAGAIN)) {
  2302. av_usleep(10000);
  2303. ret = 0;
  2304. continue;
  2305. } else if (ret < 0)
  2306. break;
  2307. pthread_mutex_lock(&f->fifo_lock);
  2308. while (!av_fifo_space(f->fifo))
  2309. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  2310. av_dup_packet(&pkt);
  2311. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  2312. pthread_mutex_unlock(&f->fifo_lock);
  2313. }
  2314. f->finished = 1;
  2315. return NULL;
  2316. }
  2317. static void free_input_threads(void)
  2318. {
  2319. int i;
  2320. if (nb_input_files == 1)
  2321. return;
  2322. transcoding_finished = 1;
  2323. for (i = 0; i < nb_input_files; i++) {
  2324. InputFile *f = input_files[i];
  2325. AVPacket pkt;
  2326. if (!f->fifo || f->joined)
  2327. continue;
  2328. pthread_mutex_lock(&f->fifo_lock);
  2329. while (av_fifo_size(f->fifo)) {
  2330. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2331. av_free_packet(&pkt);
  2332. }
  2333. pthread_cond_signal(&f->fifo_cond);
  2334. pthread_mutex_unlock(&f->fifo_lock);
  2335. pthread_join(f->thread, NULL);
  2336. f->joined = 1;
  2337. while (av_fifo_size(f->fifo)) {
  2338. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2339. av_free_packet(&pkt);
  2340. }
  2341. av_fifo_free(f->fifo);
  2342. }
  2343. }
  2344. static int init_input_threads(void)
  2345. {
  2346. int i, ret;
  2347. if (nb_input_files == 1)
  2348. return 0;
  2349. for (i = 0; i < nb_input_files; i++) {
  2350. InputFile *f = input_files[i];
  2351. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  2352. return AVERROR(ENOMEM);
  2353. pthread_mutex_init(&f->fifo_lock, NULL);
  2354. pthread_cond_init (&f->fifo_cond, NULL);
  2355. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  2356. return AVERROR(ret);
  2357. }
  2358. return 0;
  2359. }
  2360. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  2361. {
  2362. int ret = 0;
  2363. pthread_mutex_lock(&f->fifo_lock);
  2364. if (av_fifo_size(f->fifo)) {
  2365. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  2366. pthread_cond_signal(&f->fifo_cond);
  2367. } else {
  2368. if (f->finished)
  2369. ret = AVERROR_EOF;
  2370. else
  2371. ret = AVERROR(EAGAIN);
  2372. }
  2373. pthread_mutex_unlock(&f->fifo_lock);
  2374. return ret;
  2375. }
  2376. #endif
  2377. static int get_input_packet(InputFile *f, AVPacket *pkt)
  2378. {
  2379. #if HAVE_PTHREADS
  2380. if (nb_input_files > 1)
  2381. return get_input_packet_mt(f, pkt);
  2382. #endif
  2383. return av_read_frame(f->ctx, pkt);
  2384. }
  2385. static int got_eagain(void)
  2386. {
  2387. int i;
  2388. for (i = 0; i < nb_output_streams; i++)
  2389. if (output_streams[i]->unavailable)
  2390. return 1;
  2391. return 0;
  2392. }
  2393. static void reset_eagain(void)
  2394. {
  2395. int i;
  2396. for (i = 0; i < nb_input_files; i++)
  2397. input_files[i]->eagain = 0;
  2398. for (i = 0; i < nb_output_streams; i++)
  2399. output_streams[i]->unavailable = 0;
  2400. }
  2401. /*
  2402. * Return
  2403. * - 0 -- one packet was read and processed
  2404. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  2405. * this function should be called again
  2406. * - AVERROR_EOF -- this function should not be called again
  2407. */
  2408. static int process_input(int file_index)
  2409. {
  2410. InputFile *ifile = input_files[file_index];
  2411. AVFormatContext *is;
  2412. InputStream *ist;
  2413. AVPacket pkt;
  2414. int ret, i, j;
  2415. is = ifile->ctx;
  2416. ret = get_input_packet(ifile, &pkt);
  2417. if (ret == AVERROR(EAGAIN)) {
  2418. ifile->eagain = 1;
  2419. return ret;
  2420. }
  2421. if (ret < 0) {
  2422. if (ret != AVERROR_EOF) {
  2423. print_error(is->filename, ret);
  2424. if (exit_on_error)
  2425. exit(1);
  2426. }
  2427. ifile->eof_reached = 1;
  2428. for (i = 0; i < ifile->nb_streams; i++) {
  2429. ist = input_streams[ifile->ist_index + i];
  2430. if (ist->decoding_needed)
  2431. output_packet(ist, NULL);
  2432. /* mark all outputs that don't go through lavfi as finished */
  2433. for (j = 0; j < nb_output_streams; j++) {
  2434. OutputStream *ost = output_streams[j];
  2435. if (ost->source_index == ifile->ist_index + i &&
  2436. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  2437. close_output_stream(ost);
  2438. }
  2439. }
  2440. return AVERROR(EAGAIN);
  2441. }
  2442. reset_eagain();
  2443. if (do_pkt_dump) {
  2444. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  2445. is->streams[pkt.stream_index]);
  2446. }
  2447. /* the following test is needed in case new streams appear
  2448. dynamically in stream : we ignore them */
  2449. if (pkt.stream_index >= ifile->nb_streams) {
  2450. report_new_stream(file_index, &pkt);
  2451. goto discard_packet;
  2452. }
  2453. ist = input_streams[ifile->ist_index + pkt.stream_index];
  2454. if (ist->discard)
  2455. goto discard_packet;
  2456. if (debug_ts) {
  2457. av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
  2458. "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",
  2459. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
  2460. av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
  2461. av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
  2462. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2463. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2464. av_ts2str(input_files[ist->file_index]->ts_offset),
  2465. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  2466. }
  2467. if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
  2468. int64_t stime, stime2;
  2469. // Correcting starttime based on the enabled streams
  2470. // 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.
  2471. // so we instead do it here as part of discontinuity handling
  2472. if ( ist->next_dts == AV_NOPTS_VALUE
  2473. && ifile->ts_offset == -is->start_time
  2474. && (is->iformat->flags & AVFMT_TS_DISCONT)) {
  2475. int64_t new_start_time = INT64_MAX;
  2476. for (i=0; i<is->nb_streams; i++) {
  2477. AVStream *st = is->streams[i];
  2478. if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
  2479. continue;
  2480. new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
  2481. }
  2482. if (new_start_time > is->start_time) {
  2483. av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
  2484. ifile->ts_offset = -new_start_time;
  2485. }
  2486. }
  2487. stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
  2488. stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
  2489. ist->wrap_correction_done = 1;
  2490. if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  2491. pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
  2492. ist->wrap_correction_done = 0;
  2493. }
  2494. if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  2495. pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
  2496. ist->wrap_correction_done = 0;
  2497. }
  2498. }
  2499. if (pkt.dts != AV_NOPTS_VALUE)
  2500. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2501. if (pkt.pts != AV_NOPTS_VALUE)
  2502. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2503. if (pkt.pts != AV_NOPTS_VALUE)
  2504. pkt.pts *= ist->ts_scale;
  2505. if (pkt.dts != AV_NOPTS_VALUE)
  2506. pkt.dts *= ist->ts_scale;
  2507. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  2508. !copy_ts) {
  2509. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2510. int64_t delta = pkt_dts - ist->next_dts;
  2511. if (is->iformat->flags & AVFMT_TS_DISCONT) {
  2512. if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2513. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2514. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2515. pkt_dts+1<ist->pts){
  2516. ifile->ts_offset -= delta;
  2517. av_log(NULL, AV_LOG_DEBUG,
  2518. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2519. delta, ifile->ts_offset);
  2520. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2521. if (pkt.pts != AV_NOPTS_VALUE)
  2522. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2523. }
  2524. } else {
  2525. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2526. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
  2527. ) {
  2528. av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
  2529. pkt.dts = AV_NOPTS_VALUE;
  2530. }
  2531. if (pkt.pts != AV_NOPTS_VALUE){
  2532. int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
  2533. delta = pkt_pts - ist->next_dts;
  2534. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2535. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)
  2536. ) {
  2537. av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
  2538. pkt.pts = AV_NOPTS_VALUE;
  2539. }
  2540. }
  2541. }
  2542. }
  2543. if (debug_ts) {
  2544. 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",
  2545. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),
  2546. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2547. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2548. av_ts2str(input_files[ist->file_index]->ts_offset),
  2549. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  2550. }
  2551. sub2video_heartbeat(ist, pkt.pts);
  2552. ret = output_packet(ist, &pkt);
  2553. if (ret < 0) {
  2554. char buf[128];
  2555. av_strerror(ret, buf, sizeof(buf));
  2556. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
  2557. ist->file_index, ist->st->index, buf);
  2558. if (exit_on_error)
  2559. exit(1);
  2560. }
  2561. discard_packet:
  2562. av_free_packet(&pkt);
  2563. return 0;
  2564. }
  2565. /**
  2566. * Perform a step of transcoding for the specified filter graph.
  2567. *
  2568. * @param[in] graph filter graph to consider
  2569. * @param[out] best_ist input stream where a frame would allow to continue
  2570. * @return 0 for success, <0 for error
  2571. */
  2572. static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
  2573. {
  2574. int i, ret;
  2575. int nb_requests, nb_requests_max = 0;
  2576. InputFilter *ifilter;
  2577. InputStream *ist;
  2578. *best_ist = NULL;
  2579. ret = avfilter_graph_request_oldest(graph->graph);
  2580. if (ret >= 0)
  2581. return reap_filters();
  2582. if (ret == AVERROR_EOF) {
  2583. ret = reap_filters();
  2584. for (i = 0; i < graph->nb_outputs; i++)
  2585. close_output_stream(graph->outputs[i]->ost);
  2586. return ret;
  2587. }
  2588. if (ret != AVERROR(EAGAIN))
  2589. return ret;
  2590. for (i = 0; i < graph->nb_inputs; i++) {
  2591. ifilter = graph->inputs[i];
  2592. ist = ifilter->ist;
  2593. if (input_files[ist->file_index]->eagain ||
  2594. input_files[ist->file_index]->eof_reached)
  2595. continue;
  2596. nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
  2597. if (nb_requests > nb_requests_max) {
  2598. nb_requests_max = nb_requests;
  2599. *best_ist = ist;
  2600. }
  2601. }
  2602. if (!*best_ist)
  2603. for (i = 0; i < graph->nb_outputs; i++)
  2604. graph->outputs[i]->ost->unavailable = 1;
  2605. return 0;
  2606. }
  2607. /**
  2608. * Run a single step of transcoding.
  2609. *
  2610. * @return 0 for success, <0 for error
  2611. */
  2612. static int transcode_step(void)
  2613. {
  2614. OutputStream *ost;
  2615. InputStream *ist;
  2616. int ret;
  2617. ost = choose_output();
  2618. if (!ost) {
  2619. if (got_eagain()) {
  2620. reset_eagain();
  2621. av_usleep(10000);
  2622. return 0;
  2623. }
  2624. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
  2625. return AVERROR_EOF;
  2626. }
  2627. if (ost->filter) {
  2628. if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
  2629. return ret;
  2630. if (!ist)
  2631. return 0;
  2632. } else {
  2633. av_assert0(ost->source_index >= 0);
  2634. ist = input_streams[ost->source_index];
  2635. }
  2636. ret = process_input(ist->file_index);
  2637. if (ret == AVERROR(EAGAIN)) {
  2638. if (input_files[ist->file_index]->eagain)
  2639. ost->unavailable = 1;
  2640. return 0;
  2641. }
  2642. if (ret < 0)
  2643. return ret == AVERROR_EOF ? 0 : ret;
  2644. return reap_filters();
  2645. }
  2646. /*
  2647. * The following code is the main loop of the file converter
  2648. */
  2649. static int transcode(void)
  2650. {
  2651. int ret, i;
  2652. AVFormatContext *os;
  2653. OutputStream *ost;
  2654. InputStream *ist;
  2655. int64_t timer_start;
  2656. ret = transcode_init();
  2657. if (ret < 0)
  2658. goto fail;
  2659. if (stdin_interaction) {
  2660. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  2661. }
  2662. timer_start = av_gettime();
  2663. #if HAVE_PTHREADS
  2664. if ((ret = init_input_threads()) < 0)
  2665. goto fail;
  2666. #endif
  2667. while (!received_sigterm) {
  2668. int64_t cur_time= av_gettime();
  2669. /* if 'q' pressed, exits */
  2670. if (stdin_interaction)
  2671. if (check_keyboard_interaction(cur_time) < 0)
  2672. break;
  2673. /* check if there's any stream where output is still needed */
  2674. if (!need_output()) {
  2675. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  2676. break;
  2677. }
  2678. ret = transcode_step();
  2679. if (ret < 0) {
  2680. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  2681. continue;
  2682. av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
  2683. break;
  2684. }
  2685. /* dump report by using the output first video and audio streams */
  2686. print_report(0, timer_start, cur_time);
  2687. }
  2688. #if HAVE_PTHREADS
  2689. free_input_threads();
  2690. #endif
  2691. /* at the end of stream, we must flush the decoder buffers */
  2692. for (i = 0; i < nb_input_streams; i++) {
  2693. ist = input_streams[i];
  2694. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  2695. output_packet(ist, NULL);
  2696. }
  2697. }
  2698. flush_encoders();
  2699. term_exit();
  2700. /* write the trailer if needed and close file */
  2701. for (i = 0; i < nb_output_files; i++) {
  2702. os = output_files[i]->ctx;
  2703. av_write_trailer(os);
  2704. }
  2705. /* dump report by using the first video and audio streams */
  2706. print_report(1, timer_start, av_gettime());
  2707. /* close each encoder */
  2708. for (i = 0; i < nb_output_streams; i++) {
  2709. ost = output_streams[i];
  2710. if (ost->encoding_needed) {
  2711. av_freep(&ost->st->codec->stats_in);
  2712. avcodec_close(ost->st->codec);
  2713. }
  2714. }
  2715. /* close each decoder */
  2716. for (i = 0; i < nb_input_streams; i++) {
  2717. ist = input_streams[i];
  2718. if (ist->decoding_needed) {
  2719. avcodec_close(ist->st->codec);
  2720. }
  2721. }
  2722. /* finished ! */
  2723. ret = 0;
  2724. fail:
  2725. #if HAVE_PTHREADS
  2726. free_input_threads();
  2727. #endif
  2728. if (output_streams) {
  2729. for (i = 0; i < nb_output_streams; i++) {
  2730. ost = output_streams[i];
  2731. if (ost) {
  2732. if (ost->stream_copy)
  2733. av_freep(&ost->st->codec->extradata);
  2734. if (ost->logfile) {
  2735. fclose(ost->logfile);
  2736. ost->logfile = NULL;
  2737. }
  2738. av_freep(&ost->st->codec->subtitle_header);
  2739. av_free(ost->forced_kf_pts);
  2740. av_dict_free(&ost->opts);
  2741. }
  2742. }
  2743. }
  2744. return ret;
  2745. }
  2746. static int64_t getutime(void)
  2747. {
  2748. #if HAVE_GETRUSAGE
  2749. struct rusage rusage;
  2750. getrusage(RUSAGE_SELF, &rusage);
  2751. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2752. #elif HAVE_GETPROCESSTIMES
  2753. HANDLE proc;
  2754. FILETIME c, e, k, u;
  2755. proc = GetCurrentProcess();
  2756. GetProcessTimes(proc, &c, &e, &k, &u);
  2757. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  2758. #else
  2759. return av_gettime();
  2760. #endif
  2761. }
  2762. static int64_t getmaxrss(void)
  2763. {
  2764. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  2765. struct rusage rusage;
  2766. getrusage(RUSAGE_SELF, &rusage);
  2767. return (int64_t)rusage.ru_maxrss * 1024;
  2768. #elif HAVE_GETPROCESSMEMORYINFO
  2769. HANDLE proc;
  2770. PROCESS_MEMORY_COUNTERS memcounters;
  2771. proc = GetCurrentProcess();
  2772. memcounters.cb = sizeof(memcounters);
  2773. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  2774. return memcounters.PeakPagefileUsage;
  2775. #else
  2776. return 0;
  2777. #endif
  2778. }
  2779. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
  2780. {
  2781. }
  2782. int main(int argc, char **argv)
  2783. {
  2784. int ret;
  2785. int64_t ti;
  2786. atexit(exit_program);
  2787. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
  2788. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2789. parse_loglevel(argc, argv, options);
  2790. if(argc>1 && !strcmp(argv[1], "-d")){
  2791. run_as_daemon=1;
  2792. av_log_set_callback(log_callback_null);
  2793. argc--;
  2794. argv++;
  2795. }
  2796. avcodec_register_all();
  2797. #if CONFIG_AVDEVICE
  2798. avdevice_register_all();
  2799. #endif
  2800. avfilter_register_all();
  2801. av_register_all();
  2802. avformat_network_init();
  2803. show_banner(argc, argv, options);
  2804. term_init();
  2805. /* parse options and open all input/output files */
  2806. ret = ffmpeg_parse_options(argc, argv);
  2807. if (ret < 0)
  2808. exit(1);
  2809. if (nb_output_files <= 0 && nb_input_files == 0) {
  2810. show_usage();
  2811. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  2812. exit(1);
  2813. }
  2814. /* file converter / grab */
  2815. if (nb_output_files <= 0) {
  2816. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  2817. exit(1);
  2818. }
  2819. // if (nb_input_files == 0) {
  2820. // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
  2821. // exit(1);
  2822. // }
  2823. current_time = ti = getutime();
  2824. if (transcode() < 0)
  2825. exit(1);
  2826. ti = getutime() - ti;
  2827. if (do_benchmark) {
  2828. int maxrss = getmaxrss() / 1024;
  2829. printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
  2830. }
  2831. exit(0);
  2832. return 0;
  2833. }