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.

2680 lines
88KB

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