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.

3099 lines
107KB

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