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.

3062 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. subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
  607. subtitle_out_max_size, sub);
  608. if (subtitle_out_size < 0) {
  609. av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
  610. exit_program(1);
  611. }
  612. av_init_packet(&pkt);
  613. pkt.data = subtitle_out;
  614. pkt.size = subtitle_out_size;
  615. pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
  616. pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);
  617. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
  618. /* XXX: the pts correction is handled here. Maybe handling
  619. it in the codec would be better */
  620. if (i == 0)
  621. pkt.pts += 90 * sub->start_display_time;
  622. else
  623. pkt.pts += 90 * sub->end_display_time;
  624. }
  625. write_frame(s, &pkt, ost);
  626. subtitle_size += pkt.size;
  627. }
  628. }
  629. static void do_video_out(AVFormatContext *s,
  630. OutputStream *ost,
  631. AVFrame *in_picture,
  632. float quality)
  633. {
  634. int ret, format_video_sync;
  635. AVPacket pkt;
  636. AVCodecContext *enc = ost->st->codec;
  637. int nb_frames, i;
  638. double sync_ipts, delta;
  639. double duration = 0;
  640. int frame_size = 0;
  641. InputStream *ist = NULL;
  642. if (ost->source_index >= 0)
  643. ist = input_streams[ost->source_index];
  644. if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)
  645. duration = 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base));
  646. sync_ipts = in_picture->pts;
  647. delta = sync_ipts - ost->sync_opts + duration;
  648. /* by default, we output a single frame */
  649. nb_frames = 1;
  650. format_video_sync = video_sync_method;
  651. if (format_video_sync == VSYNC_AUTO)
  652. format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : 1;
  653. switch (format_video_sync) {
  654. case VSYNC_CFR:
  655. // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c
  656. if (delta < -1.1)
  657. nb_frames = 0;
  658. else if (delta > 1.1)
  659. nb_frames = lrintf(delta);
  660. break;
  661. case VSYNC_VFR:
  662. if (delta <= -0.6)
  663. nb_frames = 0;
  664. else if (delta > 0.6)
  665. ost->sync_opts = lrint(sync_ipts);
  666. break;
  667. case VSYNC_DROP:
  668. case VSYNC_PASSTHROUGH:
  669. ost->sync_opts = lrint(sync_ipts);
  670. break;
  671. default:
  672. av_assert0(0);
  673. }
  674. nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);
  675. if (nb_frames == 0) {
  676. nb_frames_drop++;
  677. av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
  678. return;
  679. } else if (nb_frames > 1) {
  680. if (nb_frames > dts_error_threshold * 30) {
  681. av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skiping\n", nb_frames - 1);
  682. nb_frames_drop++;
  683. return;
  684. }
  685. nb_frames_dup += nb_frames - 1;
  686. av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);
  687. }
  688. /* duplicates frame if needed */
  689. for (i = 0; i < nb_frames; i++) {
  690. av_init_packet(&pkt);
  691. pkt.data = NULL;
  692. pkt.size = 0;
  693. in_picture->pts = ost->sync_opts;
  694. if (!check_recording_time(ost))
  695. return;
  696. if (s->oformat->flags & AVFMT_RAWPICTURE &&
  697. enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
  698. /* raw pictures are written as AVPicture structure to
  699. avoid any copies. We support temporarily the older
  700. method. */
  701. enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
  702. enc->coded_frame->top_field_first = in_picture->top_field_first;
  703. pkt.data = (uint8_t *)in_picture;
  704. pkt.size = sizeof(AVPicture);
  705. pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
  706. pkt.flags |= AV_PKT_FLAG_KEY;
  707. write_frame(s, &pkt, ost);
  708. video_size += pkt.size;
  709. } else {
  710. int got_packet;
  711. AVFrame big_picture;
  712. big_picture = *in_picture;
  713. /* better than nothing: use input picture interlaced
  714. settings */
  715. big_picture.interlaced_frame = in_picture->interlaced_frame;
  716. if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME)) {
  717. if (ost->top_field_first == -1)
  718. big_picture.top_field_first = in_picture->top_field_first;
  719. else
  720. big_picture.top_field_first = !!ost->top_field_first;
  721. }
  722. /* handles same_quant here. This is not correct because it may
  723. not be a global option */
  724. big_picture.quality = quality;
  725. if (!enc->me_threshold)
  726. big_picture.pict_type = 0;
  727. if (ost->forced_kf_index < ost->forced_kf_count &&
  728. big_picture.pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
  729. big_picture.pict_type = AV_PICTURE_TYPE_I;
  730. ost->forced_kf_index++;
  731. }
  732. update_benchmark(NULL);
  733. ret = avcodec_encode_video2(enc, &pkt, &big_picture, &got_packet);
  734. update_benchmark("encode_video %d.%d", ost->file_index, ost->index);
  735. if (ret < 0) {
  736. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
  737. exit_program(1);
  738. }
  739. if (got_packet) {
  740. if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & CODEC_CAP_DELAY))
  741. pkt.pts = ost->sync_opts;
  742. if (pkt.pts != AV_NOPTS_VALUE)
  743. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  744. if (pkt.dts != AV_NOPTS_VALUE)
  745. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  746. if (debug_ts) {
  747. av_log(NULL, AV_LOG_INFO, "encoder -> type:video "
  748. "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",
  749. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),
  750. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));
  751. }
  752. write_frame(s, &pkt, ost);
  753. frame_size = pkt.size;
  754. video_size += pkt.size;
  755. av_free_packet(&pkt);
  756. /* if two pass, output log */
  757. if (ost->logfile && enc->stats_out) {
  758. fprintf(ost->logfile, "%s", enc->stats_out);
  759. }
  760. }
  761. }
  762. ost->sync_opts++;
  763. /*
  764. * For video, number of frames in == number of packets out.
  765. * But there may be reordering, so we can't throw away frames on encoder
  766. * flush, we need to limit them here, before they go into encoder.
  767. */
  768. ost->frame_number++;
  769. }
  770. if (vstats_filename && frame_size)
  771. do_video_stats(output_files[ost->file_index]->ctx, ost, frame_size);
  772. }
  773. static double psnr(double d)
  774. {
  775. return -10.0 * log(d) / log(10.0);
  776. }
  777. static void do_video_stats(AVFormatContext *os, OutputStream *ost,
  778. int frame_size)
  779. {
  780. AVCodecContext *enc;
  781. int frame_number;
  782. double ti1, bitrate, avg_bitrate;
  783. /* this is executed just the first time do_video_stats is called */
  784. if (!vstats_file) {
  785. vstats_file = fopen(vstats_filename, "w");
  786. if (!vstats_file) {
  787. perror("fopen");
  788. exit_program(1);
  789. }
  790. }
  791. enc = ost->st->codec;
  792. if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  793. frame_number = ost->frame_number;
  794. fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
  795. if (enc->flags&CODEC_FLAG_PSNR)
  796. fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
  797. fprintf(vstats_file,"f_size= %6d ", frame_size);
  798. /* compute pts value */
  799. ti1 = ost->sync_opts * av_q2d(enc->time_base);
  800. if (ti1 < 0.01)
  801. ti1 = 0.01;
  802. bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
  803. avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
  804. fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  805. (double)video_size / 1024, ti1, bitrate, avg_bitrate);
  806. fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
  807. }
  808. }
  809. /* check for new output on any of the filtergraphs */
  810. static int poll_filters(void)
  811. {
  812. AVFilterBufferRef *picref;
  813. AVFrame *filtered_frame = NULL;
  814. int i, ret, ret_all;
  815. unsigned nb_success = 1, av_uninit(nb_eof);
  816. int64_t frame_pts;
  817. while (1) {
  818. /* Reap all buffers present in the buffer sinks */
  819. for (i = 0; i < nb_output_streams; i++) {
  820. OutputStream *ost = output_streams[i];
  821. OutputFile *of = output_files[ost->file_index];
  822. int ret = 0;
  823. if (!ost->filter)
  824. continue;
  825. if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
  826. return AVERROR(ENOMEM);
  827. } else
  828. avcodec_get_frame_defaults(ost->filtered_frame);
  829. filtered_frame = ost->filtered_frame;
  830. while (1) {
  831. ret = av_buffersink_get_buffer_ref(ost->filter->filter, &picref,
  832. AV_BUFFERSINK_FLAG_NO_REQUEST);
  833. if (ret < 0) {
  834. if (ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) {
  835. char buf[256];
  836. av_strerror(ret, buf, sizeof(buf));
  837. av_log(NULL, AV_LOG_WARNING,
  838. "Error in av_buffersink_get_buffer_ref(): %s\n", buf);
  839. }
  840. break;
  841. }
  842. frame_pts = AV_NOPTS_VALUE;
  843. if (picref->pts != AV_NOPTS_VALUE) {
  844. filtered_frame->pts = frame_pts = av_rescale_q(picref->pts,
  845. ost->filter->filter->inputs[0]->time_base,
  846. ost->st->codec->time_base) -
  847. av_rescale_q(of->start_time,
  848. AV_TIME_BASE_Q,
  849. ost->st->codec->time_base);
  850. if (of->start_time && filtered_frame->pts < 0) {
  851. avfilter_unref_buffer(picref);
  852. continue;
  853. }
  854. }
  855. //if (ost->source_index >= 0)
  856. // *filtered_frame= *input_streams[ost->source_index]->decoded_frame; //for me_threshold
  857. switch (ost->filter->filter->inputs[0]->type) {
  858. case AVMEDIA_TYPE_VIDEO:
  859. avfilter_copy_buf_props(filtered_frame, picref);
  860. filtered_frame->pts = frame_pts;
  861. if (!ost->frame_aspect_ratio)
  862. ost->st->codec->sample_aspect_ratio = picref->video->sample_aspect_ratio;
  863. do_video_out(of->ctx, ost, filtered_frame,
  864. same_quant ? ost->last_quality :
  865. ost->st->codec->global_quality);
  866. break;
  867. case AVMEDIA_TYPE_AUDIO:
  868. avfilter_copy_buf_props(filtered_frame, picref);
  869. filtered_frame->pts = frame_pts;
  870. do_audio_out(of->ctx, ost, filtered_frame);
  871. break;
  872. default:
  873. // TODO support subtitle filters
  874. av_assert0(0);
  875. }
  876. avfilter_unref_buffer(picref);
  877. }
  878. }
  879. if (!nb_success) /* from last round */
  880. break;
  881. /* Request frames through all the graphs */
  882. ret_all = nb_success = nb_eof = 0;
  883. for (i = 0; i < nb_filtergraphs; i++) {
  884. ret = avfilter_graph_request_oldest(filtergraphs[i]->graph);
  885. if (!ret) {
  886. nb_success++;
  887. } else if (ret == AVERROR_EOF) {
  888. nb_eof++;
  889. } else if (ret != AVERROR(EAGAIN)) {
  890. char buf[256];
  891. av_strerror(ret, buf, sizeof(buf));
  892. av_log(NULL, AV_LOG_WARNING,
  893. "Error in request_frame(): %s\n", buf);
  894. ret_all = ret;
  895. }
  896. }
  897. /* Try again if anything succeeded */
  898. }
  899. return nb_eof == nb_filtergraphs ? AVERROR_EOF : ret_all;
  900. }
  901. static void print_report(int is_last_report, int64_t timer_start, int64_t cur_time)
  902. {
  903. char buf[1024];
  904. AVBPrint buf_script;
  905. OutputStream *ost;
  906. AVFormatContext *oc;
  907. int64_t total_size;
  908. AVCodecContext *enc;
  909. int frame_number, vid, i;
  910. double bitrate;
  911. int64_t pts = INT64_MAX;
  912. static int64_t last_time = -1;
  913. static int qp_histogram[52];
  914. int hours, mins, secs, us;
  915. if (!print_stats && !is_last_report && !progress_avio)
  916. return;
  917. if (!is_last_report) {
  918. if (last_time == -1) {
  919. last_time = cur_time;
  920. return;
  921. }
  922. if ((cur_time - last_time) < 500000)
  923. return;
  924. last_time = cur_time;
  925. }
  926. oc = output_files[0]->ctx;
  927. total_size = avio_size(oc->pb);
  928. if (total_size < 0) { // FIXME improve avio_size() so it works with non seekable output too
  929. total_size = avio_tell(oc->pb);
  930. if (total_size < 0)
  931. total_size = 0;
  932. }
  933. buf[0] = '\0';
  934. vid = 0;
  935. av_bprint_init(&buf_script, 0, 1);
  936. for (i = 0; i < nb_output_streams; i++) {
  937. float q = -1;
  938. ost = output_streams[i];
  939. enc = ost->st->codec;
  940. if (!ost->stream_copy && enc->coded_frame)
  941. q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
  942. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  943. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
  944. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  945. ost->file_index, ost->index, q);
  946. }
  947. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  948. float fps, t = (cur_time-timer_start) / 1000000.0;
  949. frame_number = ost->frame_number;
  950. fps = t > 1 ? frame_number / t : 0;
  951. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3.*f q=%3.1f ",
  952. frame_number, fps < 9.95, fps, q);
  953. av_bprintf(&buf_script, "frame=%d\n", frame_number);
  954. av_bprintf(&buf_script, "fps=%.1f\n", fps);
  955. av_bprintf(&buf_script, "stream_%d_%d_q=%.1f\n",
  956. ost->file_index, ost->index, q);
  957. if (is_last_report)
  958. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
  959. if (qp_hist) {
  960. int j;
  961. int qp = lrintf(q);
  962. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
  963. qp_histogram[qp]++;
  964. for (j = 0; j < 32; j++)
  965. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log(qp_histogram[j] + 1) / log(2)));
  966. }
  967. if (enc->flags&CODEC_FLAG_PSNR) {
  968. int j;
  969. double error, error_sum = 0;
  970. double scale, scale_sum = 0;
  971. double p;
  972. char type[3] = { 'Y','U','V' };
  973. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
  974. for (j = 0; j < 3; j++) {
  975. if (is_last_report) {
  976. error = enc->error[j];
  977. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
  978. } else {
  979. error = enc->coded_frame->error[j];
  980. scale = enc->width * enc->height * 255.0 * 255.0;
  981. }
  982. if (j)
  983. scale /= 4;
  984. error_sum += error;
  985. scale_sum += scale;
  986. p = psnr(error / scale);
  987. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], p);
  988. av_bprintf(&buf_script, "stream_%d_%d_psnr_%c=%2.2f\n",
  989. ost->file_index, ost->index, type[i] | 32, p);
  990. }
  991. p = psnr(error_sum / scale_sum);
  992. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
  993. av_bprintf(&buf_script, "stream_%d_%d_psnr_all=%2.2f\n",
  994. ost->file_index, ost->index, p);
  995. }
  996. vid = 1;
  997. }
  998. /* compute min output value */
  999. pts = FFMIN(pts, av_rescale_q(ost->st->pts.val,
  1000. ost->st->time_base, AV_TIME_BASE_Q));
  1001. }
  1002. secs = pts / AV_TIME_BASE;
  1003. us = pts % AV_TIME_BASE;
  1004. mins = secs / 60;
  1005. secs %= 60;
  1006. hours = mins / 60;
  1007. mins %= 60;
  1008. bitrate = pts ? total_size * 8 / (pts / 1000.0) : 0;
  1009. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1010. "size=%8.0fkB time=", total_size / 1024.0);
  1011. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1012. "%02d:%02d:%02d.%02d ", hours, mins, secs,
  1013. (100 * us) / AV_TIME_BASE);
  1014. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  1015. "bitrate=%6.1fkbits/s", bitrate);
  1016. av_bprintf(&buf_script, "total_size=%"PRId64"\n", total_size);
  1017. av_bprintf(&buf_script, "out_time_ms=%"PRId64"\n", pts);
  1018. av_bprintf(&buf_script, "out_time=%02d:%02d:%02d.%06d\n",
  1019. hours, mins, secs, us);
  1020. if (nb_frames_dup || nb_frames_drop)
  1021. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
  1022. nb_frames_dup, nb_frames_drop);
  1023. av_bprintf(&buf_script, "dup_frames=%d\n", nb_frames_dup);
  1024. av_bprintf(&buf_script, "drop_frames=%d\n", nb_frames_drop);
  1025. if (print_stats || is_last_report) {
  1026. av_log(NULL, AV_LOG_INFO, "%s \r", buf);
  1027. fflush(stderr);
  1028. }
  1029. if (progress_avio) {
  1030. av_bprintf(&buf_script, "progress=%s\n",
  1031. is_last_report ? "end" : "continue");
  1032. avio_write(progress_avio, buf_script.str,
  1033. FFMIN(buf_script.len, buf_script.size - 1));
  1034. avio_flush(progress_avio);
  1035. av_bprint_finalize(&buf_script, NULL);
  1036. if (is_last_report) {
  1037. avio_close(progress_avio);
  1038. progress_avio = NULL;
  1039. }
  1040. }
  1041. if (is_last_report) {
  1042. int64_t raw= audio_size + video_size + subtitle_size + extra_size;
  1043. av_log(NULL, AV_LOG_INFO, "\n");
  1044. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB subtitle:%1.0f global headers:%1.0fkB muxing overhead %f%%\n",
  1045. video_size / 1024.0,
  1046. audio_size / 1024.0,
  1047. subtitle_size / 1024.0,
  1048. extra_size / 1024.0,
  1049. 100.0 * (total_size - raw) / raw
  1050. );
  1051. if(video_size + audio_size + subtitle_size + extra_size == 0){
  1052. av_log(NULL, AV_LOG_WARNING, "Output file is empty, nothing was encoded (check -ss / -t / -frames parameters if used)\n");
  1053. }
  1054. }
  1055. }
  1056. static void flush_encoders(void)
  1057. {
  1058. int i, ret;
  1059. for (i = 0; i < nb_output_streams; i++) {
  1060. OutputStream *ost = output_streams[i];
  1061. AVCodecContext *enc = ost->st->codec;
  1062. AVFormatContext *os = output_files[ost->file_index]->ctx;
  1063. int stop_encoding = 0;
  1064. if (!ost->encoding_needed)
  1065. continue;
  1066. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  1067. continue;
  1068. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
  1069. continue;
  1070. for (;;) {
  1071. int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
  1072. const char *desc;
  1073. int64_t *size;
  1074. switch (ost->st->codec->codec_type) {
  1075. case AVMEDIA_TYPE_AUDIO:
  1076. encode = avcodec_encode_audio2;
  1077. desc = "Audio";
  1078. size = &audio_size;
  1079. break;
  1080. case AVMEDIA_TYPE_VIDEO:
  1081. encode = avcodec_encode_video2;
  1082. desc = "Video";
  1083. size = &video_size;
  1084. break;
  1085. default:
  1086. stop_encoding = 1;
  1087. }
  1088. if (encode) {
  1089. AVPacket pkt;
  1090. int got_packet;
  1091. av_init_packet(&pkt);
  1092. pkt.data = NULL;
  1093. pkt.size = 0;
  1094. update_benchmark(NULL);
  1095. ret = encode(enc, &pkt, NULL, &got_packet);
  1096. update_benchmark("flush %s %d.%d", desc, ost->file_index, ost->index);
  1097. if (ret < 0) {
  1098. av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
  1099. exit_program(1);
  1100. }
  1101. *size += pkt.size;
  1102. if (ost->logfile && enc->stats_out) {
  1103. fprintf(ost->logfile, "%s", enc->stats_out);
  1104. }
  1105. if (!got_packet) {
  1106. stop_encoding = 1;
  1107. break;
  1108. }
  1109. if (pkt.pts != AV_NOPTS_VALUE)
  1110. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  1111. if (pkt.dts != AV_NOPTS_VALUE)
  1112. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  1113. write_frame(os, &pkt, ost);
  1114. }
  1115. if (stop_encoding)
  1116. break;
  1117. }
  1118. }
  1119. }
  1120. /*
  1121. * Check whether a packet from ist should be written into ost at this time
  1122. */
  1123. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  1124. {
  1125. OutputFile *of = output_files[ost->file_index];
  1126. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  1127. if (ost->source_index != ist_index)
  1128. return 0;
  1129. if (of->start_time && ist->pts < of->start_time)
  1130. return 0;
  1131. return 1;
  1132. }
  1133. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  1134. {
  1135. OutputFile *of = output_files[ost->file_index];
  1136. int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
  1137. AVPicture pict;
  1138. AVPacket opkt;
  1139. av_init_packet(&opkt);
  1140. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  1141. !ost->copy_initial_nonkeyframes)
  1142. return;
  1143. if (of->recording_time != INT64_MAX &&
  1144. ist->pts >= of->recording_time + of->start_time) {
  1145. ost->is_past_recording_time = 1;
  1146. return;
  1147. }
  1148. /* force the input stream PTS */
  1149. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  1150. audio_size += pkt->size;
  1151. else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1152. video_size += pkt->size;
  1153. ost->sync_opts++;
  1154. } else if (ost->st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE) {
  1155. subtitle_size += pkt->size;
  1156. }
  1157. if (pkt->pts != AV_NOPTS_VALUE)
  1158. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  1159. else
  1160. opkt.pts = AV_NOPTS_VALUE;
  1161. if (pkt->dts == AV_NOPTS_VALUE)
  1162. opkt.dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ost->st->time_base);
  1163. else
  1164. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  1165. opkt.dts -= ost_tb_start_time;
  1166. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  1167. opkt.flags = pkt->flags;
  1168. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  1169. if ( ost->st->codec->codec_id != AV_CODEC_ID_H264
  1170. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
  1171. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
  1172. && ost->st->codec->codec_id != AV_CODEC_ID_VC1
  1173. ) {
  1174. if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY))
  1175. opkt.destruct = av_destruct_packet;
  1176. } else {
  1177. opkt.data = pkt->data;
  1178. opkt.size = pkt->size;
  1179. }
  1180. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (of->ctx->oformat->flags & AVFMT_RAWPICTURE)) {
  1181. /* store AVPicture in AVPacket, as expected by the output format */
  1182. avpicture_fill(&pict, opkt.data, ost->st->codec->pix_fmt, ost->st->codec->width, ost->st->codec->height);
  1183. opkt.data = (uint8_t *)&pict;
  1184. opkt.size = sizeof(AVPicture);
  1185. opkt.flags |= AV_PKT_FLAG_KEY;
  1186. }
  1187. write_frame(of->ctx, &opkt, ost);
  1188. ost->st->codec->frame_number++;
  1189. av_free_packet(&opkt);
  1190. }
  1191. static void rate_emu_sleep(InputStream *ist)
  1192. {
  1193. if (input_files[ist->file_index]->rate_emu) {
  1194. int64_t pts = av_rescale(ist->dts, 1000000, AV_TIME_BASE);
  1195. int64_t now = av_gettime() - ist->start;
  1196. if (pts > now)
  1197. av_usleep(pts - now);
  1198. }
  1199. }
  1200. int guess_input_channel_layout(InputStream *ist)
  1201. {
  1202. AVCodecContext *dec = ist->st->codec;
  1203. if (!dec->channel_layout) {
  1204. char layout_name[256];
  1205. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  1206. if (!dec->channel_layout)
  1207. return 0;
  1208. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  1209. dec->channels, dec->channel_layout);
  1210. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  1211. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  1212. }
  1213. return 1;
  1214. }
  1215. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  1216. {
  1217. AVFrame *decoded_frame;
  1218. AVCodecContext *avctx = ist->st->codec;
  1219. int i, ret, resample_changed;
  1220. AVRational decoded_frame_tb;
  1221. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  1222. return AVERROR(ENOMEM);
  1223. else
  1224. avcodec_get_frame_defaults(ist->decoded_frame);
  1225. decoded_frame = ist->decoded_frame;
  1226. update_benchmark(NULL);
  1227. ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
  1228. update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);
  1229. if (ret < 0) {
  1230. return ret;
  1231. }
  1232. if (avctx->sample_rate <= 0) {
  1233. av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);
  1234. return AVERROR_INVALIDDATA;
  1235. }
  1236. if (!*got_output) {
  1237. /* no audio frame */
  1238. if (!pkt->size)
  1239. for (i = 0; i < ist->nb_filters; i++)
  1240. av_buffersrc_add_ref(ist->filters[i]->filter, NULL,
  1241. AV_BUFFERSRC_FLAG_NO_COPY);
  1242. return ret;
  1243. }
  1244. #if 1
  1245. /* increment next_dts to use for the case where the input stream does not
  1246. have timestamps or there are multiple frames in the packet */
  1247. ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1248. avctx->sample_rate;
  1249. ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /
  1250. avctx->sample_rate;
  1251. #endif
  1252. rate_emu_sleep(ist);
  1253. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  1254. ist->resample_channels != avctx->channels ||
  1255. ist->resample_channel_layout != decoded_frame->channel_layout ||
  1256. ist->resample_sample_rate != decoded_frame->sample_rate;
  1257. if (resample_changed) {
  1258. char layout1[64], layout2[64];
  1259. if (!guess_input_channel_layout(ist)) {
  1260. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  1261. "layout for Input Stream #%d.%d\n", ist->file_index,
  1262. ist->st->index);
  1263. exit_program(1);
  1264. }
  1265. decoded_frame->channel_layout = avctx->channel_layout;
  1266. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  1267. ist->resample_channel_layout);
  1268. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  1269. decoded_frame->channel_layout);
  1270. av_log(NULL, AV_LOG_INFO,
  1271. "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",
  1272. ist->file_index, ist->st->index,
  1273. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  1274. ist->resample_channels, layout1,
  1275. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  1276. avctx->channels, layout2);
  1277. ist->resample_sample_fmt = decoded_frame->format;
  1278. ist->resample_sample_rate = decoded_frame->sample_rate;
  1279. ist->resample_channel_layout = decoded_frame->channel_layout;
  1280. ist->resample_channels = avctx->channels;
  1281. for (i = 0; i < nb_filtergraphs; i++)
  1282. if (ist_in_filtergraph(filtergraphs[i], ist)) {
  1283. FilterGraph *fg = filtergraphs[i];
  1284. int j;
  1285. if (configure_filtergraph(fg) < 0) {
  1286. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1287. exit_program(1);
  1288. }
  1289. for (j = 0; j < fg->nb_outputs; j++) {
  1290. OutputStream *ost = fg->outputs[j]->ost;
  1291. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  1292. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  1293. av_buffersink_set_frame_size(ost->filter->filter,
  1294. ost->st->codec->frame_size);
  1295. }
  1296. }
  1297. }
  1298. /* if the decoder provides a pts, use it instead of the last packet pts.
  1299. the decoder could be delaying output by a packet or more. */
  1300. if (decoded_frame->pts != AV_NOPTS_VALUE) {
  1301. ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);
  1302. decoded_frame_tb = avctx->time_base;
  1303. } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {
  1304. decoded_frame->pts = decoded_frame->pkt_pts;
  1305. pkt->pts = AV_NOPTS_VALUE;
  1306. decoded_frame_tb = ist->st->time_base;
  1307. } else if (pkt->pts != AV_NOPTS_VALUE) {
  1308. decoded_frame->pts = pkt->pts;
  1309. pkt->pts = AV_NOPTS_VALUE;
  1310. decoded_frame_tb = ist->st->time_base;
  1311. }else {
  1312. decoded_frame->pts = ist->dts;
  1313. decoded_frame_tb = AV_TIME_BASE_Q;
  1314. }
  1315. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1316. decoded_frame->pts = av_rescale_q(decoded_frame->pts,
  1317. decoded_frame_tb,
  1318. (AVRational){1, ist->st->codec->sample_rate});
  1319. for (i = 0; i < ist->nb_filters; i++)
  1320. av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0);
  1321. decoded_frame->pts = AV_NOPTS_VALUE;
  1322. return ret;
  1323. }
  1324. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  1325. {
  1326. AVFrame *decoded_frame;
  1327. void *buffer_to_free = NULL;
  1328. int i, ret = 0, resample_changed;
  1329. int64_t best_effort_timestamp;
  1330. AVRational *frame_sample_aspect;
  1331. float quality;
  1332. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  1333. return AVERROR(ENOMEM);
  1334. else
  1335. avcodec_get_frame_defaults(ist->decoded_frame);
  1336. decoded_frame = ist->decoded_frame;
  1337. pkt->dts = av_rescale_q(ist->dts, AV_TIME_BASE_Q, ist->st->time_base);
  1338. update_benchmark(NULL);
  1339. ret = avcodec_decode_video2(ist->st->codec,
  1340. decoded_frame, got_output, pkt);
  1341. update_benchmark("decode_video %d.%d", ist->file_index, ist->st->index);
  1342. if (ret < 0)
  1343. return ret;
  1344. quality = same_quant ? decoded_frame->quality : 0;
  1345. if (!*got_output) {
  1346. /* no picture yet */
  1347. if (!pkt->size)
  1348. for (i = 0; i < ist->nb_filters; i++)
  1349. av_buffersrc_add_ref(ist->filters[i]->filter, NULL, AV_BUFFERSRC_FLAG_NO_COPY);
  1350. return ret;
  1351. }
  1352. if(ist->top_field_first>=0)
  1353. decoded_frame->top_field_first = ist->top_field_first;
  1354. best_effort_timestamp= av_frame_get_best_effort_timestamp(decoded_frame);
  1355. if(best_effort_timestamp != AV_NOPTS_VALUE)
  1356. ist->next_pts = ist->pts = av_rescale_q(decoded_frame->pts = best_effort_timestamp, ist->st->time_base, AV_TIME_BASE_Q);
  1357. if (debug_ts) {
  1358. av_log(NULL, AV_LOG_INFO, "decoder -> ist_index:%d type:video "
  1359. "frame_pts:%s frame_pts_time:%s best_effort_ts:%"PRId64" best_effort_ts_time:%s keyframe:%d frame_type:%d \n",
  1360. ist->st->index, av_ts2str(decoded_frame->pts),
  1361. av_ts2timestr(decoded_frame->pts, &ist->st->time_base),
  1362. best_effort_timestamp,
  1363. av_ts2timestr(best_effort_timestamp, &ist->st->time_base),
  1364. decoded_frame->key_frame, decoded_frame->pict_type);
  1365. }
  1366. pkt->size = 0;
  1367. pre_process_video_frame(ist, (AVPicture *)decoded_frame, &buffer_to_free);
  1368. rate_emu_sleep(ist);
  1369. if (ist->st->sample_aspect_ratio.num)
  1370. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1371. resample_changed = ist->resample_width != decoded_frame->width ||
  1372. ist->resample_height != decoded_frame->height ||
  1373. ist->resample_pix_fmt != decoded_frame->format;
  1374. if (resample_changed) {
  1375. av_log(NULL, AV_LOG_INFO,
  1376. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1377. ist->file_index, ist->st->index,
  1378. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1379. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1380. ist->resample_width = decoded_frame->width;
  1381. ist->resample_height = decoded_frame->height;
  1382. ist->resample_pix_fmt = decoded_frame->format;
  1383. for (i = 0; i < nb_filtergraphs; i++)
  1384. if (ist_in_filtergraph(filtergraphs[i], ist) &&
  1385. configure_filtergraph(filtergraphs[i]) < 0) {
  1386. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1387. exit_program(1);
  1388. }
  1389. }
  1390. frame_sample_aspect= av_opt_ptr(avcodec_get_frame_class(), decoded_frame, "sample_aspect_ratio");
  1391. for (i = 0; i < ist->nb_filters; i++) {
  1392. int changed = ist->st->codec->width != ist->filters[i]->filter->outputs[0]->w
  1393. || ist->st->codec->height != ist->filters[i]->filter->outputs[0]->h
  1394. || ist->st->codec->pix_fmt != ist->filters[i]->filter->outputs[0]->format;
  1395. // XXX what an ugly hack
  1396. if (ist->filters[i]->graph->nb_outputs == 1)
  1397. ist->filters[i]->graph->outputs[0]->ost->last_quality = quality;
  1398. if (!frame_sample_aspect->num)
  1399. *frame_sample_aspect = ist->st->sample_aspect_ratio;
  1400. if (ist->dr1 && decoded_frame->type==FF_BUFFER_TYPE_USER && !changed) {
  1401. FrameBuffer *buf = decoded_frame->opaque;
  1402. AVFilterBufferRef *fb = avfilter_get_video_buffer_ref_from_arrays(
  1403. decoded_frame->data, decoded_frame->linesize,
  1404. AV_PERM_READ | AV_PERM_PRESERVE,
  1405. ist->st->codec->width, ist->st->codec->height,
  1406. ist->st->codec->pix_fmt);
  1407. avfilter_copy_frame_props(fb, decoded_frame);
  1408. fb->buf->priv = buf;
  1409. fb->buf->free = filter_release_buffer;
  1410. av_assert0(buf->refcount>0);
  1411. buf->refcount++;
  1412. av_buffersrc_add_ref(ist->filters[i]->filter, fb,
  1413. AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT |
  1414. AV_BUFFERSRC_FLAG_NO_COPY);
  1415. } else
  1416. if(av_buffersrc_add_frame(ist->filters[i]->filter, decoded_frame, 0)<0) {
  1417. av_log(NULL, AV_LOG_FATAL, "Failed to inject frame into filter network\n");
  1418. exit_program(1);
  1419. }
  1420. }
  1421. av_free(buffer_to_free);
  1422. return ret;
  1423. }
  1424. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1425. {
  1426. AVSubtitle subtitle;
  1427. int i, ret = avcodec_decode_subtitle2(ist->st->codec,
  1428. &subtitle, got_output, pkt);
  1429. if (ret < 0 || !*got_output) {
  1430. if (!pkt->size)
  1431. sub2video_flush(ist);
  1432. return ret;
  1433. }
  1434. rate_emu_sleep(ist);
  1435. sub2video_update(ist, &subtitle, pkt->pts);
  1436. for (i = 0; i < nb_output_streams; i++) {
  1437. OutputStream *ost = output_streams[i];
  1438. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1439. continue;
  1440. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
  1441. }
  1442. avsubtitle_free(&subtitle);
  1443. return ret;
  1444. }
  1445. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1446. static int output_packet(InputStream *ist, const AVPacket *pkt)
  1447. {
  1448. int ret = 0, i;
  1449. int got_output;
  1450. AVPacket avpkt;
  1451. if (!ist->saw_first_ts) {
  1452. 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;
  1453. ist->pts = 0;
  1454. if (pkt != NULL && pkt->pts != AV_NOPTS_VALUE && !ist->decoding_needed) {
  1455. ist->dts += av_rescale_q(pkt->pts, ist->st->time_base, AV_TIME_BASE_Q);
  1456. ist->pts = ist->dts; //unused but better to set it to a value thats not totally wrong
  1457. }
  1458. ist->saw_first_ts = 1;
  1459. }
  1460. if (ist->next_dts == AV_NOPTS_VALUE)
  1461. ist->next_dts = ist->dts;
  1462. if (ist->next_pts == AV_NOPTS_VALUE)
  1463. ist->next_pts = ist->pts;
  1464. if (pkt == NULL) {
  1465. /* EOF handling */
  1466. av_init_packet(&avpkt);
  1467. avpkt.data = NULL;
  1468. avpkt.size = 0;
  1469. goto handle_eof;
  1470. } else {
  1471. avpkt = *pkt;
  1472. }
  1473. if (pkt->dts != AV_NOPTS_VALUE) {
  1474. ist->next_dts = ist->dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1475. if (ist->st->codec->codec_type != AVMEDIA_TYPE_VIDEO || !ist->decoding_needed)
  1476. ist->next_pts = ist->pts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1477. }
  1478. // while we have more to decode or while the decoder did output something on EOF
  1479. while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
  1480. int duration;
  1481. handle_eof:
  1482. ist->pts = ist->next_pts;
  1483. ist->dts = ist->next_dts;
  1484. if (avpkt.size && avpkt.size != pkt->size) {
  1485. av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
  1486. "Multiple frames in a packet from stream %d\n", pkt->stream_index);
  1487. ist->showed_multi_packet_warning = 1;
  1488. }
  1489. switch (ist->st->codec->codec_type) {
  1490. case AVMEDIA_TYPE_AUDIO:
  1491. ret = decode_audio (ist, &avpkt, &got_output);
  1492. break;
  1493. case AVMEDIA_TYPE_VIDEO:
  1494. ret = decode_video (ist, &avpkt, &got_output);
  1495. if (avpkt.duration) {
  1496. duration = av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
  1497. } else if(ist->st->codec->time_base.num != 0 && ist->st->codec->time_base.den != 0) {
  1498. int ticks= ist->st->parser ? ist->st->parser->repeat_pict+1 : ist->st->codec->ticks_per_frame;
  1499. duration = ((int64_t)AV_TIME_BASE *
  1500. ist->st->codec->time_base.num * ticks) /
  1501. ist->st->codec->time_base.den;
  1502. } else
  1503. duration = 0;
  1504. if(ist->dts != AV_NOPTS_VALUE && duration) {
  1505. ist->next_dts += duration;
  1506. }else
  1507. ist->next_dts = AV_NOPTS_VALUE;
  1508. if (got_output)
  1509. ist->next_pts += duration; //FIXME the duration is not correct in some cases
  1510. break;
  1511. case AVMEDIA_TYPE_SUBTITLE:
  1512. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1513. break;
  1514. default:
  1515. return -1;
  1516. }
  1517. if (ret < 0)
  1518. return ret;
  1519. avpkt.dts=
  1520. avpkt.pts= AV_NOPTS_VALUE;
  1521. // touch data and size only if not EOF
  1522. if (pkt) {
  1523. if(ist->st->codec->codec_type != AVMEDIA_TYPE_AUDIO)
  1524. ret = avpkt.size;
  1525. avpkt.data += ret;
  1526. avpkt.size -= ret;
  1527. }
  1528. if (!got_output) {
  1529. continue;
  1530. }
  1531. }
  1532. /* handle stream copy */
  1533. if (!ist->decoding_needed) {
  1534. rate_emu_sleep(ist);
  1535. ist->dts = ist->next_dts;
  1536. switch (ist->st->codec->codec_type) {
  1537. case AVMEDIA_TYPE_AUDIO:
  1538. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
  1539. ist->st->codec->sample_rate;
  1540. break;
  1541. case AVMEDIA_TYPE_VIDEO:
  1542. if (pkt->duration) {
  1543. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1544. } else if(ist->st->codec->time_base.num != 0) {
  1545. int ticks= ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
  1546. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1547. ist->st->codec->time_base.num * ticks) /
  1548. ist->st->codec->time_base.den;
  1549. }
  1550. break;
  1551. }
  1552. ist->pts = ist->dts;
  1553. ist->next_pts = ist->next_dts;
  1554. }
  1555. for (i = 0; pkt && i < nb_output_streams; i++) {
  1556. OutputStream *ost = output_streams[i];
  1557. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1558. continue;
  1559. do_streamcopy(ist, ost, pkt);
  1560. }
  1561. return 0;
  1562. }
  1563. static void print_sdp(void)
  1564. {
  1565. char sdp[2048];
  1566. int i;
  1567. AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
  1568. if (!avc)
  1569. exit_program(1);
  1570. for (i = 0; i < nb_output_files; i++)
  1571. avc[i] = output_files[i]->ctx;
  1572. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1573. printf("SDP:\n%s\n", sdp);
  1574. fflush(stdout);
  1575. av_freep(&avc);
  1576. }
  1577. static int init_input_stream(int ist_index, char *error, int error_len)
  1578. {
  1579. InputStream *ist = input_streams[ist_index];
  1580. if (ist->decoding_needed) {
  1581. AVCodec *codec = ist->dec;
  1582. if (!codec) {
  1583. snprintf(error, error_len, "Decoder (codec %s) not found for input stream #%d:%d",
  1584. avcodec_get_name(ist->st->codec->codec_id), ist->file_index, ist->st->index);
  1585. return AVERROR(EINVAL);
  1586. }
  1587. ist->dr1 = (codec->capabilities & CODEC_CAP_DR1) && !do_deinterlace;
  1588. if (codec->type == AVMEDIA_TYPE_VIDEO && ist->dr1) {
  1589. ist->st->codec->get_buffer = codec_get_buffer;
  1590. ist->st->codec->release_buffer = codec_release_buffer;
  1591. ist->st->codec->opaque = &ist->buffer_pool;
  1592. }
  1593. if (!av_dict_get(ist->opts, "threads", NULL, 0))
  1594. av_dict_set(&ist->opts, "threads", "auto", 0);
  1595. if (avcodec_open2(ist->st->codec, codec, &ist->opts) < 0) {
  1596. snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
  1597. ist->file_index, ist->st->index);
  1598. return AVERROR(EINVAL);
  1599. }
  1600. assert_codec_experimental(ist->st->codec, 0);
  1601. assert_avoptions(ist->opts);
  1602. }
  1603. ist->next_pts = AV_NOPTS_VALUE;
  1604. ist->next_dts = AV_NOPTS_VALUE;
  1605. ist->is_start = 1;
  1606. return 0;
  1607. }
  1608. static InputStream *get_input_stream(OutputStream *ost)
  1609. {
  1610. if (ost->source_index >= 0)
  1611. return input_streams[ost->source_index];
  1612. return NULL;
  1613. }
  1614. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1615. AVCodecContext *avctx)
  1616. {
  1617. char *p;
  1618. int n = 1, i;
  1619. int64_t t;
  1620. for (p = kf; *p; p++)
  1621. if (*p == ',')
  1622. n++;
  1623. ost->forced_kf_count = n;
  1624. ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
  1625. if (!ost->forced_kf_pts) {
  1626. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1627. exit_program(1);
  1628. }
  1629. p = kf;
  1630. for (i = 0; i < n; i++) {
  1631. char *next = strchr(p, ',');
  1632. if (next)
  1633. *next++ = 0;
  1634. t = parse_time_or_die("force_key_frames", p, 1);
  1635. ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1636. p = next;
  1637. }
  1638. }
  1639. static void report_new_stream(int input_index, AVPacket *pkt)
  1640. {
  1641. InputFile *file = input_files[input_index];
  1642. AVStream *st = file->ctx->streams[pkt->stream_index];
  1643. if (pkt->stream_index < file->nb_streams_warn)
  1644. return;
  1645. av_log(file->ctx, AV_LOG_WARNING,
  1646. "New %s stream %d:%d at pos:%"PRId64" and DTS:%ss\n",
  1647. av_get_media_type_string(st->codec->codec_type),
  1648. input_index, pkt->stream_index,
  1649. pkt->pos, av_ts2timestr(pkt->dts, &st->time_base));
  1650. file->nb_streams_warn = pkt->stream_index + 1;
  1651. }
  1652. static int transcode_init(void)
  1653. {
  1654. int ret = 0, i, j, k;
  1655. AVFormatContext *oc;
  1656. AVCodecContext *codec, *icodec = NULL;
  1657. OutputStream *ost;
  1658. InputStream *ist;
  1659. char error[1024];
  1660. int want_sdp = 1;
  1661. /* init framerate emulation */
  1662. for (i = 0; i < nb_input_files; i++) {
  1663. InputFile *ifile = input_files[i];
  1664. if (ifile->rate_emu)
  1665. for (j = 0; j < ifile->nb_streams; j++)
  1666. input_streams[j + ifile->ist_index]->start = av_gettime();
  1667. }
  1668. /* output stream init */
  1669. for (i = 0; i < nb_output_files; i++) {
  1670. oc = output_files[i]->ctx;
  1671. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  1672. av_dump_format(oc, i, oc->filename, 1);
  1673. av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
  1674. return AVERROR(EINVAL);
  1675. }
  1676. }
  1677. /* init complex filtergraphs */
  1678. for (i = 0; i < nb_filtergraphs; i++)
  1679. if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
  1680. return ret;
  1681. /* for each output stream, we compute the right encoding parameters */
  1682. for (i = 0; i < nb_output_streams; i++) {
  1683. ost = output_streams[i];
  1684. oc = output_files[ost->file_index]->ctx;
  1685. ist = get_input_stream(ost);
  1686. if (ost->attachment_filename)
  1687. continue;
  1688. codec = ost->st->codec;
  1689. if (ist) {
  1690. icodec = ist->st->codec;
  1691. ost->st->disposition = ist->st->disposition;
  1692. codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
  1693. codec->chroma_sample_location = icodec->chroma_sample_location;
  1694. }
  1695. if (ost->stream_copy) {
  1696. uint64_t extra_size;
  1697. av_assert0(ist && !ost->filter);
  1698. extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
  1699. if (extra_size > INT_MAX) {
  1700. return AVERROR(EINVAL);
  1701. }
  1702. /* if stream_copy is selected, no need to decode or encode */
  1703. codec->codec_id = icodec->codec_id;
  1704. codec->codec_type = icodec->codec_type;
  1705. if (!codec->codec_tag) {
  1706. if (!oc->oformat->codec_tag ||
  1707. av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
  1708. av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
  1709. codec->codec_tag = icodec->codec_tag;
  1710. }
  1711. codec->bit_rate = icodec->bit_rate;
  1712. codec->rc_max_rate = icodec->rc_max_rate;
  1713. codec->rc_buffer_size = icodec->rc_buffer_size;
  1714. codec->field_order = icodec->field_order;
  1715. codec->extradata = av_mallocz(extra_size);
  1716. if (!codec->extradata) {
  1717. return AVERROR(ENOMEM);
  1718. }
  1719. memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
  1720. codec->extradata_size= icodec->extradata_size;
  1721. codec->bits_per_coded_sample = icodec->bits_per_coded_sample;
  1722. codec->time_base = ist->st->time_base;
  1723. /*
  1724. * Avi is a special case here because it supports variable fps but
  1725. * having the fps and timebase differe significantly adds quite some
  1726. * overhead
  1727. */
  1728. if(!strcmp(oc->oformat->name, "avi")) {
  1729. if ( copy_tb<0 && av_q2d(ist->st->r_frame_rate) >= av_q2d(ist->st->avg_frame_rate)
  1730. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(ist->st->time_base)
  1731. && 0.5/av_q2d(ist->st->r_frame_rate) > av_q2d(icodec->time_base)
  1732. && av_q2d(ist->st->time_base) < 1.0/500 && av_q2d(icodec->time_base) < 1.0/500
  1733. || copy_tb==2){
  1734. codec->time_base.num = ist->st->r_frame_rate.den;
  1735. codec->time_base.den = 2*ist->st->r_frame_rate.num;
  1736. codec->ticks_per_frame = 2;
  1737. } else if ( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > 2*av_q2d(ist->st->time_base)
  1738. && av_q2d(ist->st->time_base) < 1.0/500
  1739. || copy_tb==0){
  1740. codec->time_base = icodec->time_base;
  1741. codec->time_base.num *= icodec->ticks_per_frame;
  1742. codec->time_base.den *= 2;
  1743. codec->ticks_per_frame = 2;
  1744. }
  1745. } else if(!(oc->oformat->flags & AVFMT_VARIABLE_FPS)
  1746. && strcmp(oc->oformat->name, "mov") && strcmp(oc->oformat->name, "mp4") && strcmp(oc->oformat->name, "3gp")
  1747. && strcmp(oc->oformat->name, "3g2") && strcmp(oc->oformat->name, "psp") && strcmp(oc->oformat->name, "ipod")
  1748. ) {
  1749. if( copy_tb<0 && av_q2d(icodec->time_base)*icodec->ticks_per_frame > av_q2d(ist->st->time_base)
  1750. && av_q2d(ist->st->time_base) < 1.0/500
  1751. || copy_tb==0){
  1752. codec->time_base = icodec->time_base;
  1753. codec->time_base.num *= icodec->ticks_per_frame;
  1754. }
  1755. }
  1756. if(ost->frame_rate.num)
  1757. codec->time_base = av_inv_q(ost->frame_rate);
  1758. av_reduce(&codec->time_base.num, &codec->time_base.den,
  1759. codec->time_base.num, codec->time_base.den, INT_MAX);
  1760. switch (codec->codec_type) {
  1761. case AVMEDIA_TYPE_AUDIO:
  1762. if (audio_volume != 256) {
  1763. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  1764. exit_program(1);
  1765. }
  1766. codec->channel_layout = icodec->channel_layout;
  1767. codec->sample_rate = icodec->sample_rate;
  1768. codec->channels = icodec->channels;
  1769. codec->frame_size = icodec->frame_size;
  1770. codec->audio_service_type = icodec->audio_service_type;
  1771. codec->block_align = icodec->block_align;
  1772. if((codec->block_align == 1 || codec->block_align == 1152) && codec->codec_id == AV_CODEC_ID_MP3)
  1773. codec->block_align= 0;
  1774. if(codec->codec_id == AV_CODEC_ID_AC3)
  1775. codec->block_align= 0;
  1776. break;
  1777. case AVMEDIA_TYPE_VIDEO:
  1778. codec->pix_fmt = icodec->pix_fmt;
  1779. codec->width = icodec->width;
  1780. codec->height = icodec->height;
  1781. codec->has_b_frames = icodec->has_b_frames;
  1782. if (!codec->sample_aspect_ratio.num) {
  1783. codec->sample_aspect_ratio =
  1784. ost->st->sample_aspect_ratio =
  1785. ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
  1786. ist->st->codec->sample_aspect_ratio.num ?
  1787. ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
  1788. }
  1789. ost->st->avg_frame_rate = ist->st->avg_frame_rate;
  1790. break;
  1791. case AVMEDIA_TYPE_SUBTITLE:
  1792. codec->width = icodec->width;
  1793. codec->height = icodec->height;
  1794. break;
  1795. case AVMEDIA_TYPE_DATA:
  1796. case AVMEDIA_TYPE_ATTACHMENT:
  1797. break;
  1798. default:
  1799. abort();
  1800. }
  1801. } else {
  1802. if (!ost->enc)
  1803. ost->enc = avcodec_find_encoder(codec->codec_id);
  1804. if (!ost->enc) {
  1805. /* should only happen when a default codec is not present. */
  1806. snprintf(error, sizeof(error), "Encoder (codec %s) not found for output stream #%d:%d",
  1807. avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);
  1808. ret = AVERROR(EINVAL);
  1809. goto dump_format;
  1810. }
  1811. if (ist)
  1812. ist->decoding_needed = 1;
  1813. ost->encoding_needed = 1;
  1814. if (!ost->filter &&
  1815. (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  1816. codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
  1817. FilterGraph *fg;
  1818. fg = init_simple_filtergraph(ist, ost);
  1819. if (configure_filtergraph(fg)) {
  1820. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  1821. exit(1);
  1822. }
  1823. }
  1824. if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1825. if (ost->filter && !ost->frame_rate.num)
  1826. ost->frame_rate = av_buffersink_get_frame_rate(ost->filter->filter);
  1827. if (ist && !ost->frame_rate.num)
  1828. ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};
  1829. // ost->frame_rate = ist->st->avg_frame_rate.num ? ist->st->avg_frame_rate : (AVRational){25, 1};
  1830. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  1831. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  1832. ost->frame_rate = ost->enc->supported_framerates[idx];
  1833. }
  1834. }
  1835. switch (codec->codec_type) {
  1836. case AVMEDIA_TYPE_AUDIO:
  1837. codec->sample_fmt = ost->filter->filter->inputs[0]->format;
  1838. codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  1839. codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  1840. codec->channels = av_get_channel_layout_nb_channels(codec->channel_layout);
  1841. codec->time_base = (AVRational){ 1, codec->sample_rate };
  1842. break;
  1843. case AVMEDIA_TYPE_VIDEO:
  1844. codec->time_base = av_inv_q(ost->frame_rate);
  1845. if (ost->filter && !(codec->time_base.num && codec->time_base.den))
  1846. codec->time_base = ost->filter->filter->inputs[0]->time_base;
  1847. if ( av_q2d(codec->time_base) < 0.001 && video_sync_method != VSYNC_PASSTHROUGH
  1848. && (video_sync_method == VSYNC_CFR || (video_sync_method == VSYNC_AUTO && !(oc->oformat->flags & AVFMT_VARIABLE_FPS)))){
  1849. av_log(oc, AV_LOG_WARNING, "Frame rate very high for a muxer not efficiently supporting it.\n"
  1850. "Please consider specifying a lower framerate, a different muxer or -vsync 2\n");
  1851. }
  1852. for (j = 0; j < ost->forced_kf_count; j++)
  1853. ost->forced_kf_pts[j] = av_rescale_q(ost->forced_kf_pts[j],
  1854. AV_TIME_BASE_Q,
  1855. codec->time_base);
  1856. codec->width = ost->filter->filter->inputs[0]->w;
  1857. codec->height = ost->filter->filter->inputs[0]->h;
  1858. codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  1859. ost->frame_aspect_ratio ? // overridden by the -aspect cli option
  1860. av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
  1861. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  1862. codec->pix_fmt = ost->filter->filter->inputs[0]->format;
  1863. if (!icodec ||
  1864. codec->width != icodec->width ||
  1865. codec->height != icodec->height ||
  1866. codec->pix_fmt != icodec->pix_fmt) {
  1867. codec->bits_per_raw_sample = frame_bits_per_raw_sample;
  1868. }
  1869. if (ost->forced_keyframes)
  1870. parse_forced_key_frames(ost->forced_keyframes, ost,
  1871. ost->st->codec);
  1872. break;
  1873. case AVMEDIA_TYPE_SUBTITLE:
  1874. codec->time_base = (AVRational){1, 1000};
  1875. break;
  1876. default:
  1877. abort();
  1878. break;
  1879. }
  1880. /* two pass mode */
  1881. if (codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2)) {
  1882. char logfilename[1024];
  1883. FILE *f;
  1884. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  1885. pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,
  1886. i);
  1887. if (!strcmp(ost->enc->name, "libx264")) {
  1888. av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  1889. } else {
  1890. if (codec->flags & CODEC_FLAG_PASS2) {
  1891. char *logbuffer;
  1892. size_t logbuffer_size;
  1893. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
  1894. av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  1895. logfilename);
  1896. exit_program(1);
  1897. }
  1898. codec->stats_in = logbuffer;
  1899. }
  1900. if (codec->flags & CODEC_FLAG_PASS1) {
  1901. f = fopen(logfilename, "wb");
  1902. if (!f) {
  1903. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
  1904. logfilename, strerror(errno));
  1905. exit_program(1);
  1906. }
  1907. ost->logfile = f;
  1908. }
  1909. }
  1910. }
  1911. }
  1912. }
  1913. /* open each encoder */
  1914. for (i = 0; i < nb_output_streams; i++) {
  1915. ost = output_streams[i];
  1916. if (ost->encoding_needed) {
  1917. AVCodec *codec = ost->enc;
  1918. AVCodecContext *dec = NULL;
  1919. if ((ist = get_input_stream(ost)))
  1920. dec = ist->st->codec;
  1921. if (dec && dec->subtitle_header) {
  1922. /* ASS code assumes this buffer is null terminated so add extra byte. */
  1923. ost->st->codec->subtitle_header = av_mallocz(dec->subtitle_header_size + 1);
  1924. if (!ost->st->codec->subtitle_header) {
  1925. ret = AVERROR(ENOMEM);
  1926. goto dump_format;
  1927. }
  1928. memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  1929. ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
  1930. }
  1931. if (!av_dict_get(ost->opts, "threads", NULL, 0))
  1932. av_dict_set(&ost->opts, "threads", "auto", 0);
  1933. if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {
  1934. snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
  1935. ost->file_index, ost->index);
  1936. ret = AVERROR(EINVAL);
  1937. goto dump_format;
  1938. }
  1939. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  1940. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  1941. av_buffersink_set_frame_size(ost->filter->filter,
  1942. ost->st->codec->frame_size);
  1943. assert_codec_experimental(ost->st->codec, 1);
  1944. assert_avoptions(ost->opts);
  1945. if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
  1946. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  1947. " It takes bits/s as argument, not kbits/s\n");
  1948. extra_size += ost->st->codec->extradata_size;
  1949. if (ost->st->codec->me_threshold)
  1950. input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
  1951. }
  1952. }
  1953. /* init input streams */
  1954. for (i = 0; i < nb_input_streams; i++)
  1955. if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
  1956. goto dump_format;
  1957. /* discard unused programs */
  1958. for (i = 0; i < nb_input_files; i++) {
  1959. InputFile *ifile = input_files[i];
  1960. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  1961. AVProgram *p = ifile->ctx->programs[j];
  1962. int discard = AVDISCARD_ALL;
  1963. for (k = 0; k < p->nb_stream_indexes; k++)
  1964. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  1965. discard = AVDISCARD_DEFAULT;
  1966. break;
  1967. }
  1968. p->discard = discard;
  1969. }
  1970. }
  1971. /* open files and write file headers */
  1972. for (i = 0; i < nb_output_files; i++) {
  1973. oc = output_files[i]->ctx;
  1974. oc->interrupt_callback = int_cb;
  1975. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  1976. char errbuf[128];
  1977. const char *errbuf_ptr = errbuf;
  1978. if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
  1979. errbuf_ptr = strerror(AVUNERROR(ret));
  1980. snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
  1981. ret = AVERROR(EINVAL);
  1982. goto dump_format;
  1983. }
  1984. // assert_avoptions(output_files[i]->opts);
  1985. if (strcmp(oc->oformat->name, "rtp")) {
  1986. want_sdp = 0;
  1987. }
  1988. }
  1989. dump_format:
  1990. /* dump the file output parameters - cannot be done before in case
  1991. of stream copy */
  1992. for (i = 0; i < nb_output_files; i++) {
  1993. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  1994. }
  1995. /* dump the stream mapping */
  1996. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  1997. for (i = 0; i < nb_input_streams; i++) {
  1998. ist = input_streams[i];
  1999. for (j = 0; j < ist->nb_filters; j++) {
  2000. if (ist->filters[j]->graph->graph_desc) {
  2001. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  2002. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  2003. ist->filters[j]->name);
  2004. if (nb_filtergraphs > 1)
  2005. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  2006. av_log(NULL, AV_LOG_INFO, "\n");
  2007. }
  2008. }
  2009. }
  2010. for (i = 0; i < nb_output_streams; i++) {
  2011. ost = output_streams[i];
  2012. if (ost->attachment_filename) {
  2013. /* an attached file */
  2014. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  2015. ost->attachment_filename, ost->file_index, ost->index);
  2016. continue;
  2017. }
  2018. if (ost->filter && ost->filter->graph->graph_desc) {
  2019. /* output from a complex graph */
  2020. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  2021. if (nb_filtergraphs > 1)
  2022. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  2023. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  2024. ost->index, ost->enc ? ost->enc->name : "?");
  2025. continue;
  2026. }
  2027. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  2028. input_streams[ost->source_index]->file_index,
  2029. input_streams[ost->source_index]->st->index,
  2030. ost->file_index,
  2031. ost->index);
  2032. if (ost->sync_ist != input_streams[ost->source_index])
  2033. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  2034. ost->sync_ist->file_index,
  2035. ost->sync_ist->st->index);
  2036. if (ost->stream_copy)
  2037. av_log(NULL, AV_LOG_INFO, " (copy)");
  2038. else
  2039. av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
  2040. input_streams[ost->source_index]->dec->name : "?",
  2041. ost->enc ? ost->enc->name : "?");
  2042. av_log(NULL, AV_LOG_INFO, "\n");
  2043. }
  2044. if (ret) {
  2045. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  2046. return ret;
  2047. }
  2048. if (want_sdp) {
  2049. print_sdp();
  2050. }
  2051. return 0;
  2052. }
  2053. /**
  2054. * @return 1 if there are still streams where more output is wanted,
  2055. * 0 otherwise
  2056. */
  2057. static int need_output(void)
  2058. {
  2059. int i;
  2060. for (i = 0; i < nb_output_streams; i++) {
  2061. OutputStream *ost = output_streams[i];
  2062. OutputFile *of = output_files[ost->file_index];
  2063. AVFormatContext *os = output_files[ost->file_index]->ctx;
  2064. if (ost->is_past_recording_time ||
  2065. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  2066. continue;
  2067. if (ost->frame_number >= ost->max_frames) {
  2068. int j;
  2069. for (j = 0; j < of->ctx->nb_streams; j++)
  2070. output_streams[of->ost_index + j]->is_past_recording_time = 1;
  2071. continue;
  2072. }
  2073. return 1;
  2074. }
  2075. return 0;
  2076. }
  2077. static int input_acceptable(InputStream *ist)
  2078. {
  2079. av_assert1(!ist->discard);
  2080. return !input_files[ist->file_index]->unavailable &&
  2081. !input_files[ist->file_index]->eof_reached;
  2082. }
  2083. static int find_graph_input(FilterGraph *graph)
  2084. {
  2085. int i, nb_req_max = 0, file_index = -1;
  2086. for (i = 0; i < graph->nb_inputs; i++) {
  2087. int nb_req = av_buffersrc_get_nb_failed_requests(graph->inputs[i]->filter);
  2088. if (nb_req > nb_req_max) {
  2089. InputStream *ist = graph->inputs[i]->ist;
  2090. if (input_acceptable(ist)) {
  2091. nb_req_max = nb_req;
  2092. file_index = ist->file_index;
  2093. }
  2094. }
  2095. }
  2096. return file_index;
  2097. }
  2098. /**
  2099. * Select the input file to read from.
  2100. *
  2101. * @return >=0 index of the input file to use;
  2102. * -1 if no file is acceptable;
  2103. * -2 to read from filters without reading from a file
  2104. */
  2105. static int select_input_file(void)
  2106. {
  2107. int i, ret, nb_active_out = nb_output_streams, ost_index = -1;
  2108. int64_t opts_min;
  2109. OutputStream *ost;
  2110. AVFilterBufferRef *dummy;
  2111. for (i = 0; i < nb_output_streams; i++)
  2112. nb_active_out -= output_streams[i]->unavailable =
  2113. output_streams[i]->is_past_recording_time;
  2114. while (nb_active_out) {
  2115. opts_min = INT64_MAX;
  2116. ost_index = -1;
  2117. for (i = 0; i < nb_output_streams; i++) {
  2118. OutputStream *ost = output_streams[i];
  2119. int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,
  2120. AV_TIME_BASE_Q);
  2121. if (!ost->unavailable && opts < opts_min) {
  2122. opts_min = opts;
  2123. ost_index = i;
  2124. }
  2125. }
  2126. if (ost_index < 0)
  2127. return -1;
  2128. ost = output_streams[ost_index];
  2129. if (ost->source_index >= 0) {
  2130. /* ost is directly connected to an input */
  2131. InputStream *ist = input_streams[ost->source_index];
  2132. if (input_acceptable(ist))
  2133. return ist->file_index;
  2134. } else {
  2135. /* ost is connected to a complex filtergraph */
  2136. av_assert1(ost->filter);
  2137. ret = av_buffersink_get_buffer_ref(ost->filter->filter, &dummy,
  2138. AV_BUFFERSINK_FLAG_PEEK);
  2139. if (ret >= 0)
  2140. return -2;
  2141. ret = find_graph_input(ost->filter->graph);
  2142. if (ret >= 0)
  2143. return ret;
  2144. }
  2145. ost->unavailable = 1;
  2146. nb_active_out--;
  2147. }
  2148. return -1;
  2149. }
  2150. static int check_keyboard_interaction(int64_t cur_time)
  2151. {
  2152. int i, ret, key;
  2153. static int64_t last_time;
  2154. if (received_nb_signals)
  2155. return AVERROR_EXIT;
  2156. /* read_key() returns 0 on EOF */
  2157. if(cur_time - last_time >= 100000 && !run_as_daemon){
  2158. key = read_key();
  2159. last_time = cur_time;
  2160. }else
  2161. key = -1;
  2162. if (key == 'q')
  2163. return AVERROR_EXIT;
  2164. if (key == '+') av_log_set_level(av_log_get_level()+10);
  2165. if (key == '-') av_log_set_level(av_log_get_level()-10);
  2166. if (key == 's') qp_hist ^= 1;
  2167. if (key == 'h'){
  2168. if (do_hex_dump){
  2169. do_hex_dump = do_pkt_dump = 0;
  2170. } else if(do_pkt_dump){
  2171. do_hex_dump = 1;
  2172. } else
  2173. do_pkt_dump = 1;
  2174. av_log_set_level(AV_LOG_DEBUG);
  2175. }
  2176. if (key == 'c' || key == 'C'){
  2177. char buf[4096], target[64], command[256], arg[256] = {0};
  2178. double time;
  2179. int k, n = 0;
  2180. fprintf(stderr, "\nEnter command: <target> <time> <command>[ <argument>]\n");
  2181. i = 0;
  2182. while ((k = read_key()) != '\n' && k != '\r' && i < sizeof(buf)-1)
  2183. if (k > 0)
  2184. buf[i++] = k;
  2185. buf[i] = 0;
  2186. if (k > 0 &&
  2187. (n = sscanf(buf, "%63[^ ] %lf %255[^ ] %255[^\n]", target, &time, command, arg)) >= 3) {
  2188. av_log(NULL, AV_LOG_DEBUG, "Processing command target:%s time:%f command:%s arg:%s",
  2189. target, time, command, arg);
  2190. for (i = 0; i < nb_filtergraphs; i++) {
  2191. FilterGraph *fg = filtergraphs[i];
  2192. if (fg->graph) {
  2193. if (time < 0) {
  2194. ret = avfilter_graph_send_command(fg->graph, target, command, arg, buf, sizeof(buf),
  2195. key == 'c' ? AVFILTER_CMD_FLAG_ONE : 0);
  2196. fprintf(stderr, "Command reply for stream %d: ret:%d res:%s\n", i, ret, buf);
  2197. } else {
  2198. ret = avfilter_graph_queue_command(fg->graph, target, command, arg, 0, time);
  2199. }
  2200. }
  2201. }
  2202. } else {
  2203. av_log(NULL, AV_LOG_ERROR,
  2204. "Parse error, at least 3 arguments were expected, "
  2205. "only %d given in string '%s'\n", n, buf);
  2206. }
  2207. }
  2208. if (key == 'd' || key == 'D'){
  2209. int debug=0;
  2210. if(key == 'D') {
  2211. debug = input_streams[0]->st->codec->debug<<1;
  2212. if(!debug) debug = 1;
  2213. while(debug & (FF_DEBUG_DCT_COEFF|FF_DEBUG_VIS_QP|FF_DEBUG_VIS_MB_TYPE)) //unsupported, would just crash
  2214. debug += debug;
  2215. }else
  2216. if(scanf("%d", &debug)!=1)
  2217. fprintf(stderr,"error parsing debug value\n");
  2218. for(i=0;i<nb_input_streams;i++) {
  2219. input_streams[i]->st->codec->debug = debug;
  2220. }
  2221. for(i=0;i<nb_output_streams;i++) {
  2222. OutputStream *ost = output_streams[i];
  2223. ost->st->codec->debug = debug;
  2224. }
  2225. if(debug) av_log_set_level(AV_LOG_DEBUG);
  2226. fprintf(stderr,"debug=%d\n", debug);
  2227. }
  2228. if (key == '?'){
  2229. fprintf(stderr, "key function\n"
  2230. "? show this help\n"
  2231. "+ increase verbosity\n"
  2232. "- decrease verbosity\n"
  2233. "c Send command to filtergraph\n"
  2234. "D cycle through available debug modes\n"
  2235. "h dump packets/hex press to cycle through the 3 states\n"
  2236. "q quit\n"
  2237. "s Show QP histogram\n"
  2238. );
  2239. }
  2240. return 0;
  2241. }
  2242. #if HAVE_PTHREADS
  2243. static void *input_thread(void *arg)
  2244. {
  2245. InputFile *f = arg;
  2246. int ret = 0;
  2247. while (!transcoding_finished && ret >= 0) {
  2248. AVPacket pkt;
  2249. ret = av_read_frame(f->ctx, &pkt);
  2250. if (ret == AVERROR(EAGAIN)) {
  2251. av_usleep(10000);
  2252. ret = 0;
  2253. continue;
  2254. } else if (ret < 0)
  2255. break;
  2256. pthread_mutex_lock(&f->fifo_lock);
  2257. while (!av_fifo_space(f->fifo))
  2258. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  2259. av_dup_packet(&pkt);
  2260. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  2261. pthread_mutex_unlock(&f->fifo_lock);
  2262. }
  2263. f->finished = 1;
  2264. return NULL;
  2265. }
  2266. static void free_input_threads(void)
  2267. {
  2268. int i;
  2269. if (nb_input_files == 1)
  2270. return;
  2271. transcoding_finished = 1;
  2272. for (i = 0; i < nb_input_files; i++) {
  2273. InputFile *f = input_files[i];
  2274. AVPacket pkt;
  2275. if (!f->fifo || f->joined)
  2276. continue;
  2277. pthread_mutex_lock(&f->fifo_lock);
  2278. while (av_fifo_size(f->fifo)) {
  2279. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2280. av_free_packet(&pkt);
  2281. }
  2282. pthread_cond_signal(&f->fifo_cond);
  2283. pthread_mutex_unlock(&f->fifo_lock);
  2284. pthread_join(f->thread, NULL);
  2285. f->joined = 1;
  2286. while (av_fifo_size(f->fifo)) {
  2287. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2288. av_free_packet(&pkt);
  2289. }
  2290. av_fifo_free(f->fifo);
  2291. }
  2292. }
  2293. static int init_input_threads(void)
  2294. {
  2295. int i, ret;
  2296. if (nb_input_files == 1)
  2297. return 0;
  2298. for (i = 0; i < nb_input_files; i++) {
  2299. InputFile *f = input_files[i];
  2300. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  2301. return AVERROR(ENOMEM);
  2302. pthread_mutex_init(&f->fifo_lock, NULL);
  2303. pthread_cond_init (&f->fifo_cond, NULL);
  2304. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  2305. return AVERROR(ret);
  2306. }
  2307. return 0;
  2308. }
  2309. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  2310. {
  2311. int ret = 0;
  2312. pthread_mutex_lock(&f->fifo_lock);
  2313. if (av_fifo_size(f->fifo)) {
  2314. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  2315. pthread_cond_signal(&f->fifo_cond);
  2316. } else {
  2317. if (f->finished)
  2318. ret = AVERROR_EOF;
  2319. else
  2320. ret = AVERROR(EAGAIN);
  2321. }
  2322. pthread_mutex_unlock(&f->fifo_lock);
  2323. return ret;
  2324. }
  2325. #endif
  2326. static int get_input_packet(InputFile *f, AVPacket *pkt)
  2327. {
  2328. #if HAVE_PTHREADS
  2329. if (nb_input_files > 1)
  2330. return get_input_packet_mt(f, pkt);
  2331. #endif
  2332. return av_read_frame(f->ctx, pkt);
  2333. }
  2334. /*
  2335. * The following code is the main loop of the file converter
  2336. */
  2337. static int transcode(void)
  2338. {
  2339. int ret, i;
  2340. AVFormatContext *is, *os;
  2341. OutputStream *ost;
  2342. InputStream *ist;
  2343. int no_packet_count = 0;
  2344. int64_t timer_start;
  2345. ret = transcode_init();
  2346. if (ret < 0)
  2347. goto fail;
  2348. if (stdin_interaction) {
  2349. av_log(NULL, AV_LOG_INFO, "Press [q] to stop, [?] for help\n");
  2350. }
  2351. timer_start = av_gettime();
  2352. #if HAVE_PTHREADS
  2353. if ((ret = init_input_threads()) < 0)
  2354. goto fail;
  2355. #endif
  2356. for (; received_sigterm == 0;) {
  2357. int file_index, ist_index;
  2358. AVPacket pkt;
  2359. int64_t cur_time= av_gettime();
  2360. /* if 'q' pressed, exits */
  2361. if (stdin_interaction)
  2362. if (check_keyboard_interaction(cur_time) < 0)
  2363. break;
  2364. /* check if there's any stream where output is still needed */
  2365. if (!need_output()) {
  2366. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  2367. break;
  2368. }
  2369. /* select the stream that we must read now */
  2370. file_index = select_input_file();
  2371. /* if none, if is finished */
  2372. if (file_index == -2) {
  2373. poll_filters() ;
  2374. continue;
  2375. }
  2376. if (file_index < 0) {
  2377. if (no_packet_count) {
  2378. no_packet_count = 0;
  2379. for (i = 0; i < nb_input_files; i++)
  2380. input_files[i]->unavailable = 0;
  2381. av_usleep(10000);
  2382. continue;
  2383. }
  2384. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from, finishing.\n");
  2385. break;
  2386. }
  2387. is = input_files[file_index]->ctx;
  2388. ret = get_input_packet(input_files[file_index], &pkt);
  2389. if (ret == AVERROR(EAGAIN)) {
  2390. input_files[file_index]->unavailable = 1;
  2391. no_packet_count++;
  2392. continue;
  2393. }
  2394. if (ret < 0) {
  2395. if (ret != AVERROR_EOF) {
  2396. print_error(is->filename, ret);
  2397. if (exit_on_error)
  2398. exit_program(1);
  2399. }
  2400. input_files[file_index]->eof_reached = 1;
  2401. for (i = 0; i < input_files[file_index]->nb_streams; i++) {
  2402. ist = input_streams[input_files[file_index]->ist_index + i];
  2403. if (ist->decoding_needed)
  2404. output_packet(ist, NULL);
  2405. poll_filters();
  2406. }
  2407. if (opt_shortest)
  2408. break;
  2409. else
  2410. continue;
  2411. }
  2412. no_packet_count = 0;
  2413. for (i = 0; i < nb_input_files; i++)
  2414. input_files[i]->unavailable = 0;
  2415. if (do_pkt_dump) {
  2416. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  2417. is->streams[pkt.stream_index]);
  2418. }
  2419. /* the following test is needed in case new streams appear
  2420. dynamically in stream : we ignore them */
  2421. if (pkt.stream_index >= input_files[file_index]->nb_streams) {
  2422. report_new_stream(file_index, &pkt);
  2423. goto discard_packet;
  2424. }
  2425. ist_index = input_files[file_index]->ist_index + pkt.stream_index;
  2426. ist = input_streams[ist_index];
  2427. if (ist->discard)
  2428. goto discard_packet;
  2429. if(!ist->wrap_correction_done && input_files[file_index]->ctx->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){
  2430. uint64_t stime = av_rescale_q(input_files[file_index]->ctx->start_time, AV_TIME_BASE_Q, ist->st->time_base);
  2431. uint64_t stime2= stime + (1LL<<ist->st->pts_wrap_bits);
  2432. ist->wrap_correction_done = 1;
  2433. if(pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime && pkt.dts - stime > stime2 - pkt.dts) {
  2434. pkt.dts -= 1LL<<ist->st->pts_wrap_bits;
  2435. ist->wrap_correction_done = 0;
  2436. }
  2437. if(pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime && pkt.pts - stime > stime2 - pkt.pts) {
  2438. pkt.pts -= 1LL<<ist->st->pts_wrap_bits;
  2439. ist->wrap_correction_done = 0;
  2440. }
  2441. }
  2442. if (pkt.dts != AV_NOPTS_VALUE)
  2443. pkt.dts += av_rescale_q(input_files[ist->file_index]->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2444. if (pkt.pts != AV_NOPTS_VALUE)
  2445. pkt.pts += 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 *= ist->ts_scale;
  2448. if (pkt.dts != AV_NOPTS_VALUE)
  2449. pkt.dts *= ist->ts_scale;
  2450. if (debug_ts) {
  2451. av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "
  2452. "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",
  2453. ist_index, av_get_media_type_string(ist->st->codec->codec_type),
  2454. av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),
  2455. av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),
  2456. av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),
  2457. av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),
  2458. input_files[ist->file_index]->ts_offset);
  2459. }
  2460. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE && !copy_ts) {
  2461. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2462. int64_t delta = pkt_dts - ist->next_dts;
  2463. if (is->iformat->flags & AVFMT_TS_DISCONT) {
  2464. if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||
  2465. (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&
  2466. ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2467. pkt_dts+1<ist->pts){
  2468. input_files[ist->file_index]->ts_offset -= delta;
  2469. av_log(NULL, AV_LOG_DEBUG,
  2470. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2471. delta, input_files[ist->file_index]->ts_offset);
  2472. pkt.dts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2473. if (pkt.pts != AV_NOPTS_VALUE)
  2474. pkt.pts-= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2475. }
  2476. } else {
  2477. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2478. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2479. pkt_dts+1<ist->pts){
  2480. av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);
  2481. pkt.dts = AV_NOPTS_VALUE;
  2482. }
  2483. if (pkt.pts != AV_NOPTS_VALUE){
  2484. int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);
  2485. delta = pkt_pts - ist->next_dts;
  2486. if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||
  2487. (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||
  2488. pkt_pts+1<ist->pts) {
  2489. av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);
  2490. pkt.pts = AV_NOPTS_VALUE;
  2491. }
  2492. }
  2493. }
  2494. }
  2495. sub2video_heartbeat(ist, pkt.pts);
  2496. // fprintf(stderr,"read #%d.%d size=%d\n", ist->file_index, ist->st->index, pkt.size);
  2497. if ((ret = output_packet(ist, &pkt)) < 0 ||
  2498. ((ret = poll_filters()) < 0 && ret != AVERROR_EOF)) {
  2499. char buf[128];
  2500. av_strerror(ret, buf, sizeof(buf));
  2501. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",
  2502. ist->file_index, ist->st->index, buf);
  2503. if (exit_on_error)
  2504. exit_program(1);
  2505. av_free_packet(&pkt);
  2506. continue;
  2507. }
  2508. discard_packet:
  2509. av_free_packet(&pkt);
  2510. /* dump report by using the output first video and audio streams */
  2511. print_report(0, timer_start, cur_time);
  2512. }
  2513. #if HAVE_PTHREADS
  2514. free_input_threads();
  2515. #endif
  2516. /* at the end of stream, we must flush the decoder buffers */
  2517. for (i = 0; i < nb_input_streams; i++) {
  2518. ist = input_streams[i];
  2519. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  2520. output_packet(ist, NULL);
  2521. }
  2522. }
  2523. poll_filters();
  2524. flush_encoders();
  2525. term_exit();
  2526. /* write the trailer if needed and close file */
  2527. for (i = 0; i < nb_output_files; i++) {
  2528. os = output_files[i]->ctx;
  2529. av_write_trailer(os);
  2530. }
  2531. /* dump report by using the first video and audio streams */
  2532. print_report(1, timer_start, av_gettime());
  2533. /* close each encoder */
  2534. for (i = 0; i < nb_output_streams; i++) {
  2535. ost = output_streams[i];
  2536. if (ost->encoding_needed) {
  2537. av_freep(&ost->st->codec->stats_in);
  2538. avcodec_close(ost->st->codec);
  2539. }
  2540. }
  2541. /* close each decoder */
  2542. for (i = 0; i < nb_input_streams; i++) {
  2543. ist = input_streams[i];
  2544. if (ist->decoding_needed) {
  2545. avcodec_close(ist->st->codec);
  2546. }
  2547. }
  2548. /* finished ! */
  2549. ret = 0;
  2550. fail:
  2551. #if HAVE_PTHREADS
  2552. free_input_threads();
  2553. #endif
  2554. if (output_streams) {
  2555. for (i = 0; i < nb_output_streams; i++) {
  2556. ost = output_streams[i];
  2557. if (ost) {
  2558. if (ost->stream_copy)
  2559. av_freep(&ost->st->codec->extradata);
  2560. if (ost->logfile) {
  2561. fclose(ost->logfile);
  2562. ost->logfile = NULL;
  2563. }
  2564. av_freep(&ost->st->codec->subtitle_header);
  2565. av_free(ost->forced_kf_pts);
  2566. av_dict_free(&ost->opts);
  2567. }
  2568. }
  2569. }
  2570. return ret;
  2571. }
  2572. static int64_t getutime(void)
  2573. {
  2574. #if HAVE_GETRUSAGE
  2575. struct rusage rusage;
  2576. getrusage(RUSAGE_SELF, &rusage);
  2577. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2578. #elif HAVE_GETPROCESSTIMES
  2579. HANDLE proc;
  2580. FILETIME c, e, k, u;
  2581. proc = GetCurrentProcess();
  2582. GetProcessTimes(proc, &c, &e, &k, &u);
  2583. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  2584. #else
  2585. return av_gettime();
  2586. #endif
  2587. }
  2588. static int64_t getmaxrss(void)
  2589. {
  2590. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  2591. struct rusage rusage;
  2592. getrusage(RUSAGE_SELF, &rusage);
  2593. return (int64_t)rusage.ru_maxrss * 1024;
  2594. #elif HAVE_GETPROCESSMEMORYINFO
  2595. HANDLE proc;
  2596. PROCESS_MEMORY_COUNTERS memcounters;
  2597. proc = GetCurrentProcess();
  2598. memcounters.cb = sizeof(memcounters);
  2599. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  2600. return memcounters.PeakPagefileUsage;
  2601. #else
  2602. return 0;
  2603. #endif
  2604. }
  2605. static void log_callback_null(void *ptr, int level, const char *fmt, va_list vl)
  2606. {
  2607. }
  2608. static void parse_cpuflags(int argc, char **argv, const OptionDef *options)
  2609. {
  2610. int idx = locate_option(argc, argv, options, "cpuflags");
  2611. if (idx && argv[idx + 1])
  2612. opt_cpuflags("cpuflags", argv[idx + 1]);
  2613. }
  2614. int main(int argc, char **argv)
  2615. {
  2616. OptionsContext o = { 0 };
  2617. int64_t ti;
  2618. reset_options(&o, 0);
  2619. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2620. parse_loglevel(argc, argv, options);
  2621. if(argc>1 && !strcmp(argv[1], "-d")){
  2622. run_as_daemon=1;
  2623. av_log_set_callback(log_callback_null);
  2624. argc--;
  2625. argv++;
  2626. }
  2627. avcodec_register_all();
  2628. #if CONFIG_AVDEVICE
  2629. avdevice_register_all();
  2630. #endif
  2631. avfilter_register_all();
  2632. av_register_all();
  2633. avformat_network_init();
  2634. show_banner(argc, argv, options);
  2635. term_init();
  2636. parse_cpuflags(argc, argv, options);
  2637. /* parse options */
  2638. parse_options(&o, argc, argv, options, opt_output_file);
  2639. if (nb_output_files <= 0 && nb_input_files == 0) {
  2640. show_usage();
  2641. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  2642. exit_program(1);
  2643. }
  2644. /* file converter / grab */
  2645. if (nb_output_files <= 0) {
  2646. av_log(NULL, AV_LOG_FATAL, "At least one output file must be specified\n");
  2647. exit_program(1);
  2648. }
  2649. if (nb_input_files == 0) {
  2650. av_log(NULL, AV_LOG_FATAL, "At least one input file must be specified\n");
  2651. exit_program(1);
  2652. }
  2653. current_time = ti = getutime();
  2654. if (transcode() < 0)
  2655. exit_program(1);
  2656. ti = getutime() - ti;
  2657. if (do_benchmark) {
  2658. int maxrss = getmaxrss() / 1024;
  2659. printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
  2660. }
  2661. exit_program(0);
  2662. return 0;
  2663. }