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.

3147 lines
109KB

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