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.

3878 lines
137KB

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