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.

2595 lines
85KB

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