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.

2905 lines
90KB

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