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.

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