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.

2410 lines
78KB

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