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.

2706 lines
89KB

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