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.

3182 lines
109KB

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