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.

2477 lines
81KB

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