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.

4034 lines
144KB

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