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.

2633 lines
86KB

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