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.

2413 lines
79KB

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