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.

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