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.

2670 lines
87KB

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