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.

4078 lines
147KB

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