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.

4036 lines
145KB

  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 = FFABS(pts) / AV_TIME_BASE;
  1330. us = FFABS(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. if (pts < 0)
  1341. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "-");
  1342. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1343. "%02d:%02d:%02d.%02d ", hours, mins, secs,
  1344. (100 * us) / AV_TIME_BASE);
  1345. if (bitrate < 0) {
  1346. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=N/A");
  1347. av_bprintf(&buf_script, "bitrate=N/A\n");
  1348. }else{
  1349. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),"bitrate=%6.1fkbits/s", bitrate);
  1350. av_bprintf(&buf_script, "bitrate=%6.1fkbits/s\n", bitrate);
  1351. }
  1352. if (total_size < 0) av_bprintf(&buf_script, "total_size=N/A\n");
  1353. else av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
  1354. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
  1355. av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
  1356. hours, mins, secs, us);
  1357. if (nb_frames_dup || nb_frames_drop)
  1358. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
  1359. nb_frames_dup, nb_frames_drop);
  1360. av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
  1361. av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
  1362. if (print_stats || is_last_report) {
  1363. const char end = is_last_report ? '\n' : '\r';
  1364. if (print_stats==1 && AV_LOG_INFO > av_log_get_level()) {
  1365. fprintf(stderr, "%s %c", buf, end);
  1366. } else
  1367. av_log(NULL, AV_LOG_INFO, "%s %c", buf, end);
  1368. fflush(stderr);
  1369. }
  1370. if (progress_avio) {
  1371. av_bprintf(&buf_script, "progress=%s\n",
  1372. is_last_report ? "end" : "continue");
  1373. avio_write(progress_avio, buf_script.str,
  1374. FFMIN(buf_script.len, buf_script.size - 1));
  1375. avio_flush(progress_avio);
  1376. av_bprint_finalize(&buf_script, NULL);
  1377. if (is_last_report) {
  1378. avio_closep(&progress_avio);
  1379. }
  1380. }
  1381. if (is_last_report)
  1382. print_final_stats(total_size);
  1383. }
  1384. static void flush_encoders(void)
  1385. {
  1386. int i, ret;
  1387. for (i = 0; i < nb_output_streams; i++) {
  1388. OutputStream *ost = output_streams[i];
  1389. AVCodecContext *enc = ost->enc_ctx;
  1390. AVFormatContext *os = output_files[ost->file_index]->ctx;
  1391. int stop_encoding = 0;
  1392. if (!ost->encoding_needed)
  1393. continue;
  1394. if (enc->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  1395. continue;
  1396. if (enc->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
  1397. continue;
  1398. for (;;) {
  1399. int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
  1400. const char *desc;
  1401. switch (enc->codec_type) {
  1402. case AVMEDIA_TYPE_AUDIO:
  1403. encode = avcodec_encode_audio2;
  1404. desc = "Audio";
  1405. break;
  1406. case AVMEDIA_TYPE_VIDEO:
  1407. encode = avcodec_encode_video2;
  1408. desc = "Video";
  1409. break;
  1410. default:
  1411. stop_encoding = 1;
  1412. }
  1413. if (encode) {
  1414. AVPacket pkt;
  1415. int pkt_size;
  1416. int got_packet;
  1417. av_init_packet(&pkt);
  1418. pkt.data = NULL;
  1419. pkt.size = 0;
  1420. update_benchmark(NULL);
  1421. ret = encode(enc, &pkt, NULL, &got_packet);
  1422. update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
  1423. if (ret < 0) {
  1424. av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
  1425. exit_program(1);
  1426. }
  1427. if (ost->logfile && enc->stats_out) {
  1428. fprintf(ost->logfile, "%s", enc->stats_out);
  1429. }
  1430. if (!got_packet) {
  1431. stop_encoding = 1;
  1432. break;
  1433. }
  1434. if (ost->finished & MUXER_FINISHED) {
  1435. av_free_packet(&pkt);
  1436. continue;
  1437. }
  1438. av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
  1439. pkt_size = pkt.size;
  1440. write_frame(os, &pkt, ost);
  1441. if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO && vstats_filename) {
  1442. do_video_stats(ost, pkt_size);
  1443. }
  1444. }
  1445. if (stop_encoding)
  1446. break;
  1447. }
  1448. }
  1449. }
  1450. /*
  1451. * Check whether a packet from ist should be written into ost at this time
  1452. */
  1453. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  1454. {
  1455. OutputFile *of = output_files[ost->file_index];
  1456. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  1457. if (ost->source_index != ist_index)
  1458. return 0;
  1459. if (ost->finished)
  1460. return 0;
  1461. if (of->start_time != AV_NOPTS_VALUE && ist->pts < of->start_time)
  1462. return 0;
  1463. return 1;
  1464. }
  1465. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  1466. {
  1467. OutputFile *of = output_files[ost->file_index];
  1468. InputFile *f = input_files [ist->file_index];
  1469. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  1470. int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
  1471. int64_t ist_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ist->st->time_base);
  1472. AVPicture pict;
  1473. AVPacket opkt;
  1474. av_init_packet(&opkt);
  1475. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  1476. !ost->copy_initial_nonkeyframes)
  1477. return;
  1478. if (pkt->pts == AV_NOPTS_VALUE) {
  1479. if (!ost->frame_number && ist->pts < start_time &&
  1480. !ost->copy_prior_start)
  1481. return;
  1482. } else {
  1483. if (!ost->frame_number && pkt->pts < ist_tb_start_time &&
  1484. !ost->copy_prior_start)
  1485. return;
  1486. }
  1487. if (of->recording_time != INT64_MAX &&
  1488. ist->pts >= of->recording_time + start_time) {
  1489. close_output_stream(ost);
  1490. return;
  1491. }
  1492. if (f->recording_time != INT64_MAX) {
  1493. start_time = f->ctx->start_time;
  1494. if (f->start_time != AV_NOPTS_VALUE)
  1495. start_time += f->start_time;
  1496. if (ist->pts >= f->recording_time + start_time) {
  1497. close_output_stream(ost);
  1498. return;
  1499. }
  1500. }
  1501. /* force the input stream PTS */
  1502. if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
  1503. ost->sync_opts++;
  1504. if (pkt->pts != AV_NOPTS_VALUE)
  1505. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  1506. else
  1507. opkt.pts = AV_NOPTS_VALUE;
  1508. if (pkt->dts == AV_NOPTS_VALUE)
  1509. opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
  1510. else
  1511. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  1512. opkt.dts -= ost_tb_start_time;
  1513. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
  1514. int duration = av_get_audio_frame_duration(ist->dec_ctx, pkt->size);
  1515. if(!duration)
  1516. duration = ist->dec_ctx->frame_size;
  1517. opkt.dts = opkt.pts = av_rescale_delta(ist->st->time_base, pkt->dts,
  1518. (AVRational){1, ist->dec_ctx->sample_rate}, duration, &ist->filter_in_rescale_delta_last,
  1519. ost->st->time_base) - ost_tb_start_time;
  1520. }
  1521. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  1522. opkt.flags = pkt->flags;
  1523. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  1524. if ( ost->enc_ctx->codec_id != AV_CODEC_ID_H264
  1525. && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG1VIDEO
  1526. && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG2VIDEO
  1527. && ost->enc_ctx->codec_id != AV_CODEC_ID_VC1
  1528. ) {
  1529. if (av_parser_change(ost->parser, ost->st->codec,
  1530. &opkt.data, &opkt.size,
  1531. pkt->data, pkt->size,
  1532. pkt->flags & AV_PKT_FLAG_KEY)) {
  1533. opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
  1534. if (!opkt.buf)
  1535. exit_program(1);
  1536. }
  1537. } else {
  1538. opkt.data = pkt->data;
  1539. opkt.size = pkt->size;
  1540. }
  1541. av_copy_packet_side_data(&opkt, pkt);
  1542. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
  1543. /* store AVPicture in AVPacket, as expected by the output format */
  1544. avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
  1545. opkt.data = (uint8_t *)&pict;
  1546. opkt.size = sizeof(AVPicture);
  1547. opkt.flags |= AV_PKT_FLAG_KEY;
  1548. }
  1549. write_frame(of->ctx, &opkt, ost);
  1550. }
  1551. int guess_input_channel_layout(InputStream *ist)
  1552. {
  1553. AVCodecContext *dec = ist->dec_ctx;
  1554. if (!dec->channel_layout) {
  1555. char layout_name[256];
  1556. if (dec->channels > ist->guess_layout_max)
  1557. return 0;
  1558. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  1559. if (!dec->channel_layout)
  1560. return 0;
  1561. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  1562. dec->channels, dec->channel_layout);
  1563. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  1564. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  1565. }
  1566. return 1;
  1567. }
  1568. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  1569. {
  1570. AVFrame *decoded_frame, *f;
  1571. AVCodecContext *avctx = ist->dec_ctx;
  1572. int i, ret, err = 0, resample_changed;
  1573. AVRational decoded_frame_tb;
  1574. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1575. return AVERROR(ENOMEM);
  1576. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1577. return AVERROR(ENOMEM);
  1578. decoded_frame = ist->decoded_frame;
  1579. update_benchmark(NULL);
  1580. ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
  1581. update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
  1582. if (ret >= 0 && avctx->sample_rate <= 0) {
  1583. av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
  1584. ret = AVERROR_INVALIDDATA;
  1585. }
  1586. if (*got_output || ret<0 || pkt->size)
  1587. decode_error_stat[ret<0] ++;
  1588. if (!*got_output || ret < 0) {
  1589. if (!pkt->size) {
  1590. for (i = 0; i < ist->nb_filters; i++)
  1591. #if 1
  1592. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1593. #else
  1594. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1595. #endif
  1596. }
  1597. return ret;
  1598. }
  1599. ist->samples_decoded += decoded_frame->nb_samples;
  1600. ist->frames_decoded++;
  1601. #if 1
  1602. /* increment next_dts to use for the case where the input stream does not
  1603. have timestamps or there are multiple frames in the packet */
  1604. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1605. avctx->sample_rate;
  1606. ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1607. avctx->sample_rate;
  1608. #endif
  1609. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  1610. ist->resample_channels != avctx->channels ||
  1611. ist->resample_channel_layout != decoded_frame->channel_layout ||
  1612. ist->resample_sample_rate != decoded_frame->sample_rate;
  1613. if (resample_changed) {
  1614. char layout1[64], layout2[64];
  1615. if (!guess_input_channel_layout(ist)) {
  1616. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  1617. "layout for Input Stream #%d.%d\n", ist->file_index,
  1618. ist->st->index);
  1619. exit_program(1);
  1620. }
  1621. decoded_frame->channel_layout = avctx->channel_layout;
  1622. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  1623. ist->resample_channel_layout);
  1624. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  1625. decoded_frame->channel_layout);
  1626. av_log(NULL, AV_LOG_INFO,
  1627. "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",
  1628. ist->file_index, ist->st->index,
  1629. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  1630. ist->resample_channels, layout1,
  1631. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  1632. avctx->channels, layout2);
  1633. ist->resample_sample_fmt = decoded_frame->format;
  1634. ist->resample_sample_rate = decoded_frame->sample_rate;
  1635. ist->resample_channel_layout = decoded_frame->channel_layout;
  1636. ist->resample_channels = avctx->channels;
  1637. for (i = 0; i < nb_filtergraphs; i++)
  1638. if (ist_in_filtergraph(filtergraphs[i], ist)) {
  1639. FilterGraph *fg = filtergraphs[i];
  1640. if (configure_filtergraph(fg) < 0) {
  1641. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1642. exit_program(1);
  1643. }
  1644. }
  1645. }
  1646. /* if the decoder provides a pts, use it instead of the last packet pts.
  1647. the decoder could be delaying output by a packet or more. */
  1648. if (decoded_frame->pts != AV_NOPTS_VALUE) {
  1649. ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
  1650. decoded_frame_tb = avctx->time_base;
  1651. } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
  1652. decoded_frame->pts = decoded_frame->pkt_pts;
  1653. decoded_frame_tb = ist->st->time_base;
  1654. } else if (pkt->pts != AV_NOPTS_VALUE) {
  1655. decoded_frame->pts = pkt->pts;
  1656. decoded_frame_tb = ist->st->time_base;
  1657. }else {
  1658. decoded_frame->pts = ist->dts;
  1659. decoded_frame_tb = AV_TIME_BASE_Q;
  1660. }
  1661. pkt->pts = AV_NOPTS_VALUE;
  1662. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1663. decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,
  1664. (AVRational){1, avctx->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,
  1665. (AVRational){1, avctx->sample_rate});
  1666. for (i = 0; i < ist->nb_filters; i++) {
  1667. if (i < ist->nb_filters - 1) {
  1668. f = ist->filter_frame;
  1669. err = av_frame_ref(f, decoded_frame);
  1670. if (err < 0)
  1671. break;
  1672. } else
  1673. f = decoded_frame;
  1674. err = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,
  1675. AV_BUFFERSRC_FLAG_PUSH);
  1676. if (err == AVERROR_EOF)
  1677. err = 0; /* ignore */
  1678. if (err < 0)
  1679. break;
  1680. }
  1681. decoded_frame->pts = AV_NOPTS_VALUE;
  1682. av_frame_unref(ist->filter_frame);
  1683. av_frame_unref(decoded_frame);
  1684. return err < 0 ? err : ret;
  1685. }
  1686. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  1687. {
  1688. AVFrame *decoded_frame, *f;
  1689. int i, ret = 0, err = 0, resample_changed;
  1690. int64_t best_effort_timestamp;
  1691. AVRational *frame_sample_aspect;
  1692. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1693. return AVERROR(ENOMEM);
  1694. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1695. return AVERROR(ENOMEM);
  1696. decoded_frame = ist->decoded_frame;
  1697. pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  1698. update_benchmark(NULL);
  1699. ret = avcodec_decode_video2(ist->dec_ctx,
  1700. decoded_frame, got_output, pkt);
  1701. update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
  1702. // The following line may be required in some cases where there is no parser
  1703. // or the parser does not has_b_frames correctly
  1704. if (ist->st->codec->has_b_frames < ist->dec_ctx->has_b_frames) {
  1705. if (ist->dec_ctx->codec_id == AV_CODEC_ID_H264) {
  1706. ist->st->codec->has_b_frames = ist->dec_ctx->has_b_frames;
  1707. } else
  1708. av_log_ask_for_sample(
  1709. ist->dec_ctx,
  1710. "has_b_frames is larger in decoder than demuxer %d > %d ",
  1711. ist->dec_ctx->has_b_frames,
  1712. ist->st->codec->has_b_frames
  1713. );
  1714. }
  1715. if (*got_output || ret<0 || pkt->size)
  1716. decode_error_stat[ret<0] ++;
  1717. if (*got_output && ret >= 0) {
  1718. if (ist->dec_ctx->width != decoded_frame->width ||
  1719. ist->dec_ctx->height != decoded_frame->height ||
  1720. ist->dec_ctx->pix_fmt != decoded_frame->format) {
  1721. av_log(NULL, AV_LOG_DEBUG, "Frame parameters mismatch context %d,%d,%d != %d,%d,%d\n",
  1722. decoded_frame->width,
  1723. decoded_frame->height,
  1724. decoded_frame->format,
  1725. ist->dec_ctx->width,
  1726. ist->dec_ctx->height,
  1727. ist->dec_ctx->pix_fmt);
  1728. }
  1729. }
  1730. if (!*got_output || ret < 0) {
  1731. if (!pkt->size) {
  1732. for (i = 0; i < ist->nb_filters; i++)
  1733. #if 1
  1734. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  1735. #else
  1736. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1737. #endif
  1738. }
  1739. return ret;
  1740. }
  1741. if(ist->top_field_first>=0)
  1742. decoded_frame->top_field_first = ist->top_field_first;
  1743. ist->frames_decoded++;
  1744. if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
  1745. err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
  1746. if (err < 0)
  1747. goto fail;
  1748. }
  1749. ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
  1750. best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
  1751. if(best_effort_timestamp != AV_NOPTS_VALUE)
  1752. ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
  1753. if (debug_ts) {
  1754. av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
  1755. "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",
  1756. ist->st->index, av_ts2str(decoded_frame->pts),
  1757. av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
  1758. best_effort_timestamp,
  1759. av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
  1760. decoded_frame->key_frame, decoded_frame->pict_type,
  1761. ist->st->time_base.num, ist->st->time_base.den);
  1762. }
  1763. pkt->size = 0;
  1764. if (ist->st->sample_aspect_ratio.num)
  1765. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1766. resample_changed = ist->resample_width != decoded_frame->width ||
  1767. ist->resample_height != decoded_frame->height ||
  1768. ist->resample_pix_fmt != decoded_frame->format;
  1769. if (resample_changed) {
  1770. av_log(NULL, AV_LOG_INFO,
  1771. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1772. ist->file_index, ist->st->index,
  1773. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1774. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1775. ist->resample_width = decoded_frame->width;
  1776. ist->resample_height = decoded_frame->height;
  1777. ist->resample_pix_fmt = decoded_frame->format;
  1778. for (i = 0; i < nb_filtergraphs; i++) {
  1779. if (ist_in_filtergraph(filtergraphs[i], ist) && ist->reinit_filters &&
  1780. configure_filtergraph(filtergraphs[i]) < 0) {
  1781. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1782. exit_program(1);
  1783. }
  1784. }
  1785. }
  1786. frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
  1787. for (i = 0; i < ist->nb_filters; i++) {
  1788. if (!frame_sample_aspect->num)
  1789. *frame_sample_aspect = ist->st->sample_aspect_ratio;
  1790. if (i < ist->nb_filters - 1) {
  1791. f = ist->filter_frame;
  1792. err = av_frame_ref(f, decoded_frame);
  1793. if (err < 0)
  1794. break;
  1795. } else
  1796. f = decoded_frame;
  1797. ret = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f, AV_BUFFERSRC_FLAG_PUSH);
  1798. if (ret == AVERROR_EOF) {
  1799. ret = 0; /* ignore */
  1800. } else if (ret < 0) {
  1801. av_log(NULL, AV_LOG_FATAL,
  1802. "Failed to inject frame into filter network: %s\n", av_err2str(ret));
  1803. exit_program(1);
  1804. }
  1805. }
  1806. fail:
  1807. av_frame_unref(ist->filter_frame);
  1808. av_frame_unref(decoded_frame);
  1809. return err < 0 ? err : ret;
  1810. }
  1811. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1812. {
  1813. AVSubtitle subtitle;
  1814. int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
  1815. &subtitle, got_output, pkt);
  1816. if (*got_output || ret<0 || pkt->size)
  1817. decode_error_stat[ret<0] ++;
  1818. if (ret < 0 || !*got_output) {
  1819. if (!pkt->size)
  1820. sub2video_flush(ist);
  1821. return ret;
  1822. }
  1823. if (ist->fix_sub_duration) {
  1824. int end = 1;
  1825. if (ist->prev_sub.got_output) {
  1826. end = av_rescale(subtitle.pts - ist->prev_sub.subtitle.pts,
  1827. 1000, AV_TIME_BASE);
  1828. if (end < ist->prev_sub.subtitle.end_display_time) {
  1829. av_log(ist->dec_ctx, AV_LOG_DEBUG,
  1830. "Subtitle duration reduced from %d to %d%s\n",
  1831. ist->prev_sub.subtitle.end_display_time, end,
  1832. end <= 0 ? ", dropping it" : "");
  1833. ist->prev_sub.subtitle.end_display_time = end;
  1834. }
  1835. }
  1836. FFSWAP(int, *got_output, ist->prev_sub.got_output);
  1837. FFSWAP(int, ret, ist->prev_sub.ret);
  1838. FFSWAP(AVSubtitle, subtitle, ist->prev_sub.subtitle);
  1839. if (end <= 0)
  1840. goto out;
  1841. }
  1842. if (!*got_output)
  1843. return ret;
  1844. sub2video_update(ist, &subtitle);
  1845. if (!subtitle.num_rects)
  1846. goto out;
  1847. ist->frames_decoded++;
  1848. for (i = 0; i < nb_output_streams; i++) {
  1849. OutputStream *ost = output_streams[i];
  1850. if (!check_output_constraints(ist, ost) || !ost->encoding_needed
  1851. || ost->enc->type != AVMEDIA_TYPE_SUBTITLE)
  1852. continue;
  1853. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle);
  1854. }
  1855. out:
  1856. avsubtitle_free(&subtitle);
  1857. return ret;
  1858. }
  1859. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1860. static int process_input_packet(InputStream *ist, const AVPacket *pkt)
  1861. {
  1862. int ret = 0, i;
  1863. int got_output = 0;
  1864. AVPacket avpkt;
  1865. if (!ist->saw_first_ts) {
  1866. 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;
  1867. ist->pts = 0;
  1868. if (pkt && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
  1869. ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
  1870. ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
  1871. }
  1872. ist->saw_first_ts = 1;
  1873. }
  1874. if (ist->next_dts == AV_NOPTS_VALUE)
  1875. ist->next_dts = ist->dts;
  1876. if (ist->next_pts == AV_NOPTS_VALUE)
  1877. ist->next_pts = ist->pts;
  1878. if (!pkt) {
  1879. /* EOF handling */
  1880. av_init_packet(&avpkt);
  1881. avpkt.data = NULL;
  1882. avpkt.size = 0;
  1883. goto handle_eof;
  1884. } else {
  1885. avpkt = *pkt;
  1886. }
  1887. if (pkt->dts != AV_NOPTS_VALUE) {
  1888. ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1889. if (ist->dec_ctx->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
  1890. ist->next_pts = ist->pts = ist->dts;
  1891. }
  1892. // while we have more to decode or while the decoder did output something on EOF
  1893. while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
  1894. int duration;
  1895. handle_eof:
  1896. ist->pts = ist->next_pts;
  1897. ist->dts = ist->next_dts;
  1898. if (avpkt.size && avpkt.size != pkt->size &&
  1899. !(ist->dec->capabilities & CODEC_CAP_SUBFRAMES)) {
  1900. av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
  1901. "Multiple frames in a packet from stream %d\n", pkt->stream_index);
  1902. ist->showed_multi_packet_warning = 1;
  1903. }
  1904. switch (ist->dec_ctx->codec_type) {
  1905. case AVMEDIA_TYPE_AUDIO:
  1906. ret = decode_audio (ist, &avpkt, &got_output);
  1907. break;
  1908. case AVMEDIA_TYPE_VIDEO:
  1909. ret = decode_video (ist, &avpkt, &got_output);
  1910. if (avpkt.duration) {
  1911. duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
  1912. } else if(ist->dec_ctx->framerate.num != 0 && ist->dec_ctx->framerate.den != 0) {
  1913. int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict+1 : ist->dec_ctx->ticks_per_frame;
  1914. duration = ((int64_t)AV_TIME_BASE *
  1915. ist->dec_ctx->framerate.den * ticks) /
  1916. ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
  1917. } else
  1918. duration = 0;
  1919. if(ist->dts != AV_NOPTS_VALUE && duration) {
  1920. ist->next_dts += duration;
  1921. }else
  1922. ist->next_dts = AV_NOPTS_VALUE;
  1923. if (got_output)
  1924. ist->next_pts += duration; //FIXME the duration is not correct in some cases
  1925. break;
  1926. case AVMEDIA_TYPE_SUBTITLE:
  1927. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1928. break;
  1929. default:
  1930. return -1;
  1931. }
  1932. if (ret < 0)
  1933. return ret;
  1934. avpkt.dts=
  1935. avpkt.pts= AV_NOPTS_VALUE;
  1936. // touch data and size only if not EOF
  1937. if (pkt) {
  1938. if(ist->dec_ctx->codec_type != AVMEDIA_TYPE_AUDIO)
  1939. ret = avpkt.size;
  1940. avpkt.data += ret;
  1941. avpkt.size -= ret;
  1942. }
  1943. if (!got_output) {
  1944. continue;
  1945. }
  1946. if (got_output && !pkt)
  1947. break;
  1948. }
  1949. /* handle stream copy */
  1950. if (!ist->decoding_needed) {
  1951. ist->dts = ist->next_dts;
  1952. switch (ist->dec_ctx->codec_type) {
  1953. case AVMEDIA_TYPE_AUDIO:
  1954. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
  1955. ist->dec_ctx->sample_rate;
  1956. break;
  1957. case AVMEDIA_TYPE_VIDEO:
  1958. if (ist->framerate.num) {
  1959. // TODO: Remove work-around for c99-to-c89 issue 7
  1960. AVRational time_base_q = AV_TIME_BASE_Q;
  1961. int64_t next_dts = av_rescale_q(ist->next_dts, time_base_q, av_inv_q(ist->framerate));
  1962. ist->next_dts = av_rescale_q(next_dts + 1, av_inv_q(ist->framerate), time_base_q);
  1963. } else if (pkt->duration) {
  1964. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1965. } else if(ist->dec_ctx->framerate.num != 0) {
  1966. int ticks= av_stream_get_parser(ist->st) ? av_stream_get_parser(ist->st)->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
  1967. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1968. ist->dec_ctx->framerate.den * ticks) /
  1969. ist->dec_ctx->framerate.num / ist->dec_ctx->ticks_per_frame;
  1970. }
  1971. break;
  1972. }
  1973. ist->pts = ist->dts;
  1974. ist->next_pts = ist->next_dts;
  1975. }
  1976. for (i = 0; pkt && i < nb_output_streams; i++) {
  1977. OutputStream *ost = output_streams[i];
  1978. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1979. continue;
  1980. do_streamcopy(ist, ost, pkt);
  1981. }
  1982. return got_output;
  1983. }
  1984. static void print_sdp(void)
  1985. {
  1986. char sdp[16384];
  1987. int i;
  1988. int j;
  1989. AVIOContext *sdp_pb;
  1990. AVFormatContext **avc = av_malloc_array(nb_output_files, sizeof(*avc));
  1991. if (!avc)
  1992. exit_program(1);
  1993. for (i = 0, j = 0; i < nb_output_files; i++) {
  1994. if (!strcmp(output_files[i]->ctx->oformat->name, "rtp")) {
  1995. avc[j] = output_files[i]->ctx;
  1996. j++;
  1997. }
  1998. }
  1999. av_sdp_create(avc, j, sdp, sizeof(sdp));
  2000. if (!sdp_filename) {
  2001. printf("SDP:\n%s\n", sdp);
  2002. fflush(stdout);
  2003. } else {
  2004. if (avio_open2(&sdp_pb, sdp_filename, AVIO_FLAG_WRITE, &int_cb, NULL) < 0) {
  2005. av_log(NULL, AV_LOG_ERROR, "Failed to open sdp file '%s'\n", sdp_filename);
  2006. } else {
  2007. avio_printf(sdp_pb, "SDP:\n%s", sdp);
  2008. avio_closep(&sdp_pb);
  2009. av_freep(&sdp_filename);
  2010. }
  2011. }
  2012. av_freep(&avc);
  2013. }
  2014. static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
  2015. {
  2016. int i;
  2017. for (i = 0; hwaccels[i].name; i++)
  2018. if (hwaccels[i].pix_fmt == pix_fmt)
  2019. return &hwaccels[i];
  2020. return NULL;
  2021. }
  2022. static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
  2023. {
  2024. InputStream *ist = s->opaque;
  2025. const enum AVPixelFormat *p;
  2026. int ret;
  2027. for (p = pix_fmts; *p != -1; p++) {
  2028. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
  2029. const HWAccel *hwaccel;
  2030. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  2031. break;
  2032. hwaccel = get_hwaccel(*p);
  2033. if (!hwaccel ||
  2034. (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
  2035. (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
  2036. continue;
  2037. ret = hwaccel->init(s);
  2038. if (ret < 0) {
  2039. if (ist->hwaccel_id == hwaccel->id) {
  2040. av_log(NULL, AV_LOG_FATAL,
  2041. "%s hwaccel requested for input stream #%d:%d, "
  2042. "but cannot be initialized.\n", hwaccel->name,
  2043. ist->file_index, ist->st->index);
  2044. exit_program(1);
  2045. }
  2046. continue;
  2047. }
  2048. ist->active_hwaccel_id = hwaccel->id;
  2049. ist->hwaccel_pix_fmt = *p;
  2050. break;
  2051. }
  2052. return *p;
  2053. }
  2054. static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
  2055. {
  2056. InputStream *ist = s->opaque;
  2057. if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
  2058. return ist->hwaccel_get_buffer(s, frame, flags);
  2059. return avcodec_default_get_buffer2(s, frame, flags);
  2060. }
  2061. static int init_input_stream(int ist_index, char *error, int error_len)
  2062. {
  2063. int ret;
  2064. InputStream *ist = input_streams[ist_index];
  2065. if (ist->decoding_needed) {
  2066. AVCodec *codec = ist->dec;
  2067. if (!codec) {
  2068. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
  2069. avcodec_get_name(ist->dec_ctx->codec_id), ist->file_index, ist->st->index);
  2070. return AVERROR(EINVAL);
  2071. }
  2072. ist->dec_ctx->opaque = ist;
  2073. ist->dec_ctx->get_format = get_format;
  2074. ist->dec_ctx->get_buffer2 = get_buffer;
  2075. ist->dec_ctx->thread_safe_callbacks = 1;
  2076. av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
  2077. if (ist->dec_ctx->codec_id == AV_CODEC_ID_DVB_SUBTITLE &&
  2078. (ist->decoding_needed & DECODING_FOR_OST)) {
  2079. av_dict_set(&ist->decoder_opts, "compute_edt", "1", AV_DICT_DONT_OVERWRITE);
  2080. if (ist->decoding_needed & DECODING_FOR_FILTER)
  2081. 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");
  2082. }
  2083. if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
  2084. av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
  2085. if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
  2086. if (ret == AVERROR_EXPERIMENTAL)
  2087. abort_codec_experimental(codec, 0);
  2088. snprintf(error, error_len,
  2089. "Error while opening decoder for input stream "
  2090. "#%d:%d : %s",
  2091. ist->file_index, ist->st->index, av_err2str(ret));
  2092. return ret;
  2093. }
  2094. assert_avoptions(ist->decoder_opts);
  2095. }
  2096. ist->next_pts = AV_NOPTS_VALUE;
  2097. ist->next_dts = AV_NOPTS_VALUE;
  2098. return 0;
  2099. }
  2100. static InputStream *get_input_stream(OutputStream *ost)
  2101. {
  2102. if (ost->source_index >= 0)
  2103. return input_streams[ost->source_index];
  2104. return NULL;
  2105. }
  2106. static int compare_int64(const void *a, const void *b)
  2107. {
  2108. int64_t va = *(int64_t *)a, vb = *(int64_t *)b;
  2109. return va < vb ? -1 : va > vb ? +1 : 0;
  2110. }
  2111. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  2112. AVCodecContext *avctx)
  2113. {
  2114. char *p;
  2115. int n = 1, i, size, index = 0;
  2116. int64_t t, *pts;
  2117. for (p = kf; *p; p++)
  2118. if (*p == ',')
  2119. n++;
  2120. size = n;
  2121. pts = av_malloc_array(size, sizeof(*pts));
  2122. if (!pts) {
  2123. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  2124. exit_program(1);
  2125. }
  2126. p = kf;
  2127. for (i = 0; i < n; i++) {
  2128. char *next = strchr(p, ',');
  2129. if (next)
  2130. *next++ = 0;
  2131. if (!memcmp(p, "chapters", 8)) {
  2132. AVFormatContext *avf = output_files[ost->file_index]->ctx;
  2133. int j;
  2134. if (avf->nb_chapters > INT_MAX - size ||
  2135. !(pts = av_realloc_f(pts, size += avf->nb_chapters - 1,
  2136. sizeof(*pts)))) {
  2137. av_log(NULL, AV_LOG_FATAL,
  2138. "Could not allocate forced key frames array.\n");
  2139. exit_program(1);
  2140. }
  2141. t = p[8] ? parse_time_or_die("force_key_frames", p + 8, 1) : 0;
  2142. t = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  2143. for (j = 0; j < avf->nb_chapters; j++) {
  2144. AVChapter *c = avf->chapters[j];
  2145. av_assert1(index < size);
  2146. pts[index++] = av_rescale_q(c->start, c->time_base,
  2147. avctx->time_base) + t;
  2148. }
  2149. } else {
  2150. t = parse_time_or_die("force_key_frames", p, 1);
  2151. av_assert1(index < size);
  2152. pts[index++] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  2153. }
  2154. p = next;
  2155. }
  2156. av_assert0(index == size);
  2157. qsort(pts, size, sizeof(*pts), compare_int64);
  2158. ost->forced_kf_count = size;
  2159. ost->forced_kf_pts = pts;
  2160. }
  2161. static void report_new_stream(int input_index, AVPacket *pkt)
  2162. {
  2163. InputFile *file = input_files[input_index];
  2164. AVStream *st = file->ctx->streams[pkt->stream_index];
  2165. if (pkt->stream_index < file->nb_streams_warn)
  2166. return;
  2167. av_log(file->ctx, AV_LOG_WARNING,
  2168. "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
  2169. av_get_media_type_string(st->codec->codec_type),
  2170. input_index, pkt->stream_index,
  2171. pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
  2172. file->nb_streams_warn = pkt->stream_index + 1;
  2173. }
  2174. static void set_encoder_id(OutputFile *of, OutputStream *ost)
  2175. {
  2176. AVDictionaryEntry *e;
  2177. uint8_t *encoder_string;
  2178. int encoder_string_len;
  2179. int format_flags = 0;
  2180. int codec_flags = 0;
  2181. if (av_dict_get(ost->st->metadata, "encoder", NULL, 0))
  2182. return;
  2183. e = av_dict_get(of->opts, "fflags", NULL, 0);
  2184. if (e) {
  2185. const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
  2186. if (!o)
  2187. return;
  2188. av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
  2189. }
  2190. e = av_dict_get(ost->encoder_opts, "flags", NULL, 0);
  2191. if (e) {
  2192. const AVOption *o = av_opt_find(ost->enc_ctx, "flags", NULL, 0, 0);
  2193. if (!o)
  2194. return;
  2195. av_opt_eval_flags(ost->enc_ctx, o, e->value, &codec_flags);
  2196. }
  2197. encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
  2198. encoder_string = av_mallocz(encoder_string_len);
  2199. if (!encoder_string)
  2200. exit_program(1);
  2201. if (!(format_flags & AVFMT_FLAG_BITEXACT) && !(codec_flags & CODEC_FLAG_BITEXACT))
  2202. av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
  2203. else
  2204. av_strlcpy(encoder_string, "Lavc ", encoder_string_len);
  2205. av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
  2206. av_dict_set(&ost->st->metadata, "encoder", encoder_string,
  2207. AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
  2208. }
  2209. static int transcode_init(void)
  2210. {
  2211. int ret = 0, i, j, k;
  2212. AVFormatContext *oc;
  2213. OutputStream *ost;
  2214. InputStream *ist;
  2215. char error[1024] = {0};
  2216. int want_sdp = 1;
  2217. for (i = 0; i < nb_filtergraphs; i++) {
  2218. FilterGraph *fg = filtergraphs[i];
  2219. for (j = 0; j < fg->nb_outputs; j++) {
  2220. OutputFilter *ofilter = fg->outputs[j];
  2221. if (!ofilter->ost || ofilter->ost->source_index >= 0)
  2222. continue;
  2223. if (fg->nb_inputs != 1)
  2224. continue;
  2225. for (k = nb_input_streams-1; k >= 0 ; k--)
  2226. if (fg->inputs[0]->ist == input_streams[k])
  2227. break;
  2228. ofilter->ost->source_index = k;
  2229. }
  2230. }
  2231. /* init framerate emulation */
  2232. for (i = 0; i < nb_input_files; i++) {
  2233. InputFile *ifile = input_files[i];
  2234. if (ifile->rate_emu)
  2235. for (j = 0; j < ifile->nb_streams; j++)
  2236. input_streams[j + ifile->ist_index]->start = av_gettime_relative();
  2237. }
  2238. /* output stream init */
  2239. for (i = 0; i < nb_output_files; i++) {
  2240. oc = output_files[i]->ctx;
  2241. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  2242. av_dump_format(oc, i, oc->filename, 1);
  2243. av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
  2244. return AVERROR(EINVAL);
  2245. }
  2246. }
  2247. /* init complex filtergraphs */
  2248. for (i = 0; i < nb_filtergraphs; i++)
  2249. if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
  2250. return ret;
  2251. /* for each output stream, we compute the right encoding parameters */
  2252. for (i = 0; i < nb_output_streams; i++) {
  2253. AVCodecContext *enc_ctx;
  2254. AVCodecContext *dec_ctx = NULL;
  2255. ost = output_streams[i];
  2256. oc = output_files[ost->file_index]->ctx;
  2257. ist = get_input_stream(ost);
  2258. if (ost->attachment_filename)
  2259. continue;
  2260. enc_ctx = ost->enc_ctx;
  2261. if (ist) {
  2262. dec_ctx = ist->dec_ctx;
  2263. ost->st->disposition = ist->st->disposition;
  2264. enc_ctx->bits_per_raw_sample = dec_ctx->bits_per_raw_sample;
  2265. enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
  2266. } else {
  2267. for (j=0; j<oc->nb_streams; j++) {
  2268. AVStream *st = oc->streams[j];
  2269. if (st != ost->st && st->codec->codec_type == enc_ctx->codec_type)
  2270. break;
  2271. }
  2272. if (j == oc->nb_streams)
  2273. if (enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO || enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
  2274. ost->st->disposition = AV_DISPOSITION_DEFAULT;
  2275. }
  2276. if (ost->stream_copy) {
  2277. AVRational sar;
  2278. uint64_t extra_size;
  2279. av_assert0(ist && !ost->filter);
  2280. extra_size = (uint64_t)dec_ctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
  2281. if (extra_size > INT_MAX) {
  2282. return AVERROR(EINVAL);
  2283. }
  2284. /* if stream_copy is selected, no need to decode or encode */
  2285. enc_ctx->codec_id = dec_ctx->codec_id;
  2286. enc_ctx->codec_type = dec_ctx->codec_type;
  2287. if (!enc_ctx->codec_tag) {
  2288. unsigned int codec_tag;
  2289. if (!oc->oformat->codec_tag ||
  2290. av_codec_get_id (oc->oformat->codec_tag, dec_ctx->codec_tag) == enc_ctx->codec_id ||
  2291. !av_codec_get_tag2(oc->oformat->codec_tag, dec_ctx->codec_id, &codec_tag))
  2292. enc_ctx->codec_tag = dec_ctx->codec_tag;
  2293. }
  2294. enc_ctx->bit_rate = dec_ctx->bit_rate;
  2295. enc_ctx->rc_max_rate = dec_ctx->rc_max_rate;
  2296. enc_ctx->rc_buffer_size = dec_ctx->rc_buffer_size;
  2297. enc_ctx->field_order = dec_ctx->field_order;
  2298. enc_ctx->extradata = av_mallocz(extra_size);
  2299. if (!enc_ctx->extradata) {
  2300. return AVERROR(ENOMEM);
  2301. }
  2302. memcpy(enc_ctx->extradata, dec_ctx->extradata, dec_ctx->extradata_size);
  2303. enc_ctx->extradata_size= dec_ctx->extradata_size;
  2304. enc_ctx->bits_per_coded_sample = dec_ctx->bits_per_coded_sample;
  2305. enc_ctx->time_base = ist->st->time_base;
  2306. /*
  2307. * Avi is a special case here because it supports variable fps but
  2308. * having the fps and timebase differe significantly adds quite some
  2309. * overhead
  2310. */
  2311. if(!strcmp(oc->oformat->name, "avi")) {
  2312. if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
  2313. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
  2314. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(dec_ctx->time_base)
  2315. && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(dec_ctx->time_base) < 1.0/500
  2316. || copy_tb==2){
  2317. enc_ctx->time_base.num = ist->st->r_frame_rate.den;
  2318. enc_ctx->time_base.den = 2*ist->st->r_frame_rate.num;
  2319. enc_ctx->ticks_per_frame = 2;
  2320. } else if ( copy_tb<0 && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > 2*av_q2d(ist->st->time_base)
  2321. && av_q2d(ist->st->time_base) < 1.0/500
  2322. || copy_tb==0){
  2323. enc_ctx->time_base = dec_ctx->time_base;
  2324. enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
  2325. enc_ctx->time_base.den *= 2;
  2326. enc_ctx->ticks_per_frame = 2;
  2327. }
  2328. } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
  2329. && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
  2330. && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
  2331. && strcmp(oc->oformat->name, "f4v")
  2332. ) {
  2333. if( copy_tb<0 && dec_ctx->time_base.den
  2334. && av_q2d(dec_ctx->time_base)*dec_ctx->ticks_per_frame > av_q2d(ist->st->time_base)
  2335. && av_q2d(ist->st->time_base) < 1.0/500
  2336. || copy_tb==0){
  2337. enc_ctx->time_base = dec_ctx->time_base;
  2338. enc_ctx->time_base.num *= dec_ctx->ticks_per_frame;
  2339. }
  2340. }
  2341. if ( enc_ctx->codec_tag == AV_RL32("tmcd")
  2342. && dec_ctx->time_base.num < dec_ctx->time_base.den
  2343. && dec_ctx->time_base.num > 0
  2344. && 121LL*dec_ctx->time_base.num > dec_ctx->time_base.den) {
  2345. enc_ctx->time_base = dec_ctx->time_base;
  2346. }
  2347. if (ist && !ost->frame_rate.num)
  2348. ost->frame_rate = ist->framerate;
  2349. if(ost->frame_rate.num)
  2350. enc_ctx->time_base = av_inv_q(ost->frame_rate);
  2351. av_reduce(&enc_ctx->time_base.num, &enc_ctx->time_base.den,
  2352. enc_ctx->time_base.num, enc_ctx->time_base.den, INT_MAX);
  2353. if (ist->st->nb_side_data) {
  2354. ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
  2355. sizeof(*ist->st->side_data));
  2356. if (!ost->st->side_data)
  2357. return AVERROR(ENOMEM);
  2358. for (j = 0; j < ist->st->nb_side_data; j++) {
  2359. const AVPacketSideData *sd_src = &ist->st->side_data[j];
  2360. AVPacketSideData *sd_dst = &ost->st->side_data[j];
  2361. sd_dst->data = av_malloc(sd_src->size);
  2362. if (!sd_dst->data)
  2363. return AVERROR(ENOMEM);
  2364. memcpy(sd_dst->data, sd_src->data, sd_src->size);
  2365. sd_dst->size = sd_src->size;
  2366. sd_dst->type = sd_src->type;
  2367. ost->st->nb_side_data++;
  2368. }
  2369. }
  2370. ost->parser = av_parser_init(enc_ctx->codec_id);
  2371. switch (enc_ctx->codec_type) {
  2372. case AVMEDIA_TYPE_AUDIO:
  2373. if (audio_volume != 256) {
  2374. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  2375. exit_program(1);
  2376. }
  2377. enc_ctx->channel_layout = dec_ctx->channel_layout;
  2378. enc_ctx->sample_rate = dec_ctx->sample_rate;
  2379. enc_ctx->channels = dec_ctx->channels;
  2380. enc_ctx->frame_size = dec_ctx->frame_size;
  2381. enc_ctx->audio_service_type = dec_ctx->audio_service_type;
  2382. enc_ctx->block_align = dec_ctx->block_align;
  2383. enc_ctx->initial_padding = dec_ctx->delay;
  2384. #if FF_API_AUDIOENC_DELAY
  2385. enc_ctx->delay = dec_ctx->delay;
  2386. #endif
  2387. if((enc_ctx->block_align == 1 || enc_ctx->block_align == 1152 || enc_ctx->block_align == 576) && enc_ctx->codec_id == AV_CODEC_ID_MP3)
  2388. enc_ctx->block_align= 0;
  2389. if(enc_ctx->codec_id == AV_CODEC_ID_AC3)
  2390. enc_ctx->block_align= 0;
  2391. break;
  2392. case AVMEDIA_TYPE_VIDEO:
  2393. enc_ctx->pix_fmt = dec_ctx->pix_fmt;
  2394. enc_ctx->width = dec_ctx->width;
  2395. enc_ctx->height = dec_ctx->height;
  2396. enc_ctx->has_b_frames = dec_ctx->has_b_frames;
  2397. if (ost->frame_aspect_ratio.num) { // overridden by the -aspect cli option
  2398. sar =
  2399. av_mul_q(ost->frame_aspect_ratio,
  2400. (AVRational){ enc_ctx->height, enc_ctx->width });
  2401. av_log(NULL, AV_LOG_WARNING, "Overriding aspect ratio "
  2402. "with stream copy may produce invalid files\n");
  2403. }
  2404. else if (ist->st->sample_aspect_ratio.num)
  2405. sar = ist->st->sample_aspect_ratio;
  2406. else
  2407. sar = dec_ctx->sample_aspect_ratio;
  2408. ost->st->sample_aspect_ratio = enc_ctx->sample_aspect_ratio = sar;
  2409. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
  2410. ost->st->r_frame_rate = ist->st->r_frame_rate;
  2411. break;
  2412. case AVMEDIA_TYPE_SUBTITLE:
  2413. enc_ctx->width = dec_ctx->width;
  2414. enc_ctx->height = dec_ctx->height;
  2415. break;
  2416. case AVMEDIA_TYPE_DATA:
  2417. case AVMEDIA_TYPE_ATTACHMENT:
  2418. break;
  2419. default:
  2420. abort();
  2421. }
  2422. } else {
  2423. if (!ost->enc)
  2424. ost->enc = avcodec_find_encoder(enc_ctx->codec_id);
  2425. if (!ost->enc) {
  2426. /* should only happen when a default codec is not present. */
  2427. snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
  2428. avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
  2429. ret = AVERROR(EINVAL);
  2430. goto dump_format;
  2431. }
  2432. if (ist)
  2433. ist->decoding_needed |= DECODING_FOR_OST;
  2434. ost->encoding_needed = 1;
  2435. set_encoder_id(output_files[ost->file_index], ost);
  2436. if (!ost->filter &&
  2437. (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  2438. enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO)) {
  2439. FilterGraph *fg;
  2440. fg = init_simple_filtergraph(ist, ost);
  2441. if (configure_filtergraph(fg)) {
  2442. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  2443. exit_program(1);
  2444. }
  2445. }
  2446. if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  2447. if (ost->filter && !ost->frame_rate.num)
  2448. ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
  2449. if (ist && !ost->frame_rate.num)
  2450. ost->frame_rate = ist->framerate;
  2451. if (ist && !ost->frame_rate.num)
  2452. ost->frame_rate = ist->st->r_frame_rate;
  2453. if (ist && !ost->frame_rate.num) {
  2454. ost->frame_rate = (AVRational){25, 1};
  2455. av_log(NULL, AV_LOG_WARNING,
  2456. "No information "
  2457. "about the input framerate is available. Falling "
  2458. "back to a default value of 25fps for output stream #%d:%d. Use the -r option "
  2459. "if you want a different framerate.\n",
  2460. ost->file_index, ost->index);
  2461. }
  2462. // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
  2463. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  2464. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  2465. ost->frame_rate = ost->enc->supported_framerates[idx];
  2466. }
  2467. if (enc_ctx->codec_id == AV_CODEC_ID_MPEG4) {
  2468. av_reduce(&ost->frame_rate.num, &ost->frame_rate.den,
  2469. ost->frame_rate.num, ost->frame_rate.den, 65535);
  2470. }
  2471. }
  2472. switch (enc_ctx->codec_type) {
  2473. case AVMEDIA_TYPE_AUDIO:
  2474. enc_ctx->sample_fmt = ost->filter->filter->inputs[0]->format;
  2475. enc_ctx->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  2476. enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  2477. enc_ctx->channels = avfilter_link_get_channels(ost->filter->filter->inputs[0]);
  2478. enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate };
  2479. break;
  2480. case AVMEDIA_TYPE_VIDEO:
  2481. enc_ctx->time_base = av_inv_q(ost->frame_rate);
  2482. if (ost->filter && !(enc_ctx->time_base.num && enc_ctx->time_base.den))
  2483. enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;
  2484. if ( av_q2d(enc_ctx->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
  2485. && (video_sync_method == VSYNC_CFR || video_sync_method == VSYNC_VSCFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
  2486. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
  2487. "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
  2488. }
  2489. for (j = 0; j < ost->forced_kf_count; j++)
  2490. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
  2491. AV_TIME_BASE_Q,
  2492. enc_ctx->time_base);
  2493. enc_ctx->width = ost->filter->filter->inputs[0]->w;
  2494. enc_ctx->height = ost->filter->filter->inputs[0]->h;
  2495. enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  2496. ost->frame_aspect_ratio.num ? // overridden by the -aspect cli option
  2497. av_mul_q(ost->frame_aspect_ratio, (AVRational){ enc_ctx->height, enc_ctx->width }) :
  2498. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  2499. if (!strncmp(ost->enc->name, "libx264", 7) &&
  2500. enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
  2501. ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
  2502. av_log(NULL, AV_LOG_WARNING,
  2503. "No pixel format specified, %s for H.264 encoding chosen.\n"
  2504. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2505. av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
  2506. if (!strncmp(ost->enc->name, "mpeg2video", 10) &&
  2507. enc_ctx->pix_fmt == AV_PIX_FMT_NONE &&
  2508. ost->filter->filter->inputs[0]->format != AV_PIX_FMT_YUV420P)
  2509. av_log(NULL, AV_LOG_WARNING,
  2510. "No pixel format specified, %s for MPEG-2 encoding chosen.\n"
  2511. "Use -pix_fmt yuv420p for compatibility with outdated media players.\n",
  2512. av_get_pix_fmt_name(ost->filter->filter->inputs[0]->format));
  2513. enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;
  2514. ost->st->avg_frame_rate = ost->frame_rate;
  2515. if (!dec_ctx ||
  2516. enc_ctx->width != dec_ctx->width ||
  2517. enc_ctx->height != dec_ctx->height ||
  2518. enc_ctx->pix_fmt != dec_ctx->pix_fmt) {
  2519. enc_ctx->bits_per_raw_sample = frame_bits_per_raw_sample;
  2520. }
  2521. if (ost->forced_keyframes) {
  2522. if (!strncmp(ost->forced_keyframes, "expr:", 5)) {
  2523. ret = av_expr_parse(&ost->forced_keyframes_pexpr, ost->forced_keyframes+5,
  2524. forced_keyframes_const_names, NULL, NULL, NULL, NULL, 0, NULL);
  2525. if (ret < 0) {
  2526. av_log(NULL, AV_LOG_ERROR,
  2527. "Invalid force_key_frames expression '%s'\n", ost->forced_keyframes+5);
  2528. return ret;
  2529. }
  2530. ost->forced_keyframes_expr_const_values[FKF_N] = 0;
  2531. ost->forced_keyframes_expr_const_values[FKF_N_FORCED] = 0;
  2532. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] = NAN;
  2533. ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] = NAN;
  2534. } else {
  2535. parse_forced_key_frames(ost->forced_keyframes, ost, ost->enc_ctx);
  2536. }
  2537. }
  2538. break;
  2539. case AVMEDIA_TYPE_SUBTITLE:
  2540. enc_ctx->time_base = (AVRational){1, 1000};
  2541. if (!enc_ctx->width) {
  2542. enc_ctx->width = input_streams[ost->source_index]->st->codec->width;
  2543. enc_ctx->height = input_streams[ost->source_index]->st->codec->height;
  2544. }
  2545. break;
  2546. case AVMEDIA_TYPE_DATA:
  2547. break;
  2548. default:
  2549. abort();
  2550. break;
  2551. }
  2552. /* two pass mode */
  2553. if (enc_ctx->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
  2554. char logfilename[1024];
  2555. FILE *f;
  2556. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  2557. ost->logfile_prefix ? ost->logfile_prefix :
  2558. DEFAULT_PASS_LOGFILENAME_PREFIX,
  2559. i);
  2560. if (!strcmp(ost->enc->name, "libx264")) {
  2561. av_dict_set(&ost->encoder_opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  2562. } else {
  2563. if (enc_ctx->flags & CODEC_FLAG_PASS2) {
  2564. char *logbuffer;
  2565. size_t logbuffer_size;
  2566. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
  2567. av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  2568. logfilename);
  2569. exit_program(1);
  2570. }
  2571. enc_ctx->stats_in = logbuffer;
  2572. }
  2573. if (enc_ctx->flags & CODEC_FLAG_PASS1) {
  2574. f = av_fopen_utf8(logfilename, "wb");
  2575. if (!f) {
  2576. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
  2577. logfilename, strerror(errno));
  2578. exit_program(1);
  2579. }
  2580. ost->logfile = f;
  2581. }
  2582. }
  2583. }
  2584. }
  2585. if (ost->disposition) {
  2586. static const AVOption opts[] = {
  2587. { "disposition" , NULL, 0, AV_OPT_TYPE_FLAGS, { .i64 = 0 }, INT64_MIN, INT64_MAX, .unit = "flags" },
  2588. { "default" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DEFAULT }, .unit = "flags" },
  2589. { "dub" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DUB }, .unit = "flags" },
  2590. { "original" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_ORIGINAL }, .unit = "flags" },
  2591. { "comment" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_COMMENT }, .unit = "flags" },
  2592. { "lyrics" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_LYRICS }, .unit = "flags" },
  2593. { "karaoke" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_KARAOKE }, .unit = "flags" },
  2594. { "forced" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_FORCED }, .unit = "flags" },
  2595. { "hearing_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_HEARING_IMPAIRED }, .unit = "flags" },
  2596. { "visual_impaired" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_VISUAL_IMPAIRED }, .unit = "flags" },
  2597. { "clean_effects" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CLEAN_EFFECTS }, .unit = "flags" },
  2598. { "captions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_CAPTIONS }, .unit = "flags" },
  2599. { "descriptions" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_DESCRIPTIONS }, .unit = "flags" },
  2600. { "metadata" , NULL, 0, AV_OPT_TYPE_CONST, { .i64 = AV_DISPOSITION_METADATA }, .unit = "flags" },
  2601. { NULL },
  2602. };
  2603. static const AVClass class = {
  2604. .class_name = "",
  2605. .item_name = av_default_item_name,
  2606. .option = opts,
  2607. .version = LIBAVUTIL_VERSION_INT,
  2608. };
  2609. const AVClass *pclass = &class;
  2610. ret = av_opt_eval_flags(&pclass, &opts[0], ost->disposition, &ost->st->disposition);
  2611. if (ret < 0)
  2612. goto dump_format;
  2613. }
  2614. }
  2615. /* open each encoder */
  2616. for (i = 0; i < nb_output_streams; i++) {
  2617. ost = output_streams[i];
  2618. if (ost->encoding_needed) {
  2619. AVCodec *codec = ost->enc;
  2620. AVCodecContext *dec = NULL;
  2621. if ((ist = get_input_stream(ost)))
  2622. dec = ist->dec_ctx;
  2623. if (dec && dec->subtitle_header) {
  2624. /* ASS code assumes this buffer is null terminated so add extra byte. */
  2625. ost->enc_ctx->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
  2626. if (!ost->enc_ctx->subtitle_header) {
  2627. ret = AVERROR(ENOMEM);
  2628. goto dump_format;
  2629. }
  2630. memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  2631. ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
  2632. }
  2633. if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
  2634. av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
  2635. av_dict_set(&ost->encoder_opts, "side_data_only_packets", "1", 0);
  2636. if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
  2637. if (ret == AVERROR_EXPERIMENTAL)
  2638. abort_codec_experimental(codec, 1);
  2639. snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
  2640. ost->file_index, ost->index);
  2641. goto dump_format;
  2642. }
  2643. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  2644. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  2645. av_buffersink_set_frame_size(ost->filter->filter,
  2646. ost->enc_ctx->frame_size);
  2647. assert_avoptions(ost->encoder_opts);
  2648. if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
  2649. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  2650. " It takes bits/s as argument, not kbits/s\n");
  2651. } else {
  2652. ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
  2653. if (ret < 0) {
  2654. av_log(NULL, AV_LOG_FATAL,
  2655. "Error setting up codec context options.\n");
  2656. return ret;
  2657. }
  2658. }
  2659. ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);
  2660. if (ret < 0) {
  2661. av_log(NULL, AV_LOG_FATAL,
  2662. "Error initializing the output stream codec context.\n");
  2663. exit_program(1);
  2664. }
  2665. ost->st->codec->codec= ost->enc_ctx->codec;
  2666. // copy timebase while removing common factors
  2667. ost->st->time_base = av_add_q(ost->enc_ctx->time_base, (AVRational){0, 1});
  2668. }
  2669. /* init input streams */
  2670. for (i = 0; i < nb_input_streams; i++)
  2671. if ((ret = init_input_stream(i, error, sizeof(error))) < 0) {
  2672. for (i = 0; i < nb_output_streams; i++) {
  2673. ost = output_streams[i];
  2674. avcodec_close(ost->enc_ctx);
  2675. }
  2676. goto dump_format;
  2677. }
  2678. /* discard unused programs */
  2679. for (i = 0; i < nb_input_files; i++) {
  2680. InputFile *ifile = input_files[i];
  2681. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  2682. AVProgram *p = ifile->ctx->programs[j];
  2683. int discard = AVDISCARD_ALL;
  2684. for (k = 0; k < p->nb_stream_indexes; k++)
  2685. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  2686. discard = AVDISCARD_DEFAULT;
  2687. break;
  2688. }
  2689. p->discard = discard;
  2690. }
  2691. }
  2692. /* open files and write file headers */
  2693. for (i = 0; i < nb_output_files; i++) {
  2694. oc = output_files[i]->ctx;
  2695. oc->interrupt_callback = int_cb;
  2696. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  2697. snprintf(error, sizeof(error),
  2698. "Could not write header for output file #%d "
  2699. "(incorrect codec parameters ?): %s",
  2700. i, av_err2str(ret));
  2701. ret = AVERROR(EINVAL);
  2702. goto dump_format;
  2703. }
  2704. // assert_avoptions(output_files[i]->opts);
  2705. if (strcmp(oc->oformat->name, "rtp")) {
  2706. want_sdp = 0;
  2707. }
  2708. }
  2709. dump_format:
  2710. /* dump the file output parameters - cannot be done before in case
  2711. of stream copy */
  2712. for (i = 0; i < nb_output_files; i++) {
  2713. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  2714. }
  2715. /* dump the stream mapping */
  2716. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  2717. for (i = 0; i < nb_input_streams; i++) {
  2718. ist = input_streams[i];
  2719. for (j = 0; j < ist->nb_filters; j++) {
  2720. if (ist->filters[j]->graph->graph_desc) {
  2721. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  2722. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  2723. ist->filters[j]->name);
  2724. if (nb_filtergraphs > 1)
  2725. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  2726. av_log(NULL, AV_LOG_INFO, "\n");
  2727. }
  2728. }
  2729. }
  2730. for (i = 0; i < nb_output_streams; i++) {
  2731. ost = output_streams[i];
  2732. if (ost->attachment_filename) {
  2733. /* an attached file */
  2734. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  2735. ost->attachment_filename, ost->file_index, ost->index);
  2736. continue;
  2737. }
  2738. if (ost->filter && ost->filter->graph->graph_desc) {
  2739. /* output from a complex graph */
  2740. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  2741. if (nb_filtergraphs > 1)
  2742. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  2743. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  2744. ost->index, ost->enc ? ost->enc->name : "?");
  2745. continue;
  2746. }
  2747. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  2748. input_streams[ost->source_index]->file_index,
  2749. input_streams[ost->source_index]->st->index,
  2750. ost->file_index,
  2751. ost->index);
  2752. if (ost->sync_ist != input_streams[ost->source_index])
  2753. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  2754. ost->sync_ist->file_index,
  2755. ost->sync_ist->st->index);
  2756. if (ost->stream_copy)
  2757. av_log(NULL, AV_LOG_INFO, " (copy)");
  2758. else {
  2759. const AVCodec *in_codec = input_streams[ost->source_index]->dec;
  2760. const AVCodec *out_codec = ost->enc;
  2761. const char *decoder_name = "?";
  2762. const char *in_codec_name = "?";
  2763. const char *encoder_name = "?";
  2764. const char *out_codec_name = "?";
  2765. if (in_codec) {
  2766. decoder_name = in_codec->name;
  2767. in_codec_name = avcodec_descriptor_get(in_codec->id)->name;
  2768. if (!strcmp(decoder_name, in_codec_name))
  2769. decoder_name = "native";
  2770. }
  2771. if (out_codec) {
  2772. encoder_name = out_codec->name;
  2773. out_codec_name = avcodec_descriptor_get(out_codec->id)->name;
  2774. if (!strcmp(encoder_name, out_codec_name))
  2775. encoder_name = "native";
  2776. }
  2777. av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
  2778. in_codec_name, decoder_name,
  2779. out_codec_name, encoder_name);
  2780. }
  2781. av_log(NULL, AV_LOG_INFO, "\n");
  2782. }
  2783. if (ret) {
  2784. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  2785. return ret;
  2786. }
  2787. if (sdp_filename || want_sdp) {
  2788. print_sdp();
  2789. }
  2790. transcode_init_done = 1;
  2791. return 0;
  2792. }
  2793. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  2794. static int need_output(void)
  2795. {
  2796. int i;
  2797. for (i = 0; i < nb_output_streams; i++) {
  2798. OutputStream *ost = output_streams[i];
  2799. OutputFile *of = output_files[ost->file_index];
  2800. AVFormatContext *os = output_files[ost->file_index]->ctx;
  2801. if (ost->finished ||
  2802. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  2803. continue;
  2804. if (ost->frame_number >= ost->max_frames) {
  2805. int j;
  2806. for (j = 0; j < of->ctx->nb_streams; j++)
  2807. close_output_stream(output_streams[of->ost_index + j]);
  2808. continue;
  2809. }
  2810. return 1;
  2811. }
  2812. return 0;
  2813. }
  2814. /**
  2815. * Select the output stream to process.
  2816. *
  2817. * @return selected output stream, or NULL if none available
  2818. */
  2819. static OutputStream *choose_output(void)
  2820. {
  2821. int i;
  2822. int64_t opts_min = INT64_MAX;
  2823. OutputStream *ost_min = NULL;
  2824. for (i = 0; i < nb_output_streams; i++) {
  2825. OutputStream *ost = output_streams[i];
  2826. int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
  2827. AV_TIME_BASE_Q);
  2828. if (!ost->finished && opts < opts_min) {
  2829. opts_min = opts;
  2830. ost_min = ost->unavailable ? NULL : ost;
  2831. }
  2832. }
  2833. return ost_min;
  2834. }
  2835. static int check_keyboard_interaction(int64_t cur_time)
  2836. {
  2837. int i, ret, key;
  2838. static int64_t last_time;
  2839. if (received_nb_signals)
  2840. return AVERROR_EXIT;
  2841. /* read_key() returns 0 on EOF */
  2842. if(cur_time - last_time >= 100000 && !run_as_daemon){
  2843. key = read_key();
  2844. last_time = cur_time;
  2845. }else
  2846. key = -1;
  2847. if (key == 'q')
  2848. return AVERROR_EXIT;
  2849. if (key == '+') av_log_set_level(av_log_get_level()+10);
  2850. if (key == '-') av_log_set_level(av_log_get_level()-10);
  2851. if (key == 's') qp_hist ^= 1;
  2852. if (key == 'h'){
  2853. if (do_hex_dump){
  2854. do_hex_dump = do_pkt_dump = 0;
  2855. } else if(do_pkt_dump){
  2856. do_hex_dump = 1;
  2857. } else
  2858. do_pkt_dump = 1;
  2859. av_log_set_level(AV_LOG_DEBUG);
  2860. }
  2861. if (key == 'c' || key == 'C'){
  2862. char buf[4096], target[64], command[256], arg[256] = {0};
  2863. double time;
  2864. int k, n = 0;
  2865. fprintf(stderr, "\nEnter command: <target>|all <time>|-1 <command>[ <argument>]\n");
  2866. i = 0;
  2867. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  2868. if (k > 0)
  2869. buf[i++] = k;
  2870. buf[i] = 0;
  2871. if (k > 0 &&
  2872. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  2873. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  2874. target, time, command, arg);
  2875. for (i = 0; i < nb_filtergraphs; i++) {
  2876. FilterGraph *fg = filtergraphs[i];
  2877. if (fg->graph) {
  2878. if (time < 0) {
  2879. ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
  2880. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
  2881. fprintf(stderr, "Command reply for stream %d: ret:%d res:\n%s", i, ret, buf);
  2882. } else if (key == 'c') {
  2883. fprintf(stderr, "Queing commands only on filters supporting the specific command is unsupported\n");
  2884. ret = AVERROR_PATCHWELCOME;
  2885. } else {
  2886. ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
  2887. }
  2888. }
  2889. }
  2890. } else {
  2891. av_log(NULL, AV_LOG_ERROR,
  2892. "Parse error, at least 3 arguments were expected, "
  2893. "only %d given in string '%s'\n", n, buf);
  2894. }
  2895. }
  2896. if (key == 'd' || key == 'D'){
  2897. int debug=0;
  2898. if(key == 'D') {
  2899. debug = input_streams[0]->st->codec->debug<<1;
  2900. if(!debug) debug = 1;
  2901. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
  2902. debug += debug;
  2903. }else
  2904. if(scanf("%d", &debug)!=1)
  2905. fprintf(stderr,"error parsing debug value\n");
  2906. for(i=0;i<nb_input_streams;i++) {
  2907. input_streams[i]->st->codec->debug = debug;
  2908. }
  2909. for(i=0;i<nb_output_streams;i++) {
  2910. OutputStream *ost = output_streams[i];
  2911. ost->enc_ctx->debug = debug;
  2912. }
  2913. if(debug) av_log_set_level(AV_LOG_DEBUG);
  2914. fprintf(stderr,"debug=%d\n", debug);
  2915. }
  2916. if (key == '?'){
  2917. fprintf(stderr, "key function\n"
  2918. "? show this help\n"
  2919. "+ increase verbosity\n"
  2920. "- decrease verbosity\n"
  2921. "c Send command to first matching filter supporting it\n"
  2922. "C Send/Que command to all matching filters\n"
  2923. "D cycle through available debug modes\n"
  2924. "h dump packets/hex press to cycle through the 3 states\n"
  2925. "q quit\n"
  2926. "s Show QP histogram\n"
  2927. );
  2928. }
  2929. return 0;
  2930. }
  2931. #if HAVE_PTHREADS
  2932. static void *input_thread(void *arg)
  2933. {
  2934. InputFile *f = arg;
  2935. int ret = 0;
  2936. while (1) {
  2937. AVPacket pkt;
  2938. ret = av_read_frame(f->ctx, &pkt);
  2939. if (ret == AVERROR(EAGAIN)) {
  2940. av_usleep(10000);
  2941. continue;
  2942. }
  2943. if (ret < 0) {
  2944. av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
  2945. break;
  2946. }
  2947. av_dup_packet(&pkt);
  2948. ret = av_thread_message_queue_send(f->in_thread_queue, &pkt, 0);
  2949. if (ret < 0) {
  2950. if (ret != AVERROR_EOF)
  2951. av_log(f->ctx, AV_LOG_ERROR,
  2952. "Unable to send packet to main thread: %s\n",
  2953. av_err2str(ret));
  2954. av_free_packet(&pkt);
  2955. av_thread_message_queue_set_err_recv(f->in_thread_queue, ret);
  2956. break;
  2957. }
  2958. }
  2959. return NULL;
  2960. }
  2961. static void free_input_threads(void)
  2962. {
  2963. int i;
  2964. for (i = 0; i < nb_input_files; i++) {
  2965. InputFile *f = input_files[i];
  2966. AVPacket pkt;
  2967. if (!f->in_thread_queue)
  2968. continue;
  2969. av_thread_message_queue_set_err_send(f->in_thread_queue, AVERROR_EOF);
  2970. while (av_thread_message_queue_recv(f->in_thread_queue, &pkt, 0) >= 0)
  2971. av_free_packet(&pkt);
  2972. pthread_join(f->thread, NULL);
  2973. f->joined = 1;
  2974. av_thread_message_queue_free(&f->in_thread_queue);
  2975. }
  2976. }
  2977. static int init_input_threads(void)
  2978. {
  2979. int i, ret;
  2980. if (nb_input_files == 1)
  2981. return 0;
  2982. for (i = 0; i < nb_input_files; i++) {
  2983. InputFile *f = input_files[i];
  2984. if (f->ctx->pb ? !f->ctx->pb->seekable :
  2985. strcmp(f->ctx->iformat->name, "lavfi"))
  2986. f->non_blocking = 1;
  2987. ret = av_thread_message_queue_alloc(&f->in_thread_queue,
  2988. 8, sizeof(AVPacket));
  2989. if (ret < 0)
  2990. return ret;
  2991. if ((ret = pthread_create(&f->thread, NULL, input_thread, f))) {
  2992. av_log(NULL, AV_LOG_ERROR, "pthread_create failed: %s. Try to increase `ulimit -v` or decrease `ulimit -s`.\n", strerror(ret));
  2993. av_thread_message_queue_free(&f->in_thread_queue);
  2994. return AVERROR(ret);
  2995. }
  2996. }
  2997. return 0;
  2998. }
  2999. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  3000. {
  3001. return av_thread_message_queue_recv(f->in_thread_queue, pkt,
  3002. f->non_blocking ?
  3003. AV_THREAD_MESSAGE_NONBLOCK : 0);
  3004. }
  3005. #endif
  3006. static int get_input_packet(InputFile *f, AVPacket *pkt)
  3007. {
  3008. if (f->rate_emu) {
  3009. int i;
  3010. for (i = 0; i < f->nb_streams; i++) {
  3011. InputStream *ist = input_streams[f->ist_index + i];
  3012. int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
  3013. int64_t now = av_gettime_relative() - ist->start;
  3014. if (pts > now)
  3015. return AVERROR(EAGAIN);
  3016. }
  3017. }
  3018. #if HAVE_PTHREADS
  3019. if (nb_input_files > 1)
  3020. return get_input_packet_mt(f, pkt);
  3021. #endif
  3022. return av_read_frame(f->ctx, pkt);
  3023. }
  3024. static int got_eagain(void)
  3025. {
  3026. int i;
  3027. for (i = 0; i < nb_output_streams; i++)
  3028. if (output_streams[i]->unavailable)
  3029. return 1;
  3030. return 0;
  3031. }
  3032. static void reset_eagain(void)
  3033. {
  3034. int i;
  3035. for (i = 0; i < nb_input_files; i++)
  3036. input_files[i]->eagain = 0;
  3037. for (i = 0; i < nb_output_streams; i++)
  3038. output_streams[i]->unavailable = 0;
  3039. }
  3040. /*
  3041. * Return
  3042. * - 0 -- one packet was read and processed
  3043. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  3044. * this function should be called again
  3045. * - AVERROR_EOF -- this function should not be called again
  3046. */
  3047. static int process_input(int file_index)
  3048. {
  3049. InputFile *ifile = input_files[file_index];
  3050. AVFormatContext *is;
  3051. InputStream *ist;
  3052. AVPacket pkt;
  3053. int ret, i, j;
  3054. is = ifile->ctx;
  3055. ret = get_input_packet(ifile, &pkt);
  3056. if (ret == AVERROR(EAGAIN)) {
  3057. ifile->eagain = 1;
  3058. return ret;
  3059. }
  3060. if (ret < 0) {
  3061. if (ret != AVERROR_EOF) {
  3062. print_error(is->filename, ret);
  3063. if (exit_on_error)
  3064. exit_program(1);
  3065. }
  3066. for (i = 0; i < ifile->nb_streams; i++) {
  3067. ist = input_streams[ifile->ist_index + i];
  3068. if (ist->decoding_needed) {
  3069. ret = process_input_packet(ist, NULL);
  3070. if (ret>0)
  3071. return 0;
  3072. }
  3073. /* mark all outputs that don't go through lavfi as finished */
  3074. for (j = 0; j < nb_output_streams; j++) {
  3075. OutputStream *ost = output_streams[j];
  3076. if (ost->source_index == ifile->ist_index + i &&
  3077. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  3078. finish_output_stream(ost);
  3079. }
  3080. }
  3081. ifile->eof_reached = 1;
  3082. return AVERROR(EAGAIN);
  3083. }
  3084. reset_eagain();
  3085. if (do_pkt_dump) {
  3086. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  3087. is->streams[pkt.stream_index]);
  3088. }
  3089. /* the following test is needed in case new streams appear
  3090. dynamically in stream : we ignore them */
  3091. if (pkt.stream_index >= ifile->nb_streams) {
  3092. report_new_stream(file_index, &pkt);
  3093. goto discard_packet;
  3094. }
  3095. ist = input_streams[ifile->ist_index + pkt.stream_index];
  3096. ist->data_size += pkt.size;
  3097. ist->nb_packets++;
  3098. if (ist->discard)
  3099. goto discard_packet;
  3100. if (debug_ts) {
  3101. av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
  3102. "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",
  3103. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
  3104. av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
  3105. av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
  3106. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  3107. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  3108. av_ts2str(input_files[ist->file_index]->ts_offset),
  3109. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  3110. }
  3111. if(!ist->wrap_correction_done && is->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
  3112. int64_t stime, stime2;
  3113. // Correcting starttime based on the enabled streams
  3114. // 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.
  3115. // so we instead do it here as part of discontinuity handling
  3116. if ( ist->next_dts == AV_NOPTS_VALUE
  3117. && ifile->ts_offset == -is->start_time
  3118. && (is->iformat->flags & AVFMT_TS_DISCONT)) {
  3119. int64_t new_start_time = INT64_MAX;
  3120. for (i=0; i<is->nb_streams; i++) {
  3121. AVStream *st = is->streams[i];
  3122. if(st->discard == AVDISCARD_ALL || st->start_time == AV_NOPTS_VALUE)
  3123. continue;
  3124. new_start_time = FFMIN(new_start_time, av_rescale_q(st->start_time, st->time_base, AV_TIME_BASE_Q));
  3125. }
  3126. if (new_start_time > is->start_time) {
  3127. av_log(is, AV_LOG_VERBOSE, "Correcting start time by %"PRId64"\n", new_start_time - is->start_time);
  3128. ifile->ts_offset = -new_start_time;
  3129. }
  3130. }
  3131. stime = av_rescale_q(is->start_time, AV_TIME_BASE_Q, ist->st->time_base);
  3132. stime2= stime + (1ULL<<ist->st->pts_wrap_bits);
  3133. ist->wrap_correction_done = 1;
  3134. if(stime2 > stime && pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  3135. pkt.dts -= 1ULL<<ist->st->pts_wrap_bits;
  3136. ist->wrap_correction_done = 0;
  3137. }
  3138. if(stime2 > stime && pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime + (1LL<<(ist->st->pts_wrap_bits-1))) {
  3139. pkt.pts -= 1ULL<<ist->st->pts_wrap_bits;
  3140. ist->wrap_correction_done = 0;
  3141. }
  3142. }
  3143. /* add the stream-global side data to the first packet */
  3144. if (ist->nb_packets == 1) {
  3145. if (ist->st->nb_side_data)
  3146. av_packet_split_side_data(&pkt);
  3147. for (i = 0; i < ist->st->nb_side_data; i++) {
  3148. AVPacketSideData *src_sd = &ist->st->side_data[i];
  3149. uint8_t *dst_data;
  3150. if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
  3151. continue;
  3152. dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
  3153. if (!dst_data)
  3154. exit_program(1);
  3155. memcpy(dst_data, src_sd->data, src_sd->size);
  3156. }
  3157. }
  3158. if (pkt.dts != AV_NOPTS_VALUE)
  3159. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  3160. if (pkt.pts != AV_NOPTS_VALUE)
  3161. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  3162. if (pkt.pts != AV_NOPTS_VALUE)
  3163. pkt.pts *= ist->ts_scale;
  3164. if (pkt.dts != AV_NOPTS_VALUE)
  3165. pkt.dts *= ist->ts_scale;
  3166. if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  3167. ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
  3168. pkt.dts != AV_NOPTS_VALUE && ist->next_dts == AV_NOPTS_VALUE && !copy_ts
  3169. && (is->iformat->flags & AVFMT_TS_DISCONT) && ifile->last_ts != AV_NOPTS_VALUE) {
  3170. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  3171. int64_t delta = pkt_dts - ifile->last_ts;
  3172. if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  3173. delta > 1LL*dts_delta_threshold*AV_TIME_BASE){
  3174. ifile->ts_offset -= delta;
  3175. av_log(NULL, AV_LOG_DEBUG,
  3176. "Inter stream timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  3177. delta, ifile->ts_offset);
  3178. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  3179. if (pkt.pts != AV_NOPTS_VALUE)
  3180. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  3181. }
  3182. }
  3183. if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  3184. ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
  3185. pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  3186. !copy_ts) {
  3187. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  3188. int64_t delta = pkt_dts - ist->next_dts;
  3189. if (is->iformat->flags & AVFMT_TS_DISCONT) {
  3190. if (delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  3191. delta > 1LL*dts_delta_threshold*AV_TIME_BASE ||
  3192. pkt_dts + AV_TIME_BASE/10 < FFMAX(ist->pts, ist->dts)) {
  3193. ifile->ts_offset -= delta;
  3194. av_log(NULL, AV_LOG_DEBUG,
  3195. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  3196. delta, ifile->ts_offset);
  3197. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  3198. if (pkt.pts != AV_NOPTS_VALUE)
  3199. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  3200. }
  3201. } else {
  3202. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  3203. delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
  3204. av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
  3205. pkt.dts = AV_NOPTS_VALUE;
  3206. }
  3207. if (pkt.pts != AV_NOPTS_VALUE){
  3208. int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
  3209. delta = pkt_pts - ist->next_dts;
  3210. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  3211. delta > 1LL*dts_error_threshold*AV_TIME_BASE) {
  3212. av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
  3213. pkt.pts = AV_NOPTS_VALUE;
  3214. }
  3215. }
  3216. }
  3217. }
  3218. if (pkt.dts != AV_NOPTS_VALUE)
  3219. ifile->last_ts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  3220. if (debug_ts) {
  3221. 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",
  3222. ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->dec_ctx->codec_type),
  3223. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  3224. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  3225. av_ts2str(input_files[ist->file_index]->ts_offset),
  3226. av_ts2timestr(input_files[ist->file_index]->ts_offset, &AV_TIME_BASE_Q));
  3227. }
  3228. sub2video_heartbeat(ist, pkt.pts);
  3229. ret = process_input_packet(ist, &pkt);
  3230. if (ret < 0) {
  3231. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
  3232. ist->file_index, ist->st->index, av_err2str(ret));
  3233. if (exit_on_error)
  3234. exit_program(1);
  3235. }
  3236. discard_packet:
  3237. av_free_packet(&pkt);
  3238. return 0;
  3239. }
  3240. /**
  3241. * Perform a step of transcoding for the specified filter graph.
  3242. *
  3243. * @param[in] graph filter graph to consider
  3244. * @param[out] best_ist input stream where a frame would allow to continue
  3245. * @return 0 for success, <0 for error
  3246. */
  3247. static int transcode_from_filter(FilterGraph *graph, InputStream **best_ist)
  3248. {
  3249. int i, ret;
  3250. int nb_requests, nb_requests_max = 0;
  3251. InputFilter *ifilter;
  3252. InputStream *ist;
  3253. *best_ist = NULL;
  3254. ret = avfilter_graph_request_oldest(graph->graph);
  3255. if (ret >= 0)
  3256. return reap_filters();
  3257. if (ret == AVERROR_EOF) {
  3258. ret = reap_filters();
  3259. for (i = 0; i < graph->nb_outputs; i++)
  3260. close_output_stream(graph->outputs[i]->ost);
  3261. return ret;
  3262. }
  3263. if (ret != AVERROR(EAGAIN))
  3264. return ret;
  3265. for (i = 0; i < graph->nb_inputs; i++) {
  3266. ifilter = graph->inputs[i];
  3267. ist = ifilter->ist;
  3268. if (input_files[ist->file_index]->eagain ||
  3269. input_files[ist->file_index]->eof_reached)
  3270. continue;
  3271. nb_requests = av_buffersrc_get_nb_failed_requests(ifilter->filter);
  3272. if (nb_requests > nb_requests_max) {
  3273. nb_requests_max = nb_requests;
  3274. *best_ist = ist;
  3275. }
  3276. }
  3277. if (!*best_ist)
  3278. for (i = 0; i < graph->nb_outputs; i++)
  3279. graph->outputs[i]->ost->unavailable = 1;
  3280. return 0;
  3281. }
  3282. /**
  3283. * Run a single step of transcoding.
  3284. *
  3285. * @return 0 for success, <0 for error
  3286. */
  3287. static int transcode_step(void)
  3288. {
  3289. OutputStream *ost;
  3290. InputStream *ist;
  3291. int ret;
  3292. ost = choose_output();
  3293. if (!ost) {
  3294. if (got_eagain()) {
  3295. reset_eagain();
  3296. av_usleep(10000);
  3297. return 0;
  3298. }
  3299. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
  3300. return AVERROR_EOF;
  3301. }
  3302. if (ost->filter) {
  3303. if ((ret = transcode_from_filter(ost->filter->graph, &ist)) < 0)
  3304. return ret;
  3305. if (!ist)
  3306. return 0;
  3307. } else {
  3308. av_assert0(ost->source_index >= 0);
  3309. ist = input_streams[ost->source_index];
  3310. }
  3311. ret = process_input(ist->file_index);
  3312. if (ret == AVERROR(EAGAIN)) {
  3313. if (input_files[ist->file_index]->eagain)
  3314. ost->unavailable = 1;
  3315. return 0;
  3316. }
  3317. if (ret < 0)
  3318. return ret == AVERROR_EOF ? 0 : ret;
  3319. return reap_filters();
  3320. }
  3321. /*
  3322. * The following code is the main loop of the file converter
  3323. */
  3324. static int transcode(void)
  3325. {
  3326. int ret, i;
  3327. AVFormatContext *os;
  3328. OutputStream *ost;
  3329. InputStream *ist;
  3330. int64_t timer_start;
  3331. ret = transcode_init();
  3332. if (ret < 0)
  3333. goto fail;
  3334. if (stdin_interaction) {
  3335. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  3336. }
  3337. timer_start = av_gettime_relative();
  3338. #if HAVE_PTHREADS
  3339. if ((ret = init_input_threads()) < 0)
  3340. goto fail;
  3341. #endif
  3342. while (!received_sigterm) {
  3343. int64_t cur_time= av_gettime_relative();
  3344. /* if 'q' pressed, exits */
  3345. if (stdin_interaction)
  3346. if (check_keyboard_interaction(cur_time) < 0)
  3347. break;
  3348. /* check if there's any stream where output is still needed */
  3349. if (!need_output()) {
  3350. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  3351. break;
  3352. }
  3353. ret = transcode_step();
  3354. if (ret < 0) {
  3355. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  3356. continue;
  3357. av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
  3358. break;
  3359. }
  3360. /* dump report by using the output first video and audio streams */
  3361. print_report(0, timer_start, cur_time);
  3362. }
  3363. #if HAVE_PTHREADS
  3364. free_input_threads();
  3365. #endif
  3366. /* at the end of stream, we must flush the decoder buffers */
  3367. for (i = 0; i < nb_input_streams; i++) {
  3368. ist = input_streams[i];
  3369. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  3370. process_input_packet(ist, NULL);
  3371. }
  3372. }
  3373. flush_encoders();
  3374. term_exit();
  3375. /* write the trailer if needed and close file */
  3376. for (i = 0; i < nb_output_files; i++) {
  3377. os = output_files[i]->ctx;
  3378. av_write_trailer(os);
  3379. }
  3380. /* dump report by using the first video and audio streams */
  3381. print_report(1, timer_start, av_gettime_relative());
  3382. /* close each encoder */
  3383. for (i = 0; i < nb_output_streams; i++) {
  3384. ost = output_streams[i];
  3385. if (ost->encoding_needed) {
  3386. av_freep(&ost->enc_ctx->stats_in);
  3387. }
  3388. }
  3389. /* close each decoder */
  3390. for (i = 0; i < nb_input_streams; i++) {
  3391. ist = input_streams[i];
  3392. if (ist->decoding_needed) {
  3393. avcodec_close(ist->dec_ctx);
  3394. if (ist->hwaccel_uninit)
  3395. ist->hwaccel_uninit(ist->dec_ctx);
  3396. }
  3397. }
  3398. /* finished ! */
  3399. ret = 0;
  3400. fail:
  3401. #if HAVE_PTHREADS
  3402. free_input_threads();
  3403. #endif
  3404. if (output_streams) {
  3405. for (i = 0; i < nb_output_streams; i++) {
  3406. ost = output_streams[i];
  3407. if (ost) {
  3408. if (ost->logfile) {
  3409. fclose(ost->logfile);
  3410. ost->logfile = NULL;
  3411. }
  3412. av_freep(&ost->forced_kf_pts);
  3413. av_freep(&ost->apad);
  3414. av_freep(&ost->disposition);
  3415. av_dict_free(&ost->encoder_opts);
  3416. av_dict_free(&ost->swr_opts);
  3417. av_dict_free(&ost->resample_opts);
  3418. av_dict_free(&ost->bsf_args);
  3419. }
  3420. }
  3421. }
  3422. return ret;
  3423. }
  3424. static int64_t getutime(void)
  3425. {
  3426. #if HAVE_GETRUSAGE
  3427. struct rusage rusage;
  3428. getrusage(RUSAGE_SELF, &rusage);
  3429. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  3430. #elif HAVE_GETPROCESSTIMES
  3431. HANDLE proc;
  3432. FILETIME c, e, k, u;
  3433. proc = GetCurrentProcess();
  3434. GetProcessTimes(proc, &c, &e, &k, &u);
  3435. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  3436. #else
  3437. return av_gettime_relative();
  3438. #endif
  3439. }
  3440. static int64_t getmaxrss(void)
  3441. {
  3442. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  3443. struct rusage rusage;
  3444. getrusage(RUSAGE_SELF, &rusage);
  3445. return (int64_t)rusage.ru_maxrss * 1024;
  3446. #elif HAVE_GETPROCESSMEMORYINFO
  3447. HANDLE proc;
  3448. PROCESS_MEMORY_COUNTERS memcounters;
  3449. proc = GetCurrentProcess();
  3450. memcounters.cb = sizeof(memcounters);
  3451. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  3452. return memcounters.PeakPagefileUsage;
  3453. #else
  3454. return 0;
  3455. #endif
  3456. }
  3457. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
  3458. {
  3459. }
  3460. int main(int argc, char **argv)
  3461. {
  3462. int ret;
  3463. int64_t ti;
  3464. register_exit(ffmpeg_cleanup);
  3465. setvbuf(stderr,NULL,_IONBF,0); /* win32 runtime needs this */
  3466. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  3467. parse_loglevel(argc, argv, options);
  3468. if(argc>1 && !strcmp(argv[1], "-d")){
  3469. run_as_daemon=1;
  3470. av_log_set_callback(log_callback_null);
  3471. argc--;
  3472. argv++;
  3473. }
  3474. avcodec_register_all();
  3475. #if CONFIG_AVDEVICE
  3476. avdevice_register_all();
  3477. #endif
  3478. avfilter_register_all();
  3479. av_register_all();
  3480. avformat_network_init();
  3481. show_banner(argc, argv, options);
  3482. term_init();
  3483. /* parse options and open all input/output files */
  3484. ret = ffmpeg_parse_options(argc, argv);
  3485. if (ret < 0)
  3486. exit_program(1);
  3487. if (nb_output_files <= 0 && nb_input_files == 0) {
  3488. show_usage();
  3489. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  3490. exit_program(1);
  3491. }
  3492. /* file converter / grab */
  3493. if (nb_output_files <= 0) {
  3494. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  3495. exit_program(1);
  3496. }
  3497. // if (nb_input_files == 0) {
  3498. // av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
  3499. // exit_program(1);
  3500. // }
  3501. current_time = ti = getutime();
  3502. if (transcode() < 0)
  3503. exit_program(1);
  3504. ti = getutime() - ti;
  3505. if (do_benchmark) {
  3506. printf("bench: utime=%0.3fs\n", ti / 1000000.0);
  3507. }
  3508. av_log(NULL, AV_LOG_DEBUG, "%"PRIu64" frames successfully decoded, %"PRIu64" decoding errors\n",
  3509. decode_error_stat[0], decode_error_stat[1]);
  3510. if ((decode_error_stat[0] + decode_error_stat[1]) * max_error_rate < decode_error_stat[1])
  3511. exit_program(69);
  3512. exit_program(received_nb_signals ? 255 : main_return_code);
  3513. return main_return_code;
  3514. }