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.

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