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.

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