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.

4108 lines
148KB

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