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.

3582 lines
126KB

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