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.

3337 lines
117KB

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