You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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