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.

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