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.

3230 lines
111KB

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