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.

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