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.

2453 lines
80KB

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