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.

2369 lines
78KB

  1. /*
  2. * avconv main
  3. * Copyright (c) 2000-2011 The libav developers.
  4. *
  5. * This file is part of Libav.
  6. *
  7. * Libav is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * Libav is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with Libav; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "config.h"
  22. #include <ctype.h>
  23. #include <string.h>
  24. #include <math.h>
  25. #include <stdlib.h>
  26. #include <errno.h>
  27. #include <signal.h>
  28. #include <limits.h>
  29. #include "libavformat/avformat.h"
  30. #include "libavdevice/avdevice.h"
  31. #include "libswscale/swscale.h"
  32. #include "libavresample/avresample.h"
  33. #include "libavutil/opt.h"
  34. #include "libavutil/channel_layout.h"
  35. #include "libavutil/parseutils.h"
  36. #include "libavutil/samplefmt.h"
  37. #include "libavutil/colorspace.h"
  38. #include "libavutil/fifo.h"
  39. #include "libavutil/intreadwrite.h"
  40. #include "libavutil/dict.h"
  41. #include "libavutil/mathematics.h"
  42. #include "libavutil/pixdesc.h"
  43. #include "libavutil/avstring.h"
  44. #include "libavutil/libm.h"
  45. #include "libavutil/imgutils.h"
  46. #include "libavutil/time.h"
  47. #include "libavformat/os_support.h"
  48. # include "libavfilter/avfilter.h"
  49. # include "libavfilter/buffersrc.h"
  50. # include "libavfilter/buffersink.h"
  51. #if HAVE_SYS_RESOURCE_H
  52. #include <sys/time.h>
  53. #include <sys/types.h>
  54. #include <sys/resource.h>
  55. #elif HAVE_GETPROCESSTIMES
  56. #include <windows.h>
  57. #endif
  58. #if HAVE_GETPROCESSMEMORYINFO
  59. #include <windows.h>
  60. #include <psapi.h>
  61. #endif
  62. #if HAVE_SYS_SELECT_H
  63. #include <sys/select.h>
  64. #endif
  65. #if HAVE_PTHREADS
  66. #include <pthread.h>
  67. #endif
  68. #include <time.h>
  69. #include "avconv.h"
  70. #include "cmdutils.h"
  71. #include "libavutil/avassert.h"
  72. const char program_name[] = "avconv";
  73. const int program_birth_year = 2000;
  74. static FILE *vstats_file;
  75. static int64_t video_size = 0;
  76. static int64_t audio_size = 0;
  77. static int64_t extra_size = 0;
  78. static int nb_frames_dup = 0;
  79. static int nb_frames_drop = 0;
  80. #if HAVE_PTHREADS
  81. /* signal to input threads that they should exit; set by the main thread */
  82. static int transcoding_finished;
  83. #endif
  84. #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
  85. InputStream **input_streams = NULL;
  86. int nb_input_streams = 0;
  87. InputFile **input_files = NULL;
  88. int nb_input_files = 0;
  89. OutputStream **output_streams = NULL;
  90. int nb_output_streams = 0;
  91. OutputFile **output_files = NULL;
  92. int nb_output_files = 0;
  93. FilterGraph **filtergraphs;
  94. int nb_filtergraphs;
  95. static void term_exit(void)
  96. {
  97. av_log(NULL, AV_LOG_QUIET, "");
  98. }
  99. static volatile int received_sigterm = 0;
  100. static volatile int received_nb_signals = 0;
  101. static void
  102. sigterm_handler(int sig)
  103. {
  104. received_sigterm = sig;
  105. received_nb_signals++;
  106. term_exit();
  107. }
  108. static void term_init(void)
  109. {
  110. signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  111. signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  112. #ifdef SIGXCPU
  113. signal(SIGXCPU, sigterm_handler);
  114. #endif
  115. }
  116. static int decode_interrupt_cb(void *ctx)
  117. {
  118. return received_nb_signals > 1;
  119. }
  120. const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
  121. static void exit_program(void)
  122. {
  123. int i, j;
  124. for (i = 0; i < nb_filtergraphs; i++) {
  125. avfilter_graph_free(&filtergraphs[i]->graph);
  126. for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
  127. av_freep(&filtergraphs[i]->inputs[j]->name);
  128. av_freep(&filtergraphs[i]->inputs[j]);
  129. }
  130. av_freep(&filtergraphs[i]->inputs);
  131. for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
  132. av_freep(&filtergraphs[i]->outputs[j]->name);
  133. av_freep(&filtergraphs[i]->outputs[j]);
  134. }
  135. av_freep(&filtergraphs[i]->outputs);
  136. av_freep(&filtergraphs[i]->graph_desc);
  137. av_freep(&filtergraphs[i]);
  138. }
  139. av_freep(&filtergraphs);
  140. /* close files */
  141. for (i = 0; i < nb_output_files; i++) {
  142. AVFormatContext *s = output_files[i]->ctx;
  143. if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
  144. avio_close(s->pb);
  145. avformat_free_context(s);
  146. av_dict_free(&output_files[i]->opts);
  147. av_freep(&output_files[i]);
  148. }
  149. for (i = 0; i < nb_output_streams; i++) {
  150. AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
  151. while (bsfc) {
  152. AVBitStreamFilterContext *next = bsfc->next;
  153. av_bitstream_filter_close(bsfc);
  154. bsfc = next;
  155. }
  156. output_streams[i]->bitstream_filters = NULL;
  157. avcodec_free_frame(&output_streams[i]->filtered_frame);
  158. av_freep(&output_streams[i]->forced_keyframes);
  159. av_freep(&output_streams[i]->avfilter);
  160. av_freep(&output_streams[i]->logfile_prefix);
  161. av_freep(&output_streams[i]);
  162. }
  163. for (i = 0; i < nb_input_files; i++) {
  164. avformat_close_input(&input_files[i]->ctx);
  165. av_freep(&input_files[i]);
  166. }
  167. for (i = 0; i < nb_input_streams; i++) {
  168. av_frame_free(&input_streams[i]->decoded_frame);
  169. av_frame_free(&input_streams[i]->filter_frame);
  170. av_dict_free(&input_streams[i]->opts);
  171. av_freep(&input_streams[i]->filters);
  172. av_freep(&input_streams[i]);
  173. }
  174. if (vstats_file)
  175. fclose(vstats_file);
  176. av_free(vstats_filename);
  177. av_freep(&input_streams);
  178. av_freep(&input_files);
  179. av_freep(&output_streams);
  180. av_freep(&output_files);
  181. uninit_opts();
  182. avformat_network_deinit();
  183. if (received_sigterm) {
  184. av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",
  185. (int) received_sigterm);
  186. exit (255);
  187. }
  188. }
  189. void assert_avoptions(AVDictionary *m)
  190. {
  191. AVDictionaryEntry *t;
  192. if ((t = av_dict_get(m, "", NULL, AV_DICT_IGNORE_SUFFIX))) {
  193. av_log(NULL, AV_LOG_FATAL, "Option %s not found.\n", t->key);
  194. exit(1);
  195. }
  196. }
  197. static void abort_codec_experimental(AVCodec *c, int encoder)
  198. {
  199. const char *codec_string = encoder ? "encoder" : "decoder";
  200. AVCodec *codec;
  201. av_log(NULL, AV_LOG_FATAL, "%s '%s' is experimental and might produce bad "
  202. "results.\nAdd '-strict experimental' if you want to use it.\n",
  203. codec_string, c->name);
  204. codec = encoder ? avcodec_find_encoder(c->id) : avcodec_find_decoder(c->id);
  205. if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))
  206. av_log(NULL, AV_LOG_FATAL, "Or use the non experimental %s '%s'.\n",
  207. codec_string, codec->name);
  208. exit(1);
  209. }
  210. /*
  211. * Update the requested input sample format based on the output sample format.
  212. * This is currently only used to request float output from decoders which
  213. * support multiple sample formats, one of which is AV_SAMPLE_FMT_FLT.
  214. * Ideally this will be removed in the future when decoders do not do format
  215. * conversion and only output in their native format.
  216. */
  217. static void update_sample_fmt(AVCodecContext *dec, AVCodec *dec_codec,
  218. AVCodecContext *enc)
  219. {
  220. /* if sample formats match or a decoder sample format has already been
  221. requested, just return */
  222. if (enc->sample_fmt == dec->sample_fmt ||
  223. dec->request_sample_fmt > AV_SAMPLE_FMT_NONE)
  224. return;
  225. /* if decoder supports more than one output format */
  226. if (dec_codec && dec_codec->sample_fmts &&
  227. dec_codec->sample_fmts[0] != AV_SAMPLE_FMT_NONE &&
  228. dec_codec->sample_fmts[1] != AV_SAMPLE_FMT_NONE) {
  229. const enum AVSampleFormat *p;
  230. int min_dec = INT_MAX, min_inc = INT_MAX;
  231. enum AVSampleFormat dec_fmt = AV_SAMPLE_FMT_NONE;
  232. enum AVSampleFormat inc_fmt = AV_SAMPLE_FMT_NONE;
  233. /* find a matching sample format in the encoder */
  234. for (p = dec_codec->sample_fmts; *p != AV_SAMPLE_FMT_NONE; p++) {
  235. if (*p == enc->sample_fmt) {
  236. dec->request_sample_fmt = *p;
  237. return;
  238. } else {
  239. enum AVSampleFormat dfmt = av_get_packed_sample_fmt(*p);
  240. enum AVSampleFormat efmt = av_get_packed_sample_fmt(enc->sample_fmt);
  241. int fmt_diff = 32 * abs(dfmt - efmt);
  242. if (av_sample_fmt_is_planar(*p) !=
  243. av_sample_fmt_is_planar(enc->sample_fmt))
  244. fmt_diff++;
  245. if (dfmt == efmt) {
  246. min_inc = fmt_diff;
  247. inc_fmt = *p;
  248. } else if (dfmt > efmt) {
  249. if (fmt_diff < min_inc) {
  250. min_inc = fmt_diff;
  251. inc_fmt = *p;
  252. }
  253. } else {
  254. if (fmt_diff < min_dec) {
  255. min_dec = fmt_diff;
  256. dec_fmt = *p;
  257. }
  258. }
  259. }
  260. }
  261. /* if none match, provide the one that matches quality closest */
  262. dec->request_sample_fmt = min_inc != INT_MAX ? inc_fmt : dec_fmt;
  263. }
  264. }
  265. static void write_frame(AVFormatContext *s, AVPacket *pkt, OutputStream *ost)
  266. {
  267. AVBitStreamFilterContext *bsfc = ost->bitstream_filters;
  268. AVCodecContext *avctx = ost->st->codec;
  269. int ret;
  270. /*
  271. * Audio encoders may split the packets -- #frames in != #packets out.
  272. * But there is no reordering, so we can limit the number of output packets
  273. * by simply dropping them here.
  274. * Counting encoded video frames needs to be done separately because of
  275. * reordering, see do_video_out()
  276. */
  277. if (!(avctx->codec_type == AVMEDIA_TYPE_VIDEO && avctx->codec)) {
  278. if (ost->frame_number >= ost->max_frames) {
  279. av_free_packet(pkt);
  280. return;
  281. }
  282. ost->frame_number++;
  283. }
  284. while (bsfc) {
  285. AVPacket new_pkt = *pkt;
  286. int a = av_bitstream_filter_filter(bsfc, avctx, NULL,
  287. &new_pkt.data, &new_pkt.size,
  288. pkt->data, pkt->size,
  289. pkt->flags & AV_PKT_FLAG_KEY);
  290. if (a > 0) {
  291. av_free_packet(pkt);
  292. new_pkt.buf = av_buffer_create(new_pkt.data, new_pkt.size,
  293. av_buffer_default_free, NULL, 0);
  294. if (!new_pkt.buf)
  295. exit(1);
  296. } else if (a < 0) {
  297. av_log(NULL, AV_LOG_ERROR, "%s failed for stream %d, codec %s",
  298. bsfc->filter->name, pkt->stream_index,
  299. avctx->codec ? avctx->codec->name : "copy");
  300. print_error("", a);
  301. if (exit_on_error)
  302. exit(1);
  303. }
  304. *pkt = new_pkt;
  305. bsfc = bsfc->next;
  306. }
  307. if (!(s->oformat->flags & AVFMT_NOTIMESTAMPS) &&
  308. ost->last_mux_dts != AV_NOPTS_VALUE &&
  309. pkt->dts < ost->last_mux_dts + !(s->oformat->flags & AVFMT_TS_NONSTRICT)) {
  310. av_log(NULL, AV_LOG_WARNING, "Non-monotonous DTS in output stream "
  311. "%d:%d; previous: %"PRId64", current: %"PRId64"; ",
  312. ost->file_index, ost->st->index, ost->last_mux_dts, pkt->dts);
  313. if (exit_on_error) {
  314. av_log(NULL, AV_LOG_FATAL, "aborting.\n");
  315. exit(1);
  316. }
  317. av_log(NULL, AV_LOG_WARNING, "changing to %"PRId64". This may result "
  318. "in incorrect timestamps in the output file.\n",
  319. ost->last_mux_dts + 1);
  320. pkt->dts = ost->last_mux_dts + 1;
  321. if (pkt->pts != AV_NOPTS_VALUE)
  322. pkt->pts = FFMAX(pkt->pts, pkt->dts);
  323. }
  324. ost->last_mux_dts = pkt->dts;
  325. pkt->stream_index = ost->index;
  326. ret = av_interleaved_write_frame(s, pkt);
  327. if (ret < 0) {
  328. print_error("av_interleaved_write_frame()", ret);
  329. exit(1);
  330. }
  331. }
  332. static int check_recording_time(OutputStream *ost)
  333. {
  334. OutputFile *of = output_files[ost->file_index];
  335. if (of->recording_time != INT64_MAX &&
  336. av_compare_ts(ost->sync_opts - ost->first_pts, ost->st->codec->time_base, of->recording_time,
  337. AV_TIME_BASE_Q) >= 0) {
  338. ost->finished = 1;
  339. return 0;
  340. }
  341. return 1;
  342. }
  343. static void do_audio_out(AVFormatContext *s, OutputStream *ost,
  344. AVFrame *frame)
  345. {
  346. AVCodecContext *enc = ost->st->codec;
  347. AVPacket pkt;
  348. int got_packet = 0;
  349. av_init_packet(&pkt);
  350. pkt.data = NULL;
  351. pkt.size = 0;
  352. if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)
  353. frame->pts = ost->sync_opts;
  354. ost->sync_opts = frame->pts + frame->nb_samples;
  355. if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {
  356. av_log(NULL, AV_LOG_FATAL, "Audio encoding failed\n");
  357. exit(1);
  358. }
  359. if (got_packet) {
  360. if (pkt.pts != AV_NOPTS_VALUE)
  361. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  362. if (pkt.dts != AV_NOPTS_VALUE)
  363. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  364. if (pkt.duration > 0)
  365. pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
  366. write_frame(s, &pkt, ost);
  367. audio_size += pkt.size;
  368. }
  369. }
  370. static void do_subtitle_out(AVFormatContext *s,
  371. OutputStream *ost,
  372. InputStream *ist,
  373. AVSubtitle *sub,
  374. int64_t pts)
  375. {
  376. static uint8_t *subtitle_out = NULL;
  377. int subtitle_out_max_size = 1024 * 1024;
  378. int subtitle_out_size, nb, i;
  379. AVCodecContext *enc;
  380. AVPacket pkt;
  381. if (pts == AV_NOPTS_VALUE) {
  382. av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");
  383. if (exit_on_error)
  384. exit(1);
  385. return;
  386. }
  387. enc = ost->st->codec;
  388. if (!subtitle_out) {
  389. subtitle_out = av_malloc(subtitle_out_max_size);
  390. }
  391. /* Note: DVB subtitle need one packet to draw them and one other
  392. packet to clear them */
  393. /* XXX: signal it in the codec context ? */
  394. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)
  395. nb = 2;
  396. else
  397. nb = 1;
  398. for (i = 0; i < nb; i++) {
  399. ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);
  400. if (!check_recording_time(ost))
  401. return;
  402. sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);
  403. // start_display_time is required to be 0
  404. sub->pts += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);
  405. sub->end_display_time -= sub->start_display_time;
  406. sub->start_display_time = 0;
  407. subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,
  408. subtitle_out_max_size, sub);
  409. if (subtitle_out_size < 0) {
  410. av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");
  411. exit(1);
  412. }
  413. av_init_packet(&pkt);
  414. pkt.data = subtitle_out;
  415. pkt.size = subtitle_out_size;
  416. pkt.pts = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);
  417. if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {
  418. /* XXX: the pts correction is handled here. Maybe handling
  419. it in the codec would be better */
  420. if (i == 0)
  421. pkt.pts += 90 * sub->start_display_time;
  422. else
  423. pkt.pts += 90 * sub->end_display_time;
  424. }
  425. write_frame(s, &pkt, ost);
  426. }
  427. }
  428. static void do_video_out(AVFormatContext *s,
  429. OutputStream *ost,
  430. AVFrame *in_picture,
  431. int *frame_size)
  432. {
  433. int ret, format_video_sync;
  434. AVPacket pkt;
  435. AVCodecContext *enc = ost->st->codec;
  436. *frame_size = 0;
  437. format_video_sync = video_sync_method;
  438. if (format_video_sync == VSYNC_AUTO)
  439. format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :
  440. (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;
  441. if (format_video_sync != VSYNC_PASSTHROUGH &&
  442. ost->frame_number &&
  443. in_picture->pts != AV_NOPTS_VALUE &&
  444. in_picture->pts < ost->sync_opts) {
  445. nb_frames_drop++;
  446. av_log(NULL, AV_LOG_VERBOSE, "*** drop!\n");
  447. return;
  448. }
  449. if (in_picture->pts == AV_NOPTS_VALUE)
  450. in_picture->pts = ost->sync_opts;
  451. ost->sync_opts = in_picture->pts;
  452. if (!ost->frame_number)
  453. ost->first_pts = in_picture->pts;
  454. av_init_packet(&pkt);
  455. pkt.data = NULL;
  456. pkt.size = 0;
  457. if (ost->frame_number >= ost->max_frames)
  458. return;
  459. if (s->oformat->flags & AVFMT_RAWPICTURE &&
  460. enc->codec->id == AV_CODEC_ID_RAWVIDEO) {
  461. /* raw pictures are written as AVPicture structure to
  462. avoid any copies. We support temporarily the older
  463. method. */
  464. enc->coded_frame->interlaced_frame = in_picture->interlaced_frame;
  465. enc->coded_frame->top_field_first = in_picture->top_field_first;
  466. pkt.data = (uint8_t *)in_picture;
  467. pkt.size = sizeof(AVPicture);
  468. pkt.pts = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);
  469. pkt.flags |= AV_PKT_FLAG_KEY;
  470. write_frame(s, &pkt, ost);
  471. } else {
  472. int got_packet;
  473. if (ost->st->codec->flags & (CODEC_FLAG_INTERLACED_DCT|CODEC_FLAG_INTERLACED_ME) &&
  474. ost->top_field_first >= 0)
  475. in_picture->top_field_first = !!ost->top_field_first;
  476. in_picture->quality = ost->st->codec->global_quality;
  477. if (!enc->me_threshold)
  478. in_picture->pict_type = 0;
  479. if (ost->forced_kf_index < ost->forced_kf_count &&
  480. in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {
  481. in_picture->pict_type = AV_PICTURE_TYPE_I;
  482. ost->forced_kf_index++;
  483. }
  484. ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);
  485. if (ret < 0) {
  486. av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");
  487. exit(1);
  488. }
  489. if (got_packet) {
  490. if (pkt.pts != AV_NOPTS_VALUE)
  491. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  492. if (pkt.dts != AV_NOPTS_VALUE)
  493. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  494. write_frame(s, &pkt, ost);
  495. *frame_size = pkt.size;
  496. video_size += pkt.size;
  497. /* if two pass, output log */
  498. if (ost->logfile && enc->stats_out) {
  499. fprintf(ost->logfile, "%s", enc->stats_out);
  500. }
  501. }
  502. }
  503. ost->sync_opts++;
  504. /*
  505. * For video, number of frames in == number of packets out.
  506. * But there may be reordering, so we can't throw away frames on encoder
  507. * flush, we need to limit them here, before they go into encoder.
  508. */
  509. ost->frame_number++;
  510. }
  511. static double psnr(double d)
  512. {
  513. return -10.0 * log(d) / log(10.0);
  514. }
  515. static void do_video_stats(OutputStream *ost, int frame_size)
  516. {
  517. AVCodecContext *enc;
  518. int frame_number;
  519. double ti1, bitrate, avg_bitrate;
  520. /* this is executed just the first time do_video_stats is called */
  521. if (!vstats_file) {
  522. vstats_file = fopen(vstats_filename, "w");
  523. if (!vstats_file) {
  524. perror("fopen");
  525. exit(1);
  526. }
  527. }
  528. enc = ost->st->codec;
  529. if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  530. frame_number = ost->frame_number;
  531. fprintf(vstats_file, "frame= %5d q= %2.1f ", frame_number, enc->coded_frame->quality / (float)FF_QP2LAMBDA);
  532. if (enc->flags&CODEC_FLAG_PSNR)
  533. fprintf(vstats_file, "PSNR= %6.2f ", psnr(enc->coded_frame->error[0] / (enc->width * enc->height * 255.0 * 255.0)));
  534. fprintf(vstats_file,"f_size= %6d ", frame_size);
  535. /* compute pts value */
  536. ti1 = ost->sync_opts * av_q2d(enc->time_base);
  537. if (ti1 < 0.01)
  538. ti1 = 0.01;
  539. bitrate = (frame_size * 8) / av_q2d(enc->time_base) / 1000.0;
  540. avg_bitrate = (double)(video_size * 8) / ti1 / 1000.0;
  541. fprintf(vstats_file, "s_size= %8.0fkB time= %0.3f br= %7.1fkbits/s avg_br= %7.1fkbits/s ",
  542. (double)video_size / 1024, ti1, bitrate, avg_bitrate);
  543. fprintf(vstats_file, "type= %c\n", av_get_picture_type_char(enc->coded_frame->pict_type));
  544. }
  545. }
  546. /*
  547. * Read one frame for lavfi output for ost and encode it.
  548. */
  549. static int poll_filter(OutputStream *ost)
  550. {
  551. OutputFile *of = output_files[ost->file_index];
  552. AVFrame *filtered_frame = NULL;
  553. int frame_size, ret;
  554. if (!ost->filtered_frame && !(ost->filtered_frame = avcodec_alloc_frame())) {
  555. return AVERROR(ENOMEM);
  556. } else
  557. avcodec_get_frame_defaults(ost->filtered_frame);
  558. filtered_frame = ost->filtered_frame;
  559. if (ost->enc->type == AVMEDIA_TYPE_AUDIO &&
  560. !(ost->enc->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE))
  561. ret = av_buffersink_get_samples(ost->filter->filter, filtered_frame,
  562. ost->st->codec->frame_size);
  563. else
  564. ret = av_buffersink_get_frame(ost->filter->filter, filtered_frame);
  565. if (ret < 0)
  566. return ret;
  567. if (filtered_frame->pts != AV_NOPTS_VALUE) {
  568. filtered_frame->pts = av_rescale_q(filtered_frame->pts,
  569. ost->filter->filter->inputs[0]->time_base,
  570. ost->st->codec->time_base) -
  571. av_rescale_q(of->start_time,
  572. AV_TIME_BASE_Q,
  573. ost->st->codec->time_base);
  574. }
  575. switch (ost->filter->filter->inputs[0]->type) {
  576. case AVMEDIA_TYPE_VIDEO:
  577. if (!ost->frame_aspect_ratio)
  578. ost->st->codec->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
  579. do_video_out(of->ctx, ost, filtered_frame, &frame_size);
  580. if (vstats_filename && frame_size)
  581. do_video_stats(ost, frame_size);
  582. break;
  583. case AVMEDIA_TYPE_AUDIO:
  584. do_audio_out(of->ctx, ost, filtered_frame);
  585. break;
  586. default:
  587. // TODO support subtitle filters
  588. av_assert0(0);
  589. }
  590. av_frame_unref(filtered_frame);
  591. return 0;
  592. }
  593. /*
  594. * Read as many frames from possible from lavfi and encode them.
  595. *
  596. * Always read from the active stream with the lowest timestamp. If no frames
  597. * are available for it then return EAGAIN and wait for more input. This way we
  598. * can use lavfi sources that generate unlimited amount of frames without memory
  599. * usage exploding.
  600. */
  601. static int poll_filters(void)
  602. {
  603. int i, j, ret = 0;
  604. while (ret >= 0 && !received_sigterm) {
  605. OutputStream *ost = NULL;
  606. int64_t min_pts = INT64_MAX;
  607. /* choose output stream with the lowest timestamp */
  608. for (i = 0; i < nb_output_streams; i++) {
  609. int64_t pts = output_streams[i]->sync_opts;
  610. if (!output_streams[i]->filter || output_streams[i]->finished)
  611. continue;
  612. pts = av_rescale_q(pts, output_streams[i]->st->codec->time_base,
  613. AV_TIME_BASE_Q);
  614. if (pts < min_pts) {
  615. min_pts = pts;
  616. ost = output_streams[i];
  617. }
  618. }
  619. if (!ost)
  620. break;
  621. ret = poll_filter(ost);
  622. if (ret == AVERROR_EOF) {
  623. OutputFile *of = output_files[ost->file_index];
  624. ost->finished = 1;
  625. if (of->shortest) {
  626. for (j = 0; j < of->ctx->nb_streams; j++)
  627. output_streams[of->ost_index + j]->finished = 1;
  628. }
  629. ret = 0;
  630. } else if (ret == AVERROR(EAGAIN))
  631. return 0;
  632. }
  633. return ret;
  634. }
  635. static void print_report(int is_last_report, int64_t timer_start)
  636. {
  637. char buf[1024];
  638. OutputStream *ost;
  639. AVFormatContext *oc;
  640. int64_t total_size;
  641. AVCodecContext *enc;
  642. int frame_number, vid, i;
  643. double bitrate, ti1, pts;
  644. static int64_t last_time = -1;
  645. static int qp_histogram[52];
  646. if (!print_stats && !is_last_report)
  647. return;
  648. if (!is_last_report) {
  649. int64_t cur_time;
  650. /* display the report every 0.5 seconds */
  651. cur_time = av_gettime();
  652. if (last_time == -1) {
  653. last_time = cur_time;
  654. return;
  655. }
  656. if ((cur_time - last_time) < 500000)
  657. return;
  658. last_time = cur_time;
  659. }
  660. oc = output_files[0]->ctx;
  661. total_size = avio_size(oc->pb);
  662. if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
  663. total_size = avio_tell(oc->pb);
  664. if (total_size < 0) {
  665. char errbuf[128];
  666. av_strerror(total_size, errbuf, sizeof(errbuf));
  667. av_log(NULL, AV_LOG_VERBOSE, "Bitrate not available, "
  668. "avio_tell() failed: %s\n", errbuf);
  669. total_size = 0;
  670. }
  671. buf[0] = '\0';
  672. ti1 = 1e10;
  673. vid = 0;
  674. for (i = 0; i < nb_output_streams; i++) {
  675. float q = -1;
  676. ost = output_streams[i];
  677. enc = ost->st->codec;
  678. if (!ost->stream_copy && enc->coded_frame)
  679. q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
  680. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  681. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
  682. }
  683. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  684. float t = (av_gettime() - timer_start) / 1000000.0;
  685. frame_number = ost->frame_number;
  686. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
  687. frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
  688. if (is_last_report)
  689. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
  690. if (qp_hist) {
  691. int j;
  692. int qp = lrintf(q);
  693. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
  694. qp_histogram[qp]++;
  695. for (j = 0; j < 32; j++)
  696. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
  697. }
  698. if (enc->flags&CODEC_FLAG_PSNR) {
  699. int j;
  700. double error, error_sum = 0;
  701. double scale, scale_sum = 0;
  702. char type[3] = { 'Y','U','V' };
  703. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
  704. for (j = 0; j < 3; j++) {
  705. if (is_last_report) {
  706. error = enc->error[j];
  707. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
  708. } else {
  709. error = enc->coded_frame->error[j];
  710. scale = enc->width * enc->height * 255.0 * 255.0;
  711. }
  712. if (j)
  713. scale /= 4;
  714. error_sum += error;
  715. scale_sum += scale;
  716. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
  717. }
  718. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
  719. }
  720. vid = 1;
  721. }
  722. /* compute min output value */
  723. pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
  724. if ((pts < ti1) && (pts > 0))
  725. ti1 = pts;
  726. }
  727. if (ti1 < 0.01)
  728. ti1 = 0.01;
  729. bitrate = (double)(total_size * 8) / ti1 / 1000.0;
  730. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  731. "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
  732. (double)total_size / 1024, ti1, bitrate);
  733. if (nb_frames_dup || nb_frames_drop)
  734. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
  735. nb_frames_dup, nb_frames_drop);
  736. av_log(NULL, AV_LOG_INFO, "%s \r", buf);
  737. fflush(stderr);
  738. if (is_last_report) {
  739. int64_t raw= audio_size + video_size + extra_size;
  740. av_log(NULL, AV_LOG_INFO, "\n");
  741. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
  742. video_size / 1024.0,
  743. audio_size / 1024.0,
  744. extra_size / 1024.0,
  745. 100.0 * (total_size - raw) / raw
  746. );
  747. }
  748. }
  749. static void flush_encoders(void)
  750. {
  751. int i, ret;
  752. for (i = 0; i < nb_output_streams; i++) {
  753. OutputStream *ost = output_streams[i];
  754. AVCodecContext *enc = ost->st->codec;
  755. AVFormatContext *os = output_files[ost->file_index]->ctx;
  756. int stop_encoding = 0;
  757. if (!ost->encoding_needed)
  758. continue;
  759. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  760. continue;
  761. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
  762. continue;
  763. for (;;) {
  764. int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
  765. const char *desc;
  766. int64_t *size;
  767. switch (ost->st->codec->codec_type) {
  768. case AVMEDIA_TYPE_AUDIO:
  769. encode = avcodec_encode_audio2;
  770. desc = "Audio";
  771. size = &audio_size;
  772. break;
  773. case AVMEDIA_TYPE_VIDEO:
  774. encode = avcodec_encode_video2;
  775. desc = "Video";
  776. size = &video_size;
  777. break;
  778. default:
  779. stop_encoding = 1;
  780. }
  781. if (encode) {
  782. AVPacket pkt;
  783. int got_packet;
  784. av_init_packet(&pkt);
  785. pkt.data = NULL;
  786. pkt.size = 0;
  787. ret = encode(enc, &pkt, NULL, &got_packet);
  788. if (ret < 0) {
  789. av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
  790. exit(1);
  791. }
  792. *size += ret;
  793. if (ost->logfile && enc->stats_out) {
  794. fprintf(ost->logfile, "%s", enc->stats_out);
  795. }
  796. if (!got_packet) {
  797. stop_encoding = 1;
  798. break;
  799. }
  800. if (pkt.pts != AV_NOPTS_VALUE)
  801. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  802. if (pkt.dts != AV_NOPTS_VALUE)
  803. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  804. if (pkt.duration > 0)
  805. pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
  806. write_frame(os, &pkt, ost);
  807. }
  808. if (stop_encoding)
  809. break;
  810. }
  811. }
  812. }
  813. /*
  814. * Check whether a packet from ist should be written into ost at this time
  815. */
  816. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  817. {
  818. OutputFile *of = output_files[ost->file_index];
  819. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  820. if (ost->source_index != ist_index)
  821. return 0;
  822. if (of->start_time && ist->last_dts < of->start_time)
  823. return 0;
  824. return 1;
  825. }
  826. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  827. {
  828. OutputFile *of = output_files[ost->file_index];
  829. int64_t ost_tb_start_time = av_rescale_q(of->start_time, AV_TIME_BASE_Q, ost->st->time_base);
  830. AVPacket opkt;
  831. av_init_packet(&opkt);
  832. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  833. !ost->copy_initial_nonkeyframes)
  834. return;
  835. if (of->recording_time != INT64_MAX &&
  836. ist->last_dts >= of->recording_time + of->start_time) {
  837. ost->finished = 1;
  838. return;
  839. }
  840. /* force the input stream PTS */
  841. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  842. audio_size += pkt->size;
  843. else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  844. video_size += pkt->size;
  845. ost->sync_opts++;
  846. }
  847. if (pkt->pts != AV_NOPTS_VALUE)
  848. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  849. else
  850. opkt.pts = AV_NOPTS_VALUE;
  851. if (pkt->dts == AV_NOPTS_VALUE)
  852. opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);
  853. else
  854. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  855. opkt.dts -= ost_tb_start_time;
  856. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  857. opkt.flags = pkt->flags;
  858. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  859. if ( ost->st->codec->codec_id != AV_CODEC_ID_H264
  860. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
  861. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
  862. && ost->st->codec->codec_id != AV_CODEC_ID_VC1
  863. ) {
  864. if (av_parser_change(ist->st->parser, ost->st->codec, &opkt.data, &opkt.size, pkt->data, pkt->size, pkt->flags & AV_PKT_FLAG_KEY)) {
  865. opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
  866. if (!opkt.buf)
  867. exit(1);
  868. }
  869. } else {
  870. opkt.data = pkt->data;
  871. opkt.size = pkt->size;
  872. }
  873. write_frame(of->ctx, &opkt, ost);
  874. ost->st->codec->frame_number++;
  875. }
  876. int guess_input_channel_layout(InputStream *ist)
  877. {
  878. AVCodecContext *dec = ist->st->codec;
  879. if (!dec->channel_layout) {
  880. char layout_name[256];
  881. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  882. if (!dec->channel_layout)
  883. return 0;
  884. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  885. dec->channels, dec->channel_layout);
  886. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  887. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  888. }
  889. return 1;
  890. }
  891. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  892. {
  893. AVFrame *decoded_frame, *f;
  894. AVCodecContext *avctx = ist->st->codec;
  895. int i, ret, err = 0, resample_changed;
  896. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  897. return AVERROR(ENOMEM);
  898. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  899. return AVERROR(ENOMEM);
  900. decoded_frame = ist->decoded_frame;
  901. ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
  902. if (!*got_output || ret < 0) {
  903. if (!pkt->size) {
  904. for (i = 0; i < ist->nb_filters; i++)
  905. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  906. }
  907. return ret;
  908. }
  909. /* if the decoder provides a pts, use it instead of the last packet pts.
  910. the decoder could be delaying output by a packet or more. */
  911. if (decoded_frame->pts != AV_NOPTS_VALUE)
  912. ist->next_dts = decoded_frame->pts;
  913. else if (pkt->pts != AV_NOPTS_VALUE) {
  914. decoded_frame->pts = pkt->pts;
  915. pkt->pts = AV_NOPTS_VALUE;
  916. }
  917. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  918. ist->resample_channels != avctx->channels ||
  919. ist->resample_channel_layout != decoded_frame->channel_layout ||
  920. ist->resample_sample_rate != decoded_frame->sample_rate;
  921. if (resample_changed) {
  922. char layout1[64], layout2[64];
  923. if (!guess_input_channel_layout(ist)) {
  924. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  925. "layout for Input Stream #%d.%d\n", ist->file_index,
  926. ist->st->index);
  927. exit(1);
  928. }
  929. decoded_frame->channel_layout = avctx->channel_layout;
  930. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  931. ist->resample_channel_layout);
  932. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  933. decoded_frame->channel_layout);
  934. av_log(NULL, AV_LOG_INFO,
  935. "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",
  936. ist->file_index, ist->st->index,
  937. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  938. ist->resample_channels, layout1,
  939. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  940. avctx->channels, layout2);
  941. ist->resample_sample_fmt = decoded_frame->format;
  942. ist->resample_sample_rate = decoded_frame->sample_rate;
  943. ist->resample_channel_layout = decoded_frame->channel_layout;
  944. ist->resample_channels = avctx->channels;
  945. for (i = 0; i < nb_filtergraphs; i++)
  946. if (ist_in_filtergraph(filtergraphs[i], ist) &&
  947. configure_filtergraph(filtergraphs[i]) < 0) {
  948. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  949. exit(1);
  950. }
  951. }
  952. if (decoded_frame->pts != AV_NOPTS_VALUE)
  953. decoded_frame->pts = av_rescale_q(decoded_frame->pts,
  954. ist->st->time_base,
  955. (AVRational){1, ist->st->codec->sample_rate});
  956. for (i = 0; i < ist->nb_filters; i++) {
  957. if (i < ist->nb_filters - 1) {
  958. f = ist->filter_frame;
  959. err = av_frame_ref(f, decoded_frame);
  960. if (err < 0)
  961. break;
  962. } else
  963. f = decoded_frame;
  964. err = av_buffersrc_add_frame(ist->filters[i]->filter, f);
  965. if (err < 0)
  966. break;
  967. }
  968. av_frame_unref(ist->filter_frame);
  969. av_frame_unref(decoded_frame);
  970. return err < 0 ? err : ret;
  971. }
  972. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  973. {
  974. AVFrame *decoded_frame, *f;
  975. void *buffer_to_free = NULL;
  976. int i, ret = 0, err = 0, resample_changed;
  977. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  978. return AVERROR(ENOMEM);
  979. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  980. return AVERROR(ENOMEM);
  981. decoded_frame = ist->decoded_frame;
  982. ret = avcodec_decode_video2(ist->st->codec,
  983. decoded_frame, got_output, pkt);
  984. if (!*got_output || ret < 0) {
  985. if (!pkt->size) {
  986. for (i = 0; i < ist->nb_filters; i++)
  987. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  988. }
  989. return ret;
  990. }
  991. decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
  992. decoded_frame->pkt_dts);
  993. pkt->size = 0;
  994. if (ist->st->sample_aspect_ratio.num)
  995. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  996. resample_changed = ist->resample_width != decoded_frame->width ||
  997. ist->resample_height != decoded_frame->height ||
  998. ist->resample_pix_fmt != decoded_frame->format;
  999. if (resample_changed) {
  1000. av_log(NULL, AV_LOG_INFO,
  1001. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1002. ist->file_index, ist->st->index,
  1003. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1004. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1005. ret = poll_filters();
  1006. if (ret < 0 && (ret != AVERROR_EOF && ret != AVERROR(EAGAIN)))
  1007. av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
  1008. ist->resample_width = decoded_frame->width;
  1009. ist->resample_height = decoded_frame->height;
  1010. ist->resample_pix_fmt = decoded_frame->format;
  1011. for (i = 0; i < nb_filtergraphs; i++)
  1012. if (ist_in_filtergraph(filtergraphs[i], ist) &&
  1013. configure_filtergraph(filtergraphs[i]) < 0) {
  1014. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1015. exit(1);
  1016. }
  1017. }
  1018. for (i = 0; i < ist->nb_filters; i++) {
  1019. if (i < ist->nb_filters - 1) {
  1020. f = ist->filter_frame;
  1021. err = av_frame_ref(f, decoded_frame);
  1022. if (err < 0)
  1023. break;
  1024. } else
  1025. f = decoded_frame;
  1026. err = av_buffersrc_add_frame(ist->filters[i]->filter, f);
  1027. if (err < 0)
  1028. break;
  1029. }
  1030. av_frame_unref(ist->filter_frame);
  1031. av_frame_unref(decoded_frame);
  1032. av_free(buffer_to_free);
  1033. return err < 0 ? err : ret;
  1034. }
  1035. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1036. {
  1037. AVSubtitle subtitle;
  1038. int i, ret = avcodec_decode_subtitle2(ist->st->codec,
  1039. &subtitle, got_output, pkt);
  1040. if (ret < 0)
  1041. return ret;
  1042. if (!*got_output)
  1043. return ret;
  1044. for (i = 0; i < nb_output_streams; i++) {
  1045. OutputStream *ost = output_streams[i];
  1046. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1047. continue;
  1048. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
  1049. }
  1050. avsubtitle_free(&subtitle);
  1051. return ret;
  1052. }
  1053. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1054. static int output_packet(InputStream *ist, const AVPacket *pkt)
  1055. {
  1056. int i;
  1057. int got_output;
  1058. AVPacket avpkt;
  1059. if (ist->next_dts == AV_NOPTS_VALUE)
  1060. ist->next_dts = ist->last_dts;
  1061. if (pkt == NULL) {
  1062. /* EOF handling */
  1063. av_init_packet(&avpkt);
  1064. avpkt.data = NULL;
  1065. avpkt.size = 0;
  1066. goto handle_eof;
  1067. } else {
  1068. avpkt = *pkt;
  1069. }
  1070. if (pkt->dts != AV_NOPTS_VALUE)
  1071. ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1072. // while we have more to decode or while the decoder did output something on EOF
  1073. while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
  1074. int ret = 0;
  1075. handle_eof:
  1076. ist->last_dts = ist->next_dts;
  1077. if (avpkt.size && avpkt.size != pkt->size) {
  1078. av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
  1079. "Multiple frames in a packet from stream %d\n", pkt->stream_index);
  1080. ist->showed_multi_packet_warning = 1;
  1081. }
  1082. switch (ist->st->codec->codec_type) {
  1083. case AVMEDIA_TYPE_AUDIO:
  1084. ret = decode_audio (ist, &avpkt, &got_output);
  1085. break;
  1086. case AVMEDIA_TYPE_VIDEO:
  1087. ret = decode_video (ist, &avpkt, &got_output);
  1088. if (avpkt.duration)
  1089. ist->next_dts += av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
  1090. else if (ist->st->avg_frame_rate.num)
  1091. ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
  1092. AV_TIME_BASE_Q);
  1093. else if (ist->st->codec->time_base.num != 0) {
  1094. int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
  1095. ist->st->codec->ticks_per_frame;
  1096. ist->next_dts += av_rescale_q(ticks, ist->st->codec->time_base, AV_TIME_BASE_Q);
  1097. }
  1098. break;
  1099. case AVMEDIA_TYPE_SUBTITLE:
  1100. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1101. break;
  1102. default:
  1103. return -1;
  1104. }
  1105. if (ret < 0)
  1106. return ret;
  1107. // touch data and size only if not EOF
  1108. if (pkt) {
  1109. avpkt.data += ret;
  1110. avpkt.size -= ret;
  1111. }
  1112. if (!got_output) {
  1113. continue;
  1114. }
  1115. }
  1116. /* handle stream copy */
  1117. if (!ist->decoding_needed) {
  1118. ist->last_dts = ist->next_dts;
  1119. switch (ist->st->codec->codec_type) {
  1120. case AVMEDIA_TYPE_AUDIO:
  1121. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
  1122. ist->st->codec->sample_rate;
  1123. break;
  1124. case AVMEDIA_TYPE_VIDEO:
  1125. if (ist->st->codec->time_base.num != 0) {
  1126. int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
  1127. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1128. ist->st->codec->time_base.num * ticks) /
  1129. ist->st->codec->time_base.den;
  1130. }
  1131. break;
  1132. }
  1133. }
  1134. for (i = 0; pkt && i < nb_output_streams; i++) {
  1135. OutputStream *ost = output_streams[i];
  1136. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1137. continue;
  1138. do_streamcopy(ist, ost, pkt);
  1139. }
  1140. return 0;
  1141. }
  1142. static void print_sdp(void)
  1143. {
  1144. char sdp[16384];
  1145. int i;
  1146. AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
  1147. if (!avc)
  1148. exit(1);
  1149. for (i = 0; i < nb_output_files; i++)
  1150. avc[i] = output_files[i]->ctx;
  1151. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1152. printf("SDP:\n%s\n", sdp);
  1153. fflush(stdout);
  1154. av_freep(&avc);
  1155. }
  1156. static int init_input_stream(int ist_index, char *error, int error_len)
  1157. {
  1158. int i, ret;
  1159. InputStream *ist = input_streams[ist_index];
  1160. if (ist->decoding_needed) {
  1161. AVCodec *codec = ist->dec;
  1162. if (!codec) {
  1163. snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
  1164. ist->st->codec->codec_id, ist->file_index, ist->st->index);
  1165. return AVERROR(EINVAL);
  1166. }
  1167. /* update requested sample format for the decoder based on the
  1168. corresponding encoder sample format */
  1169. for (i = 0; i < nb_output_streams; i++) {
  1170. OutputStream *ost = output_streams[i];
  1171. if (ost->source_index == ist_index) {
  1172. update_sample_fmt(ist->st->codec, codec, ost->st->codec);
  1173. break;
  1174. }
  1175. }
  1176. av_opt_set_int(ist->st->codec, "refcounted_frames", 1, 0);
  1177. if (!av_dict_get(ist->opts, "threads", NULL, 0))
  1178. av_dict_set(&ist->opts, "threads", "auto", 0);
  1179. if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
  1180. if (ret == AVERROR_EXPERIMENTAL)
  1181. abort_codec_experimental(codec, 0);
  1182. snprintf(error, error_len, "Error while opening decoder for input stream #%d:%d",
  1183. ist->file_index, ist->st->index);
  1184. return ret;
  1185. }
  1186. assert_avoptions(ist->opts);
  1187. }
  1188. ist->last_dts = ist->st->avg_frame_rate.num ? - ist->st->codec->has_b_frames * AV_TIME_BASE / av_q2d(ist->st->avg_frame_rate) : 0;
  1189. ist->next_dts = AV_NOPTS_VALUE;
  1190. init_pts_correction(&ist->pts_ctx);
  1191. ist->is_start = 1;
  1192. return 0;
  1193. }
  1194. static InputStream *get_input_stream(OutputStream *ost)
  1195. {
  1196. if (ost->source_index >= 0)
  1197. return input_streams[ost->source_index];
  1198. if (ost->filter) {
  1199. FilterGraph *fg = ost->filter->graph;
  1200. int i;
  1201. for (i = 0; i < fg->nb_inputs; i++)
  1202. if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
  1203. return fg->inputs[i]->ist;
  1204. }
  1205. return NULL;
  1206. }
  1207. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1208. AVCodecContext *avctx)
  1209. {
  1210. char *p;
  1211. int n = 1, i;
  1212. int64_t t;
  1213. for (p = kf; *p; p++)
  1214. if (*p == ',')
  1215. n++;
  1216. ost->forced_kf_count = n;
  1217. ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
  1218. if (!ost->forced_kf_pts) {
  1219. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1220. exit(1);
  1221. }
  1222. p = kf;
  1223. for (i = 0; i < n; i++) {
  1224. char *next = strchr(p, ',');
  1225. if (next)
  1226. *next++ = 0;
  1227. t = parse_time_or_die("force_key_frames", p, 1);
  1228. ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1229. p = next;
  1230. }
  1231. }
  1232. static int transcode_init(void)
  1233. {
  1234. int ret = 0, i, j, k;
  1235. AVFormatContext *oc;
  1236. AVCodecContext *codec;
  1237. OutputStream *ost;
  1238. InputStream *ist;
  1239. char error[1024];
  1240. int want_sdp = 1;
  1241. /* init framerate emulation */
  1242. for (i = 0; i < nb_input_files; i++) {
  1243. InputFile *ifile = input_files[i];
  1244. if (ifile->rate_emu)
  1245. for (j = 0; j < ifile->nb_streams; j++)
  1246. input_streams[j + ifile->ist_index]->start = av_gettime();
  1247. }
  1248. /* output stream init */
  1249. for (i = 0; i < nb_output_files; i++) {
  1250. oc = output_files[i]->ctx;
  1251. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  1252. av_dump_format(oc, i, oc->filename, 1);
  1253. av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
  1254. return AVERROR(EINVAL);
  1255. }
  1256. }
  1257. /* init complex filtergraphs */
  1258. for (i = 0; i < nb_filtergraphs; i++)
  1259. if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
  1260. return ret;
  1261. /* for each output stream, we compute the right encoding parameters */
  1262. for (i = 0; i < nb_output_streams; i++) {
  1263. AVCodecContext *icodec = NULL;
  1264. ost = output_streams[i];
  1265. oc = output_files[ost->file_index]->ctx;
  1266. ist = get_input_stream(ost);
  1267. if (ost->attachment_filename)
  1268. continue;
  1269. codec = ost->st->codec;
  1270. if (ist) {
  1271. icodec = ist->st->codec;
  1272. ost->st->disposition = ist->st->disposition;
  1273. codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
  1274. codec->chroma_sample_location = icodec->chroma_sample_location;
  1275. }
  1276. if (ost->stream_copy) {
  1277. uint64_t extra_size;
  1278. av_assert0(ist && !ost->filter);
  1279. extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
  1280. if (extra_size > INT_MAX) {
  1281. return AVERROR(EINVAL);
  1282. }
  1283. /* if stream_copy is selected, no need to decode or encode */
  1284. codec->codec_id = icodec->codec_id;
  1285. codec->codec_type = icodec->codec_type;
  1286. if (!codec->codec_tag) {
  1287. if (!oc->oformat->codec_tag ||
  1288. av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
  1289. av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
  1290. codec->codec_tag = icodec->codec_tag;
  1291. }
  1292. codec->bit_rate = icodec->bit_rate;
  1293. codec->rc_max_rate = icodec->rc_max_rate;
  1294. codec->rc_buffer_size = icodec->rc_buffer_size;
  1295. codec->field_order = icodec->field_order;
  1296. codec->extradata = av_mallocz(extra_size);
  1297. if (!codec->extradata) {
  1298. return AVERROR(ENOMEM);
  1299. }
  1300. memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
  1301. codec->extradata_size = icodec->extradata_size;
  1302. if (!copy_tb) {
  1303. codec->time_base = icodec->time_base;
  1304. codec->time_base.num *= icodec->ticks_per_frame;
  1305. av_reduce(&codec->time_base.num, &codec->time_base.den,
  1306. codec->time_base.num, codec->time_base.den, INT_MAX);
  1307. } else
  1308. codec->time_base = ist->st->time_base;
  1309. switch (codec->codec_type) {
  1310. case AVMEDIA_TYPE_AUDIO:
  1311. if (audio_volume != 256) {
  1312. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  1313. exit(1);
  1314. }
  1315. codec->channel_layout = icodec->channel_layout;
  1316. codec->sample_rate = icodec->sample_rate;
  1317. codec->channels = icodec->channels;
  1318. codec->frame_size = icodec->frame_size;
  1319. codec->audio_service_type = icodec->audio_service_type;
  1320. codec->block_align = icodec->block_align;
  1321. break;
  1322. case AVMEDIA_TYPE_VIDEO:
  1323. codec->pix_fmt = icodec->pix_fmt;
  1324. codec->width = icodec->width;
  1325. codec->height = icodec->height;
  1326. codec->has_b_frames = icodec->has_b_frames;
  1327. if (!codec->sample_aspect_ratio.num) {
  1328. codec->sample_aspect_ratio =
  1329. ost->st->sample_aspect_ratio =
  1330. ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :
  1331. ist->st->codec->sample_aspect_ratio.num ?
  1332. ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};
  1333. }
  1334. break;
  1335. case AVMEDIA_TYPE_SUBTITLE:
  1336. codec->width = icodec->width;
  1337. codec->height = icodec->height;
  1338. break;
  1339. case AVMEDIA_TYPE_DATA:
  1340. case AVMEDIA_TYPE_ATTACHMENT:
  1341. break;
  1342. default:
  1343. abort();
  1344. }
  1345. } else {
  1346. if (!ost->enc) {
  1347. /* should only happen when a default codec is not present. */
  1348. snprintf(error, sizeof(error), "Automatic encoder selection "
  1349. "failed for output stream #%d:%d. Default encoder for "
  1350. "format %s is probably disabled. Please choose an "
  1351. "encoder manually.\n", ost->file_index, ost->index,
  1352. oc->oformat->name);
  1353. ret = AVERROR(EINVAL);
  1354. goto dump_format;
  1355. }
  1356. if (ist)
  1357. ist->decoding_needed = 1;
  1358. ost->encoding_needed = 1;
  1359. /*
  1360. * We want CFR output if and only if one of those is true:
  1361. * 1) user specified output framerate with -r
  1362. * 2) user specified -vsync cfr
  1363. * 3) output format is CFR and the user didn't force vsync to
  1364. * something else than CFR
  1365. *
  1366. * in such a case, set ost->frame_rate
  1367. */
  1368. if (codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  1369. !ost->frame_rate.num && ist &&
  1370. (video_sync_method == VSYNC_CFR ||
  1371. (video_sync_method == VSYNC_AUTO &&
  1372. !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {
  1373. ost->frame_rate = ist->framerate.num ? ist->framerate :
  1374. ist->st->avg_frame_rate.num ?
  1375. ist->st->avg_frame_rate :
  1376. (AVRational){25, 1};
  1377. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  1378. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  1379. ost->frame_rate = ost->enc->supported_framerates[idx];
  1380. }
  1381. }
  1382. if (!ost->filter &&
  1383. (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  1384. codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
  1385. FilterGraph *fg;
  1386. fg = init_simple_filtergraph(ist, ost);
  1387. if (configure_filtergraph(fg)) {
  1388. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  1389. exit(1);
  1390. }
  1391. }
  1392. switch (codec->codec_type) {
  1393. case AVMEDIA_TYPE_AUDIO:
  1394. codec->sample_fmt = ost->filter->filter->inputs[0]->format;
  1395. codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  1396. codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  1397. codec->channels = av_get_channel_layout_nb_channels(codec->channel_layout);
  1398. codec->time_base = (AVRational){ 1, codec->sample_rate };
  1399. break;
  1400. case AVMEDIA_TYPE_VIDEO:
  1401. codec->time_base = ost->filter->filter->inputs[0]->time_base;
  1402. codec->width = ost->filter->filter->inputs[0]->w;
  1403. codec->height = ost->filter->filter->inputs[0]->h;
  1404. codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  1405. ost->frame_aspect_ratio ? // overridden by the -aspect cli option
  1406. av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
  1407. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  1408. codec->pix_fmt = ost->filter->filter->inputs[0]->format;
  1409. if (icodec &&
  1410. (codec->width != icodec->width ||
  1411. codec->height != icodec->height ||
  1412. codec->pix_fmt != icodec->pix_fmt)) {
  1413. codec->bits_per_raw_sample = 0;
  1414. }
  1415. if (ost->forced_keyframes)
  1416. parse_forced_key_frames(ost->forced_keyframes, ost,
  1417. ost->st->codec);
  1418. break;
  1419. case AVMEDIA_TYPE_SUBTITLE:
  1420. codec->time_base = (AVRational){1, 1000};
  1421. break;
  1422. default:
  1423. abort();
  1424. break;
  1425. }
  1426. /* two pass mode */
  1427. if ((codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
  1428. char logfilename[1024];
  1429. FILE *f;
  1430. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  1431. ost->logfile_prefix ? ost->logfile_prefix :
  1432. DEFAULT_PASS_LOGFILENAME_PREFIX,
  1433. i);
  1434. if (!strcmp(ost->enc->name, "libx264")) {
  1435. av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  1436. } else {
  1437. if (codec->flags & CODEC_FLAG_PASS1) {
  1438. f = fopen(logfilename, "wb");
  1439. if (!f) {
  1440. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
  1441. logfilename, strerror(errno));
  1442. exit(1);
  1443. }
  1444. ost->logfile = f;
  1445. } else {
  1446. char *logbuffer;
  1447. size_t logbuffer_size;
  1448. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
  1449. av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  1450. logfilename);
  1451. exit(1);
  1452. }
  1453. codec->stats_in = logbuffer;
  1454. }
  1455. }
  1456. }
  1457. }
  1458. }
  1459. /* open each encoder */
  1460. for (i = 0; i < nb_output_streams; i++) {
  1461. ost = output_streams[i];
  1462. if (ost->encoding_needed) {
  1463. AVCodec *codec = ost->enc;
  1464. AVCodecContext *dec = NULL;
  1465. if ((ist = get_input_stream(ost)))
  1466. dec = ist->st->codec;
  1467. if (dec && dec->subtitle_header) {
  1468. ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
  1469. if (!ost->st->codec->subtitle_header) {
  1470. ret = AVERROR(ENOMEM);
  1471. goto dump_format;
  1472. }
  1473. memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  1474. ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
  1475. }
  1476. if (!av_dict_get(ost->opts, "threads", NULL, 0))
  1477. av_dict_set(&ost->opts, "threads", "auto", 0);
  1478. if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
  1479. if (ret == AVERROR_EXPERIMENTAL)
  1480. abort_codec_experimental(codec, 1);
  1481. snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
  1482. ost->file_index, ost->index);
  1483. goto dump_format;
  1484. }
  1485. assert_avoptions(ost->opts);
  1486. if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
  1487. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  1488. "It takes bits/s as argument, not kbits/s\n");
  1489. extra_size += ost->st->codec->extradata_size;
  1490. if (ost->st->codec->me_threshold)
  1491. input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;
  1492. } else {
  1493. av_opt_set_dict(ost->st->codec, &ost->opts);
  1494. }
  1495. }
  1496. /* init input streams */
  1497. for (i = 0; i < nb_input_streams; i++)
  1498. if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
  1499. goto dump_format;
  1500. /* discard unused programs */
  1501. for (i = 0; i < nb_input_files; i++) {
  1502. InputFile *ifile = input_files[i];
  1503. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  1504. AVProgram *p = ifile->ctx->programs[j];
  1505. int discard = AVDISCARD_ALL;
  1506. for (k = 0; k < p->nb_stream_indexes; k++)
  1507. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  1508. discard = AVDISCARD_DEFAULT;
  1509. break;
  1510. }
  1511. p->discard = discard;
  1512. }
  1513. }
  1514. /* open files and write file headers */
  1515. for (i = 0; i < nb_output_files; i++) {
  1516. oc = output_files[i]->ctx;
  1517. oc->interrupt_callback = int_cb;
  1518. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  1519. char errbuf[128];
  1520. const char *errbuf_ptr = errbuf;
  1521. if (av_strerror(ret, errbuf, sizeof(errbuf)) < 0)
  1522. errbuf_ptr = strerror(AVUNERROR(ret));
  1523. snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?): %s", i, errbuf_ptr);
  1524. ret = AVERROR(EINVAL);
  1525. goto dump_format;
  1526. }
  1527. assert_avoptions(output_files[i]->opts);
  1528. if (strcmp(oc->oformat->name, "rtp")) {
  1529. want_sdp = 0;
  1530. }
  1531. }
  1532. dump_format:
  1533. /* dump the file output parameters - cannot be done before in case
  1534. of stream copy */
  1535. for (i = 0; i < nb_output_files; i++) {
  1536. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  1537. }
  1538. /* dump the stream mapping */
  1539. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  1540. for (i = 0; i < nb_input_streams; i++) {
  1541. ist = input_streams[i];
  1542. for (j = 0; j < ist->nb_filters; j++) {
  1543. if (ist->filters[j]->graph->graph_desc) {
  1544. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  1545. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  1546. ist->filters[j]->name);
  1547. if (nb_filtergraphs > 1)
  1548. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  1549. av_log(NULL, AV_LOG_INFO, "\n");
  1550. }
  1551. }
  1552. }
  1553. for (i = 0; i < nb_output_streams; i++) {
  1554. ost = output_streams[i];
  1555. if (ost->attachment_filename) {
  1556. /* an attached file */
  1557. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  1558. ost->attachment_filename, ost->file_index, ost->index);
  1559. continue;
  1560. }
  1561. if (ost->filter && ost->filter->graph->graph_desc) {
  1562. /* output from a complex graph */
  1563. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  1564. if (nb_filtergraphs > 1)
  1565. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  1566. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  1567. ost->index, ost->enc ? ost->enc->name : "?");
  1568. continue;
  1569. }
  1570. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  1571. input_streams[ost->source_index]->file_index,
  1572. input_streams[ost->source_index]->st->index,
  1573. ost->file_index,
  1574. ost->index);
  1575. if (ost->sync_ist != input_streams[ost->source_index])
  1576. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  1577. ost->sync_ist->file_index,
  1578. ost->sync_ist->st->index);
  1579. if (ost->stream_copy)
  1580. av_log(NULL, AV_LOG_INFO, " (copy)");
  1581. else
  1582. av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
  1583. input_streams[ost->source_index]->dec->name : "?",
  1584. ost->enc ? ost->enc->name : "?");
  1585. av_log(NULL, AV_LOG_INFO, "\n");
  1586. }
  1587. if (ret) {
  1588. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  1589. return ret;
  1590. }
  1591. if (want_sdp) {
  1592. print_sdp();
  1593. }
  1594. return 0;
  1595. }
  1596. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  1597. static int need_output(void)
  1598. {
  1599. int i;
  1600. for (i = 0; i < nb_output_streams; i++) {
  1601. OutputStream *ost = output_streams[i];
  1602. OutputFile *of = output_files[ost->file_index];
  1603. AVFormatContext *os = output_files[ost->file_index]->ctx;
  1604. if (ost->finished ||
  1605. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  1606. continue;
  1607. if (ost->frame_number >= ost->max_frames) {
  1608. int j;
  1609. for (j = 0; j < of->ctx->nb_streams; j++)
  1610. output_streams[of->ost_index + j]->finished = 1;
  1611. continue;
  1612. }
  1613. return 1;
  1614. }
  1615. return 0;
  1616. }
  1617. static InputFile *select_input_file(void)
  1618. {
  1619. InputFile *ifile = NULL;
  1620. int64_t ipts_min = INT64_MAX;
  1621. int i;
  1622. for (i = 0; i < nb_input_streams; i++) {
  1623. InputStream *ist = input_streams[i];
  1624. int64_t ipts = ist->last_dts;
  1625. if (ist->discard || input_files[ist->file_index]->eagain)
  1626. continue;
  1627. if (!input_files[ist->file_index]->eof_reached) {
  1628. if (ipts < ipts_min) {
  1629. ipts_min = ipts;
  1630. ifile = input_files[ist->file_index];
  1631. }
  1632. }
  1633. }
  1634. return ifile;
  1635. }
  1636. #if HAVE_PTHREADS
  1637. static void *input_thread(void *arg)
  1638. {
  1639. InputFile *f = arg;
  1640. int ret = 0;
  1641. while (!transcoding_finished && ret >= 0) {
  1642. AVPacket pkt;
  1643. ret = av_read_frame(f->ctx, &pkt);
  1644. if (ret == AVERROR(EAGAIN)) {
  1645. av_usleep(10000);
  1646. ret = 0;
  1647. continue;
  1648. } else if (ret < 0)
  1649. break;
  1650. pthread_mutex_lock(&f->fifo_lock);
  1651. while (!av_fifo_space(f->fifo))
  1652. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  1653. av_dup_packet(&pkt);
  1654. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  1655. pthread_mutex_unlock(&f->fifo_lock);
  1656. }
  1657. f->finished = 1;
  1658. return NULL;
  1659. }
  1660. static void free_input_threads(void)
  1661. {
  1662. int i;
  1663. if (nb_input_files == 1)
  1664. return;
  1665. transcoding_finished = 1;
  1666. for (i = 0; i < nb_input_files; i++) {
  1667. InputFile *f = input_files[i];
  1668. AVPacket pkt;
  1669. if (!f->fifo || f->joined)
  1670. continue;
  1671. pthread_mutex_lock(&f->fifo_lock);
  1672. while (av_fifo_size(f->fifo)) {
  1673. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  1674. av_free_packet(&pkt);
  1675. }
  1676. pthread_cond_signal(&f->fifo_cond);
  1677. pthread_mutex_unlock(&f->fifo_lock);
  1678. pthread_join(f->thread, NULL);
  1679. f->joined = 1;
  1680. while (av_fifo_size(f->fifo)) {
  1681. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  1682. av_free_packet(&pkt);
  1683. }
  1684. av_fifo_free(f->fifo);
  1685. }
  1686. }
  1687. static int init_input_threads(void)
  1688. {
  1689. int i, ret;
  1690. if (nb_input_files == 1)
  1691. return 0;
  1692. for (i = 0; i < nb_input_files; i++) {
  1693. InputFile *f = input_files[i];
  1694. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  1695. return AVERROR(ENOMEM);
  1696. pthread_mutex_init(&f->fifo_lock, NULL);
  1697. pthread_cond_init (&f->fifo_cond, NULL);
  1698. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  1699. return AVERROR(ret);
  1700. }
  1701. return 0;
  1702. }
  1703. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  1704. {
  1705. int ret = 0;
  1706. pthread_mutex_lock(&f->fifo_lock);
  1707. if (av_fifo_size(f->fifo)) {
  1708. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  1709. pthread_cond_signal(&f->fifo_cond);
  1710. } else {
  1711. if (f->finished)
  1712. ret = AVERROR_EOF;
  1713. else
  1714. ret = AVERROR(EAGAIN);
  1715. }
  1716. pthread_mutex_unlock(&f->fifo_lock);
  1717. return ret;
  1718. }
  1719. #endif
  1720. static int get_input_packet(InputFile *f, AVPacket *pkt)
  1721. {
  1722. if (f->rate_emu) {
  1723. int i;
  1724. for (i = 0; i < f->nb_streams; i++) {
  1725. InputStream *ist = input_streams[f->ist_index + i];
  1726. int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
  1727. int64_t now = av_gettime() - ist->start;
  1728. if (pts > now)
  1729. return AVERROR(EAGAIN);
  1730. }
  1731. }
  1732. #if HAVE_PTHREADS
  1733. if (nb_input_files > 1)
  1734. return get_input_packet_mt(f, pkt);
  1735. #endif
  1736. return av_read_frame(f->ctx, pkt);
  1737. }
  1738. static int got_eagain(void)
  1739. {
  1740. int i;
  1741. for (i = 0; i < nb_input_files; i++)
  1742. if (input_files[i]->eagain)
  1743. return 1;
  1744. return 0;
  1745. }
  1746. static void reset_eagain(void)
  1747. {
  1748. int i;
  1749. for (i = 0; i < nb_input_files; i++)
  1750. input_files[i]->eagain = 0;
  1751. }
  1752. /*
  1753. * Read one packet from an input file and send it for
  1754. * - decoding -> lavfi (audio/video)
  1755. * - decoding -> encoding -> muxing (subtitles)
  1756. * - muxing (streamcopy)
  1757. *
  1758. * Return
  1759. * - 0 -- one packet was read and processed
  1760. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  1761. * this function should be called again
  1762. * - AVERROR_EOF -- this function should not be called again
  1763. */
  1764. static int process_input(void)
  1765. {
  1766. InputFile *ifile;
  1767. AVFormatContext *is;
  1768. InputStream *ist;
  1769. AVPacket pkt;
  1770. int ret, i, j;
  1771. /* select the stream that we must read now */
  1772. ifile = select_input_file();
  1773. /* if none, if is finished */
  1774. if (!ifile) {
  1775. if (got_eagain()) {
  1776. reset_eagain();
  1777. av_usleep(10000);
  1778. return AVERROR(EAGAIN);
  1779. }
  1780. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from.\n");
  1781. return AVERROR_EOF;
  1782. }
  1783. is = ifile->ctx;
  1784. ret = get_input_packet(ifile, &pkt);
  1785. if (ret == AVERROR(EAGAIN)) {
  1786. ifile->eagain = 1;
  1787. return ret;
  1788. }
  1789. if (ret < 0) {
  1790. if (ret != AVERROR_EOF) {
  1791. print_error(is->filename, ret);
  1792. if (exit_on_error)
  1793. exit(1);
  1794. }
  1795. ifile->eof_reached = 1;
  1796. for (i = 0; i < ifile->nb_streams; i++) {
  1797. ist = input_streams[ifile->ist_index + i];
  1798. if (ist->decoding_needed)
  1799. output_packet(ist, NULL);
  1800. /* mark all outputs that don't go through lavfi as finished */
  1801. for (j = 0; j < nb_output_streams; j++) {
  1802. OutputStream *ost = output_streams[j];
  1803. if (ost->source_index == ifile->ist_index + i &&
  1804. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  1805. ost->finished= 1;
  1806. }
  1807. }
  1808. return AVERROR(EAGAIN);
  1809. }
  1810. reset_eagain();
  1811. if (do_pkt_dump) {
  1812. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  1813. is->streams[pkt.stream_index]);
  1814. }
  1815. /* the following test is needed in case new streams appear
  1816. dynamically in stream : we ignore them */
  1817. if (pkt.stream_index >= ifile->nb_streams)
  1818. goto discard_packet;
  1819. ist = input_streams[ifile->ist_index + pkt.stream_index];
  1820. if (ist->discard)
  1821. goto discard_packet;
  1822. if (pkt.dts != AV_NOPTS_VALUE)
  1823. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  1824. if (pkt.pts != AV_NOPTS_VALUE)
  1825. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  1826. if (pkt.pts != AV_NOPTS_VALUE)
  1827. pkt.pts *= ist->ts_scale;
  1828. if (pkt.dts != AV_NOPTS_VALUE)
  1829. pkt.dts *= ist->ts_scale;
  1830. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  1831. (is->iformat->flags & AVFMT_TS_DISCONT)) {
  1832. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  1833. int64_t delta = pkt_dts - ist->next_dts;
  1834. if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
  1835. ifile->ts_offset -= delta;
  1836. av_log(NULL, AV_LOG_DEBUG,
  1837. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  1838. delta, ifile->ts_offset);
  1839. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  1840. if (pkt.pts != AV_NOPTS_VALUE)
  1841. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  1842. }
  1843. }
  1844. ret = output_packet(ist, &pkt);
  1845. if (ret < 0) {
  1846. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
  1847. ist->file_index, ist->st->index);
  1848. if (exit_on_error)
  1849. exit(1);
  1850. }
  1851. discard_packet:
  1852. av_free_packet(&pkt);
  1853. return 0;
  1854. }
  1855. /*
  1856. * The following code is the main loop of the file converter
  1857. */
  1858. static int transcode(void)
  1859. {
  1860. int ret, i, need_input = 1;
  1861. AVFormatContext *os;
  1862. OutputStream *ost;
  1863. InputStream *ist;
  1864. int64_t timer_start;
  1865. ret = transcode_init();
  1866. if (ret < 0)
  1867. goto fail;
  1868. av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
  1869. term_init();
  1870. timer_start = av_gettime();
  1871. #if HAVE_PTHREADS
  1872. if ((ret = init_input_threads()) < 0)
  1873. goto fail;
  1874. #endif
  1875. while (!received_sigterm) {
  1876. /* check if there's any stream where output is still needed */
  1877. if (!need_output()) {
  1878. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  1879. break;
  1880. }
  1881. /* read and process one input packet if needed */
  1882. if (need_input) {
  1883. ret = process_input();
  1884. if (ret == AVERROR_EOF)
  1885. need_input = 0;
  1886. }
  1887. ret = poll_filters();
  1888. if (ret < 0) {
  1889. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  1890. continue;
  1891. av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
  1892. break;
  1893. }
  1894. /* dump report by using the output first video and audio streams */
  1895. print_report(0, timer_start);
  1896. }
  1897. #if HAVE_PTHREADS
  1898. free_input_threads();
  1899. #endif
  1900. /* at the end of stream, we must flush the decoder buffers */
  1901. for (i = 0; i < nb_input_streams; i++) {
  1902. ist = input_streams[i];
  1903. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  1904. output_packet(ist, NULL);
  1905. }
  1906. }
  1907. poll_filters();
  1908. flush_encoders();
  1909. term_exit();
  1910. /* write the trailer if needed and close file */
  1911. for (i = 0; i < nb_output_files; i++) {
  1912. os = output_files[i]->ctx;
  1913. av_write_trailer(os);
  1914. }
  1915. /* dump report by using the first video and audio streams */
  1916. print_report(1, timer_start);
  1917. /* close each encoder */
  1918. for (i = 0; i < nb_output_streams; i++) {
  1919. ost = output_streams[i];
  1920. if (ost->encoding_needed) {
  1921. av_freep(&ost->st->codec->stats_in);
  1922. avcodec_close(ost->st->codec);
  1923. }
  1924. }
  1925. /* close each decoder */
  1926. for (i = 0; i < nb_input_streams; i++) {
  1927. ist = input_streams[i];
  1928. if (ist->decoding_needed) {
  1929. avcodec_close(ist->st->codec);
  1930. }
  1931. }
  1932. /* finished ! */
  1933. ret = 0;
  1934. fail:
  1935. #if HAVE_PTHREADS
  1936. free_input_threads();
  1937. #endif
  1938. if (output_streams) {
  1939. for (i = 0; i < nb_output_streams; i++) {
  1940. ost = output_streams[i];
  1941. if (ost) {
  1942. if (ost->stream_copy)
  1943. av_freep(&ost->st->codec->extradata);
  1944. if (ost->logfile) {
  1945. fclose(ost->logfile);
  1946. ost->logfile = NULL;
  1947. }
  1948. av_freep(&ost->st->codec->subtitle_header);
  1949. av_free(ost->forced_kf_pts);
  1950. av_dict_free(&ost->opts);
  1951. av_dict_free(&ost->resample_opts);
  1952. }
  1953. }
  1954. }
  1955. return ret;
  1956. }
  1957. static int64_t getutime(void)
  1958. {
  1959. #if HAVE_GETRUSAGE
  1960. struct rusage rusage;
  1961. getrusage(RUSAGE_SELF, &rusage);
  1962. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  1963. #elif HAVE_GETPROCESSTIMES
  1964. HANDLE proc;
  1965. FILETIME c, e, k, u;
  1966. proc = GetCurrentProcess();
  1967. GetProcessTimes(proc, &c, &e, &k, &u);
  1968. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  1969. #else
  1970. return av_gettime();
  1971. #endif
  1972. }
  1973. static int64_t getmaxrss(void)
  1974. {
  1975. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  1976. struct rusage rusage;
  1977. getrusage(RUSAGE_SELF, &rusage);
  1978. return (int64_t)rusage.ru_maxrss * 1024;
  1979. #elif HAVE_GETPROCESSMEMORYINFO
  1980. HANDLE proc;
  1981. PROCESS_MEMORY_COUNTERS memcounters;
  1982. proc = GetCurrentProcess();
  1983. memcounters.cb = sizeof(memcounters);
  1984. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  1985. return memcounters.PeakPagefileUsage;
  1986. #else
  1987. return 0;
  1988. #endif
  1989. }
  1990. int main(int argc, char **argv)
  1991. {
  1992. int ret;
  1993. int64_t ti;
  1994. atexit(exit_program);
  1995. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  1996. parse_loglevel(argc, argv, options);
  1997. avcodec_register_all();
  1998. #if CONFIG_AVDEVICE
  1999. avdevice_register_all();
  2000. #endif
  2001. avfilter_register_all();
  2002. av_register_all();
  2003. avformat_network_init();
  2004. show_banner();
  2005. /* parse options and open all input/output files */
  2006. ret = avconv_parse_options(argc, argv);
  2007. if (ret < 0)
  2008. exit(1);
  2009. if (nb_output_files <= 0 && nb_input_files == 0) {
  2010. show_usage();
  2011. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  2012. exit(1);
  2013. }
  2014. /* file converter / grab */
  2015. if (nb_output_files <= 0) {
  2016. fprintf(stderr, "At least one output file must be specified\n");
  2017. exit(1);
  2018. }
  2019. ti = getutime();
  2020. if (transcode() < 0)
  2021. exit(1);
  2022. ti = getutime() - ti;
  2023. if (do_benchmark) {
  2024. int maxrss = getmaxrss() / 1024;
  2025. printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
  2026. }
  2027. exit(0);
  2028. return 0;
  2029. }