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.

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