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.

3166 lines
108KB

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