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