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.

3322 lines
116KB

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