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.

2397 lines
78KB

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