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.

2476 lines
81KB

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