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.

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