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.

2391 lines
79KB

  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/fifo.h"
  38. #include "libavutil/intreadwrite.h"
  39. #include "libavutil/dict.h"
  40. #include "libavutil/mathematics.h"
  41. #include "libavutil/pixdesc.h"
  42. #include "libavutil/avstring.h"
  43. #include "libavutil/libm.h"
  44. #include "libavutil/imgutils.h"
  45. #include "libavutil/time.h"
  46. #include "libavformat/os_support.h"
  47. # include "libavfilter/avfilter.h"
  48. # include "libavfilter/buffersrc.h"
  49. # include "libavfilter/buffersink.h"
  50. #if HAVE_SYS_RESOURCE_H
  51. #include <sys/time.h>
  52. #include <sys/types.h>
  53. #include <sys/resource.h>
  54. #elif HAVE_GETPROCESSTIMES
  55. #include <windows.h>
  56. #endif
  57. #if HAVE_GETPROCESSMEMORYINFO
  58. #include <windows.h>
  59. #include <psapi.h>
  60. #endif
  61. #if HAVE_SYS_SELECT_H
  62. #include <sys/select.h>
  63. #endif
  64. #if HAVE_PTHREADS
  65. #include <pthread.h>
  66. #endif
  67. #include <time.h>
  68. #include "avconv.h"
  69. #include "cmdutils.h"
  70. #include "libavutil/avassert.h"
  71. const char program_name[] = "avconv";
  72. const int program_birth_year = 2000;
  73. static FILE *vstats_file;
  74. static int64_t video_size = 0;
  75. static int64_t audio_size = 0;
  76. static int64_t extra_size = 0;
  77. static int nb_frames_dup = 0;
  78. static int nb_frames_drop = 0;
  79. #if HAVE_PTHREADS
  80. /* signal to input threads that they should exit; set by the main thread */
  81. static int transcoding_finished;
  82. #endif
  83. #define DEFAULT_PASS_LOGFILENAME_PREFIX "av2pass"
  84. InputStream **input_streams = NULL;
  85. int nb_input_streams = 0;
  86. InputFile **input_files = NULL;
  87. int nb_input_files = 0;
  88. OutputStream **output_streams = NULL;
  89. int nb_output_streams = 0;
  90. OutputFile **output_files = NULL;
  91. int nb_output_files = 0;
  92. FilterGraph **filtergraphs;
  93. int nb_filtergraphs;
  94. static void term_exit(void)
  95. {
  96. av_log(NULL, AV_LOG_QUIET, "");
  97. }
  98. static volatile int received_sigterm = 0;
  99. static volatile int received_nb_signals = 0;
  100. static void
  101. sigterm_handler(int sig)
  102. {
  103. received_sigterm = sig;
  104. received_nb_signals++;
  105. term_exit();
  106. }
  107. static void term_init(void)
  108. {
  109. signal(SIGINT , sigterm_handler); /* Interrupt (ANSI). */
  110. signal(SIGTERM, sigterm_handler); /* Termination (ANSI). */
  111. #ifdef SIGXCPU
  112. signal(SIGXCPU, sigterm_handler);
  113. #endif
  114. }
  115. static int decode_interrupt_cb(void *ctx)
  116. {
  117. return received_nb_signals > 1;
  118. }
  119. const AVIOInterruptCB int_cb = { decode_interrupt_cb, NULL };
  120. static void avconv_cleanup(int ret)
  121. {
  122. int i, j;
  123. for (i = 0; i < nb_filtergraphs; i++) {
  124. avfilter_graph_free(&filtergraphs[i]->graph);
  125. for (j = 0; j < filtergraphs[i]->nb_inputs; j++) {
  126. av_freep(&filtergraphs[i]->inputs[j]->name);
  127. av_freep(&filtergraphs[i]->inputs[j]);
  128. }
  129. av_freep(&filtergraphs[i]->inputs);
  130. for (j = 0; j < filtergraphs[i]->nb_outputs; j++) {
  131. av_freep(&filtergraphs[i]->outputs[j]->name);
  132. av_freep(&filtergraphs[i]->outputs[j]);
  133. }
  134. av_freep(&filtergraphs[i]->outputs);
  135. av_freep(&filtergraphs[i]->graph_desc);
  136. av_freep(&filtergraphs[i]);
  137. }
  138. av_freep(&filtergraphs);
  139. /* close files */
  140. for (i = 0; i < nb_output_files; i++) {
  141. AVFormatContext *s = output_files[i]->ctx;
  142. if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE) && s->pb)
  143. avio_close(s->pb);
  144. avformat_free_context(s);
  145. av_dict_free(&output_files[i]->opts);
  146. av_freep(&output_files[i]);
  147. }
  148. for (i = 0; i < nb_output_streams; i++) {
  149. AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;
  150. while (bsfc) {
  151. AVBitStreamFilterContext *next = bsfc->next;
  152. av_bitstream_filter_close(bsfc);
  153. bsfc = next;
  154. }
  155. output_streams[i]->bitstream_filters = NULL;
  156. avcodec_free_frame(&output_streams[i]->filtered_frame);
  157. av_parser_close(output_streams[i]->parser);
  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_program(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_program(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_program(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_program(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_program(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_program(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_program(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_program(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_program(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_program(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_program(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. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  569. filtered_frame->pts = av_rescale_q(filtered_frame->pts,
  570. ost->filter->filter->inputs[0]->time_base,
  571. ost->st->codec->time_base) -
  572. av_rescale_q(start_time,
  573. AV_TIME_BASE_Q,
  574. ost->st->codec->time_base);
  575. }
  576. switch (ost->filter->filter->inputs[0]->type) {
  577. case AVMEDIA_TYPE_VIDEO:
  578. if (!ost->frame_aspect_ratio)
  579. ost->st->codec->sample_aspect_ratio = filtered_frame->sample_aspect_ratio;
  580. do_video_out(of->ctx, ost, filtered_frame, &frame_size);
  581. if (vstats_filename && frame_size)
  582. do_video_stats(ost, frame_size);
  583. break;
  584. case AVMEDIA_TYPE_AUDIO:
  585. do_audio_out(of->ctx, ost, filtered_frame);
  586. break;
  587. default:
  588. // TODO support subtitle filters
  589. av_assert0(0);
  590. }
  591. av_frame_unref(filtered_frame);
  592. return 0;
  593. }
  594. /*
  595. * Read as many frames from possible from lavfi and encode them.
  596. *
  597. * Always read from the active stream with the lowest timestamp. If no frames
  598. * are available for it then return EAGAIN and wait for more input. This way we
  599. * can use lavfi sources that generate unlimited amount of frames without memory
  600. * usage exploding.
  601. */
  602. static int poll_filters(void)
  603. {
  604. int i, j, ret = 0;
  605. while (ret >= 0 && !received_sigterm) {
  606. OutputStream *ost = NULL;
  607. int64_t min_pts = INT64_MAX;
  608. /* choose output stream with the lowest timestamp */
  609. for (i = 0; i < nb_output_streams; i++) {
  610. int64_t pts = output_streams[i]->sync_opts;
  611. if (!output_streams[i]->filter || output_streams[i]->finished)
  612. continue;
  613. pts = av_rescale_q(pts, output_streams[i]->st->codec->time_base,
  614. AV_TIME_BASE_Q);
  615. if (pts < min_pts) {
  616. min_pts = pts;
  617. ost = output_streams[i];
  618. }
  619. }
  620. if (!ost)
  621. break;
  622. ret = poll_filter(ost);
  623. if (ret == AVERROR_EOF) {
  624. OutputFile *of = output_files[ost->file_index];
  625. ost->finished = 1;
  626. if (of->shortest) {
  627. for (j = 0; j < of->ctx->nb_streams; j++)
  628. output_streams[of->ost_index + j]->finished = 1;
  629. }
  630. ret = 0;
  631. } else if (ret == AVERROR(EAGAIN))
  632. return 0;
  633. }
  634. return ret;
  635. }
  636. static void print_report(int is_last_report, int64_t timer_start)
  637. {
  638. char buf[1024];
  639. OutputStream *ost;
  640. AVFormatContext *oc;
  641. int64_t total_size;
  642. AVCodecContext *enc;
  643. int frame_number, vid, i;
  644. double bitrate, ti1, pts;
  645. static int64_t last_time = -1;
  646. static int qp_histogram[52];
  647. if (!print_stats && !is_last_report)
  648. return;
  649. if (!is_last_report) {
  650. int64_t cur_time;
  651. /* display the report every 0.5 seconds */
  652. cur_time = av_gettime();
  653. if (last_time == -1) {
  654. last_time = cur_time;
  655. return;
  656. }
  657. if ((cur_time - last_time) < 500000)
  658. return;
  659. last_time = cur_time;
  660. }
  661. oc = output_files[0]->ctx;
  662. total_size = avio_size(oc->pb);
  663. if (total_size <= 0) // FIXME improve avio_size() so it works with non seekable output too
  664. total_size = avio_tell(oc->pb);
  665. if (total_size < 0) {
  666. char errbuf[128];
  667. av_strerror(total_size, errbuf, sizeof(errbuf));
  668. av_log(NULL, AV_LOG_VERBOSE, "Bitrate not available, "
  669. "avio_tell() failed: %s\n", errbuf);
  670. total_size = 0;
  671. }
  672. buf[0] = '\0';
  673. ti1 = 1e10;
  674. vid = 0;
  675. for (i = 0; i < nb_output_streams; i++) {
  676. float q = -1;
  677. ost = output_streams[i];
  678. enc = ost->st->codec;
  679. if (!ost->stream_copy && enc->coded_frame)
  680. q = enc->coded_frame->quality / (float)FF_QP2LAMBDA;
  681. if (vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  682. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "q=%2.1f ", q);
  683. }
  684. if (!vid && enc->codec_type == AVMEDIA_TYPE_VIDEO) {
  685. float t = (av_gettime() - timer_start) / 1000000.0;
  686. frame_number = ost->frame_number;
  687. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "frame=%5d fps=%3d q=%3.1f ",
  688. frame_number, (t > 1) ? (int)(frame_number / t + 0.5) : 0, q);
  689. if (is_last_report)
  690. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "L");
  691. if (qp_hist) {
  692. int j;
  693. int qp = lrintf(q);
  694. if (qp >= 0 && qp < FF_ARRAY_ELEMS(qp_histogram))
  695. qp_histogram[qp]++;
  696. for (j = 0; j < 32; j++)
  697. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%X", (int)lrintf(log2(qp_histogram[j] + 1)));
  698. }
  699. if (enc->flags&CODEC_FLAG_PSNR) {
  700. int j;
  701. double error, error_sum = 0;
  702. double scale, scale_sum = 0;
  703. char type[3] = { 'Y','U','V' };
  704. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "PSNR=");
  705. for (j = 0; j < 3; j++) {
  706. if (is_last_report) {
  707. error = enc->error[j];
  708. scale = enc->width * enc->height * 255.0 * 255.0 * frame_number;
  709. } else {
  710. error = enc->coded_frame->error[j];
  711. scale = enc->width * enc->height * 255.0 * 255.0;
  712. }
  713. if (j)
  714. scale /= 4;
  715. error_sum += error;
  716. scale_sum += scale;
  717. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "%c:%2.2f ", type[j], psnr(error / scale));
  718. }
  719. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), "*:%2.2f ", psnr(error_sum / scale_sum));
  720. }
  721. vid = 1;
  722. }
  723. /* compute min output value */
  724. pts = (double)ost->st->pts.val * av_q2d(ost->st->time_base);
  725. if ((pts < ti1) && (pts > 0))
  726. ti1 = pts;
  727. }
  728. if (ti1 < 0.01)
  729. ti1 = 0.01;
  730. bitrate = (double)(total_size * 8) / ti1 / 1000.0;
  731. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf),
  732. "size=%8.0fkB time=%0.2f bitrate=%6.1fkbits/s",
  733. (double)total_size / 1024, ti1, bitrate);
  734. if (nb_frames_dup || nb_frames_drop)
  735. snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), " dup=%d drop=%d",
  736. nb_frames_dup, nb_frames_drop);
  737. av_log(NULL, AV_LOG_INFO, "%s \r", buf);
  738. fflush(stderr);
  739. if (is_last_report) {
  740. int64_t raw= audio_size + video_size + extra_size;
  741. av_log(NULL, AV_LOG_INFO, "\n");
  742. av_log(NULL, AV_LOG_INFO, "video:%1.0fkB audio:%1.0fkB global headers:%1.0fkB muxing overhead %f%%\n",
  743. video_size / 1024.0,
  744. audio_size / 1024.0,
  745. extra_size / 1024.0,
  746. 100.0 * (total_size - raw) / raw
  747. );
  748. }
  749. }
  750. static void flush_encoders(void)
  751. {
  752. int i, ret;
  753. for (i = 0; i < nb_output_streams; i++) {
  754. OutputStream *ost = output_streams[i];
  755. AVCodecContext *enc = ost->st->codec;
  756. AVFormatContext *os = output_files[ost->file_index]->ctx;
  757. int stop_encoding = 0;
  758. if (!ost->encoding_needed)
  759. continue;
  760. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO && enc->frame_size <= 1)
  761. continue;
  762. if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO && (os->oformat->flags & AVFMT_RAWPICTURE) && enc->codec->id == AV_CODEC_ID_RAWVIDEO)
  763. continue;
  764. for (;;) {
  765. int (*encode)(AVCodecContext*, AVPacket*, const AVFrame*, int*) = NULL;
  766. const char *desc;
  767. int64_t *size;
  768. switch (ost->st->codec->codec_type) {
  769. case AVMEDIA_TYPE_AUDIO:
  770. encode = avcodec_encode_audio2;
  771. desc = "Audio";
  772. size = &audio_size;
  773. break;
  774. case AVMEDIA_TYPE_VIDEO:
  775. encode = avcodec_encode_video2;
  776. desc = "Video";
  777. size = &video_size;
  778. break;
  779. default:
  780. stop_encoding = 1;
  781. }
  782. if (encode) {
  783. AVPacket pkt;
  784. int got_packet;
  785. av_init_packet(&pkt);
  786. pkt.data = NULL;
  787. pkt.size = 0;
  788. ret = encode(enc, &pkt, NULL, &got_packet);
  789. if (ret < 0) {
  790. av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
  791. exit_program(1);
  792. }
  793. *size += ret;
  794. if (ost->logfile && enc->stats_out) {
  795. fprintf(ost->logfile, "%s", enc->stats_out);
  796. }
  797. if (!got_packet) {
  798. stop_encoding = 1;
  799. break;
  800. }
  801. if (pkt.pts != AV_NOPTS_VALUE)
  802. pkt.pts = av_rescale_q(pkt.pts, enc->time_base, ost->st->time_base);
  803. if (pkt.dts != AV_NOPTS_VALUE)
  804. pkt.dts = av_rescale_q(pkt.dts, enc->time_base, ost->st->time_base);
  805. if (pkt.duration > 0)
  806. pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);
  807. write_frame(os, &pkt, ost);
  808. }
  809. if (stop_encoding)
  810. break;
  811. }
  812. }
  813. }
  814. /*
  815. * Check whether a packet from ist should be written into ost at this time
  816. */
  817. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  818. {
  819. OutputFile *of = output_files[ost->file_index];
  820. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  821. if (ost->source_index != ist_index)
  822. return 0;
  823. if (of->start_time != AV_NOPTS_VALUE && ist->last_dts < of->start_time)
  824. return 0;
  825. return 1;
  826. }
  827. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  828. {
  829. OutputFile *of = output_files[ost->file_index];
  830. InputFile *f = input_files [ist->file_index];
  831. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  832. int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
  833. AVPacket opkt;
  834. av_init_packet(&opkt);
  835. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  836. !ost->copy_initial_nonkeyframes)
  837. return;
  838. if (of->recording_time != INT64_MAX &&
  839. ist->last_dts >= of->recording_time + start_time) {
  840. ost->finished = 1;
  841. return;
  842. }
  843. if (f->recording_time != INT64_MAX) {
  844. start_time = f->ctx->start_time;
  845. if (f->start_time != AV_NOPTS_VALUE)
  846. start_time += f->start_time;
  847. if (ist->last_dts >= f->recording_time + start_time) {
  848. ost->finished = 1;
  849. return;
  850. }
  851. }
  852. /* force the input stream PTS */
  853. if (ost->st->codec->codec_type == AVMEDIA_TYPE_AUDIO)
  854. audio_size += pkt->size;
  855. else if (ost->st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  856. video_size += pkt->size;
  857. ost->sync_opts++;
  858. }
  859. if (pkt->pts != AV_NOPTS_VALUE)
  860. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  861. else
  862. opkt.pts = AV_NOPTS_VALUE;
  863. if (pkt->dts == AV_NOPTS_VALUE)
  864. opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);
  865. else
  866. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  867. opkt.dts -= ost_tb_start_time;
  868. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  869. opkt.flags = pkt->flags;
  870. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  871. if ( ost->st->codec->codec_id != AV_CODEC_ID_H264
  872. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG1VIDEO
  873. && ost->st->codec->codec_id != AV_CODEC_ID_MPEG2VIDEO
  874. && ost->st->codec->codec_id != AV_CODEC_ID_VC1
  875. ) {
  876. if (av_parser_change(ost->parser, ost->st->codec,
  877. &opkt.data, &opkt.size,
  878. pkt->data, pkt->size,
  879. pkt->flags & AV_PKT_FLAG_KEY)) {
  880. opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
  881. if (!opkt.buf)
  882. exit_program(1);
  883. }
  884. } else {
  885. opkt.data = pkt->data;
  886. opkt.size = pkt->size;
  887. }
  888. write_frame(of->ctx, &opkt, ost);
  889. ost->st->codec->frame_number++;
  890. }
  891. int guess_input_channel_layout(InputStream *ist)
  892. {
  893. AVCodecContext *dec = ist->st->codec;
  894. if (!dec->channel_layout) {
  895. char layout_name[256];
  896. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  897. if (!dec->channel_layout)
  898. return 0;
  899. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  900. dec->channels, dec->channel_layout);
  901. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  902. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  903. }
  904. return 1;
  905. }
  906. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  907. {
  908. AVFrame *decoded_frame, *f;
  909. AVCodecContext *avctx = ist->st->codec;
  910. int i, ret, err = 0, resample_changed;
  911. if (!ist->decoded_frame && !(ist->decoded_frame = avcodec_alloc_frame()))
  912. return AVERROR(ENOMEM);
  913. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  914. return AVERROR(ENOMEM);
  915. decoded_frame = ist->decoded_frame;
  916. ret = avcodec_decode_audio4(avctx, decoded_frame, got_output, pkt);
  917. if (!*got_output || ret < 0) {
  918. if (!pkt->size) {
  919. for (i = 0; i < ist->nb_filters; i++)
  920. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  921. }
  922. return ret;
  923. }
  924. /* if the decoder provides a pts, use it instead of the last packet pts.
  925. the decoder could be delaying output by a packet or more. */
  926. if (decoded_frame->pts != AV_NOPTS_VALUE)
  927. ist->next_dts = decoded_frame->pts;
  928. else if (pkt->pts != AV_NOPTS_VALUE) {
  929. decoded_frame->pts = pkt->pts;
  930. pkt->pts = AV_NOPTS_VALUE;
  931. }
  932. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  933. ist->resample_channels != avctx->channels ||
  934. ist->resample_channel_layout != decoded_frame->channel_layout ||
  935. ist->resample_sample_rate != decoded_frame->sample_rate;
  936. if (resample_changed) {
  937. char layout1[64], layout2[64];
  938. if (!guess_input_channel_layout(ist)) {
  939. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  940. "layout for Input Stream #%d.%d\n", ist->file_index,
  941. ist->st->index);
  942. exit_program(1);
  943. }
  944. decoded_frame->channel_layout = avctx->channel_layout;
  945. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  946. ist->resample_channel_layout);
  947. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  948. decoded_frame->channel_layout);
  949. av_log(NULL, AV_LOG_INFO,
  950. "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",
  951. ist->file_index, ist->st->index,
  952. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  953. ist->resample_channels, layout1,
  954. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  955. avctx->channels, layout2);
  956. ist->resample_sample_fmt = decoded_frame->format;
  957. ist->resample_sample_rate = decoded_frame->sample_rate;
  958. ist->resample_channel_layout = decoded_frame->channel_layout;
  959. ist->resample_channels = avctx->channels;
  960. for (i = 0; i < nb_filtergraphs; i++)
  961. if (ist_in_filtergraph(filtergraphs[i], ist) &&
  962. configure_filtergraph(filtergraphs[i]) < 0) {
  963. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  964. exit_program(1);
  965. }
  966. }
  967. if (decoded_frame->pts != AV_NOPTS_VALUE)
  968. decoded_frame->pts = av_rescale_q(decoded_frame->pts,
  969. ist->st->time_base,
  970. (AVRational){1, ist->st->codec->sample_rate});
  971. for (i = 0; i < ist->nb_filters; i++) {
  972. if (i < ist->nb_filters - 1) {
  973. f = ist->filter_frame;
  974. err = av_frame_ref(f, decoded_frame);
  975. if (err < 0)
  976. break;
  977. } else
  978. f = decoded_frame;
  979. err = av_buffersrc_add_frame(ist->filters[i]->filter, f);
  980. if (err < 0)
  981. break;
  982. }
  983. av_frame_unref(ist->filter_frame);
  984. av_frame_unref(decoded_frame);
  985. return err < 0 ? err : ret;
  986. }
  987. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  988. {
  989. AVFrame *decoded_frame, *f;
  990. int i, ret = 0, err = 0, resample_changed;
  991. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  992. return AVERROR(ENOMEM);
  993. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  994. return AVERROR(ENOMEM);
  995. decoded_frame = ist->decoded_frame;
  996. ret = avcodec_decode_video2(ist->st->codec,
  997. decoded_frame, got_output, pkt);
  998. if (!*got_output || ret < 0) {
  999. if (!pkt->size) {
  1000. for (i = 0; i < ist->nb_filters; i++)
  1001. av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1002. }
  1003. return ret;
  1004. }
  1005. decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
  1006. decoded_frame->pkt_dts);
  1007. pkt->size = 0;
  1008. if (ist->st->sample_aspect_ratio.num)
  1009. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1010. resample_changed = ist->resample_width != decoded_frame->width ||
  1011. ist->resample_height != decoded_frame->height ||
  1012. ist->resample_pix_fmt != decoded_frame->format;
  1013. if (resample_changed) {
  1014. av_log(NULL, AV_LOG_INFO,
  1015. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1016. ist->file_index, ist->st->index,
  1017. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1018. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1019. ret = poll_filters();
  1020. if (ret < 0 && (ret != AVERROR_EOF && ret != AVERROR(EAGAIN)))
  1021. av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
  1022. ist->resample_width = decoded_frame->width;
  1023. ist->resample_height = decoded_frame->height;
  1024. ist->resample_pix_fmt = decoded_frame->format;
  1025. for (i = 0; i < nb_filtergraphs; i++)
  1026. if (ist_in_filtergraph(filtergraphs[i], ist) &&
  1027. configure_filtergraph(filtergraphs[i]) < 0) {
  1028. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1029. exit_program(1);
  1030. }
  1031. }
  1032. for (i = 0; i < ist->nb_filters; i++) {
  1033. if (i < ist->nb_filters - 1) {
  1034. f = ist->filter_frame;
  1035. err = av_frame_ref(f, decoded_frame);
  1036. if (err < 0)
  1037. break;
  1038. } else
  1039. f = decoded_frame;
  1040. err = av_buffersrc_add_frame(ist->filters[i]->filter, f);
  1041. if (err < 0)
  1042. break;
  1043. }
  1044. av_frame_unref(ist->filter_frame);
  1045. av_frame_unref(decoded_frame);
  1046. return err < 0 ? err : ret;
  1047. }
  1048. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1049. {
  1050. AVSubtitle subtitle;
  1051. int i, ret = avcodec_decode_subtitle2(ist->st->codec,
  1052. &subtitle, got_output, pkt);
  1053. if (ret < 0)
  1054. return ret;
  1055. if (!*got_output)
  1056. return ret;
  1057. for (i = 0; i < nb_output_streams; i++) {
  1058. OutputStream *ost = output_streams[i];
  1059. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1060. continue;
  1061. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
  1062. }
  1063. avsubtitle_free(&subtitle);
  1064. return ret;
  1065. }
  1066. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1067. static int output_packet(InputStream *ist, const AVPacket *pkt)
  1068. {
  1069. int i;
  1070. int got_output;
  1071. AVPacket avpkt;
  1072. if (ist->next_dts == AV_NOPTS_VALUE)
  1073. ist->next_dts = ist->last_dts;
  1074. if (pkt == NULL) {
  1075. /* EOF handling */
  1076. av_init_packet(&avpkt);
  1077. avpkt.data = NULL;
  1078. avpkt.size = 0;
  1079. goto handle_eof;
  1080. } else {
  1081. avpkt = *pkt;
  1082. }
  1083. if (pkt->dts != AV_NOPTS_VALUE)
  1084. ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1085. // while we have more to decode or while the decoder did output something on EOF
  1086. while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {
  1087. int ret = 0;
  1088. handle_eof:
  1089. ist->last_dts = ist->next_dts;
  1090. if (avpkt.size && avpkt.size != pkt->size) {
  1091. av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,
  1092. "Multiple frames in a packet from stream %d\n", pkt->stream_index);
  1093. ist->showed_multi_packet_warning = 1;
  1094. }
  1095. switch (ist->st->codec->codec_type) {
  1096. case AVMEDIA_TYPE_AUDIO:
  1097. ret = decode_audio (ist, &avpkt, &got_output);
  1098. break;
  1099. case AVMEDIA_TYPE_VIDEO:
  1100. ret = decode_video (ist, &avpkt, &got_output);
  1101. if (avpkt.duration)
  1102. ist->next_dts += av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);
  1103. else if (ist->st->avg_frame_rate.num)
  1104. ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
  1105. AV_TIME_BASE_Q);
  1106. else if (ist->st->codec->time_base.num != 0) {
  1107. int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
  1108. ist->st->codec->ticks_per_frame;
  1109. ist->next_dts += av_rescale_q(ticks, ist->st->codec->time_base, AV_TIME_BASE_Q);
  1110. }
  1111. break;
  1112. case AVMEDIA_TYPE_SUBTITLE:
  1113. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1114. break;
  1115. default:
  1116. return -1;
  1117. }
  1118. if (ret < 0)
  1119. return ret;
  1120. // touch data and size only if not EOF
  1121. if (pkt) {
  1122. avpkt.data += ret;
  1123. avpkt.size -= ret;
  1124. }
  1125. if (!got_output) {
  1126. continue;
  1127. }
  1128. }
  1129. /* handle stream copy */
  1130. if (!ist->decoding_needed) {
  1131. ist->last_dts = ist->next_dts;
  1132. switch (ist->st->codec->codec_type) {
  1133. case AVMEDIA_TYPE_AUDIO:
  1134. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->st->codec->frame_size) /
  1135. ist->st->codec->sample_rate;
  1136. break;
  1137. case AVMEDIA_TYPE_VIDEO:
  1138. if (ist->st->codec->time_base.num != 0) {
  1139. int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->st->codec->ticks_per_frame;
  1140. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1141. ist->st->codec->time_base.num * ticks) /
  1142. ist->st->codec->time_base.den;
  1143. }
  1144. break;
  1145. }
  1146. }
  1147. for (i = 0; pkt && i < nb_output_streams; i++) {
  1148. OutputStream *ost = output_streams[i];
  1149. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1150. continue;
  1151. do_streamcopy(ist, ost, pkt);
  1152. }
  1153. return 0;
  1154. }
  1155. static void print_sdp(void)
  1156. {
  1157. char sdp[16384];
  1158. int i;
  1159. AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
  1160. if (!avc)
  1161. exit_program(1);
  1162. for (i = 0; i < nb_output_files; i++)
  1163. avc[i] = output_files[i]->ctx;
  1164. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1165. printf("SDP:\n%s\n", sdp);
  1166. fflush(stdout);
  1167. av_freep(&avc);
  1168. }
  1169. static int init_input_stream(int ist_index, char *error, int error_len)
  1170. {
  1171. int i, ret;
  1172. InputStream *ist = input_streams[ist_index];
  1173. if (ist->decoding_needed) {
  1174. AVCodec *codec = ist->dec;
  1175. if (!codec) {
  1176. snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
  1177. ist->st->codec->codec_id, ist->file_index, ist->st->index);
  1178. return AVERROR(EINVAL);
  1179. }
  1180. /* update requested sample format for the decoder based on the
  1181. corresponding encoder sample format */
  1182. for (i = 0; i < nb_output_streams; i++) {
  1183. OutputStream *ost = output_streams[i];
  1184. if (ost->source_index == ist_index) {
  1185. update_sample_fmt(ist->st->codec, codec, ost->st->codec);
  1186. break;
  1187. }
  1188. }
  1189. av_opt_set_int(ist->st->codec, "refcounted_frames", 1, 0);
  1190. if (!av_dict_get(ist->opts, "threads", NULL, 0))
  1191. av_dict_set(&ist->opts, "threads", "auto", 0);
  1192. if ((ret = avcodec_open2(ist->st->codec, codec, &ist->opts)) < 0) {
  1193. char errbuf[128];
  1194. if (ret == AVERROR_EXPERIMENTAL)
  1195. abort_codec_experimental(codec, 0);
  1196. av_strerror(ret, errbuf, sizeof(errbuf));
  1197. snprintf(error, error_len,
  1198. "Error while opening decoder for input stream "
  1199. "#%d:%d : %s",
  1200. ist->file_index, ist->st->index, errbuf);
  1201. return ret;
  1202. }
  1203. assert_avoptions(ist->opts);
  1204. }
  1205. 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;
  1206. ist->next_dts = AV_NOPTS_VALUE;
  1207. init_pts_correction(&ist->pts_ctx);
  1208. ist->is_start = 1;
  1209. return 0;
  1210. }
  1211. static InputStream *get_input_stream(OutputStream *ost)
  1212. {
  1213. if (ost->source_index >= 0)
  1214. return input_streams[ost->source_index];
  1215. if (ost->filter) {
  1216. FilterGraph *fg = ost->filter->graph;
  1217. int i;
  1218. for (i = 0; i < fg->nb_inputs; i++)
  1219. if (fg->inputs[i]->ist->st->codec->codec_type == ost->st->codec->codec_type)
  1220. return fg->inputs[i]->ist;
  1221. }
  1222. return NULL;
  1223. }
  1224. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1225. AVCodecContext *avctx)
  1226. {
  1227. char *p;
  1228. int n = 1, i;
  1229. int64_t t;
  1230. for (p = kf; *p; p++)
  1231. if (*p == ',')
  1232. n++;
  1233. ost->forced_kf_count = n;
  1234. ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
  1235. if (!ost->forced_kf_pts) {
  1236. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1237. exit_program(1);
  1238. }
  1239. p = kf;
  1240. for (i = 0; i < n; i++) {
  1241. char *next = strchr(p, ',');
  1242. if (next)
  1243. *next++ = 0;
  1244. t = parse_time_or_die("force_key_frames", p, 1);
  1245. ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1246. p = next;
  1247. }
  1248. }
  1249. static int transcode_init(void)
  1250. {
  1251. int ret = 0, i, j, k;
  1252. AVFormatContext *oc;
  1253. AVCodecContext *codec;
  1254. OutputStream *ost;
  1255. InputStream *ist;
  1256. char error[1024];
  1257. int want_sdp = 1;
  1258. /* init framerate emulation */
  1259. for (i = 0; i < nb_input_files; i++) {
  1260. InputFile *ifile = input_files[i];
  1261. if (ifile->rate_emu)
  1262. for (j = 0; j < ifile->nb_streams; j++)
  1263. input_streams[j + ifile->ist_index]->start = av_gettime();
  1264. }
  1265. /* output stream init */
  1266. for (i = 0; i < nb_output_files; i++) {
  1267. oc = output_files[i]->ctx;
  1268. if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {
  1269. av_dump_format(oc, i, oc->filename, 1);
  1270. av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);
  1271. return AVERROR(EINVAL);
  1272. }
  1273. }
  1274. /* init complex filtergraphs */
  1275. for (i = 0; i < nb_filtergraphs; i++)
  1276. if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)
  1277. return ret;
  1278. /* for each output stream, we compute the right encoding parameters */
  1279. for (i = 0; i < nb_output_streams; i++) {
  1280. AVCodecContext *icodec = NULL;
  1281. ost = output_streams[i];
  1282. oc = output_files[ost->file_index]->ctx;
  1283. ist = get_input_stream(ost);
  1284. if (ost->attachment_filename)
  1285. continue;
  1286. codec = ost->st->codec;
  1287. if (ist) {
  1288. icodec = ist->st->codec;
  1289. ost->st->disposition = ist->st->disposition;
  1290. codec->bits_per_raw_sample = icodec->bits_per_raw_sample;
  1291. codec->chroma_sample_location = icodec->chroma_sample_location;
  1292. }
  1293. if (ost->stream_copy) {
  1294. AVRational sar;
  1295. uint64_t extra_size;
  1296. av_assert0(ist && !ost->filter);
  1297. extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;
  1298. if (extra_size > INT_MAX) {
  1299. return AVERROR(EINVAL);
  1300. }
  1301. /* if stream_copy is selected, no need to decode or encode */
  1302. codec->codec_id = icodec->codec_id;
  1303. codec->codec_type = icodec->codec_type;
  1304. if (!codec->codec_tag) {
  1305. if (!oc->oformat->codec_tag ||
  1306. av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||
  1307. av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)
  1308. codec->codec_tag = icodec->codec_tag;
  1309. }
  1310. codec->bit_rate = icodec->bit_rate;
  1311. codec->rc_max_rate = icodec->rc_max_rate;
  1312. codec->rc_buffer_size = icodec->rc_buffer_size;
  1313. codec->field_order = icodec->field_order;
  1314. codec->extradata = av_mallocz(extra_size);
  1315. if (!codec->extradata) {
  1316. return AVERROR(ENOMEM);
  1317. }
  1318. memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);
  1319. codec->extradata_size = icodec->extradata_size;
  1320. if (!copy_tb) {
  1321. codec->time_base = icodec->time_base;
  1322. codec->time_base.num *= icodec->ticks_per_frame;
  1323. av_reduce(&codec->time_base.num, &codec->time_base.den,
  1324. codec->time_base.num, codec->time_base.den, INT_MAX);
  1325. } else
  1326. codec->time_base = ist->st->time_base;
  1327. ost->parser = av_parser_init(codec->codec_id);
  1328. switch (codec->codec_type) {
  1329. case AVMEDIA_TYPE_AUDIO:
  1330. if (audio_volume != 256) {
  1331. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  1332. exit_program(1);
  1333. }
  1334. codec->channel_layout = icodec->channel_layout;
  1335. codec->sample_rate = icodec->sample_rate;
  1336. codec->channels = icodec->channels;
  1337. codec->frame_size = icodec->frame_size;
  1338. codec->audio_service_type = icodec->audio_service_type;
  1339. codec->block_align = icodec->block_align;
  1340. break;
  1341. case AVMEDIA_TYPE_VIDEO:
  1342. codec->pix_fmt = icodec->pix_fmt;
  1343. codec->width = icodec->width;
  1344. codec->height = icodec->height;
  1345. codec->has_b_frames = icodec->has_b_frames;
  1346. if (ost->frame_aspect_ratio)
  1347. sar = av_d2q(ost->frame_aspect_ratio * codec->height / codec->width, 255);
  1348. else if (ist->st->sample_aspect_ratio.num)
  1349. sar = ist->st->sample_aspect_ratio;
  1350. else
  1351. sar = icodec->sample_aspect_ratio;
  1352. ost->st->sample_aspect_ratio = codec->sample_aspect_ratio = sar;
  1353. break;
  1354. case AVMEDIA_TYPE_SUBTITLE:
  1355. codec->width = icodec->width;
  1356. codec->height = icodec->height;
  1357. break;
  1358. case AVMEDIA_TYPE_DATA:
  1359. case AVMEDIA_TYPE_ATTACHMENT:
  1360. break;
  1361. default:
  1362. abort();
  1363. }
  1364. } else {
  1365. if (!ost->enc) {
  1366. /* should only happen when a default codec is not present. */
  1367. snprintf(error, sizeof(error), "Automatic encoder selection "
  1368. "failed for output stream #%d:%d. Default encoder for "
  1369. "format %s is probably disabled. Please choose an "
  1370. "encoder manually.\n", ost->file_index, ost->index,
  1371. oc->oformat->name);
  1372. ret = AVERROR(EINVAL);
  1373. goto dump_format;
  1374. }
  1375. if (ist)
  1376. ist->decoding_needed = 1;
  1377. ost->encoding_needed = 1;
  1378. /*
  1379. * We want CFR output if and only if one of those is true:
  1380. * 1) user specified output framerate with -r
  1381. * 2) user specified -vsync cfr
  1382. * 3) output format is CFR and the user didn't force vsync to
  1383. * something else than CFR
  1384. *
  1385. * in such a case, set ost->frame_rate
  1386. */
  1387. if (codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  1388. !ost->frame_rate.num && ist &&
  1389. (video_sync_method == VSYNC_CFR ||
  1390. (video_sync_method == VSYNC_AUTO &&
  1391. !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {
  1392. ost->frame_rate = ist->framerate.num ? ist->framerate :
  1393. ist->st->avg_frame_rate.num ?
  1394. ist->st->avg_frame_rate :
  1395. (AVRational){25, 1};
  1396. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  1397. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  1398. ost->frame_rate = ost->enc->supported_framerates[idx];
  1399. }
  1400. }
  1401. if (!ost->filter &&
  1402. (codec->codec_type == AVMEDIA_TYPE_VIDEO ||
  1403. codec->codec_type == AVMEDIA_TYPE_AUDIO)) {
  1404. FilterGraph *fg;
  1405. fg = init_simple_filtergraph(ist, ost);
  1406. if (configure_filtergraph(fg)) {
  1407. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  1408. exit_program(1);
  1409. }
  1410. }
  1411. switch (codec->codec_type) {
  1412. case AVMEDIA_TYPE_AUDIO:
  1413. codec->sample_fmt = ost->filter->filter->inputs[0]->format;
  1414. codec->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  1415. codec->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  1416. codec->channels = av_get_channel_layout_nb_channels(codec->channel_layout);
  1417. codec->time_base = (AVRational){ 1, codec->sample_rate };
  1418. break;
  1419. case AVMEDIA_TYPE_VIDEO:
  1420. codec->time_base = ost->filter->filter->inputs[0]->time_base;
  1421. codec->width = ost->filter->filter->inputs[0]->w;
  1422. codec->height = ost->filter->filter->inputs[0]->h;
  1423. codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  1424. ost->frame_aspect_ratio ? // overridden by the -aspect cli option
  1425. av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :
  1426. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  1427. codec->pix_fmt = ost->filter->filter->inputs[0]->format;
  1428. if (icodec &&
  1429. (codec->width != icodec->width ||
  1430. codec->height != icodec->height ||
  1431. codec->pix_fmt != icodec->pix_fmt)) {
  1432. codec->bits_per_raw_sample = 0;
  1433. }
  1434. if (ost->forced_keyframes)
  1435. parse_forced_key_frames(ost->forced_keyframes, ost,
  1436. ost->st->codec);
  1437. break;
  1438. case AVMEDIA_TYPE_SUBTITLE:
  1439. codec->time_base = (AVRational){1, 1000};
  1440. break;
  1441. default:
  1442. abort();
  1443. break;
  1444. }
  1445. /* two pass mode */
  1446. if ((codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {
  1447. char logfilename[1024];
  1448. FILE *f;
  1449. snprintf(logfilename, sizeof(logfilename), "%s-%d.log",
  1450. ost->logfile_prefix ? ost->logfile_prefix :
  1451. DEFAULT_PASS_LOGFILENAME_PREFIX,
  1452. i);
  1453. if (!strcmp(ost->enc->name, "libx264")) {
  1454. av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);
  1455. } else {
  1456. if (codec->flags & CODEC_FLAG_PASS1) {
  1457. f = fopen(logfilename, "wb");
  1458. if (!f) {
  1459. av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",
  1460. logfilename, strerror(errno));
  1461. exit_program(1);
  1462. }
  1463. ost->logfile = f;
  1464. } else {
  1465. char *logbuffer;
  1466. size_t logbuffer_size;
  1467. if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {
  1468. av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",
  1469. logfilename);
  1470. exit_program(1);
  1471. }
  1472. codec->stats_in = logbuffer;
  1473. }
  1474. }
  1475. }
  1476. }
  1477. }
  1478. /* open each encoder */
  1479. for (i = 0; i < nb_output_streams; i++) {
  1480. ost = output_streams[i];
  1481. if (ost->encoding_needed) {
  1482. AVCodec *codec = ost->enc;
  1483. AVCodecContext *dec = NULL;
  1484. if ((ist = get_input_stream(ost)))
  1485. dec = ist->st->codec;
  1486. if (dec && dec->subtitle_header) {
  1487. ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);
  1488. if (!ost->st->codec->subtitle_header) {
  1489. ret = AVERROR(ENOMEM);
  1490. goto dump_format;
  1491. }
  1492. memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  1493. ost->st->codec->subtitle_header_size = dec->subtitle_header_size;
  1494. }
  1495. if (!av_dict_get(ost->opts, "threads", NULL, 0))
  1496. av_dict_set(&ost->opts, "threads", "auto", 0);
  1497. if ((ret = avcodec_open2(ost->st->codec, codec, &ost->opts)) < 0) {
  1498. if (ret == AVERROR_EXPERIMENTAL)
  1499. abort_codec_experimental(codec, 1);
  1500. snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",
  1501. ost->file_index, ost->index);
  1502. goto dump_format;
  1503. }
  1504. assert_avoptions(ost->opts);
  1505. if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)
  1506. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  1507. "It takes bits/s as argument, not kbits/s\n");
  1508. extra_size += ost->st->codec->extradata_size;
  1509. } else {
  1510. av_opt_set_dict(ost->st->codec, &ost->opts);
  1511. }
  1512. }
  1513. /* init input streams */
  1514. for (i = 0; i < nb_input_streams; i++)
  1515. if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
  1516. goto dump_format;
  1517. /* discard unused programs */
  1518. for (i = 0; i < nb_input_files; i++) {
  1519. InputFile *ifile = input_files[i];
  1520. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  1521. AVProgram *p = ifile->ctx->programs[j];
  1522. int discard = AVDISCARD_ALL;
  1523. for (k = 0; k < p->nb_stream_indexes; k++)
  1524. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  1525. discard = AVDISCARD_DEFAULT;
  1526. break;
  1527. }
  1528. p->discard = discard;
  1529. }
  1530. }
  1531. /* open files and write file headers */
  1532. for (i = 0; i < nb_output_files; i++) {
  1533. oc = output_files[i]->ctx;
  1534. oc->interrupt_callback = int_cb;
  1535. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  1536. char errbuf[128];
  1537. av_strerror(ret, errbuf, sizeof(errbuf));
  1538. snprintf(error, sizeof(error),
  1539. "Could not write header for output file #%d "
  1540. "(incorrect codec parameters ?): %s",
  1541. i, errbuf);
  1542. ret = AVERROR(EINVAL);
  1543. goto dump_format;
  1544. }
  1545. assert_avoptions(output_files[i]->opts);
  1546. if (strcmp(oc->oformat->name, "rtp")) {
  1547. want_sdp = 0;
  1548. }
  1549. }
  1550. dump_format:
  1551. /* dump the file output parameters - cannot be done before in case
  1552. of stream copy */
  1553. for (i = 0; i < nb_output_files; i++) {
  1554. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  1555. }
  1556. /* dump the stream mapping */
  1557. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  1558. for (i = 0; i < nb_input_streams; i++) {
  1559. ist = input_streams[i];
  1560. for (j = 0; j < ist->nb_filters; j++) {
  1561. if (ist->filters[j]->graph->graph_desc) {
  1562. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  1563. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  1564. ist->filters[j]->name);
  1565. if (nb_filtergraphs > 1)
  1566. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  1567. av_log(NULL, AV_LOG_INFO, "\n");
  1568. }
  1569. }
  1570. }
  1571. for (i = 0; i < nb_output_streams; i++) {
  1572. ost = output_streams[i];
  1573. if (ost->attachment_filename) {
  1574. /* an attached file */
  1575. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  1576. ost->attachment_filename, ost->file_index, ost->index);
  1577. continue;
  1578. }
  1579. if (ost->filter && ost->filter->graph->graph_desc) {
  1580. /* output from a complex graph */
  1581. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  1582. if (nb_filtergraphs > 1)
  1583. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  1584. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  1585. ost->index, ost->enc ? ost->enc->name : "?");
  1586. continue;
  1587. }
  1588. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  1589. input_streams[ost->source_index]->file_index,
  1590. input_streams[ost->source_index]->st->index,
  1591. ost->file_index,
  1592. ost->index);
  1593. if (ost->sync_ist != input_streams[ost->source_index])
  1594. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  1595. ost->sync_ist->file_index,
  1596. ost->sync_ist->st->index);
  1597. if (ost->stream_copy)
  1598. av_log(NULL, AV_LOG_INFO, " (copy)");
  1599. else
  1600. av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?
  1601. input_streams[ost->source_index]->dec->name : "?",
  1602. ost->enc ? ost->enc->name : "?");
  1603. av_log(NULL, AV_LOG_INFO, "\n");
  1604. }
  1605. if (ret) {
  1606. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  1607. return ret;
  1608. }
  1609. if (want_sdp) {
  1610. print_sdp();
  1611. }
  1612. return 0;
  1613. }
  1614. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  1615. static int need_output(void)
  1616. {
  1617. int i;
  1618. for (i = 0; i < nb_output_streams; i++) {
  1619. OutputStream *ost = output_streams[i];
  1620. OutputFile *of = output_files[ost->file_index];
  1621. AVFormatContext *os = output_files[ost->file_index]->ctx;
  1622. if (ost->finished ||
  1623. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  1624. continue;
  1625. if (ost->frame_number >= ost->max_frames) {
  1626. int j;
  1627. for (j = 0; j < of->ctx->nb_streams; j++)
  1628. output_streams[of->ost_index + j]->finished = 1;
  1629. continue;
  1630. }
  1631. return 1;
  1632. }
  1633. return 0;
  1634. }
  1635. static InputFile *select_input_file(void)
  1636. {
  1637. InputFile *ifile = NULL;
  1638. int64_t ipts_min = INT64_MAX;
  1639. int i;
  1640. for (i = 0; i < nb_input_streams; i++) {
  1641. InputStream *ist = input_streams[i];
  1642. int64_t ipts = ist->last_dts;
  1643. if (ist->discard || input_files[ist->file_index]->eagain)
  1644. continue;
  1645. if (!input_files[ist->file_index]->eof_reached) {
  1646. if (ipts < ipts_min) {
  1647. ipts_min = ipts;
  1648. ifile = input_files[ist->file_index];
  1649. }
  1650. }
  1651. }
  1652. return ifile;
  1653. }
  1654. #if HAVE_PTHREADS
  1655. static void *input_thread(void *arg)
  1656. {
  1657. InputFile *f = arg;
  1658. int ret = 0;
  1659. while (!transcoding_finished && ret >= 0) {
  1660. AVPacket pkt;
  1661. ret = av_read_frame(f->ctx, &pkt);
  1662. if (ret == AVERROR(EAGAIN)) {
  1663. av_usleep(10000);
  1664. ret = 0;
  1665. continue;
  1666. } else if (ret < 0)
  1667. break;
  1668. pthread_mutex_lock(&f->fifo_lock);
  1669. while (!av_fifo_space(f->fifo))
  1670. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  1671. av_dup_packet(&pkt);
  1672. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  1673. pthread_mutex_unlock(&f->fifo_lock);
  1674. }
  1675. f->finished = 1;
  1676. return NULL;
  1677. }
  1678. static void free_input_threads(void)
  1679. {
  1680. int i;
  1681. if (nb_input_files == 1)
  1682. return;
  1683. transcoding_finished = 1;
  1684. for (i = 0; i < nb_input_files; i++) {
  1685. InputFile *f = input_files[i];
  1686. AVPacket pkt;
  1687. if (!f->fifo || f->joined)
  1688. continue;
  1689. pthread_mutex_lock(&f->fifo_lock);
  1690. while (av_fifo_size(f->fifo)) {
  1691. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  1692. av_free_packet(&pkt);
  1693. }
  1694. pthread_cond_signal(&f->fifo_cond);
  1695. pthread_mutex_unlock(&f->fifo_lock);
  1696. pthread_join(f->thread, NULL);
  1697. f->joined = 1;
  1698. while (av_fifo_size(f->fifo)) {
  1699. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  1700. av_free_packet(&pkt);
  1701. }
  1702. av_fifo_free(f->fifo);
  1703. }
  1704. }
  1705. static int init_input_threads(void)
  1706. {
  1707. int i, ret;
  1708. if (nb_input_files == 1)
  1709. return 0;
  1710. for (i = 0; i < nb_input_files; i++) {
  1711. InputFile *f = input_files[i];
  1712. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  1713. return AVERROR(ENOMEM);
  1714. pthread_mutex_init(&f->fifo_lock, NULL);
  1715. pthread_cond_init (&f->fifo_cond, NULL);
  1716. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  1717. return AVERROR(ret);
  1718. }
  1719. return 0;
  1720. }
  1721. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  1722. {
  1723. int ret = 0;
  1724. pthread_mutex_lock(&f->fifo_lock);
  1725. if (av_fifo_size(f->fifo)) {
  1726. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  1727. pthread_cond_signal(&f->fifo_cond);
  1728. } else {
  1729. if (f->finished)
  1730. ret = AVERROR_EOF;
  1731. else
  1732. ret = AVERROR(EAGAIN);
  1733. }
  1734. pthread_mutex_unlock(&f->fifo_lock);
  1735. return ret;
  1736. }
  1737. #endif
  1738. static int get_input_packet(InputFile *f, AVPacket *pkt)
  1739. {
  1740. if (f->rate_emu) {
  1741. int i;
  1742. for (i = 0; i < f->nb_streams; i++) {
  1743. InputStream *ist = input_streams[f->ist_index + i];
  1744. int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
  1745. int64_t now = av_gettime() - ist->start;
  1746. if (pts > now)
  1747. return AVERROR(EAGAIN);
  1748. }
  1749. }
  1750. #if HAVE_PTHREADS
  1751. if (nb_input_files > 1)
  1752. return get_input_packet_mt(f, pkt);
  1753. #endif
  1754. return av_read_frame(f->ctx, pkt);
  1755. }
  1756. static int got_eagain(void)
  1757. {
  1758. int i;
  1759. for (i = 0; i < nb_input_files; i++)
  1760. if (input_files[i]->eagain)
  1761. return 1;
  1762. return 0;
  1763. }
  1764. static void reset_eagain(void)
  1765. {
  1766. int i;
  1767. for (i = 0; i < nb_input_files; i++)
  1768. input_files[i]->eagain = 0;
  1769. }
  1770. /*
  1771. * Read one packet from an input file and send it for
  1772. * - decoding -> lavfi (audio/video)
  1773. * - decoding -> encoding -> muxing (subtitles)
  1774. * - muxing (streamcopy)
  1775. *
  1776. * Return
  1777. * - 0 -- one packet was read and processed
  1778. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  1779. * this function should be called again
  1780. * - AVERROR_EOF -- this function should not be called again
  1781. */
  1782. static int process_input(void)
  1783. {
  1784. InputFile *ifile;
  1785. AVFormatContext *is;
  1786. InputStream *ist;
  1787. AVPacket pkt;
  1788. int ret, i, j;
  1789. /* select the stream that we must read now */
  1790. ifile = select_input_file();
  1791. /* if none, if is finished */
  1792. if (!ifile) {
  1793. if (got_eagain()) {
  1794. reset_eagain();
  1795. av_usleep(10000);
  1796. return AVERROR(EAGAIN);
  1797. }
  1798. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from.\n");
  1799. return AVERROR_EOF;
  1800. }
  1801. is = ifile->ctx;
  1802. ret = get_input_packet(ifile, &pkt);
  1803. if (ret == AVERROR(EAGAIN)) {
  1804. ifile->eagain = 1;
  1805. return ret;
  1806. }
  1807. if (ret < 0) {
  1808. if (ret != AVERROR_EOF) {
  1809. print_error(is->filename, ret);
  1810. if (exit_on_error)
  1811. exit_program(1);
  1812. }
  1813. ifile->eof_reached = 1;
  1814. for (i = 0; i < ifile->nb_streams; i++) {
  1815. ist = input_streams[ifile->ist_index + i];
  1816. if (ist->decoding_needed)
  1817. output_packet(ist, NULL);
  1818. /* mark all outputs that don't go through lavfi as finished */
  1819. for (j = 0; j < nb_output_streams; j++) {
  1820. OutputStream *ost = output_streams[j];
  1821. if (ost->source_index == ifile->ist_index + i &&
  1822. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  1823. ost->finished= 1;
  1824. }
  1825. }
  1826. return AVERROR(EAGAIN);
  1827. }
  1828. reset_eagain();
  1829. if (do_pkt_dump) {
  1830. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  1831. is->streams[pkt.stream_index]);
  1832. }
  1833. /* the following test is needed in case new streams appear
  1834. dynamically in stream : we ignore them */
  1835. if (pkt.stream_index >= ifile->nb_streams)
  1836. goto discard_packet;
  1837. ist = input_streams[ifile->ist_index + pkt.stream_index];
  1838. if (ist->discard)
  1839. goto discard_packet;
  1840. if (pkt.dts != AV_NOPTS_VALUE)
  1841. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  1842. if (pkt.pts != AV_NOPTS_VALUE)
  1843. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  1844. if (pkt.pts != AV_NOPTS_VALUE)
  1845. pkt.pts *= ist->ts_scale;
  1846. if (pkt.dts != AV_NOPTS_VALUE)
  1847. pkt.dts *= ist->ts_scale;
  1848. if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  1849. (is->iformat->flags & AVFMT_TS_DISCONT)) {
  1850. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  1851. int64_t delta = pkt_dts - ist->next_dts;
  1852. if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
  1853. ifile->ts_offset -= delta;
  1854. av_log(NULL, AV_LOG_DEBUG,
  1855. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  1856. delta, ifile->ts_offset);
  1857. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  1858. if (pkt.pts != AV_NOPTS_VALUE)
  1859. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  1860. }
  1861. }
  1862. ret = output_packet(ist, &pkt);
  1863. if (ret < 0) {
  1864. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
  1865. ist->file_index, ist->st->index);
  1866. if (exit_on_error)
  1867. exit_program(1);
  1868. }
  1869. discard_packet:
  1870. av_free_packet(&pkt);
  1871. return 0;
  1872. }
  1873. /*
  1874. * The following code is the main loop of the file converter
  1875. */
  1876. static int transcode(void)
  1877. {
  1878. int ret, i, need_input = 1;
  1879. AVFormatContext *os;
  1880. OutputStream *ost;
  1881. InputStream *ist;
  1882. int64_t timer_start;
  1883. ret = transcode_init();
  1884. if (ret < 0)
  1885. goto fail;
  1886. av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
  1887. term_init();
  1888. timer_start = av_gettime();
  1889. #if HAVE_PTHREADS
  1890. if ((ret = init_input_threads()) < 0)
  1891. goto fail;
  1892. #endif
  1893. while (!received_sigterm) {
  1894. /* check if there's any stream where output is still needed */
  1895. if (!need_output()) {
  1896. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  1897. break;
  1898. }
  1899. /* read and process one input packet if needed */
  1900. if (need_input) {
  1901. ret = process_input();
  1902. if (ret == AVERROR_EOF)
  1903. need_input = 0;
  1904. }
  1905. ret = poll_filters();
  1906. if (ret < 0) {
  1907. if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
  1908. continue;
  1909. av_log(NULL, AV_LOG_ERROR, "Error while filtering.\n");
  1910. break;
  1911. }
  1912. /* dump report by using the output first video and audio streams */
  1913. print_report(0, timer_start);
  1914. }
  1915. #if HAVE_PTHREADS
  1916. free_input_threads();
  1917. #endif
  1918. /* at the end of stream, we must flush the decoder buffers */
  1919. for (i = 0; i < nb_input_streams; i++) {
  1920. ist = input_streams[i];
  1921. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  1922. output_packet(ist, NULL);
  1923. }
  1924. }
  1925. poll_filters();
  1926. flush_encoders();
  1927. term_exit();
  1928. /* write the trailer if needed and close file */
  1929. for (i = 0; i < nb_output_files; i++) {
  1930. os = output_files[i]->ctx;
  1931. av_write_trailer(os);
  1932. }
  1933. /* dump report by using the first video and audio streams */
  1934. print_report(1, timer_start);
  1935. /* close each encoder */
  1936. for (i = 0; i < nb_output_streams; i++) {
  1937. ost = output_streams[i];
  1938. if (ost->encoding_needed) {
  1939. av_freep(&ost->st->codec->stats_in);
  1940. avcodec_close(ost->st->codec);
  1941. }
  1942. }
  1943. /* close each decoder */
  1944. for (i = 0; i < nb_input_streams; i++) {
  1945. ist = input_streams[i];
  1946. if (ist->decoding_needed) {
  1947. avcodec_close(ist->st->codec);
  1948. }
  1949. }
  1950. /* finished ! */
  1951. ret = 0;
  1952. fail:
  1953. #if HAVE_PTHREADS
  1954. free_input_threads();
  1955. #endif
  1956. if (output_streams) {
  1957. for (i = 0; i < nb_output_streams; i++) {
  1958. ost = output_streams[i];
  1959. if (ost) {
  1960. if (ost->stream_copy)
  1961. av_freep(&ost->st->codec->extradata);
  1962. if (ost->logfile) {
  1963. fclose(ost->logfile);
  1964. ost->logfile = NULL;
  1965. }
  1966. av_freep(&ost->st->codec->subtitle_header);
  1967. av_free(ost->forced_kf_pts);
  1968. av_dict_free(&ost->opts);
  1969. av_dict_free(&ost->resample_opts);
  1970. }
  1971. }
  1972. }
  1973. return ret;
  1974. }
  1975. static int64_t getutime(void)
  1976. {
  1977. #if HAVE_GETRUSAGE
  1978. struct rusage rusage;
  1979. getrusage(RUSAGE_SELF, &rusage);
  1980. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  1981. #elif HAVE_GETPROCESSTIMES
  1982. HANDLE proc;
  1983. FILETIME c, e, k, u;
  1984. proc = GetCurrentProcess();
  1985. GetProcessTimes(proc, &c, &e, &k, &u);
  1986. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  1987. #else
  1988. return av_gettime();
  1989. #endif
  1990. }
  1991. static int64_t getmaxrss(void)
  1992. {
  1993. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  1994. struct rusage rusage;
  1995. getrusage(RUSAGE_SELF, &rusage);
  1996. return (int64_t)rusage.ru_maxrss * 1024;
  1997. #elif HAVE_GETPROCESSMEMORYINFO
  1998. HANDLE proc;
  1999. PROCESS_MEMORY_COUNTERS memcounters;
  2000. proc = GetCurrentProcess();
  2001. memcounters.cb = sizeof(memcounters);
  2002. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  2003. return memcounters.PeakPagefileUsage;
  2004. #else
  2005. return 0;
  2006. #endif
  2007. }
  2008. int main(int argc, char **argv)
  2009. {
  2010. int ret;
  2011. int64_t ti;
  2012. register_exit(avconv_cleanup);
  2013. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2014. parse_loglevel(argc, argv, options);
  2015. avcodec_register_all();
  2016. #if CONFIG_AVDEVICE
  2017. avdevice_register_all();
  2018. #endif
  2019. avfilter_register_all();
  2020. av_register_all();
  2021. avformat_network_init();
  2022. show_banner();
  2023. /* parse options and open all input/output files */
  2024. ret = avconv_parse_options(argc, argv);
  2025. if (ret < 0)
  2026. exit_program(1);
  2027. if (nb_output_files <= 0 && nb_input_files == 0) {
  2028. show_usage();
  2029. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  2030. exit_program(1);
  2031. }
  2032. /* file converter / grab */
  2033. if (nb_output_files <= 0) {
  2034. fprintf(stderr, "At least one output file must be specified\n");
  2035. exit_program(1);
  2036. }
  2037. ti = getutime();
  2038. if (transcode() < 0)
  2039. exit_program(1);
  2040. ti = getutime() - ti;
  2041. if (do_benchmark) {
  2042. int maxrss = getmaxrss() / 1024;
  2043. printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
  2044. }
  2045. exit_program(0);
  2046. return 0;
  2047. }