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.

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