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.

3064 lines
107KB

  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. #if HAVE_ISATTY
  32. #include <unistd.h>
  33. #endif
  34. #include "libavformat/avformat.h"
  35. #include "libavdevice/avdevice.h"
  36. #include "libswscale/swscale.h"
  37. #include "libswresample/swresample.h"
  38. #include "libavutil/opt.h"
  39. #include "libavutil/audioconvert.h"
  40. #include "libavutil/parseutils.h"
  41. #include "libavutil/samplefmt.h"
  42. #include "libavutil/colorspace.h"
  43. #include "libavutil/fifo.h"
  44. #include "libavutil/intreadwrite.h"
  45. #include "libavutil/dict.h"
  46. #include "libavutil/mathematics.h"
  47. #include "libavutil/pixdesc.h"
  48. #include "libavutil/avstring.h"
  49. #include "libavutil/libm.h"
  50. #include "libavutil/imgutils.h"
  51. #include "libavutil/timestamp.h"
  52. #include "libavutil/bprint.h"
  53. #include "libavutil/time.h"
  54. #include "libavformat/os_support.h"
  55. #include "libavformat/ffm.h" // not public API
  56. # include "libavfilter/avcodec.h"
  57. # include "libavfilter/avfilter.h"
  58. # include "libavfilter/avfiltergraph.h"
  59. # include "libavfilter/buffersrc.h"
  60. # include "libavfilter/buffersink.h"
  61. #if HAVE_SYS_RESOURCE_H
  62. #include <sys/types.h>
  63. #include <sys/resource.h>
  64. #elif HAVE_GETPROCESSTIMES
  65. #include <windows.h>
  66. #endif
  67. #if HAVE_GETPROCESSMEMORYINFO
  68. #include <windows.h>
  69. #include <psapi.h>
  70. #endif
  71. #if HAVE_SYS_SELECT_H
  72. #include <sys/select.h>
  73. #endif
  74. #if HAVE_TERMIOS_H
  75. #include <fcntl.h>
  76. #include <sys/ioctl.h>
  77. #include <sys/time.h>
  78. #include <termios.h>
  79. #elif HAVE_KBHIT
  80. #include <conio.h>
  81. #endif
  82. #if HAVE_PTHREADS
  83. #include <pthread.h>
  84. #endif
  85. #include <time.h>
  86. #include "ffmpeg.h"
  87. #include "cmdutils.h"
  88. #include "libavutil/avassert.h"
  89. const char program_name[] = "ffmpeg";
  90. const int program_birth_year = 2000;
  91. static FILE *vstats_file;
  92. static void do_video_stats(AVFormatContext *os, OutputStream *ost, int frame_size);
  93. static int64_t getutime(void);
  94. static int run_as_daemon = 0;
  95. static int64_t video_size = 0;
  96. static int64_t audio_size = 0;
  97. static int64_t subtitle_size = 0;
  98. static int64_t extra_size = 0;
  99. static int nb_frames_dup = 0;
  100. static int nb_frames_drop = 0;
  101. static int current_time;
  102. AVIOContext *progress_avio = NULL;
  103. static uint8_t *subtitle_out;
  104. #if HAVE_PTHREADS
  105. /* signal to input threads that they should exit; set by the main thread */
  106. static int transcoding_finished;
  107. #endif
  108. #define DEFAULT_PASS_LOGFILENAME_PREFIX "ffmpeg2pass"
  109. InputStream **input_streams = NULL;
  110. int nb_input_streams = 0;
  111. InputFile **input_files = NULL;
  112. int nb_input_files = 0;
  113. OutputStream **output_streams = NULL;
  114. int nb_output_streams = 0;
  115. OutputFile **output_files = NULL;
  116. int nb_output_files = 0;
  117. FilterGraph **filtergraphs;
  118. int nb_filtergraphs;
  119. #if HAVE_TERMIOS_H
  120. /* init terminal so that we can grab keys */
  121. static struct termios oldtty;
  122. static int restore_tty;
  123. #endif
  124. /* sub2video hack:
  125. Convert subtitles to video with alpha to insert them in filter graphs.
  126. This is a temporary solution until libavfilter gets real subtitles support.
  127. */
  128. static void sub2video_copy_rect(uint8_t *dst, int dst_linesize, int w, int h,
  129. AVSubtitleRect *r)
  130. {
  131. uint32_t *pal, *dst2;
  132. uint8_t *src, *src2;
  133. int x, y;
  134. if (r->type != SUBTITLE_BITMAP) {
  135. av_log(NULL, AV_LOG_WARNING, "sub2video: non-bitmap subtitle\n");
  136. return;
  137. }
  138. if (r->x < 0 || r->x + r->w > w || r->y < 0 || r->y + r->h > h) {
  139. av_log(NULL, AV_LOG_WARNING, "sub2video: rectangle overflowing\n");
  140. return;
  141. }
  142. dst += r->y * dst_linesize + r->x * 4;
  143. src = r->pict.data[0];
  144. pal = (uint32_t *)r->pict.data[1];
  145. for (y = 0; y < r->h; y++) {
  146. dst2 = (uint32_t *)dst;
  147. src2 = src;
  148. for (x = 0; x < r->w; x++)
  149. *(dst2++) = pal[*(src2++)];
  150. dst += dst_linesize;
  151. src += r->pict.linesize[0];
  152. }
  153. }
  154. static void sub2video_push_ref(InputStream *ist, int64_t pts)
  155. {
  156. AVFilterBufferRef *ref = ist->sub2video.ref;
  157. int i;
  158. ist->sub2video.last_pts = ref->pts = pts;
  159. for (i = 0; i < ist->nb_filters; i++)
  160. av_buffersrc_add_ref(ist->filters[i]->filter,
  161. avfilter_ref_buffer(ref, ~0),
  162. AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
  163. AV_BUFFERSRC_FLAG_NO_COPY);
  164. }
  165. static void sub2video_update(InputStream *ist, AVSubtitle *sub, int64_t pts)
  166. {
  167. int w = ist->sub2video.w, h = ist->sub2video.h;
  168. AVFilterBufferRef *ref = ist->sub2video.ref;
  169. int8_t *dst;
  170. int dst_linesize;
  171. int i;
  172. if (!ref)
  173. return;
  174. dst = ref->data [0];
  175. dst_linesize = ref->linesize[0];
  176. memset(dst, 0, h * dst_linesize);
  177. for (i = 0; i < sub->num_rects; i++)
  178. sub2video_copy_rect(dst, dst_linesize, w, h, sub->rects[i]);
  179. sub2video_push_ref(ist, pts);
  180. }
  181. static void sub2video_heartbeat(InputStream *ist, int64_t pts)
  182. {
  183. InputFile *infile = input_files[ist->file_index];
  184. int i, j, nb_reqs;
  185. int64_t pts2;
  186. /* When a frame is read from a file, examine all sub2video streams in
  187. the same file and send the sub2video frame again. Otherwise, decoded
  188. video frames could be accumulating in the filter graph while a filter
  189. (possibly overlay) is desperately waiting for a subtitle frame. */
  190. for (i = 0; i < infile->nb_streams; i++) {
  191. InputStream *ist2 = input_streams[infile->ist_index + i];
  192. if (!ist2->sub2video.ref)
  193. continue;
  194. /* subtitles seem to be usually muxed ahead of other streams;
  195. if not, substracting a larger time here is necessary */
  196. pts2 = av_rescale_q(pts, ist->st->time_base, ist2->st->time_base) - 1;
  197. /* do not send the heartbeat frame if the subtitle is already ahead */
  198. if (pts2 <= ist2->sub2video.last_pts)
  199. continue;
  200. for (j = 0, nb_reqs = 0; j < ist2->nb_filters; j++)
  201. nb_reqs += av_buffersrc_get_nb_failed_requests(ist2->filters[j]->filter);
  202. if (nb_reqs)
  203. sub2video_push_ref(ist2, pts2);
  204. }
  205. }
  206. static void sub2video_flush(InputStream *ist)
  207. {
  208. int i;
  209. for (i = 0; i < ist->nb_filters; i++)
  210. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, 0);
  211. }
  212. /* end of sub2video hack */
  213. void term_exit(void)
  214. {
  215. av_log(NULL, AV_LOG_QUIET, "%s", "");
  216. #if HAVE_TERMIOS_H
  217. if(restore_tty)
  218. tcsetattr (0, TCSANOW, &oldtty);
  219. #endif
  220. }
  221. static volatile int received_sigterm = 0;
  222. static volatile int received_nb_signals = 0;
  223. static void
  224. sigterm_handler(int sig)
  225. {
  226. received_sigterm = sig;
  227. received_nb_signals++;
  228. term_exit();
  229. if(received_nb_signals > 3)
  230. exit(123);
  231. }
  232. void term_init(void)
  233. {
  234. #if HAVE_TERMIOS_H
  235. if(!run_as_daemon){
  236. struct termios tty;
  237. int istty = 1;
  238. #if HAVE_ISATTY
  239. istty = isatty(0) && isatty(2);
  240. #endif
  241. if (istty && tcgetattr (0, &tty) == 0) {
  242. oldtty = tty;
  243. restore_tty = 1;
  244. atexit(term_exit);
  245. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  246. |INLCR|IGNCR|ICRNL|IXON);
  247. tty.c_oflag |= OPOST;
  248. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  249. tty.c_cflag &= ~(CSIZE|PARENB);
  250. tty.c_cflag |= CS8;
  251. tty.c_cc[VMIN] = 1;
  252. tty.c_cc[VTIME] = 0;
  253. tcsetattr (0, TCSANOW, &tty);
  254. }
  255. signal(SIGQUIT, sigterm_handler); /* Quit (POSIX). */
  256. }
  257. #endif
  258. avformat_network_deinit();
  259. signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  260. signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  261. #ifdef SIGXCPU
  262. signal(SIGXCPU, sigterm_handler);
  263. #endif
  264. }
  265. /* read a key without blocking */
  266. static int read_key(void)
  267. {
  268. unsigned char ch;
  269. #if HAVE_TERMIOS_H
  270. int n = 1;
  271. struct timeval tv;
  272. fd_set rfds;
  273. FD_ZERO(&rfds);
  274. FD_SET(0, &rfds);
  275. tv.tv_sec = 0;
  276. tv.tv_usec = 0;
  277. n = select(1, &rfds, NULL, NULL, &tv);
  278. if (n > 0) {
  279. n = read(0, &ch, 1);
  280. if (n == 1)
  281. return ch;
  282. return n;
  283. }
  284. #elif HAVE_KBHIT
  285. # if HAVE_PEEKNAMEDPIPE
  286. static int is_pipe;
  287. static HANDLE input_handle;
  288. DWORD dw, nchars;
  289. if(!input_handle){
  290. input_handle = GetStdHandle(STD_INPUT_HANDLE);
  291. is_pipe = !GetConsoleMode(input_handle, &dw);
  292. }
  293. if (stdin->_cnt > 0) {
  294. read(0, &ch, 1);
  295. return ch;
  296. }
  297. if (is_pipe) {
  298. /* When running under a GUI, you will end here. */
  299. if (!PeekNamedPipe(input_handle, NULL, 0, NULL, &nchars, NULL))
  300. return -1;
  301. //Read it
  302. if(nchars != 0) {
  303. read(0, &ch, 1);
  304. return ch;
  305. }else{
  306. return -1;
  307. }
  308. }
  309. # endif
  310. if(kbhit())
  311. return(getch());
  312. #endif
  313. return -1;
  314. }
  315. static int decode_interrupt_cb(void *ctx)
  316. {
  317. return received_nb_signals > 1;
  318. }
  319. const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
  320. void av_noreturn exit_program(int ret)
  321. {
  322. int i, j;
  323. for (i = 0; i < nb_filtergraphs; i++) {
  324. avfilter_graph_free(&filtergraphs[i]->graph);
  325. for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
  326. av_freep(&filtergraphs[i]->inputs[j]->name);
  327. av_freep(&filtergraphs[i]->inputs[j]);
  328. }
  329. av_freep(&filtergraphs[i]->inputs);
  330. for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
  331. av_freep(&filtergraphs[i]->outputs[j]->name);
  332. av_freep(&filtergraphs[i]->outputs[j]);
  333. }
  334. av_freep(&filtergraphs[i]->outputs);
  335. av_freep(&filtergraphs[i]);
  336. }
  337. av_freep(&filtergraphs);
  338. av_freep(&subtitle_out);
  339. /* close files */
  340. for (i = 0; i < nb_output_files; i++) {
  341. AVFormatContext *s = output_files[i]->ctx;
  342. if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
  343. avio_close(s->pb);
  344. avformat_free_context(s);
  345. av_dict_free(&output_files[i]->opts);
  346. av_freep(&output_files[i]);
  347. }
  348. for (i = 0; i < nb_output_streams; i++) {
  349. AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
  350. while (bsfc) {
  351. AVBitStreamFilterContext *next = bsfc->next;
  352. av_bitstream_filter_close(bsfc);
  353. bsfc = next;
  354. }
  355. output_streams[i]->bitstream_filters = NULL;
  356. av_freep(&output_streams[i]->forced_keyframes);
  357. av_freep(&output_streams[i]->avfilter);
  358. av_freep(&output_streams[i]->filtered_frame);
  359. av_freep(&output_streams[i]);
  360. }
  361. for (i = 0; i < nb_input_files; i++) {
  362. avformat_close_input(&input_files[i]->ctx);
  363. av_freep(&input_files[i]);
  364. }
  365. for (i = 0; i < nb_input_streams; i++) {
  366. av_freep(&input_streams[i]->decoded_frame);
  367. av_dict_free(&input_streams[i]->opts);
  368. free_buffer_pool(&input_streams[i]->buffer_pool);
  369. avfilter_unref_bufferp(&input_streams[i]->sub2video.ref);
  370. av_freep(&input_streams[i]->filters);
  371. av_freep(&input_streams[i]);
  372. }
  373. if (vstats_file)
  374. fclose(vstats_file);
  375. av_free(vstats_filename);
  376. av_freep(&input_streams);
  377. av_freep(&input_files);
  378. av_freep(&output_streams);
  379. av_freep(&output_files);
  380. uninit_opts();
  381. avfilter_uninit();
  382. avformat_network_deinit();
  383. if (received_sigterm) {
  384. av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
  385. (int) received_sigterm);
  386. exit (255);
  387. }
  388. exit(ret);
  389. }
  390. void assert_avoptions(AVDictionary *m)
  391. {
  392. AVDictionaryEntry *t;
  393. if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  394. av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
  395. exit_program(1);
  396. }
  397. }
  398. static void assert_codec_experimental(AVCodecContext *c, int encoder)
  399. {
  400. const char *codec_string = encoder ? "encoder" : "decoder";
  401. AVCodec *codec;
  402. if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&
  403. c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
  404. av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
  405. "results.\nAdd '-strict experimental' if you want to use it.\n",
  406. codec_string, c->codec->name);
  407. codec = encoder ? avcodec_find_encoder(c->codec->id) : avcodec_find_decoder(c->codec->id);
  408. if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
  409. av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
  410. codec_string, codec->name);
  411. exit_program(1);
  412. }
  413. }
  414. static void update_benchmark(const char *fmt, ...)
  415. {
  416. if (do_benchmark_all) {
  417. int64_t t = getutime();
  418. va_list va;
  419. char buf[1024];
  420. if (fmt) {
  421. va_start(va, fmt);
  422. vsnprintf(buf, sizeof(buf), fmt, va);
  423. va_end(va);
  424. printf("bench: %8"PRIu64" %s \n", t - current_time, buf);
  425. }
  426. current_time = t;
  427. }
  428. }
  429. static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
  430. {
  431. AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
  432. AVCodecContext *avctx = ost->st->codec;
  433. int ret;
  434. if ((avctx->codec_type == AVMEDIA_TYPE_VIDEO && video_sync_method == VSYNC_DROP) ||
  435. (avctx->codec_type == AVMEDIA_TYPE_AUDIO && audio_sync_method < 0))
  436. pkt->pts = pkt->dts = AV_NOPTS_VALUE;
  437. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && pkt->dts != AV_NOPTS_VALUE) {
  438. int64_t max = ost->st->cur_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT);
  439. if (ost->st->cur_dts && ost->st->cur_dts != AV_NOPTS_VALUE && max > pkt->dts) {
  440. av_log(s, max - pkt->dts > 2 ? AV_LOG_WARNING : AV_LOG_DEBUG, "Audio timestamp %"PRId64" < %"PRId64" invalid, cliping\n", pkt->dts, max);
  441. pkt->pts = pkt->dts = max;
  442. }
  443. }
  444. /*
  445. * Audio encoders may split the packets -- #frames in != #packets out.
  446. * But there is no reordering, so we can limit the number of output packets
  447. * by simply dropping them here.
  448. * Counting encoded video frames needs to be done separately because of
  449. * reordering, see do_video_out()
  450. */
  451. if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
  452. if (ost->frame_number >= ost->max_frames) {
  453. av_free_packet(pkt);
  454. return;
  455. }
  456. ost->frame_number++;
  457. }
  458. while (bsfc) {
  459. AVPacket new_pkt = *pkt;
  460. int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
  461. &new_pkt.data, &new_pkt.size,
  462. pkt->data, pkt->size,
  463. pkt->flags & AV_PKT_FLAG_KEY);
  464. if (a > 0) {
  465. av_free_packet(pkt);
  466. new_pkt.destruct = av_destruct_packet;
  467. } else if (a < 0) {
  468. av_log(NULL, AV_LOG_ERROR, "Failed to open bitstream filter %s for stream %d with codec %s",
  469. bsfc->filter->name, pkt->stream_index,
  470. avctx->codec ? avctx->codec->name : "copy");
  471. print_error("", a);
  472. if (exit_on_error)
  473. exit_program(1);
  474. }
  475. *pkt = new_pkt;
  476. bsfc = bsfc->next;
  477. }
  478. pkt->stream_index = ost->index;
  479. ret = av_interleaved_write_frame(s, pkt);
  480. if (ret < 0) {
  481. print_error("av_interleaved_write_frame()", ret);
  482. exit_program(1);
  483. }
  484. }
  485. static int check_recording_time(OutputStream *ost)
  486. {
  487. OutputFile *of = output_files[ost->file_index];
  488. if (of->recording_time != INT64_MAX &&
  489. av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
  490. AV_TIME_BASE_Q) >= 0) {
  491. ost->is_past_recording_time = 1;
  492. return 0;
  493. }
  494. return 1;
  495. }
  496. static void do_audio_out(AVFormatContext *s, OutputStream *ost,
  497. AVFrame *frame)
  498. {
  499. AVCodecContext *enc = ost->st->codec;
  500. AVPacket pkt;
  501. int got_packet = 0;
  502. av_init_packet(&pkt);
  503. pkt.data = NULL;
  504. pkt.size = 0;
  505. if (!check_recording_time(ost))
  506. return;
  507. if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
  508. frame->pts = ost->sync_opts;
  509. ost->sync_opts = frame->pts + frame->nb_samples;
  510. av_assert0(pkt.size || !pkt.data);
  511. update_benchmark(NULL);
  512. if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
  513. av_log(NULL, AV_LOG_FATAL, "Audio encoding failed (avcodec_encode_audio2)\n");
  514. exit_program(1);
  515. }
  516. update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);
  517. if (got_packet) {
  518. if (pkt.pts != AV_NOPTS_VALUE)
  519. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  520. if (pkt.dts != AV_NOPTS_VALUE)
  521. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  522. if (pkt.duration > 0)
  523. pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
  524. if (debug_ts) {
  525. av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "
  526. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  527. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
  528. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
  529. }
  530. write_frame(s, &pkt, ost);
  531. audio_size += pkt.size;
  532. av_free_packet(&pkt);
  533. }
  534. }
  535. static void pre_process_video_frame(InputStream *ist, AVPicture *picture, void **bufp)
  536. {
  537. AVCodecContext *dec;
  538. AVPicture *picture2;
  539. AVPicture picture_tmp;
  540. uint8_t *buf = 0;
  541. dec = ist->st->codec;
  542. /* deinterlace : must be done before any resize */
  543. if (do_deinterlace) {
  544. int size;
  545. /* create temporary picture */
  546. size = avpicture_get_size(dec->pix_fmt, dec->width, dec->height);
  547. buf = av_malloc(size);
  548. if (!buf)
  549. return;
  550. picture2 = &picture_tmp;
  551. avpicture_fill(picture2, buf, dec->pix_fmt, dec->width, dec->height);
  552. if (avpicture_deinterlace(picture2, picture,
  553. dec->pix_fmt, dec->width, dec->height) < 0) {
  554. /* if error, do not deinterlace */
  555. av_log(NULL, AV_LOG_WARNING, "Deinterlacing failed\n");
  556. av_free(buf);
  557. buf = NULL;
  558. picture2 = picture;
  559. }
  560. } else {
  561. picture2 = picture;
  562. }
  563. if (picture != picture2)
  564. *picture = *picture2;
  565. *bufp = buf;
  566. }
  567. static void do_subtitle_out(AVFormatContext *s,
  568. OutputStream *ost,
  569. InputStream *ist,
  570. AVSubtitle *sub,
  571. int64_t pts)
  572. {
  573. int subtitle_out_max_size = 1024 * 1024;
  574. int subtitle_out_size, nb, i;
  575. AVCodecContext *enc;
  576. AVPacket pkt;
  577. if (pts == AV_NOPTS_VALUE) {
  578. av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
  579. if (exit_on_error)
  580. exit_program(1);
  581. return;
  582. }
  583. enc = ost->st->codec;
  584. if (!subtitle_out) {
  585. subtitle_out = av_malloc(subtitle_out_max_size);
  586. }
  587. /* Note: DVB subtitle need one packet to draw them and one other
  588. packet to clear them */
  589. /* XXX: signal it in the codec context ? */
  590. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
  591. nb = 2;
  592. else
  593. nb = 1;
  594. /* shift timestamp to honor -ss and make check_recording_time() work with -t */
  595. pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q)
  596. - output_files[ost->file_index]->start_time;
  597. for (i = 0; i < nb; i++) {
  598. ost->sync_opts = av_rescale_q(pts, AV_TIME_BASE_Q, enc->time_base);
  599. if (!check_recording_time(ost))
  600. return;
  601. sub->pts = pts;
  602. // start_display_time is required to be 0
  603. sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
  604. sub->end_display_time -= sub->start_display_time;
  605. sub->start_display_time = 0;
  606. if (i == 1)
  607. sub->num_rects = 0;
  608. subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
  609. subtitle_out_max_size, sub);
  610. if (subtitle_out_size < 0) {
  611. av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
  612. exit_program(1);
  613. }
  614. av_init_packet(&pkt);
  615. pkt.data = subtitle_out;
  616. pkt.size = subtitle_out_size;
  617. pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
  618. pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
  619. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
  620. /* XXX: the pts correction is handled here. Maybe handling
  621. it in the codec would be better */
  622. if (i == 0)
  623. pkt.pts += 90 * sub->start_display_time;
  624. else
  625. pkt.pts += 90 * sub->end_display_time;
  626. }
  627. write_frame(s, &pkt, ost);
  628. subtitle_size += pkt.size;
  629. }
  630. }
  631. static void do_video_out(AVFormatContext *s,
  632. OutputStream *ost,
  633. AVFrame *in_picture,
  634. float quality)
  635. {
  636. int ret, format_video_sync;
  637. AVPacket pkt;
  638. AVCodecContext *enc = ost->st->codec;
  639. int nb_frames, i;
  640. double sync_ipts, delta;
  641. double duration = 0;
  642. int frame_size = 0;
  643. InputStream *ist = NULL;
  644. if (ost->source_index >= 0)
  645. ist = input_streams[ost->source_index];
  646. if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
  647. duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
  648. sync_ipts = in_picture->pts;
  649. delta = sync_ipts - ost->sync_opts + duration;
  650. /* by default, we output a single frame */
  651. nb_frames = 1;
  652. format_video_sync = video_sync_method;
  653. if (format_video_sync == VSYNC_AUTO)
  654. format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;
  655. switch (format_video_sync) {
  656. case VSYNC_CFR:
  657. // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
  658. if (delta < -1.1)
  659. nb_frames = 0;
  660. else if (delta > 1.1)
  661. nb_frames = lrintf(delta);
  662. break;
  663. case VSYNC_VFR:
  664. if (delta <= -0.6)
  665. nb_frames = 0;
  666. else if (delta > 0.6)
  667. ost->sync_opts = lrint(sync_ipts);
  668. break;
  669. case VSYNC_DROP:
  670. case VSYNC_PASSTHROUGH:
  671. ost->sync_opts = lrint(sync_ipts);
  672. break;
  673. default:
  674. av_assert0(0);
  675. }
  676. nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
  677. if (nb_frames == 0) {
  678. nb_frames_drop++;
  679. av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
  680. return;
  681. } else if (nb_frames > 1) {
  682. if (nb_frames > dts_error_threshold * 30) {
  683. av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skiping\n", nb_frames - 1);
  684. nb_frames_drop++;
  685. return;
  686. }
  687. nb_frames_dup += nb_frames - 1;
  688. av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
  689. }
  690. /* duplicates frame if needed */
  691. for (i = 0; i < nb_frames; i++) {
  692. av_init_packet(&pkt);
  693. pkt.data = NULL;
  694. pkt.size = 0;
  695. in_picture->pts = ost->sync_opts;
  696. if (!check_recording_time(ost))
  697. return;
  698. if (s->oformat->flags & AVFMT_RAWPICTURE &&
  699. enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
  700. /* raw pictures are written as AVPicture structure to
  701. avoid any copies. We support temporarily the older
  702. method. */
  703. enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
  704. enc->coded_frame->top_field_first = in_picture->top_field_first;
  705. pkt.data = (uint8_t *)in_picture;
  706. pkt.size = sizeof(AVPicture);
  707. pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
  708. pkt.flags |= AV_PKT_FLAG_KEY;
  709. write_frame(s, &pkt, ost);
  710. video_size += pkt.size;
  711. } else {
  712. int got_packet;
  713. AVFrame big_picture;
  714. big_picture = *in_picture;
  715. /* better than nothing: use input picture interlaced
  716. settings */
  717. big_picture.interlaced_frame = in_picture->interlaced_frame;
  718. if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
  719. if (ost->top_field_first == -1)
  720. big_picture.top_field_first = in_picture->top_field_first;
  721. else
  722. big_picture.top_field_first = !!ost->top_field_first;
  723. }
  724. /* handles same_quant here. This is not correct because it may
  725. not be a global option */
  726. big_picture.quality = quality;
  727. if (!enc->me_threshold)
  728. big_picture.pict_type = 0;
  729. if (ost->forced_kf_index < ost->forced_kf_count &&
  730. big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
  731. big_picture.pict_type = AV_PICTURE_TYPE_I;
  732. ost->forced_kf_index++;
  733. }
  734. update_benchmark(NULL);
  735. ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
  736. update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
  737. if (ret < 0) {
  738. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
  739. exit_program(1);
  740. }
  741. if (got_packet) {
  742. if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
  743. pkt.pts = ost->sync_opts;
  744. if (pkt.pts != AV_NOPTS_VALUE)
  745. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  746. if (pkt.dts != AV_NOPTS_VALUE)
  747. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  748. if (debug_ts) {
  749. av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
  750. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  751. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
  752. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
  753. }
  754. write_frame(s, &pkt, ost);
  755. frame_size = pkt.size;
  756. video_size += pkt.size;
  757. av_free_packet(&pkt);
  758. /* if two pass, output log */
  759. if (ost->logfile && enc->stats_out) {
  760. fprintf(ost->logfile, "%s", enc->stats_out);
  761. }
  762. }
  763. }
  764. ost->sync_opts++;
  765. /*
  766. * For video, number of frames in == number of packets out.
  767. * But there may be reordering, so we can't throw away frames on encoder
  768. * flush, we need to limit them here, before they go into encoder.
  769. */
  770. ost->frame_number++;
  771. }
  772. if (vstats_filename && frame_size)
  773. do_video_stats(output_files[ost->file_index]->ctx, ost, frame_size);
  774. }
  775. static double psnr(double d)
  776. {
  777. return -10.0 * log(d) / log(10.0);
  778. }
  779. static void do_video_stats(AVFormatContext *os, OutputStream *ost,
  780. int frame_size)
  781. {
  782. AVCodecContext *enc;
  783. int frame_number;
  784. double ti1, bitrate, avg_bitrate;
  785. /* this is executed just the first time do_video_stats is called */
  786. if (!vstats_file) {
  787. vstats_file = fopen(vstats_filename, "w");
  788. if (!vstats_file) {
  789. perror("fopen");
  790. exit_program(1);
  791. }
  792. }
  793. enc = ost->st->codec;
  794. if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  795. frame_number = ost->frame_number;
  796. fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
  797. if (enc->flags&CODEC_FLAG_PSNR)
  798. fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
  799. fprintf(vstats_file,"f_size= %6d ", frame_size);
  800. /* compute pts value */
  801. ti1 = ost->sync_opts * av_q2d(enc->time_base);
  802. if (ti1 < 0.01)
  803. ti1 = 0.01;
  804. bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
  805. avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
  806. fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  807. (double)video_size / 1024, ti1, bitrate, avg_bitrate);
  808. fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
  809. }
  810. }
  811. /* check for new output on any of the filtergraphs */
  812. static int poll_filters(void)
  813. {
  814. AVFilterBufferRef *picref;
  815. AVFrame *filtered_frame = NULL;
  816. int i, ret, ret_all;
  817. unsigned nb_success = 1, av_uninit(nb_eof);
  818. int64_t frame_pts;
  819. while (1) {
  820. /* Reap all buffers present in the buffer sinks */
  821. for (i = 0; i < nb_output_streams; i++) {
  822. OutputStream *ost = output_streams[i];
  823. OutputFile *of = output_files[ost->file_index];
  824. int ret = 0;
  825. if (!ost->filter)
  826. continue;
  827. if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
  828. return AVERROR(ENOMEM);
  829. } else
  830. avcodec_get_frame_defaults(ost->filtered_frame);
  831. filtered_frame = ost->filtered_frame;
  832. while (1) {
  833. ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
  834. AV_BUFFERSINK_FLAG_NO_REQUEST);
  835. if (ret < 0) {
  836. if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
  837. char buf[256];
  838. av_strerror(ret, buf, sizeof(buf));
  839. av_log(NULL, AV_LOG_WARNING,
  840. "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
  841. }
  842. break;
  843. }
  844. frame_pts = AV_NOPTS_VALUE;
  845. if (picref->pts != AV_NOPTS_VALUE) {
  846. filtered_frame->pts = frame_pts = av_rescale_q(picref->pts,
  847. ost->filter->filter->inputs[0]->time_base,
  848. ost->st->codec->time_base) -
  849. av_rescale_q(of->start_time,
  850. AV_TIME_BASE_Q,
  851. ost->st->codec->time_base);
  852. if (of->start_time && filtered_frame->pts < 0) {
  853. avfilter_unref_buffer(picref);
  854. continue;
  855. }
  856. }
  857. //if (ost->source_index >= 0)
  858. // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
  859. switch (ost->filter->filter->inputs[0]->type) {
  860. case AVMEDIA_TYPE_VIDEO:
  861. avfilter_copy_buf_props(filtered_frame, picref);
  862. filtered_frame->pts = frame_pts;
  863. if (!ost->frame_aspect_ratio)
  864. ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
  865. do_video_out(of->ctx, ost, filtered_frame,
  866. same_quant ? ost->last_quality :
  867. ost->st->codec->global_quality);
  868. break;
  869. case AVMEDIA_TYPE_AUDIO:
  870. avfilter_copy_buf_props(filtered_frame, picref);
  871. filtered_frame->pts = frame_pts;
  872. do_audio_out(of->ctx, ost, filtered_frame);
  873. break;
  874. default:
  875. // TODO support subtitle filters
  876. av_assert0(0);
  877. }
  878. avfilter_unref_buffer(picref);
  879. }
  880. }
  881. if (!nb_success) /* from last round */
  882. break;
  883. /* Request frames through all the graphs */
  884. ret_all = nb_success = nb_eof = 0;
  885. for (i = 0; i < nb_filtergraphs; i++) {
  886. ret = avfilter_graph_request_oldest(filtergraphs[i]->graph);
  887. if (!ret) {
  888. nb_success++;
  889. } else if (ret == AVERROR_EOF) {
  890. nb_eof++;
  891. } else if (ret != AVERROR(EAGAIN)) {
  892. char buf[256];
  893. av_strerror(ret, buf, sizeof(buf));
  894. av_log(NULL, AV_LOG_WARNING,
  895. "Error in request_frame(): %s\n", buf);
  896. ret_all = ret;
  897. }
  898. }
  899. /* Try again if anything succeeded */
  900. }
  901. return nb_eof == nb_filtergraphs ? AVERROR_EOF : ret_all;
  902. }
  903. static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
  904. {
  905. char buf[1024];
  906. AVBPrint buf_script;
  907. OutputStream *ost;
  908. AVFormatContext *oc;
  909. int64_t total_size;
  910. AVCodecContext *enc;
  911. int frame_number, vid, i;
  912. double bitrate;
  913. int64_t pts = INT64_MAX;
  914. static int64_t last_time = -1;
  915. static int qp_histogram[52];
  916. int hours, mins, secs, us;
  917. if (!print_stats && !is_last_report && !progress_avio)
  918. return;
  919. if (!is_last_report) {
  920. if (last_time == -1) {
  921. last_time = cur_time;
  922. return;
  923. }
  924. if ((cur_time - last_time) < 500000)
  925. return;
  926. last_time = cur_time;
  927. }
  928. oc = output_files[0]->ctx;
  929. total_size = avio_size(oc->pb);
  930. if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
  931. total_size = avio_tell(oc->pb);
  932. if (total_size < 0)
  933. total_size = 0;
  934. }
  935. buf[0] = '\0';
  936. vid = 0;
  937. av_bprint_init(&buf_script, 0, 1);
  938. for (i = 0; i < nb_output_streams; i++) {
  939. float q = -1;
  940. ost = output_streams[i];
  941. enc = ost->st->codec;
  942. if (!ost->stream_copy && enc->coded_frame)
  943. q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
  944. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  945. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
  946. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  947. ost->file_index, ost->index, q);
  948. }
  949. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  950. float fps, t = (cur_time-timer_start) / 1000000.0;
  951. frame_number = ost->frame_number;
  952. fps = t > 1 ? frame_number / t : 0;
  953. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
  954. frame_number, fps < 9.95, fps, q);
  955. av_bprintf(&buf_script, "frame=%d\n", frame_number);
  956. av_bprintf(&buf_script, "fps=%.1f\n", fps);
  957. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  958. ost->file_index, ost->index, q);
  959. if (is_last_report)
  960. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
  961. if (qp_hist) {
  962. int j;
  963. int qp = lrintf(q);
  964. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
  965. qp_histogram[qp]++;
  966. for (j = 0; j < 32; j++)
  967. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
  968. }
  969. if (enc->flags&CODEC_FLAG_PSNR) {
  970. int j;
  971. double error, error_sum = 0;
  972. double scale, scale_sum = 0;
  973. double p;
  974. char type[3] = { 'Y','U','V' };
  975. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
  976. for (j = 0; j < 3; j++) {
  977. if (is_last_report) {
  978. error = enc->error[j];
  979. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
  980. } else {
  981. error = enc->coded_frame->error[j];
  982. scale = enc->width * enc->height * 255.0 * 255.0;
  983. }
  984. if (j)
  985. scale /= 4;
  986. error_sum += error;
  987. scale_sum += scale;
  988. p = psnr(error / scale);
  989. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
  990. av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
  991. ost->file_index, ost->index, type[i] | 32, p);
  992. }
  993. p = psnr(error_sum / scale_sum);
  994. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
  995. av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
  996. ost->file_index, ost->index, p);
  997. }
  998. vid = 1;
  999. }
  1000. /* compute min output value */
  1001. pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
  1002. ost->st->time_base, AV_TIME_BASE_Q));
  1003. }
  1004. secs = pts / AV_TIME_BASE;
  1005. us = pts % AV_TIME_BASE;
  1006. mins = secs / 60;
  1007. secs %= 60;
  1008. hours = mins / 60;
  1009. mins %= 60;
  1010. bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
  1011. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1012. "size=%8.0fkB time=", total_size / 1024.0);
  1013. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1014. "%02d:%02d:%02d.%02d ", hours, mins, secs,
  1015. (100 * us) / AV_TIME_BASE);
  1016. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1017. "bitrate=%6.1fkbits/s", bitrate);
  1018. av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
  1019. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
  1020. av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
  1021. hours, mins, secs, us);
  1022. if (nb_frames_dup || nb_frames_drop)
  1023. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
  1024. nb_frames_dup, nb_frames_drop);
  1025. av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
  1026. av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
  1027. if (print_stats || is_last_report) {
  1028. av_log(NULL, AV_LOG_INFO, "%s \r", buf);
  1029. fflush(stderr);
  1030. }
  1031. if (progress_avio) {
  1032. av_bprintf(&buf_script, "progress=%s\n",
  1033. is_last_report ? "end" : "continue");
  1034. avio_write(progress_avio, buf_script.str,
  1035. FFMIN(buf_script.len, buf_script.size - 1));
  1036. avio_flush(progress_avio);
  1037. av_bprint_finalize(&buf_script, NULL);
  1038. if (is_last_report) {
  1039. avio_close(progress_avio);
  1040. progress_avio = NULL;
  1041. }
  1042. }
  1043. if (is_last_report) {
  1044. int64_t raw= audio_size + video_size + subtitle_size + extra_size;
  1045. av_log(NULL, AV_LOG_INFO, "\n");
  1046. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
  1047. video_size / 1024.0,
  1048. audio_size / 1024.0,
  1049. subtitle_size / 1024.0,
  1050. extra_size / 1024.0,
  1051. 100.0 * (total_size - raw) / raw
  1052. );
  1053. if(video_size + audio_size + subtitle_size + extra_size == 0){
  1054. av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
  1055. }
  1056. }
  1057. }
  1058. static void flush_encoders(void)
  1059. {
  1060. int i, ret;
  1061. for (i = 0; i < nb_output_streams; i++) {
  1062. OutputStream *ost = output_streams[i];
  1063. AVCodecContext *enc = ost->st->codec;
  1064. AVFormatContext *os = output_files[ost->file_index]->ctx;
  1065. int stop_encoding = 0;
  1066. if (!ost->encoding_needed)
  1067. continue;
  1068. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  1069. continue;
  1070. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
  1071. continue;
  1072. for (;;) {
  1073. int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
  1074. const char *desc;
  1075. int64_t *size;
  1076. switch (ost->st->codec->codec_type) {
  1077. case AVMEDIA_TYPE_AUDIO:
  1078. encode = avcodec_encode_audio2;
  1079. desc = "Audio";
  1080. size = &audio_size;
  1081. break;
  1082. case AVMEDIA_TYPE_VIDEO:
  1083. encode = avcodec_encode_video2;
  1084. desc = "Video";
  1085. size = &video_size;
  1086. break;
  1087. default:
  1088. stop_encoding = 1;
  1089. }
  1090. if (encode) {
  1091. AVPacket pkt;
  1092. int got_packet;
  1093. av_init_packet(&pkt);
  1094. pkt.data = NULL;
  1095. pkt.size = 0;
  1096. update_benchmark(NULL);
  1097. ret = encode(enc, &pkt, NULL, &got_packet);
  1098. update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
  1099. if (ret < 0) {
  1100. av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
  1101. exit_program(1);
  1102. }
  1103. *size += pkt.size;
  1104. if (ost->logfile && enc->stats_out) {
  1105. fprintf(ost->logfile, "%s", enc->stats_out);
  1106. }
  1107. if (!got_packet) {
  1108. stop_encoding = 1;
  1109. break;
  1110. }
  1111. if (pkt.pts != AV_NOPTS_VALUE)
  1112. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  1113. if (pkt.dts != AV_NOPTS_VALUE)
  1114. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  1115. write_frame(os, &pkt, ost);
  1116. }
  1117. if (stop_encoding)
  1118. break;
  1119. }
  1120. }
  1121. }
  1122. /*
  1123. * Check whether a packet from ist should be written into ost at this time
  1124. */
  1125. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  1126. {
  1127. OutputFile *of = output_files[ost->file_index];
  1128. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  1129. if (ost->source_index != ist_index)
  1130. return 0;
  1131. if (of->start_time && ist->pts < of->start_time)
  1132. return 0;
  1133. return 1;
  1134. }
  1135. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  1136. {
  1137. OutputFile *of = output_files[ost->file_index];
  1138. int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
  1139. AVPicture pict;
  1140. AVPacket opkt;
  1141. av_init_packet(&opkt);
  1142. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  1143. !ost->copy_initial_nonkeyframes)
  1144. return;
  1145. if (of->recording_time != INT64_MAX &&
  1146. ist->pts >= of->recording_time + of->start_time) {
  1147. ost->is_past_recording_time = 1;
  1148. return;
  1149. }
  1150. /* force the input stream PTS */
  1151. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  1152. audio_size += pkt->size;
  1153. else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1154. video_size += pkt->size;
  1155. ost->sync_opts++;
  1156. } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1157. subtitle_size += pkt->size;
  1158. }
  1159. if (pkt->pts != AV_NOPTS_VALUE)
  1160. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  1161. else
  1162. opkt.pts = AV_NOPTS_VALUE;
  1163. if (pkt->dts == AV_NOPTS_VALUE)
  1164. opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
  1165. else
  1166. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  1167. opkt.dts -= ost_tb_start_time;
  1168. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  1169. opkt.flags = pkt->flags;
  1170. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  1171. if ( ost->st->codec->codec_id != AV_CODEC_ID_H264
  1172. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
  1173. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
  1174. && ost->st->codec->codec_id != AV_CODEC_ID_VC1
  1175. ) {
  1176. if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
  1177. opkt.destruct = av_destruct_packet;
  1178. } else {
  1179. opkt.data = pkt->data;
  1180. opkt.size = pkt->size;
  1181. }
  1182. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
  1183. /* store AVPicture in AVPacket, as expected by the output format */
  1184. avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
  1185. opkt.data = (uint8_t *)&pict;
  1186. opkt.size = sizeof(AVPicture);
  1187. opkt.flags |= AV_PKT_FLAG_KEY;
  1188. }
  1189. write_frame(of->ctx, &opkt, ost);
  1190. ost->st->codec->frame_number++;
  1191. av_free_packet(&opkt);
  1192. }
  1193. static void rate_emu_sleep(InputStream *ist)
  1194. {
  1195. if (input_files[ist->file_index]->rate_emu) {
  1196. int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
  1197. int64_t now = av_gettime() - ist->start;
  1198. if (pts > now)
  1199. av_usleep(pts - now);
  1200. }
  1201. }
  1202. int guess_input_channel_layout(InputStream *ist)
  1203. {
  1204. AVCodecContext *dec = ist->st->codec;
  1205. if (!dec->channel_layout) {
  1206. char layout_name[256];
  1207. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  1208. if (!dec->channel_layout)
  1209. return 0;
  1210. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  1211. dec->channels, dec->channel_layout);
  1212. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  1213. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  1214. }
  1215. return 1;
  1216. }
  1217. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  1218. {
  1219. AVFrame *decoded_frame;
  1220. AVCodecContext *avctx = ist->st->codec;
  1221. int i, ret, resample_changed;
  1222. AVRational decoded_frame_tb;
  1223. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  1224. return AVERROR(ENOMEM);
  1225. else
  1226. avcodec_get_frame_defaults(ist->decoded_frame);
  1227. decoded_frame = ist->decoded_frame;
  1228. update_benchmark(NULL);
  1229. ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
  1230. update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
  1231. if (ret < 0) {
  1232. return ret;
  1233. }
  1234. if (avctx->sample_rate <= 0) {
  1235. av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
  1236. return AVERROR_INVALIDDATA;
  1237. }
  1238. if (!*got_output) {
  1239. /* no audio frame */
  1240. if (!pkt->size)
  1241. for (i = 0; i < ist->nb_filters; i++)
  1242. av_buffersrc_add_ref(ist->filters[i]->filter, NULL,
  1243. AV_BUFFERSRC_FLAG_NO_COPY);
  1244. return ret;
  1245. }
  1246. #if 1
  1247. /* increment next_dts to use for the case where the input stream does not
  1248. have timestamps or there are multiple frames in the packet */
  1249. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1250. avctx->sample_rate;
  1251. ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1252. avctx->sample_rate;
  1253. #endif
  1254. rate_emu_sleep(ist);
  1255. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  1256. ist->resample_channels != avctx->channels ||
  1257. ist->resample_channel_layout != decoded_frame->channel_layout ||
  1258. ist->resample_sample_rate != decoded_frame->sample_rate;
  1259. if (resample_changed) {
  1260. char layout1[64], layout2[64];
  1261. if (!guess_input_channel_layout(ist)) {
  1262. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  1263. "layout for Input Stream #%d.%d\n", ist->file_index,
  1264. ist->st->index);
  1265. exit_program(1);
  1266. }
  1267. decoded_frame->channel_layout = avctx->channel_layout;
  1268. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  1269. ist->resample_channel_layout);
  1270. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  1271. decoded_frame->channel_layout);
  1272. av_log(NULL, AV_LOG_INFO,
  1273. "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",
  1274. ist->file_index, ist->st->index,
  1275. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  1276. ist->resample_channels, layout1,
  1277. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  1278. avctx->channels, layout2);
  1279. ist->resample_sample_fmt = decoded_frame->format;
  1280. ist->resample_sample_rate = decoded_frame->sample_rate;
  1281. ist->resample_channel_layout = decoded_frame->channel_layout;
  1282. ist->resample_channels = avctx->channels;
  1283. for (i = 0; i < nb_filtergraphs; i++)
  1284. if (ist_in_filtergraph(filtergraphs[i], ist)) {
  1285. FilterGraph *fg = filtergraphs[i];
  1286. int j;
  1287. if (configure_filtergraph(fg) < 0) {
  1288. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1289. exit_program(1);
  1290. }
  1291. for (j = 0; j < fg->nb_outputs; j++) {
  1292. OutputStream *ost = fg->outputs[j]->ost;
  1293. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  1294. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  1295. av_buffersink_set_frame_size(ost->filter->filter,
  1296. ost->st->codec->frame_size);
  1297. }
  1298. }
  1299. }
  1300. /* if the decoder provides a pts, use it instead of the last packet pts.
  1301. the decoder could be delaying output by a packet or more. */
  1302. if (decoded_frame->pts != AV_NOPTS_VALUE) {
  1303. ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
  1304. decoded_frame_tb = avctx->time_base;
  1305. } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
  1306. decoded_frame->pts = decoded_frame->pkt_pts;
  1307. pkt->pts = AV_NOPTS_VALUE;
  1308. decoded_frame_tb = ist->st->time_base;
  1309. } else if (pkt->pts != AV_NOPTS_VALUE) {
  1310. decoded_frame->pts = pkt->pts;
  1311. pkt->pts = AV_NOPTS_VALUE;
  1312. decoded_frame_tb = ist->st->time_base;
  1313. }else {
  1314. decoded_frame->pts = ist->dts;
  1315. decoded_frame_tb = AV_TIME_BASE_Q;
  1316. }
  1317. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1318. decoded_frame->pts = av_rescale_q(decoded_frame->pts,
  1319. decoded_frame_tb,
  1320. (AVRational){1, ist->st->codec->sample_rate});
  1321. for (i = 0; i < ist->nb_filters; i++)
  1322. av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0);
  1323. decoded_frame->pts = AV_NOPTS_VALUE;
  1324. return ret;
  1325. }
  1326. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  1327. {
  1328. AVFrame *decoded_frame;
  1329. void *buffer_to_free = NULL;
  1330. int i, ret = 0, resample_changed;
  1331. int64_t best_effort_timestamp;
  1332. AVRational *frame_sample_aspect;
  1333. float quality;
  1334. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  1335. return AVERROR(ENOMEM);
  1336. else
  1337. avcodec_get_frame_defaults(ist->decoded_frame);
  1338. decoded_frame = ist->decoded_frame;
  1339. pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  1340. update_benchmark(NULL);
  1341. ret = avcodec_decode_video2(ist->st->codec,
  1342. decoded_frame, got_output, pkt);
  1343. update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
  1344. if (ret < 0)
  1345. return ret;
  1346. quality = same_quant ? decoded_frame->quality : 0;
  1347. if (!*got_output) {
  1348. /* no picture yet */
  1349. if (!pkt->size)
  1350. for (i = 0; i < ist->nb_filters; i++)
  1351. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, AV_BUFFERSRC_FLAG_NO_COPY);
  1352. return ret;
  1353. }
  1354. if(ist->top_field_first>=0)
  1355. decoded_frame->top_field_first = ist->top_field_first;
  1356. best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
  1357. if(best_effort_timestamp != AV_NOPTS_VALUE)
  1358. ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
  1359. if (debug_ts) {
  1360. av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
  1361. "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
  1362. ist->st->index, av_ts2str(decoded_frame->pts),
  1363. av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
  1364. best_effort_timestamp,
  1365. av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
  1366. decoded_frame->key_frame, decoded_frame->pict_type);
  1367. }
  1368. pkt->size = 0;
  1369. pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
  1370. rate_emu_sleep(ist);
  1371. if (ist->st->sample_aspect_ratio.num)
  1372. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1373. resample_changed = ist->resample_width != decoded_frame->width ||
  1374. ist->resample_height != decoded_frame->height ||
  1375. ist->resample_pix_fmt != decoded_frame->format;
  1376. if (resample_changed) {
  1377. av_log(NULL, AV_LOG_INFO,
  1378. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1379. ist->file_index, ist->st->index,
  1380. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1381. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1382. ist->resample_width = decoded_frame->width;
  1383. ist->resample_height = decoded_frame->height;
  1384. ist->resample_pix_fmt = decoded_frame->format;
  1385. for (i = 0; i < nb_filtergraphs; i++)
  1386. if (ist_in_filtergraph(filtergraphs[i], ist) &&
  1387. configure_filtergraph(filtergraphs[i]) < 0) {
  1388. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1389. exit_program(1);
  1390. }
  1391. }
  1392. frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
  1393. for (i = 0; i < ist->nb_filters; i++) {
  1394. int changed = ist->st->codec->width != ist->filters[i]->filter->outputs[0]->w
  1395. || ist->st->codec->height != ist->filters[i]->filter->outputs[0]->h
  1396. || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
  1397. // XXX what an ugly hack
  1398. if (ist->filters[i]->graph->nb_outputs == 1)
  1399. ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
  1400. if (!frame_sample_aspect->num)
  1401. *frame_sample_aspect = ist->st->sample_aspect_ratio;
  1402. if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
  1403. FrameBuffer *buf = decoded_frame->opaque;
  1404. AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
  1405. decoded_frame->data, decoded_frame->linesize,
  1406. AV_PERM_READ | AV_PERM_PRESERVE,
  1407. ist->st->codec->width, ist->st->codec->height,
  1408. ist->st->codec->pix_fmt);
  1409. avfilter_copy_frame_props(fb, decoded_frame);
  1410. fb->buf->priv = buf;
  1411. fb->buf->free = filter_release_buffer;
  1412. av_assert0(buf->refcount>0);
  1413. buf->refcount++;
  1414. av_buffersrc_add_ref(ist->filters[i]->filter, fb,
  1415. AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
  1416. AV_BUFFERSRC_FLAG_NO_COPY);
  1417. } else
  1418. if(av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0)<0) {
  1419. av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
  1420. exit_program(1);
  1421. }
  1422. }
  1423. av_free(buffer_to_free);
  1424. return ret;
  1425. }
  1426. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1427. {
  1428. AVSubtitle subtitle;
  1429. int i, ret = avcodec_decode_subtitle2(ist->st->codec,
  1430. &subtitle, got_output, pkt);
  1431. if (ret < 0 || !*got_output) {
  1432. if (!pkt->size)
  1433. sub2video_flush(ist);
  1434. return ret;
  1435. }
  1436. rate_emu_sleep(ist);
  1437. sub2video_update(ist, &subtitle, pkt->pts);
  1438. for (i = 0; i < nb_output_streams; i++) {
  1439. OutputStream *ost = output_streams[i];
  1440. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1441. continue;
  1442. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
  1443. }
  1444. avsubtitle_free(&subtitle);
  1445. return ret;
  1446. }
  1447. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1448. static int output_packet(InputStream *ist, const AVPacket *pkt)
  1449. {
  1450. int ret = 0, i;
  1451. int got_output;
  1452. AVPacket avpkt;
  1453. if (!ist->saw_first_ts) {
  1454. ist->dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
  1455. ist->pts = 0;
  1456. if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
  1457. ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
  1458. ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
  1459. }
  1460. ist->saw_first_ts = 1;
  1461. }
  1462. if (ist->next_dts == AV_NOPTS_VALUE)
  1463. ist->next_dts = ist->dts;
  1464. if (ist->next_pts == AV_NOPTS_VALUE)
  1465. ist->next_pts = ist->pts;
  1466. if (pkt == NULL) {
  1467. /* EOF handling */
  1468. av_init_packet(&avpkt);
  1469. avpkt.data = NULL;
  1470. avpkt.size = 0;
  1471. goto handle_eof;
  1472. } else {
  1473. avpkt = *pkt;
  1474. }
  1475. if (pkt->dts != AV_NOPTS_VALUE) {
  1476. ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1477. if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
  1478. ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1479. }
  1480. // while we have more to decode or while the decoder did output something on EOF
  1481. while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
  1482. int duration;
  1483. handle_eof:
  1484. ist->pts = ist->next_pts;
  1485. ist->dts = ist->next_dts;
  1486. if (avpkt.size && avpkt.size != pkt->size) {
  1487. av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
  1488. "Multiple frames in a packet from stream %d\n", pkt->stream_index);
  1489. ist->showed_multi_packet_warning = 1;
  1490. }
  1491. switch (ist->st->codec->codec_type) {
  1492. case AVMEDIA_TYPE_AUDIO:
  1493. ret = decode_audio (ist, &avpkt, &got_output);
  1494. break;
  1495. case AVMEDIA_TYPE_VIDEO:
  1496. ret = decode_video (ist, &avpkt, &got_output);
  1497. if (avpkt.duration) {
  1498. duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
  1499. } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
  1500. int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
  1501. duration = ((int64_t)AV_TIME_BASE *
  1502. ist->st->codec->time_base.num * ticks) /
  1503. ist->st->codec->time_base.den;
  1504. } else
  1505. duration = 0;
  1506. if(ist->dts != AV_NOPTS_VALUE && duration) {
  1507. ist->next_dts += duration;
  1508. }else
  1509. ist->next_dts = AV_NOPTS_VALUE;
  1510. if (got_output)
  1511. ist->next_pts += duration; //FIXME the duration is not correct in some cases
  1512. break;
  1513. case AVMEDIA_TYPE_SUBTITLE:
  1514. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1515. break;
  1516. default:
  1517. return -1;
  1518. }
  1519. if (ret < 0)
  1520. return ret;
  1521. avpkt.dts=
  1522. avpkt.pts= AV_NOPTS_VALUE;
  1523. // touch data and size only if not EOF
  1524. if (pkt) {
  1525. if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  1526. ret = avpkt.size;
  1527. avpkt.data += ret;
  1528. avpkt.size -= ret;
  1529. }
  1530. if (!got_output) {
  1531. continue;
  1532. }
  1533. }
  1534. /* handle stream copy */
  1535. if (!ist->decoding_needed) {
  1536. rate_emu_sleep(ist);
  1537. ist->dts = ist->next_dts;
  1538. switch (ist->st->codec->codec_type) {
  1539. case AVMEDIA_TYPE_AUDIO:
  1540. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
  1541. ist->st->codec->sample_rate;
  1542. break;
  1543. case AVMEDIA_TYPE_VIDEO:
  1544. if (pkt->duration) {
  1545. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1546. } else if(ist->st->codec->time_base.num != 0) {
  1547. int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
  1548. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1549. ist->st->codec->time_base.num * ticks) /
  1550. ist->st->codec->time_base.den;
  1551. }
  1552. break;
  1553. }
  1554. ist->pts = ist->dts;
  1555. ist->next_pts = ist->next_dts;
  1556. }
  1557. for (i = 0; pkt && i < nb_output_streams; i++) {
  1558. OutputStream *ost = output_streams[i];
  1559. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1560. continue;
  1561. do_streamcopy(ist, ost, pkt);
  1562. }
  1563. return 0;
  1564. }
  1565. static void print_sdp(void)
  1566. {
  1567. char sdp[2048];
  1568. int i;
  1569. AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
  1570. if (!avc)
  1571. exit_program(1);
  1572. for (i = 0; i < nb_output_files; i++)
  1573. avc[i] = output_files[i]->ctx;
  1574. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1575. printf("SDP:\n%s\n", sdp);
  1576. fflush(stdout);
  1577. av_freep(&avc);
  1578. }
  1579. static int init_input_stream(int ist_index, char *error, int error_len)
  1580. {
  1581. InputStream *ist = input_streams[ist_index];
  1582. if (ist->decoding_needed) {
  1583. AVCodec *codec = ist->dec;
  1584. if (!codec) {
  1585. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
  1586. avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
  1587. return AVERROR(EINVAL);
  1588. }
  1589. ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !do_deinterlace;
  1590. if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
  1591. ist->st->codec->get_buffer = codec_get_buffer;
  1592. ist->st->codec->release_buffer = codec_release_buffer;
  1593. ist->st->codec->opaque = &ist->buffer_pool;
  1594. }
  1595. if (!av_dict_get(ist->opts, "threads", NULL, 0))
  1596. av_dict_set(&ist->opts, "threads", "auto", 0);
  1597. if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
  1598. snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
  1599. ist->file_index, ist->st->index);
  1600. return AVERROR(EINVAL);
  1601. }
  1602. assert_codec_experimental(ist->st->codec, 0);
  1603. assert_avoptions(ist->opts);
  1604. }
  1605. ist->next_pts = AV_NOPTS_VALUE;
  1606. ist->next_dts = AV_NOPTS_VALUE;
  1607. ist->is_start = 1;
  1608. return 0;
  1609. }
  1610. static InputStream *get_input_stream(OutputStream *ost)
  1611. {
  1612. if (ost->source_index >= 0)
  1613. return input_streams[ost->source_index];
  1614. return NULL;
  1615. }
  1616. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1617. AVCodecContext *avctx)
  1618. {
  1619. char *p;
  1620. int n = 1, i;
  1621. int64_t t;
  1622. for (p = kf; *p; p++)
  1623. if (*p == ',')
  1624. n++;
  1625. ost->forced_kf_count = n;
  1626. ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
  1627. if (!ost->forced_kf_pts) {
  1628. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1629. exit_program(1);
  1630. }
  1631. p = kf;
  1632. for (i = 0; i < n; i++) {
  1633. char *next = strchr(p, ',');
  1634. if (next)
  1635. *next++ = 0;
  1636. t = parse_time_or_die("force_key_frames", p, 1);
  1637. ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1638. p = next;
  1639. }
  1640. }
  1641. static void report_new_stream(int input_index, AVPacket *pkt)
  1642. {
  1643. InputFile *file = input_files[input_index];
  1644. AVStream *st = file->ctx->streams[pkt->stream_index];
  1645. if (pkt->stream_index < file->nb_streams_warn)
  1646. return;
  1647. av_log(file->ctx, AV_LOG_WARNING,
  1648. "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
  1649. av_get_media_type_string(st->codec->codec_type),
  1650. input_index, pkt->stream_index,
  1651. pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
  1652. file->nb_streams_warn = pkt->stream_index + 1;
  1653. }
  1654. static int transcode_init(void)
  1655. {
  1656. int ret = 0, i, j, k;
  1657. AVFormatContext *oc;
  1658. AVCodecContext *codec, *icodec = NULL;
  1659. OutputStream *ost;
  1660. InputStream *ist;
  1661. char error[1024];
  1662. int want_sdp = 1;
  1663. /* init framerate emulation */
  1664. for (i = 0; i < nb_input_files; i++) {
  1665. InputFile *ifile = input_files[i];
  1666. if (ifile->rate_emu)
  1667. for (j = 0; j < ifile->nb_streams; j++)
  1668. input_streams[j + ifile->ist_index]->start = av_gettime();
  1669. }
  1670. /* output stream init */
  1671. for (i = 0; i < nb_output_files; i++) {
  1672. oc = output_files[i]->ctx;
  1673. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  1674. av_dump_format(oc, i, oc->filename, 1);
  1675. av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
  1676. return AVERROR(EINVAL);
  1677. }
  1678. }
  1679. /* init complex filtergraphs */
  1680. for (i = 0; i < nb_filtergraphs; i++)
  1681. if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
  1682. return ret;
  1683. /* for each output stream, we compute the right encoding parameters */
  1684. for (i = 0; i < nb_output_streams; i++) {
  1685. ost = output_streams[i];
  1686. oc = output_files[ost->file_index]->ctx;
  1687. ist = get_input_stream(ost);
  1688. if (ost->attachment_filename)
  1689. continue;
  1690. codec = ost->st->codec;
  1691. if (ist) {
  1692. icodec = ist->st->codec;
  1693. ost->st->disposition = ist->st->disposition;
  1694. codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
  1695. codec->chroma_sample_location = icodec->chroma_sample_location;
  1696. }
  1697. if (ost->stream_copy) {
  1698. uint64_t extra_size;
  1699. av_assert0(ist && !ost->filter);
  1700. extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
  1701. if (extra_size > INT_MAX) {
  1702. return AVERROR(EINVAL);
  1703. }
  1704. /* if stream_copy is selected, no need to decode or encode */
  1705. codec->codec_id = icodec->codec_id;
  1706. codec->codec_type = icodec->codec_type;
  1707. if (!codec->codec_tag) {
  1708. if (!oc->oformat->codec_tag ||
  1709. av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
  1710. av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
  1711. codec->codec_tag = icodec->codec_tag;
  1712. }
  1713. codec->bit_rate = icodec->bit_rate;
  1714. codec->rc_max_rate = icodec->rc_max_rate;
  1715. codec->rc_buffer_size = icodec->rc_buffer_size;
  1716. codec->field_order = icodec->field_order;
  1717. codec->extradata = av_mallocz(extra_size);
  1718. if (!codec->extradata) {
  1719. return AVERROR(ENOMEM);
  1720. }
  1721. memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
  1722. codec->extradata_size= icodec->extradata_size;
  1723. codec->bits_per_coded_sample = icodec->bits_per_coded_sample;
  1724. codec->time_base = ist->st->time_base;
  1725. /*
  1726. * Avi is a special case here because it supports variable fps but
  1727. * having the fps and timebase differe significantly adds quite some
  1728. * overhead
  1729. */
  1730. if(!strcmp(oc->oformat->name, "avi")) {
  1731. if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
  1732. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
  1733. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
  1734. && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
  1735. || copy_tb==2){
  1736. codec->time_base.num = ist->st->r_frame_rate.den;
  1737. codec->time_base.den = 2*ist->st->r_frame_rate.num;
  1738. codec->ticks_per_frame = 2;
  1739. } else if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
  1740. && av_q2d(ist->st->time_base) < 1.0/500
  1741. || copy_tb==0){
  1742. codec->time_base = icodec->time_base;
  1743. codec->time_base.num *= icodec->ticks_per_frame;
  1744. codec->time_base.den *= 2;
  1745. codec->ticks_per_frame = 2;
  1746. }
  1747. } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
  1748. && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
  1749. && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
  1750. ) {
  1751. if( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
  1752. && av_q2d(ist->st->time_base) < 1.0/500
  1753. || copy_tb==0){
  1754. codec->time_base = icodec->time_base;
  1755. codec->time_base.num *= icodec->ticks_per_frame;
  1756. }
  1757. }
  1758. if(ost->frame_rate.num)
  1759. codec->time_base = av_inv_q(ost->frame_rate);
  1760. av_reduce(&codec->time_base.num, &codec->time_base.den,
  1761. codec->time_base.num, codec->time_base.den, INT_MAX);
  1762. switch (codec->codec_type) {
  1763. case AVMEDIA_TYPE_AUDIO:
  1764. if (audio_volume != 256) {
  1765. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  1766. exit_program(1);
  1767. }
  1768. codec->channel_layout = icodec->channel_layout;
  1769. codec->sample_rate = icodec->sample_rate;
  1770. codec->channels = icodec->channels;
  1771. codec->frame_size = icodec->frame_size;
  1772. codec->audio_service_type = icodec->audio_service_type;
  1773. codec->block_align = icodec->block_align;
  1774. if((codec->block_align == 1 || codec->block_align == 1152) && codec->codec_id == AV_CODEC_ID_MP3)
  1775. codec->block_align= 0;
  1776. if(codec->codec_id == AV_CODEC_ID_AC3)
  1777. codec->block_align= 0;
  1778. break;
  1779. case AVMEDIA_TYPE_VIDEO:
  1780. codec->pix_fmt = icodec->pix_fmt;
  1781. codec->width = icodec->width;
  1782. codec->height = icodec->height;
  1783. codec->has_b_frames = icodec->has_b_frames;
  1784. if (!codec->sample_aspect_ratio.num) {
  1785. codec->sample_aspect_ratio =
  1786. ost->st->sample_aspect_ratio =
  1787. ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
  1788. ist->st->codec->sample_aspect_ratio.num ?
  1789. ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
  1790. }
  1791. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
  1792. break;
  1793. case AVMEDIA_TYPE_SUBTITLE:
  1794. codec->width = icodec->width;
  1795. codec->height = icodec->height;
  1796. break;
  1797. case AVMEDIA_TYPE_DATA:
  1798. case AVMEDIA_TYPE_ATTACHMENT:
  1799. break;
  1800. default:
  1801. abort();
  1802. }
  1803. } else {
  1804. if (!ost->enc)
  1805. ost->enc = avcodec_find_encoder(codec->codec_id);
  1806. if (!ost->enc) {
  1807. /* should only happen when a default codec is not present. */
  1808. snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
  1809. avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
  1810. ret = AVERROR(EINVAL);
  1811. goto dump_format;
  1812. }
  1813. if (ist)
  1814. ist->decoding_needed = 1;
  1815. ost->encoding_needed = 1;
  1816. if (!ost->filter &&
  1817. (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  1818. codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
  1819. FilterGraph *fg;
  1820. fg = init_simple_filtergraph(ist, ost);
  1821. if (configure_filtergraph(fg)) {
  1822. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  1823. exit(1);
  1824. }
  1825. }
  1826. if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1827. if (ost->filter && !ost->frame_rate.num)
  1828. ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
  1829. if (ist && !ost->frame_rate.num)
  1830. ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
  1831. // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
  1832. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  1833. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  1834. ost->frame_rate = ost->enc->supported_framerates[idx];
  1835. }
  1836. }
  1837. switch (codec->codec_type) {
  1838. case AVMEDIA_TYPE_AUDIO:
  1839. codec->sample_fmt = ost->filter->filter->inputs[0]->format;
  1840. codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  1841. codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  1842. codec->channels = av_get_channel_layout_nb_channels(codec->channel_layout);
  1843. codec->time_base = (AVRational){ 1, codec->sample_rate };
  1844. break;
  1845. case AVMEDIA_TYPE_VIDEO:
  1846. codec->time_base = av_inv_q(ost->frame_rate);
  1847. if (ost->filter && !(codec->time_base.num && codec->time_base.den))
  1848. codec->time_base = ost->filter->filter->inputs[0]->time_base;
  1849. if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
  1850. && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
  1851. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
  1852. "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
  1853. }
  1854. for (j = 0; j < ost->forced_kf_count; j++)
  1855. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
  1856. AV_TIME_BASE_Q,
  1857. codec->time_base);
  1858. codec->width = ost->filter->filter->inputs[0]->w;
  1859. codec->height = ost->filter->filter->inputs[0]->h;
  1860. codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  1861. ost->frame_aspect_ratio ? // overridden by the -aspect cli option
  1862. av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
  1863. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  1864. codec->pix_fmt = ost->filter->filter->inputs[0]->format;
  1865. if (!icodec ||
  1866. codec->width != icodec->width ||
  1867. codec->height != icodec->height ||
  1868. codec->pix_fmt != icodec->pix_fmt) {
  1869. codec->bits_per_raw_sample = frame_bits_per_raw_sample;
  1870. }
  1871. if (ost->forced_keyframes)
  1872. parse_forced_key_frames(ost->forced_keyframes, ost,
  1873. ost->st->codec);
  1874. break;
  1875. case AVMEDIA_TYPE_SUBTITLE:
  1876. codec->time_base = (AVRational){1, 1000};
  1877. break;
  1878. default:
  1879. abort();
  1880. break;
  1881. }
  1882. /* two pass mode */
  1883. if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
  1884. char logfilename[1024];
  1885. FILE *f;
  1886. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  1887. pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
  1888. i);
  1889. if (!strcmp(ost->enc->name, "libx264")) {
  1890. av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  1891. } else {
  1892. if (codec->flags & CODEC_FLAG_PASS2) {
  1893. char *logbuffer;
  1894. size_t logbuffer_size;
  1895. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
  1896. av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  1897. logfilename);
  1898. exit_program(1);
  1899. }
  1900. codec->stats_in = logbuffer;
  1901. }
  1902. if (codec->flags & CODEC_FLAG_PASS1) {
  1903. f = fopen(logfilename, "wb");
  1904. if (!f) {
  1905. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
  1906. logfilename, strerror(errno));
  1907. exit_program(1);
  1908. }
  1909. ost->logfile = f;
  1910. }
  1911. }
  1912. }
  1913. }
  1914. }
  1915. /* open each encoder */
  1916. for (i = 0; i < nb_output_streams; i++) {
  1917. ost = output_streams[i];
  1918. if (ost->encoding_needed) {
  1919. AVCodec *codec = ost->enc;
  1920. AVCodecContext *dec = NULL;
  1921. if ((ist = get_input_stream(ost)))
  1922. dec = ist->st->codec;
  1923. if (dec && dec->subtitle_header) {
  1924. /* ASS code assumes this buffer is null terminated so add extra byte. */
  1925. ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
  1926. if (!ost->st->codec->subtitle_header) {
  1927. ret = AVERROR(ENOMEM);
  1928. goto dump_format;
  1929. }
  1930. memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  1931. ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
  1932. }
  1933. if (!av_dict_get(ost->opts, "threads", NULL, 0))
  1934. av_dict_set(&ost->opts, "threads", "auto", 0);
  1935. if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
  1936. snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
  1937. ost->file_index, ost->index);
  1938. ret = AVERROR(EINVAL);
  1939. goto dump_format;
  1940. }
  1941. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  1942. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  1943. av_buffersink_set_frame_size(ost->filter->filter,
  1944. ost->st->codec->frame_size);
  1945. assert_codec_experimental(ost->st->codec, 1);
  1946. assert_avoptions(ost->opts);
  1947. if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
  1948. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  1949. " It takes bits/s as argument, not kbits/s\n");
  1950. extra_size += ost->st->codec->extradata_size;
  1951. if (ost->st->codec->me_threshold)
  1952. input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
  1953. }
  1954. }
  1955. /* init input streams */
  1956. for (i = 0; i < nb_input_streams; i++)
  1957. if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
  1958. goto dump_format;
  1959. /* discard unused programs */
  1960. for (i = 0; i < nb_input_files; i++) {
  1961. InputFile *ifile = input_files[i];
  1962. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  1963. AVProgram *p = ifile->ctx->programs[j];
  1964. int discard = AVDISCARD_ALL;
  1965. for (k = 0; k < p->nb_stream_indexes; k++)
  1966. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  1967. discard = AVDISCARD_DEFAULT;
  1968. break;
  1969. }
  1970. p->discard = discard;
  1971. }
  1972. }
  1973. /* open files and write file headers */
  1974. for (i = 0; i < nb_output_files; i++) {
  1975. oc = output_files[i]->ctx;
  1976. oc->interrupt_callback = int_cb;
  1977. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  1978. char errbuf[128];
  1979. const char *errbuf_ptr = errbuf;
  1980. if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
  1981. errbuf_ptr = strerror(AVUNERROR(ret));
  1982. snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
  1983. ret = AVERROR(EINVAL);
  1984. goto dump_format;
  1985. }
  1986. // assert_avoptions(output_files[i]->opts);
  1987. if (strcmp(oc->oformat->name, "rtp")) {
  1988. want_sdp = 0;
  1989. }
  1990. }
  1991. dump_format:
  1992. /* dump the file output parameters - cannot be done before in case
  1993. of stream copy */
  1994. for (i = 0; i < nb_output_files; i++) {
  1995. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  1996. }
  1997. /* dump the stream mapping */
  1998. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  1999. for (i = 0; i < nb_input_streams; i++) {
  2000. ist = input_streams[i];
  2001. for (j = 0; j < ist->nb_filters; j++) {
  2002. if (ist->filters[j]->graph->graph_desc) {
  2003. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  2004. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  2005. ist->filters[j]->name);
  2006. if (nb_filtergraphs > 1)
  2007. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  2008. av_log(NULL, AV_LOG_INFO, "\n");
  2009. }
  2010. }
  2011. }
  2012. for (i = 0; i < nb_output_streams; i++) {
  2013. ost = output_streams[i];
  2014. if (ost->attachment_filename) {
  2015. /* an attached file */
  2016. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  2017. ost->attachment_filename, ost->file_index, ost->index);
  2018. continue;
  2019. }
  2020. if (ost->filter && ost->filter->graph->graph_desc) {
  2021. /* output from a complex graph */
  2022. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  2023. if (nb_filtergraphs > 1)
  2024. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  2025. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  2026. ost->index, ost->enc ? ost->enc->name : "?");
  2027. continue;
  2028. }
  2029. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  2030. input_streams[ost->source_index]->file_index,
  2031. input_streams[ost->source_index]->st->index,
  2032. ost->file_index,
  2033. ost->index);
  2034. if (ost->sync_ist != input_streams[ost->source_index])
  2035. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  2036. ost->sync_ist->file_index,
  2037. ost->sync_ist->st->index);
  2038. if (ost->stream_copy)
  2039. av_log(NULL, AV_LOG_INFO, " (copy)");
  2040. else
  2041. av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
  2042. input_streams[ost->source_index]->dec->name : "?",
  2043. ost->enc ? ost->enc->name : "?");
  2044. av_log(NULL, AV_LOG_INFO, "\n");
  2045. }
  2046. if (ret) {
  2047. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  2048. return ret;
  2049. }
  2050. if (want_sdp) {
  2051. print_sdp();
  2052. }
  2053. return 0;
  2054. }
  2055. /**
  2056. * @return 1 if there are still streams where more output is wanted,
  2057. * 0 otherwise
  2058. */
  2059. static int need_output(void)
  2060. {
  2061. int i;
  2062. for (i = 0; i < nb_output_streams; i++) {
  2063. OutputStream *ost = output_streams[i];
  2064. OutputFile *of = output_files[ost->file_index];
  2065. AVFormatContext *os = output_files[ost->file_index]->ctx;
  2066. if (ost->is_past_recording_time ||
  2067. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  2068. continue;
  2069. if (ost->frame_number >= ost->max_frames) {
  2070. int j;
  2071. for (j = 0; j < of->ctx->nb_streams; j++)
  2072. output_streams[of->ost_index + j]->is_past_recording_time = 1;
  2073. continue;
  2074. }
  2075. return 1;
  2076. }
  2077. return 0;
  2078. }
  2079. static int input_acceptable(InputStream *ist)
  2080. {
  2081. av_assert1(!ist->discard);
  2082. return !input_files[ist->file_index]->unavailable &&
  2083. !input_files[ist->file_index]->eof_reached;
  2084. }
  2085. static int find_graph_input(FilterGraph *graph)
  2086. {
  2087. int i, nb_req_max = 0, file_index = -1;
  2088. for (i = 0; i < graph->nb_inputs; i++) {
  2089. int nb_req = av_buffersrc_get_nb_failed_requests(graph->inputs[i]->filter);
  2090. if (nb_req > nb_req_max) {
  2091. InputStream *ist = graph->inputs[i]->ist;
  2092. if (input_acceptable(ist)) {
  2093. nb_req_max = nb_req;
  2094. file_index = ist->file_index;
  2095. }
  2096. }
  2097. }
  2098. return file_index;
  2099. }
  2100. /**
  2101. * Select the input file to read from.
  2102. *
  2103. * @return >=0 index of the input file to use;
  2104. * -1 if no file is acceptable;
  2105. * -2 to read from filters without reading from a file
  2106. */
  2107. static int select_input_file(void)
  2108. {
  2109. int i, ret, nb_active_out = nb_output_streams, ost_index = -1;
  2110. int64_t opts_min;
  2111. OutputStream *ost;
  2112. AVFilterBufferRef *dummy;
  2113. for (i = 0; i < nb_output_streams; i++)
  2114. nb_active_out -= output_streams[i]->unavailable =
  2115. output_streams[i]->is_past_recording_time;
  2116. while (nb_active_out) {
  2117. opts_min = INT64_MAX;
  2118. ost_index = -1;
  2119. for (i = 0; i < nb_output_streams; i++) {
  2120. OutputStream *ost = output_streams[i];
  2121. int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
  2122. AV_TIME_BASE_Q);
  2123. if (!ost->unavailable && opts < opts_min) {
  2124. opts_min = opts;
  2125. ost_index = i;
  2126. }
  2127. }
  2128. if (ost_index < 0)
  2129. return -1;
  2130. ost = output_streams[ost_index];
  2131. if (ost->source_index >= 0) {
  2132. /* ost is directly connected to an input */
  2133. InputStream *ist = input_streams[ost->source_index];
  2134. if (input_acceptable(ist))
  2135. return ist->file_index;
  2136. } else {
  2137. /* ost is connected to a complex filtergraph */
  2138. av_assert1(ost->filter);
  2139. ret = av_buffersink_get_buffer_ref(ost->filter->filter, &dummy,
  2140. AV_BUFFERSINK_FLAG_PEEK);
  2141. if (ret >= 0)
  2142. return -2;
  2143. ret = find_graph_input(ost->filter->graph);
  2144. if (ret >= 0)
  2145. return ret;
  2146. }
  2147. ost->unavailable = 1;
  2148. nb_active_out--;
  2149. }
  2150. return -1;
  2151. }
  2152. static int check_keyboard_interaction(int64_t cur_time)
  2153. {
  2154. int i, ret, key;
  2155. static int64_t last_time;
  2156. if (received_nb_signals)
  2157. return AVERROR_EXIT;
  2158. /* read_key() returns 0 on EOF */
  2159. if(cur_time - last_time >= 100000 && !run_as_daemon){
  2160. key = read_key();
  2161. last_time = cur_time;
  2162. }else
  2163. key = -1;
  2164. if (key == 'q')
  2165. return AVERROR_EXIT;
  2166. if (key == '+') av_log_set_level(av_log_get_level()+10);
  2167. if (key == '-') av_log_set_level(av_log_get_level()-10);
  2168. if (key == 's') qp_hist ^= 1;
  2169. if (key == 'h'){
  2170. if (do_hex_dump){
  2171. do_hex_dump = do_pkt_dump = 0;
  2172. } else if(do_pkt_dump){
  2173. do_hex_dump = 1;
  2174. } else
  2175. do_pkt_dump = 1;
  2176. av_log_set_level(AV_LOG_DEBUG);
  2177. }
  2178. if (key == 'c' || key == 'C'){
  2179. char buf[4096], target[64], command[256], arg[256] = {0};
  2180. double time;
  2181. int k, n = 0;
  2182. fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
  2183. i = 0;
  2184. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  2185. if (k > 0)
  2186. buf[i++] = k;
  2187. buf[i] = 0;
  2188. if (k > 0 &&
  2189. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  2190. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  2191. target, time, command, arg);
  2192. for (i = 0; i < nb_filtergraphs; i++) {
  2193. FilterGraph *fg = filtergraphs[i];
  2194. if (fg->graph) {
  2195. if (time < 0) {
  2196. ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
  2197. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
  2198. fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
  2199. } else {
  2200. ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
  2201. }
  2202. }
  2203. }
  2204. } else {
  2205. av_log(NULL, AV_LOG_ERROR,
  2206. "Parse error, at least 3 arguments were expected, "
  2207. "only %d given in string '%s'\n", n, buf);
  2208. }
  2209. }
  2210. if (key == 'd' || key == 'D'){
  2211. int debug=0;
  2212. if(key == 'D') {
  2213. debug = input_streams[0]->st->codec->debug<<1;
  2214. if(!debug) debug = 1;
  2215. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
  2216. debug += debug;
  2217. }else
  2218. if(scanf("%d", &debug)!=1)
  2219. fprintf(stderr,"error parsing debug value\n");
  2220. for(i=0;i<nb_input_streams;i++) {
  2221. input_streams[i]->st->codec->debug = debug;
  2222. }
  2223. for(i=0;i<nb_output_streams;i++) {
  2224. OutputStream *ost = output_streams[i];
  2225. ost->st->codec->debug = debug;
  2226. }
  2227. if(debug) av_log_set_level(AV_LOG_DEBUG);
  2228. fprintf(stderr,"debug=%d\n", debug);
  2229. }
  2230. if (key == '?'){
  2231. fprintf(stderr, "key function\n"
  2232. "? show this help\n"
  2233. "+ increase verbosity\n"
  2234. "- decrease verbosity\n"
  2235. "c Send command to filtergraph\n"
  2236. "D cycle through available debug modes\n"
  2237. "h dump packets/hex press to cycle through the 3 states\n"
  2238. "q quit\n"
  2239. "s Show QP histogram\n"
  2240. );
  2241. }
  2242. return 0;
  2243. }
  2244. #if HAVE_PTHREADS
  2245. static void *input_thread(void *arg)
  2246. {
  2247. InputFile *f = arg;
  2248. int ret = 0;
  2249. while (!transcoding_finished && ret >= 0) {
  2250. AVPacket pkt;
  2251. ret = av_read_frame(f->ctx, &pkt);
  2252. if (ret == AVERROR(EAGAIN)) {
  2253. av_usleep(10000);
  2254. ret = 0;
  2255. continue;
  2256. } else if (ret < 0)
  2257. break;
  2258. pthread_mutex_lock(&f->fifo_lock);
  2259. while (!av_fifo_space(f->fifo))
  2260. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  2261. av_dup_packet(&pkt);
  2262. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  2263. pthread_mutex_unlock(&f->fifo_lock);
  2264. }
  2265. f->finished = 1;
  2266. return NULL;
  2267. }
  2268. static void free_input_threads(void)
  2269. {
  2270. int i;
  2271. if (nb_input_files == 1)
  2272. return;
  2273. transcoding_finished = 1;
  2274. for (i = 0; i < nb_input_files; i++) {
  2275. InputFile *f = input_files[i];
  2276. AVPacket pkt;
  2277. if (!f->fifo || f->joined)
  2278. continue;
  2279. pthread_mutex_lock(&f->fifo_lock);
  2280. while (av_fifo_size(f->fifo)) {
  2281. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2282. av_free_packet(&pkt);
  2283. }
  2284. pthread_cond_signal(&f->fifo_cond);
  2285. pthread_mutex_unlock(&f->fifo_lock);
  2286. pthread_join(f->thread, NULL);
  2287. f->joined = 1;
  2288. while (av_fifo_size(f->fifo)) {
  2289. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2290. av_free_packet(&pkt);
  2291. }
  2292. av_fifo_free(f->fifo);
  2293. }
  2294. }
  2295. static int init_input_threads(void)
  2296. {
  2297. int i, ret;
  2298. if (nb_input_files == 1)
  2299. return 0;
  2300. for (i = 0; i < nb_input_files; i++) {
  2301. InputFile *f = input_files[i];
  2302. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  2303. return AVERROR(ENOMEM);
  2304. pthread_mutex_init(&f->fifo_lock, NULL);
  2305. pthread_cond_init (&f->fifo_cond, NULL);
  2306. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  2307. return AVERROR(ret);
  2308. }
  2309. return 0;
  2310. }
  2311. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  2312. {
  2313. int ret = 0;
  2314. pthread_mutex_lock(&f->fifo_lock);
  2315. if (av_fifo_size(f->fifo)) {
  2316. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  2317. pthread_cond_signal(&f->fifo_cond);
  2318. } else {
  2319. if (f->finished)
  2320. ret = AVERROR_EOF;
  2321. else
  2322. ret = AVERROR(EAGAIN);
  2323. }
  2324. pthread_mutex_unlock(&f->fifo_lock);
  2325. return ret;
  2326. }
  2327. #endif
  2328. static int get_input_packet(InputFile *f, AVPacket *pkt)
  2329. {
  2330. #if HAVE_PTHREADS
  2331. if (nb_input_files > 1)
  2332. return get_input_packet_mt(f, pkt);
  2333. #endif
  2334. return av_read_frame(f->ctx, pkt);
  2335. }
  2336. /*
  2337. * The following code is the main loop of the file converter
  2338. */
  2339. static int transcode(void)
  2340. {
  2341. int ret, i;
  2342. AVFormatContext *is, *os;
  2343. OutputStream *ost;
  2344. InputStream *ist;
  2345. int no_packet_count = 0;
  2346. int64_t timer_start;
  2347. ret = transcode_init();
  2348. if (ret < 0)
  2349. goto fail;
  2350. if (stdin_interaction) {
  2351. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  2352. }
  2353. timer_start = av_gettime();
  2354. #if HAVE_PTHREADS
  2355. if ((ret = init_input_threads()) < 0)
  2356. goto fail;
  2357. #endif
  2358. for (; received_sigterm == 0;) {
  2359. int file_index, ist_index;
  2360. AVPacket pkt;
  2361. int64_t cur_time= av_gettime();
  2362. /* if 'q' pressed, exits */
  2363. if (stdin_interaction)
  2364. if (check_keyboard_interaction(cur_time) < 0)
  2365. break;
  2366. /* check if there's any stream where output is still needed */
  2367. if (!need_output()) {
  2368. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  2369. break;
  2370. }
  2371. /* select the stream that we must read now */
  2372. file_index = select_input_file();
  2373. /* if none, if is finished */
  2374. if (file_index == -2) {
  2375. poll_filters() ;
  2376. continue;
  2377. }
  2378. if (file_index < 0) {
  2379. if (no_packet_count) {
  2380. no_packet_count = 0;
  2381. for (i = 0; i < nb_input_files; i++)
  2382. input_files[i]->unavailable = 0;
  2383. av_usleep(10000);
  2384. continue;
  2385. }
  2386. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
  2387. break;
  2388. }
  2389. is = input_files[file_index]->ctx;
  2390. ret = get_input_packet(input_files[file_index], &pkt);
  2391. if (ret == AVERROR(EAGAIN)) {
  2392. input_files[file_index]->unavailable = 1;
  2393. no_packet_count++;
  2394. continue;
  2395. }
  2396. if (ret < 0) {
  2397. if (ret != AVERROR_EOF) {
  2398. print_error(is->filename, ret);
  2399. if (exit_on_error)
  2400. exit_program(1);
  2401. }
  2402. input_files[file_index]->eof_reached = 1;
  2403. for (i = 0; i < input_files[file_index]->nb_streams; i++) {
  2404. ist = input_streams[input_files[file_index]->ist_index + i];
  2405. if (ist->decoding_needed)
  2406. output_packet(ist, NULL);
  2407. poll_filters();
  2408. }
  2409. if (opt_shortest)
  2410. break;
  2411. else
  2412. continue;
  2413. }
  2414. no_packet_count = 0;
  2415. for (i = 0; i < nb_input_files; i++)
  2416. input_files[i]->unavailable = 0;
  2417. if (do_pkt_dump) {
  2418. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  2419. is->streams[pkt.stream_index]);
  2420. }
  2421. /* the following test is needed in case new streams appear
  2422. dynamically in stream : we ignore them */
  2423. if (pkt.stream_index >= input_files[file_index]->nb_streams) {
  2424. report_new_stream(file_index, &pkt);
  2425. goto discard_packet;
  2426. }
  2427. ist_index = input_files[file_index]->ist_index + pkt.stream_index;
  2428. ist = input_streams[ist_index];
  2429. if (ist->discard)
  2430. goto discard_packet;
  2431. if(!ist->wrap_correction_done && input_files[file_index]->ctx->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
  2432. uint64_t stime = av_rescale_q(input_files[file_index]->ctx->start_time, AV_TIME_BASE_Q, ist->st->time_base);
  2433. uint64_t stime2= stime + (1LL<<ist->st->pts_wrap_bits);
  2434. ist->wrap_correction_done = 1;
  2435. if(pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime && pkt.dts - stime > stime2 - pkt.dts) {
  2436. pkt.dts -= 1LL<<ist->st->pts_wrap_bits;
  2437. ist->wrap_correction_done = 0;
  2438. }
  2439. if(pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime && pkt.pts - stime > stime2 - pkt.pts) {
  2440. pkt.pts -= 1LL<<ist->st->pts_wrap_bits;
  2441. ist->wrap_correction_done = 0;
  2442. }
  2443. }
  2444. if (pkt.dts != AV_NOPTS_VALUE)
  2445. pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2446. if (pkt.pts != AV_NOPTS_VALUE)
  2447. pkt.pts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2448. if (pkt.pts != AV_NOPTS_VALUE)
  2449. pkt.pts *= ist->ts_scale;
  2450. if (pkt.dts != AV_NOPTS_VALUE)
  2451. pkt.dts *= ist->ts_scale;
  2452. if (debug_ts) {
  2453. av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
  2454. "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:%"PRId64"\n",
  2455. ist_index, av_get_media_type_string(ist->st->codec->codec_type),
  2456. av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
  2457. av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
  2458. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2459. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2460. input_files[ist->file_index]->ts_offset);
  2461. }
  2462. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
  2463. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2464. int64_t delta = pkt_dts - ist->next_dts;
  2465. if (is->iformat->flags & AVFMT_TS_DISCONT) {
  2466. if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2467. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2468. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2469. pkt_dts+1<ist->pts){
  2470. input_files[ist->file_index]->ts_offset -= delta;
  2471. av_log(NULL, AV_LOG_DEBUG,
  2472. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2473. delta, input_files[ist->file_index]->ts_offset);
  2474. pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2475. if (pkt.pts != AV_NOPTS_VALUE)
  2476. pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2477. }
  2478. } else {
  2479. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2480. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2481. pkt_dts+1<ist->pts){
  2482. av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
  2483. pkt.dts = AV_NOPTS_VALUE;
  2484. }
  2485. if (pkt.pts != AV_NOPTS_VALUE){
  2486. int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
  2487. delta = pkt_pts - ist->next_dts;
  2488. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2489. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2490. pkt_pts+1<ist->pts) {
  2491. av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
  2492. pkt.pts = AV_NOPTS_VALUE;
  2493. }
  2494. }
  2495. }
  2496. }
  2497. sub2video_heartbeat(ist, pkt.pts);
  2498. // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
  2499. if ((ret = output_packet(ist, &pkt)) < 0 ||
  2500. ((ret = poll_filters()) < 0 && ret != AVERROR_EOF)) {
  2501. char buf[128];
  2502. av_strerror(ret, buf, sizeof(buf));
  2503. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
  2504. ist->file_index, ist->st->index, buf);
  2505. if (exit_on_error)
  2506. exit_program(1);
  2507. av_free_packet(&pkt);
  2508. continue;
  2509. }
  2510. discard_packet:
  2511. av_free_packet(&pkt);
  2512. /* dump report by using the output first video and audio streams */
  2513. print_report(0, timer_start, cur_time);
  2514. }
  2515. #if HAVE_PTHREADS
  2516. free_input_threads();
  2517. #endif
  2518. /* at the end of stream, we must flush the decoder buffers */
  2519. for (i = 0; i < nb_input_streams; i++) {
  2520. ist = input_streams[i];
  2521. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  2522. output_packet(ist, NULL);
  2523. }
  2524. }
  2525. poll_filters();
  2526. flush_encoders();
  2527. term_exit();
  2528. /* write the trailer if needed and close file */
  2529. for (i = 0; i < nb_output_files; i++) {
  2530. os = output_files[i]->ctx;
  2531. av_write_trailer(os);
  2532. }
  2533. /* dump report by using the first video and audio streams */
  2534. print_report(1, timer_start, av_gettime());
  2535. /* close each encoder */
  2536. for (i = 0; i < nb_output_streams; i++) {
  2537. ost = output_streams[i];
  2538. if (ost->encoding_needed) {
  2539. av_freep(&ost->st->codec->stats_in);
  2540. avcodec_close(ost->st->codec);
  2541. }
  2542. }
  2543. /* close each decoder */
  2544. for (i = 0; i < nb_input_streams; i++) {
  2545. ist = input_streams[i];
  2546. if (ist->decoding_needed) {
  2547. avcodec_close(ist->st->codec);
  2548. }
  2549. }
  2550. /* finished ! */
  2551. ret = 0;
  2552. fail:
  2553. #if HAVE_PTHREADS
  2554. free_input_threads();
  2555. #endif
  2556. if (output_streams) {
  2557. for (i = 0; i < nb_output_streams; i++) {
  2558. ost = output_streams[i];
  2559. if (ost) {
  2560. if (ost->stream_copy)
  2561. av_freep(&ost->st->codec->extradata);
  2562. if (ost->logfile) {
  2563. fclose(ost->logfile);
  2564. ost->logfile = NULL;
  2565. }
  2566. av_freep(&ost->st->codec->subtitle_header);
  2567. av_free(ost->forced_kf_pts);
  2568. av_dict_free(&ost->opts);
  2569. }
  2570. }
  2571. }
  2572. return ret;
  2573. }
  2574. static int64_t getutime(void)
  2575. {
  2576. #if HAVE_GETRUSAGE
  2577. struct rusage rusage;
  2578. getrusage(RUSAGE_SELF, &rusage);
  2579. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2580. #elif HAVE_GETPROCESSTIMES
  2581. HANDLE proc;
  2582. FILETIME c, e, k, u;
  2583. proc = GetCurrentProcess();
  2584. GetProcessTimes(proc, &c, &e, &k, &u);
  2585. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  2586. #else
  2587. return av_gettime();
  2588. #endif
  2589. }
  2590. static int64_t getmaxrss(void)
  2591. {
  2592. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  2593. struct rusage rusage;
  2594. getrusage(RUSAGE_SELF, &rusage);
  2595. return (int64_t)rusage.ru_maxrss * 1024;
  2596. #elif HAVE_GETPROCESSMEMORYINFO
  2597. HANDLE proc;
  2598. PROCESS_MEMORY_COUNTERS memcounters;
  2599. proc = GetCurrentProcess();
  2600. memcounters.cb = sizeof(memcounters);
  2601. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  2602. return memcounters.PeakPagefileUsage;
  2603. #else
  2604. return 0;
  2605. #endif
  2606. }
  2607. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
  2608. {
  2609. }
  2610. static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
  2611. {
  2612. int idx = locate_option(argc, argv, options, "cpuflags");
  2613. if (idx && argv[idx + 1])
  2614. opt_cpuflags("cpuflags", argv[idx + 1]);
  2615. }
  2616. int main(int argc, char **argv)
  2617. {
  2618. OptionsContext o = { 0 };
  2619. int64_t ti;
  2620. reset_options(&o, 0);
  2621. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2622. parse_loglevel(argc, argv, options);
  2623. if(argc>1 && !strcmp(argv[1], "-d")){
  2624. run_as_daemon=1;
  2625. av_log_set_callback(log_callback_null);
  2626. argc--;
  2627. argv++;
  2628. }
  2629. avcodec_register_all();
  2630. #if CONFIG_AVDEVICE
  2631. avdevice_register_all();
  2632. #endif
  2633. avfilter_register_all();
  2634. av_register_all();
  2635. avformat_network_init();
  2636. show_banner(argc, argv, options);
  2637. term_init();
  2638. parse_cpuflags(argc, argv, options);
  2639. /* parse options */
  2640. parse_options(&o, argc, argv, options, opt_output_file);
  2641. if (nb_output_files <= 0 && nb_input_files == 0) {
  2642. show_usage();
  2643. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  2644. exit_program(1);
  2645. }
  2646. /* file converter / grab */
  2647. if (nb_output_files <= 0) {
  2648. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  2649. exit_program(1);
  2650. }
  2651. if (nb_input_files == 0) {
  2652. av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
  2653. exit_program(1);
  2654. }
  2655. current_time = ti = getutime();
  2656. if (transcode() < 0)
  2657. exit_program(1);
  2658. ti = getutime() - ti;
  2659. if (do_benchmark) {
  2660. int maxrss = getmaxrss() / 1024;
  2661. printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
  2662. }
  2663. exit_program(0);
  2664. return 0;
  2665. }