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.

2411 lines
79KB

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