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.

2595 lines
84KB

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