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.

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