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.

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