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.

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