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.

2621 lines
84KB

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