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.

3168 lines
108KB

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