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.

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