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.

3660 lines
129KB

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