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.

2951 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 = { 0 };
  949. av_init_packet(&opkt);
  950. // EOF: flush output bitstream filters.
  951. if (!pkt) {
  952. output_packet(of, &opkt, ost, 1);
  953. return;
  954. }
  955. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  956. !ost->copy_initial_nonkeyframes)
  957. return;
  958. if (of->recording_time != INT64_MAX &&
  959. ist->last_dts >= of->recording_time + start_time) {
  960. ost->finished = 1;
  961. return;
  962. }
  963. if (f->recording_time != INT64_MAX) {
  964. start_time = f->ctx->start_time;
  965. if (f->start_time != AV_NOPTS_VALUE)
  966. start_time += f->start_time;
  967. if (ist->last_dts >= f->recording_time + start_time) {
  968. ost->finished = 1;
  969. return;
  970. }
  971. }
  972. /* force the input stream PTS */
  973. if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
  974. ost->sync_opts++;
  975. if (pkt->pts != AV_NOPTS_VALUE)
  976. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->mux_timebase) - ost_tb_start_time;
  977. else
  978. opkt.pts = AV_NOPTS_VALUE;
  979. if (pkt->dts == AV_NOPTS_VALUE)
  980. opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->mux_timebase);
  981. else
  982. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->mux_timebase);
  983. opkt.dts -= ost_tb_start_time;
  984. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->mux_timebase);
  985. opkt.flags = pkt->flags;
  986. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  987. if ( ost->enc_ctx->codec_id != AV_CODEC_ID_H264
  988. && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG1VIDEO
  989. && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG2VIDEO
  990. && ost->enc_ctx->codec_id != AV_CODEC_ID_VC1
  991. ) {
  992. if (av_parser_change(ost->parser, ost->parser_avctx,
  993. &opkt.data, &opkt.size,
  994. pkt->data, pkt->size,
  995. pkt->flags & AV_PKT_FLAG_KEY)) {
  996. opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
  997. if (!opkt.buf)
  998. exit_program(1);
  999. }
  1000. } else {
  1001. opkt.data = pkt->data;
  1002. opkt.size = pkt->size;
  1003. }
  1004. output_packet(of, &opkt, ost, 0);
  1005. }
  1006. static int ifilter_send_frame(InputFilter *ifilter, AVFrame *frame)
  1007. {
  1008. FilterGraph *fg = ifilter->graph;
  1009. int need_reinit, ret, i;
  1010. /* determine if the parameters for this input changed */
  1011. need_reinit = ifilter->format != frame->format;
  1012. if (!!ifilter->hw_frames_ctx != !!frame->hw_frames_ctx ||
  1013. (ifilter->hw_frames_ctx && ifilter->hw_frames_ctx->data != frame->hw_frames_ctx->data))
  1014. need_reinit = 1;
  1015. switch (ifilter->ist->st->codecpar->codec_type) {
  1016. case AVMEDIA_TYPE_AUDIO:
  1017. need_reinit |= ifilter->sample_rate != frame->sample_rate ||
  1018. ifilter->channel_layout != frame->channel_layout;
  1019. break;
  1020. case AVMEDIA_TYPE_VIDEO:
  1021. need_reinit |= ifilter->width != frame->width ||
  1022. ifilter->height != frame->height;
  1023. break;
  1024. }
  1025. if (need_reinit) {
  1026. ret = ifilter_parameters_from_frame(ifilter, frame);
  1027. if (ret < 0)
  1028. return ret;
  1029. }
  1030. /* (re)init the graph if possible, otherwise buffer the frame and return */
  1031. if (need_reinit || !fg->graph) {
  1032. for (i = 0; i < fg->nb_inputs; i++) {
  1033. if (fg->inputs[i]->format < 0) {
  1034. AVFrame *tmp = av_frame_clone(frame);
  1035. if (!tmp)
  1036. return AVERROR(ENOMEM);
  1037. av_frame_unref(frame);
  1038. if (!av_fifo_space(ifilter->frame_queue)) {
  1039. ret = av_fifo_realloc2(ifilter->frame_queue, 2 * av_fifo_size(ifilter->frame_queue));
  1040. if (ret < 0)
  1041. return ret;
  1042. }
  1043. av_fifo_generic_write(ifilter->frame_queue, &tmp, sizeof(tmp), NULL);
  1044. return 0;
  1045. }
  1046. }
  1047. ret = poll_filters();
  1048. if (ret < 0 && ret != AVERROR_EOF) {
  1049. char errbuf[128];
  1050. av_strerror(ret, errbuf, sizeof(errbuf));
  1051. av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
  1052. return ret;
  1053. }
  1054. ret = configure_filtergraph(fg);
  1055. if (ret < 0) {
  1056. av_log(NULL, AV_LOG_ERROR, "Error reinitializing filters!\n");
  1057. return ret;
  1058. }
  1059. }
  1060. ret = av_buffersrc_add_frame(ifilter->filter, frame);
  1061. if (ret < 0) {
  1062. av_log(NULL, AV_LOG_ERROR, "Error while filtering\n");
  1063. return ret;
  1064. }
  1065. return 0;
  1066. }
  1067. static int ifilter_send_eof(InputFilter *ifilter)
  1068. {
  1069. int i, j, ret;
  1070. ifilter->eof = 1;
  1071. if (ifilter->filter) {
  1072. ret = av_buffersrc_add_frame(ifilter->filter, NULL);
  1073. if (ret < 0)
  1074. return ret;
  1075. } else {
  1076. // the filtergraph was never configured
  1077. FilterGraph *fg = ifilter->graph;
  1078. for (i = 0; i < fg->nb_inputs; i++)
  1079. if (!fg->inputs[i]->eof)
  1080. break;
  1081. if (i == fg->nb_inputs) {
  1082. // All the input streams have finished without the filtergraph
  1083. // ever being configured.
  1084. // Mark the output streams as finished.
  1085. for (j = 0; j < fg->nb_outputs; j++)
  1086. finish_output_stream(fg->outputs[j]->ost);
  1087. }
  1088. }
  1089. return 0;
  1090. }
  1091. // This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
  1092. // There is the following difference: if you got a frame, you must call
  1093. // it again with pkt=NULL. pkt==NULL is treated differently from pkt.size==0
  1094. // (pkt==NULL means get more output, pkt.size==0 is a flush/drain packet)
  1095. static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
  1096. {
  1097. int ret;
  1098. *got_frame = 0;
  1099. if (pkt) {
  1100. ret = avcodec_send_packet(avctx, pkt);
  1101. // In particular, we don't expect AVERROR(EAGAIN), because we read all
  1102. // decoded frames with avcodec_receive_frame() until done.
  1103. if (ret < 0)
  1104. return ret == AVERROR_EOF ? 0 : ret;
  1105. }
  1106. ret = avcodec_receive_frame(avctx, frame);
  1107. if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
  1108. return ret;
  1109. if (ret >= 0)
  1110. *got_frame = 1;
  1111. return 0;
  1112. }
  1113. int guess_input_channel_layout(InputStream *ist)
  1114. {
  1115. AVCodecContext *dec = ist->dec_ctx;
  1116. if (!dec->channel_layout) {
  1117. char layout_name[256];
  1118. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  1119. if (!dec->channel_layout)
  1120. return 0;
  1121. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  1122. dec->channels, dec->channel_layout);
  1123. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  1124. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  1125. }
  1126. return 1;
  1127. }
  1128. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output,
  1129. int *decode_failed)
  1130. {
  1131. AVFrame *decoded_frame, *f;
  1132. AVCodecContext *avctx = ist->dec_ctx;
  1133. int i, ret, err = 0;
  1134. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1135. return AVERROR(ENOMEM);
  1136. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1137. return AVERROR(ENOMEM);
  1138. decoded_frame = ist->decoded_frame;
  1139. ret = decode(avctx, decoded_frame, got_output, pkt);
  1140. if (ret < 0)
  1141. *decode_failed = 1;
  1142. if (!*got_output || ret < 0)
  1143. return ret;
  1144. ist->samples_decoded += decoded_frame->nb_samples;
  1145. ist->frames_decoded++;
  1146. /* if the decoder provides a pts, use it instead of the last packet pts.
  1147. the decoder could be delaying output by a packet or more. */
  1148. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1149. ist->next_dts = av_rescale_q(decoded_frame->pts, ist->st->time_base, AV_TIME_BASE_Q);
  1150. else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
  1151. decoded_frame->pts = pkt->pts;
  1152. }
  1153. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1154. decoded_frame->pts = av_rescale_q(decoded_frame->pts,
  1155. ist->st->time_base,
  1156. (AVRational){1, avctx->sample_rate});
  1157. ist->nb_samples = decoded_frame->nb_samples;
  1158. for (i = 0; i < ist->nb_filters; i++) {
  1159. if (i < ist->nb_filters - 1) {
  1160. f = ist->filter_frame;
  1161. err = av_frame_ref(f, decoded_frame);
  1162. if (err < 0)
  1163. break;
  1164. } else
  1165. f = decoded_frame;
  1166. err = ifilter_send_frame(ist->filters[i], f);
  1167. if (err < 0)
  1168. break;
  1169. }
  1170. av_frame_unref(ist->filter_frame);
  1171. av_frame_unref(decoded_frame);
  1172. return err < 0 ? err : ret;
  1173. }
  1174. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output,
  1175. int *decode_failed)
  1176. {
  1177. AVFrame *decoded_frame, *f;
  1178. int i, ret = 0, err = 0;
  1179. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1180. return AVERROR(ENOMEM);
  1181. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1182. return AVERROR(ENOMEM);
  1183. decoded_frame = ist->decoded_frame;
  1184. ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt);
  1185. if (ret < 0)
  1186. *decode_failed = 1;
  1187. if (!*got_output || ret < 0)
  1188. return ret;
  1189. ist->frames_decoded++;
  1190. if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
  1191. err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
  1192. if (err < 0)
  1193. goto fail;
  1194. }
  1195. ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
  1196. decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pts,
  1197. decoded_frame->pkt_dts);
  1198. if (ist->framerate.num)
  1199. decoded_frame->pts = ist->cfr_next_pts++;
  1200. if (ist->st->sample_aspect_ratio.num)
  1201. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1202. for (i = 0; i < ist->nb_filters; i++) {
  1203. if (i < ist->nb_filters - 1) {
  1204. f = ist->filter_frame;
  1205. err = av_frame_ref(f, decoded_frame);
  1206. if (err < 0)
  1207. break;
  1208. } else
  1209. f = decoded_frame;
  1210. err = ifilter_send_frame(ist->filters[i], f);
  1211. if (err < 0)
  1212. break;
  1213. }
  1214. fail:
  1215. av_frame_unref(ist->filter_frame);
  1216. av_frame_unref(decoded_frame);
  1217. return err < 0 ? err : ret;
  1218. }
  1219. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output,
  1220. int *decode_failed)
  1221. {
  1222. AVSubtitle subtitle;
  1223. int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
  1224. &subtitle, got_output, pkt);
  1225. if (ret < 0) {
  1226. *decode_failed = 1;
  1227. return ret;
  1228. }
  1229. if (!*got_output)
  1230. return ret;
  1231. ist->frames_decoded++;
  1232. for (i = 0; i < nb_output_streams; i++) {
  1233. OutputStream *ost = output_streams[i];
  1234. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1235. continue;
  1236. do_subtitle_out(output_files[ost->file_index], ost, ist, &subtitle, pkt->pts);
  1237. }
  1238. avsubtitle_free(&subtitle);
  1239. return ret;
  1240. }
  1241. static int send_filter_eof(InputStream *ist)
  1242. {
  1243. int i, ret;
  1244. for (i = 0; i < ist->nb_filters; i++) {
  1245. ret = ifilter_send_eof(ist->filters[i]);
  1246. if (ret < 0)
  1247. return ret;
  1248. }
  1249. return 0;
  1250. }
  1251. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1252. static void process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
  1253. {
  1254. int i;
  1255. int repeating = 0;
  1256. AVPacket avpkt;
  1257. if (ist->next_dts == AV_NOPTS_VALUE)
  1258. ist->next_dts = ist->last_dts;
  1259. if (!pkt) {
  1260. /* EOF handling */
  1261. av_init_packet(&avpkt);
  1262. avpkt.data = NULL;
  1263. avpkt.size = 0;
  1264. } else {
  1265. avpkt = *pkt;
  1266. }
  1267. if (pkt && pkt->dts != AV_NOPTS_VALUE)
  1268. ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1269. // while we have more to decode or while the decoder did output something on EOF
  1270. while (ist->decoding_needed && (!pkt || avpkt.size > 0)) {
  1271. int ret = 0;
  1272. int got_output = 0;
  1273. int decode_failed = 0;
  1274. if (!repeating)
  1275. ist->last_dts = ist->next_dts;
  1276. switch (ist->dec_ctx->codec_type) {
  1277. case AVMEDIA_TYPE_AUDIO:
  1278. ret = decode_audio (ist, repeating ? NULL : &avpkt, &got_output,
  1279. &decode_failed);
  1280. break;
  1281. case AVMEDIA_TYPE_VIDEO:
  1282. ret = decode_video (ist, repeating ? NULL : &avpkt, &got_output,
  1283. &decode_failed);
  1284. if (repeating && !got_output)
  1285. ;
  1286. else if (pkt && pkt->duration)
  1287. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1288. else if (ist->st->avg_frame_rate.num)
  1289. ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
  1290. AV_TIME_BASE_Q);
  1291. else if (ist->dec_ctx->framerate.num != 0) {
  1292. int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
  1293. ist->dec_ctx->ticks_per_frame;
  1294. ist->next_dts += av_rescale_q(ticks, ist->dec_ctx->framerate, AV_TIME_BASE_Q);
  1295. }
  1296. break;
  1297. case AVMEDIA_TYPE_SUBTITLE:
  1298. if (repeating)
  1299. break;
  1300. ret = transcode_subtitles(ist, &avpkt, &got_output, &decode_failed);
  1301. break;
  1302. default:
  1303. return;
  1304. }
  1305. if (ret < 0) {
  1306. if (decode_failed) {
  1307. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
  1308. ist->file_index, ist->st->index);
  1309. } else {
  1310. av_log(NULL, AV_LOG_FATAL, "Error while processing the decoded "
  1311. "data for stream #%d:%d\n", ist->file_index, ist->st->index);
  1312. }
  1313. if (!decode_failed || exit_on_error)
  1314. exit_program(1);
  1315. break;
  1316. }
  1317. if (!got_output)
  1318. break;
  1319. repeating = 1;
  1320. }
  1321. /* after flushing, send an EOF on all the filter inputs attached to the stream */
  1322. /* except when looping we need to flush but not to send an EOF */
  1323. if (!pkt && ist->decoding_needed && !no_eof) {
  1324. int ret = send_filter_eof(ist);
  1325. if (ret < 0) {
  1326. av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
  1327. exit_program(1);
  1328. }
  1329. }
  1330. /* handle stream copy */
  1331. if (!ist->decoding_needed) {
  1332. ist->last_dts = ist->next_dts;
  1333. switch (ist->dec_ctx->codec_type) {
  1334. case AVMEDIA_TYPE_AUDIO:
  1335. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
  1336. ist->dec_ctx->sample_rate;
  1337. break;
  1338. case AVMEDIA_TYPE_VIDEO:
  1339. if (ist->dec_ctx->framerate.num != 0) {
  1340. int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
  1341. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1342. ist->dec_ctx->framerate.den * ticks) /
  1343. ist->dec_ctx->framerate.num;
  1344. }
  1345. break;
  1346. }
  1347. }
  1348. for (i = 0; i < nb_output_streams; i++) {
  1349. OutputStream *ost = output_streams[i];
  1350. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1351. continue;
  1352. do_streamcopy(ist, ost, pkt);
  1353. }
  1354. return;
  1355. }
  1356. static void print_sdp(void)
  1357. {
  1358. char sdp[16384];
  1359. int i;
  1360. AVFormatContext **avc;
  1361. for (i = 0; i < nb_output_files; i++) {
  1362. if (!output_files[i]->header_written)
  1363. return;
  1364. }
  1365. avc = av_malloc(sizeof(*avc) * nb_output_files);
  1366. if (!avc)
  1367. exit_program(1);
  1368. for (i = 0; i < nb_output_files; i++)
  1369. avc[i] = output_files[i]->ctx;
  1370. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1371. printf("SDP:\n%s\n", sdp);
  1372. fflush(stdout);
  1373. av_freep(&avc);
  1374. }
  1375. static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
  1376. {
  1377. int i;
  1378. for (i = 0; hwaccels[i].name; i++)
  1379. if (hwaccels[i].pix_fmt == pix_fmt)
  1380. return &hwaccels[i];
  1381. return NULL;
  1382. }
  1383. static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
  1384. {
  1385. InputStream *ist = s->opaque;
  1386. const enum AVPixelFormat *p;
  1387. int ret;
  1388. for (p = pix_fmts; *p != -1; p++) {
  1389. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
  1390. const HWAccel *hwaccel;
  1391. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  1392. break;
  1393. hwaccel = get_hwaccel(*p);
  1394. if (!hwaccel ||
  1395. (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
  1396. (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
  1397. continue;
  1398. ret = hwaccel->init(s);
  1399. if (ret < 0) {
  1400. if (ist->hwaccel_id == hwaccel->id) {
  1401. av_log(NULL, AV_LOG_FATAL,
  1402. "%s hwaccel requested for input stream #%d:%d, "
  1403. "but cannot be initialized.\n", hwaccel->name,
  1404. ist->file_index, ist->st->index);
  1405. return AV_PIX_FMT_NONE;
  1406. }
  1407. continue;
  1408. }
  1409. if (ist->hw_frames_ctx) {
  1410. s->hw_frames_ctx = av_buffer_ref(ist->hw_frames_ctx);
  1411. if (!s->hw_frames_ctx)
  1412. return AV_PIX_FMT_NONE;
  1413. }
  1414. ist->active_hwaccel_id = hwaccel->id;
  1415. ist->hwaccel_pix_fmt = *p;
  1416. break;
  1417. }
  1418. return *p;
  1419. }
  1420. static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
  1421. {
  1422. InputStream *ist = s->opaque;
  1423. if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
  1424. return ist->hwaccel_get_buffer(s, frame, flags);
  1425. return avcodec_default_get_buffer2(s, frame, flags);
  1426. }
  1427. static int init_input_stream(int ist_index, char *error, int error_len)
  1428. {
  1429. int ret;
  1430. InputStream *ist = input_streams[ist_index];
  1431. if (ist->decoding_needed) {
  1432. AVCodec *codec = ist->dec;
  1433. if (!codec) {
  1434. snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
  1435. ist->dec_ctx->codec_id, ist->file_index, ist->st->index);
  1436. return AVERROR(EINVAL);
  1437. }
  1438. ist->dec_ctx->opaque = ist;
  1439. ist->dec_ctx->get_format = get_format;
  1440. ist->dec_ctx->get_buffer2 = get_buffer;
  1441. ist->dec_ctx->thread_safe_callbacks = 1;
  1442. av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
  1443. if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
  1444. av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
  1445. ret = hw_device_setup_for_decode(ist);
  1446. if (ret < 0) {
  1447. char errbuf[128];
  1448. av_strerror(ret, errbuf, sizeof(errbuf));
  1449. snprintf(error, error_len, "Device setup failed for "
  1450. "decoder on input stream #%d:%d : %s",
  1451. ist->file_index, ist->st->index, errbuf);
  1452. return ret;
  1453. }
  1454. if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
  1455. char errbuf[128];
  1456. if (ret == AVERROR_EXPERIMENTAL)
  1457. abort_codec_experimental(codec, 0);
  1458. av_strerror(ret, errbuf, sizeof(errbuf));
  1459. snprintf(error, error_len,
  1460. "Error while opening decoder for input stream "
  1461. "#%d:%d : %s",
  1462. ist->file_index, ist->st->index, errbuf);
  1463. return ret;
  1464. }
  1465. assert_avoptions(ist->decoder_opts);
  1466. }
  1467. 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;
  1468. ist->next_dts = AV_NOPTS_VALUE;
  1469. init_pts_correction(&ist->pts_ctx);
  1470. return 0;
  1471. }
  1472. static InputStream *get_input_stream(OutputStream *ost)
  1473. {
  1474. if (ost->source_index >= 0)
  1475. return input_streams[ost->source_index];
  1476. if (ost->filter) {
  1477. FilterGraph *fg = ost->filter->graph;
  1478. int i;
  1479. for (i = 0; i < fg->nb_inputs; i++)
  1480. if (fg->inputs[i]->ist->dec_ctx->codec_type == ost->enc_ctx->codec_type)
  1481. return fg->inputs[i]->ist;
  1482. }
  1483. return NULL;
  1484. }
  1485. /* open the muxer when all the streams are initialized */
  1486. static int check_init_output_file(OutputFile *of, int file_index)
  1487. {
  1488. int ret, i;
  1489. for (i = 0; i < of->ctx->nb_streams; i++) {
  1490. OutputStream *ost = output_streams[of->ost_index + i];
  1491. if (!ost->initialized)
  1492. return 0;
  1493. }
  1494. of->ctx->interrupt_callback = int_cb;
  1495. ret = avformat_write_header(of->ctx, &of->opts);
  1496. if (ret < 0) {
  1497. char errbuf[128];
  1498. av_strerror(ret, errbuf, sizeof(errbuf));
  1499. av_log(NULL, AV_LOG_ERROR,
  1500. "Could not write header for output file #%d "
  1501. "(incorrect codec parameters ?): %s",
  1502. file_index, errbuf);
  1503. return ret;
  1504. }
  1505. assert_avoptions(of->opts);
  1506. of->header_written = 1;
  1507. av_dump_format(of->ctx, file_index, of->ctx->filename, 1);
  1508. if (want_sdp)
  1509. print_sdp();
  1510. /* flush the muxing queues */
  1511. for (i = 0; i < of->ctx->nb_streams; i++) {
  1512. OutputStream *ost = output_streams[of->ost_index + i];
  1513. while (av_fifo_size(ost->muxing_queue)) {
  1514. AVPacket pkt;
  1515. av_fifo_generic_read(ost->muxing_queue, &pkt, sizeof(pkt), NULL);
  1516. write_packet(of, &pkt, ost);
  1517. }
  1518. }
  1519. return 0;
  1520. }
  1521. static int init_output_bsfs(OutputStream *ost)
  1522. {
  1523. AVBSFContext *ctx;
  1524. int i, ret;
  1525. if (!ost->nb_bitstream_filters)
  1526. return 0;
  1527. for (i = 0; i < ost->nb_bitstream_filters; i++) {
  1528. ctx = ost->bsf_ctx[i];
  1529. ret = avcodec_parameters_copy(ctx->par_in,
  1530. i ? ost->bsf_ctx[i - 1]->par_out : ost->st->codecpar);
  1531. if (ret < 0)
  1532. return ret;
  1533. ctx->time_base_in = i ? ost->bsf_ctx[i - 1]->time_base_out : ost->st->time_base;
  1534. ret = av_bsf_init(ctx);
  1535. if (ret < 0) {
  1536. av_log(NULL, AV_LOG_ERROR, "Error initializing bitstream filter: %s\n",
  1537. ctx->filter->name);
  1538. return ret;
  1539. }
  1540. }
  1541. ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
  1542. if (ret < 0)
  1543. return ret;
  1544. ost->st->time_base = ctx->time_base_out;
  1545. return 0;
  1546. }
  1547. static int init_output_stream_streamcopy(OutputStream *ost)
  1548. {
  1549. OutputFile *of = output_files[ost->file_index];
  1550. InputStream *ist = get_input_stream(ost);
  1551. AVCodecParameters *par_dst = ost->st->codecpar;
  1552. AVCodecParameters *par_src = ist->st->codecpar;
  1553. AVRational sar;
  1554. uint32_t codec_tag = par_dst->codec_tag;
  1555. int i, ret;
  1556. if (!codec_tag) {
  1557. if (!of->ctx->oformat->codec_tag ||
  1558. av_codec_get_id (of->ctx->oformat->codec_tag, par_src->codec_tag) == par_src->codec_id ||
  1559. av_codec_get_tag(of->ctx->oformat->codec_tag, par_src->codec_id) <= 0)
  1560. codec_tag = par_src->codec_tag;
  1561. }
  1562. ret = avcodec_parameters_copy(par_dst, par_src);
  1563. if (ret < 0)
  1564. return ret;
  1565. par_dst->codec_tag = codec_tag;
  1566. ost->st->disposition = ist->st->disposition;
  1567. ost->st->time_base = ist->st->time_base;
  1568. if (ost->bitrate_override)
  1569. par_dst->bit_rate = ost->bitrate_override;
  1570. if (ist->st->nb_side_data) {
  1571. ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
  1572. sizeof(*ist->st->side_data));
  1573. if (!ost->st->side_data)
  1574. return AVERROR(ENOMEM);
  1575. for (i = 0; i < ist->st->nb_side_data; i++) {
  1576. const AVPacketSideData *sd_src = &ist->st->side_data[i];
  1577. AVPacketSideData *sd_dst = &ost->st->side_data[i];
  1578. sd_dst->data = av_malloc(sd_src->size);
  1579. if (!sd_dst->data)
  1580. return AVERROR(ENOMEM);
  1581. memcpy(sd_dst->data, sd_src->data, sd_src->size);
  1582. sd_dst->size = sd_src->size;
  1583. sd_dst->type = sd_src->type;
  1584. ost->st->nb_side_data++;
  1585. }
  1586. }
  1587. ost->parser = av_parser_init(par_dst->codec_id);
  1588. ost->parser_avctx = avcodec_alloc_context3(NULL);
  1589. if (!ost->parser_avctx)
  1590. return AVERROR(ENOMEM);
  1591. if (par_dst->codec_type == AVMEDIA_TYPE_VIDEO) {
  1592. if (ost->frame_aspect_ratio)
  1593. sar = av_d2q(ost->frame_aspect_ratio * par_dst->height / par_dst->width, 255);
  1594. else if (ist->st->sample_aspect_ratio.num)
  1595. sar = ist->st->sample_aspect_ratio;
  1596. else
  1597. sar = par_src->sample_aspect_ratio;
  1598. ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
  1599. }
  1600. return 0;
  1601. }
  1602. static void set_encoder_id(OutputFile *of, OutputStream *ost)
  1603. {
  1604. AVDictionaryEntry *e;
  1605. uint8_t *encoder_string;
  1606. int encoder_string_len;
  1607. int format_flags = 0;
  1608. e = av_dict_get(of->opts, "fflags", NULL, 0);
  1609. if (e) {
  1610. const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
  1611. if (!o)
  1612. return;
  1613. av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
  1614. }
  1615. encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
  1616. encoder_string = av_mallocz(encoder_string_len);
  1617. if (!encoder_string)
  1618. exit_program(1);
  1619. if (!(format_flags & AVFMT_FLAG_BITEXACT))
  1620. av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
  1621. av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
  1622. av_dict_set(&ost->st->metadata, "encoder", encoder_string,
  1623. AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
  1624. }
  1625. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1626. AVCodecContext *avctx)
  1627. {
  1628. char *p;
  1629. int n = 1, i;
  1630. int64_t t;
  1631. for (p = kf; *p; p++)
  1632. if (*p == ',')
  1633. n++;
  1634. ost->forced_kf_count = n;
  1635. ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
  1636. if (!ost->forced_kf_pts) {
  1637. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1638. exit_program(1);
  1639. }
  1640. p = kf;
  1641. for (i = 0; i < n; i++) {
  1642. char *next = strchr(p, ',');
  1643. if (next)
  1644. *next++ = 0;
  1645. t = parse_time_or_die("force_key_frames", p, 1);
  1646. ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1647. p = next;
  1648. }
  1649. }
  1650. static int init_output_stream_encode(OutputStream *ost)
  1651. {
  1652. InputStream *ist = get_input_stream(ost);
  1653. AVCodecContext *enc_ctx = ost->enc_ctx;
  1654. AVCodecContext *dec_ctx = NULL;
  1655. set_encoder_id(output_files[ost->file_index], ost);
  1656. if (ist) {
  1657. ost->st->disposition = ist->st->disposition;
  1658. dec_ctx = ist->dec_ctx;
  1659. enc_ctx->bits_per_raw_sample = dec_ctx->bits_per_raw_sample;
  1660. enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
  1661. }
  1662. switch (enc_ctx->codec_type) {
  1663. case AVMEDIA_TYPE_AUDIO:
  1664. enc_ctx->sample_fmt = ost->filter->filter->inputs[0]->format;
  1665. enc_ctx->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  1666. enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  1667. enc_ctx->channels = av_get_channel_layout_nb_channels(enc_ctx->channel_layout);
  1668. enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate };
  1669. break;
  1670. case AVMEDIA_TYPE_VIDEO:
  1671. enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;
  1672. enc_ctx->width = ost->filter->filter->inputs[0]->w;
  1673. enc_ctx->height = ost->filter->filter->inputs[0]->h;
  1674. enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  1675. ost->frame_aspect_ratio ? // overridden by the -aspect cli option
  1676. av_d2q(ost->frame_aspect_ratio * enc_ctx->height/enc_ctx->width, 255) :
  1677. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  1678. enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;
  1679. enc_ctx->framerate = ost->frame_rate;
  1680. ost->st->avg_frame_rate = ost->frame_rate;
  1681. if (dec_ctx &&
  1682. (enc_ctx->width != dec_ctx->width ||
  1683. enc_ctx->height != dec_ctx->height ||
  1684. enc_ctx->pix_fmt != dec_ctx->pix_fmt)) {
  1685. enc_ctx->bits_per_raw_sample = 0;
  1686. }
  1687. if (ost->forced_keyframes)
  1688. parse_forced_key_frames(ost->forced_keyframes, ost,
  1689. ost->enc_ctx);
  1690. break;
  1691. case AVMEDIA_TYPE_SUBTITLE:
  1692. enc_ctx->time_base = (AVRational){1, 1000};
  1693. break;
  1694. default:
  1695. abort();
  1696. break;
  1697. }
  1698. return 0;
  1699. }
  1700. static int init_output_stream(OutputStream *ost, char *error, int error_len)
  1701. {
  1702. int ret = 0;
  1703. if (ost->encoding_needed) {
  1704. AVCodec *codec = ost->enc;
  1705. AVCodecContext *dec = NULL;
  1706. InputStream *ist;
  1707. ret = init_output_stream_encode(ost);
  1708. if (ret < 0)
  1709. return ret;
  1710. if ((ist = get_input_stream(ost)))
  1711. dec = ist->dec_ctx;
  1712. if (dec && dec->subtitle_header) {
  1713. ost->enc_ctx->subtitle_header = av_malloc(dec->subtitle_header_size);
  1714. if (!ost->enc_ctx->subtitle_header)
  1715. return AVERROR(ENOMEM);
  1716. memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  1717. ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
  1718. }
  1719. if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
  1720. av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
  1721. if (ost->filter && ost->filter->filter->inputs[0]->hw_frames_ctx &&
  1722. ((AVHWFramesContext*)ost->filter->filter->inputs[0]->hw_frames_ctx->data)->format ==
  1723. ost->filter->filter->inputs[0]->format) {
  1724. ost->enc_ctx->hw_frames_ctx = av_buffer_ref(ost->filter->filter->inputs[0]->hw_frames_ctx);
  1725. if (!ost->enc_ctx->hw_frames_ctx)
  1726. return AVERROR(ENOMEM);
  1727. } else {
  1728. ret = hw_device_setup_for_encode(ost);
  1729. if (ret < 0) {
  1730. char errbuf[128];
  1731. av_strerror(ret, errbuf, sizeof(errbuf));
  1732. snprintf(error, error_len, "Device setup failed for "
  1733. "encoder on output stream #%d:%d : %s",
  1734. ost->file_index, ost->index, errbuf);
  1735. return ret;
  1736. }
  1737. }
  1738. if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
  1739. if (ret == AVERROR_EXPERIMENTAL)
  1740. abort_codec_experimental(codec, 1);
  1741. snprintf(error, error_len,
  1742. "Error while opening encoder for output stream #%d:%d - "
  1743. "maybe incorrect parameters such as bit_rate, rate, width or height",
  1744. ost->file_index, ost->index);
  1745. return ret;
  1746. }
  1747. assert_avoptions(ost->encoder_opts);
  1748. if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
  1749. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  1750. "It takes bits/s as argument, not kbits/s\n");
  1751. ret = avcodec_parameters_from_context(ost->st->codecpar, ost->enc_ctx);
  1752. if (ret < 0) {
  1753. av_log(NULL, AV_LOG_FATAL,
  1754. "Error initializing the output stream codec context.\n");
  1755. exit_program(1);
  1756. }
  1757. if (ost->enc_ctx->nb_coded_side_data) {
  1758. int i;
  1759. ost->st->side_data = av_realloc_array(NULL, ost->enc_ctx->nb_coded_side_data,
  1760. sizeof(*ost->st->side_data));
  1761. if (!ost->st->side_data)
  1762. return AVERROR(ENOMEM);
  1763. for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
  1764. const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
  1765. AVPacketSideData *sd_dst = &ost->st->side_data[i];
  1766. sd_dst->data = av_malloc(sd_src->size);
  1767. if (!sd_dst->data)
  1768. return AVERROR(ENOMEM);
  1769. memcpy(sd_dst->data, sd_src->data, sd_src->size);
  1770. sd_dst->size = sd_src->size;
  1771. sd_dst->type = sd_src->type;
  1772. ost->st->nb_side_data++;
  1773. }
  1774. }
  1775. ost->st->time_base = ost->enc_ctx->time_base;
  1776. } else if (ost->stream_copy) {
  1777. ret = init_output_stream_streamcopy(ost);
  1778. if (ret < 0)
  1779. return ret;
  1780. /*
  1781. * FIXME: will the codec context used by the parser during streamcopy
  1782. * This should go away with the new parser API.
  1783. */
  1784. ret = avcodec_parameters_to_context(ost->parser_avctx, ost->st->codecpar);
  1785. if (ret < 0)
  1786. return ret;
  1787. }
  1788. /* initialize bitstream filters for the output stream
  1789. * needs to be done here, because the codec id for streamcopy is not
  1790. * known until now */
  1791. ret = init_output_bsfs(ost);
  1792. if (ret < 0)
  1793. return ret;
  1794. ost->mux_timebase = ost->st->time_base;
  1795. ost->initialized = 1;
  1796. ret = check_init_output_file(output_files[ost->file_index], ost->file_index);
  1797. if (ret < 0)
  1798. return ret;
  1799. return ret;
  1800. }
  1801. static int transcode_init(void)
  1802. {
  1803. int ret = 0, i, j, k;
  1804. OutputStream *ost;
  1805. InputStream *ist;
  1806. char error[1024];
  1807. /* init framerate emulation */
  1808. for (i = 0; i < nb_input_files; i++) {
  1809. InputFile *ifile = input_files[i];
  1810. if (ifile->rate_emu)
  1811. for (j = 0; j < ifile->nb_streams; j++)
  1812. input_streams[j + ifile->ist_index]->start = av_gettime_relative();
  1813. }
  1814. /* init input streams */
  1815. for (i = 0; i < nb_input_streams; i++)
  1816. if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
  1817. goto dump_format;
  1818. /* open each encoder */
  1819. for (i = 0; i < nb_output_streams; i++) {
  1820. // skip streams fed from filtergraphs until we have a frame for them
  1821. if (output_streams[i]->filter)
  1822. continue;
  1823. ret = init_output_stream(output_streams[i], error, sizeof(error));
  1824. if (ret < 0)
  1825. goto dump_format;
  1826. }
  1827. /* discard unused programs */
  1828. for (i = 0; i < nb_input_files; i++) {
  1829. InputFile *ifile = input_files[i];
  1830. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  1831. AVProgram *p = ifile->ctx->programs[j];
  1832. int discard = AVDISCARD_ALL;
  1833. for (k = 0; k < p->nb_stream_indexes; k++)
  1834. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  1835. discard = AVDISCARD_DEFAULT;
  1836. break;
  1837. }
  1838. p->discard = discard;
  1839. }
  1840. }
  1841. dump_format:
  1842. /* dump the stream mapping */
  1843. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  1844. for (i = 0; i < nb_input_streams; i++) {
  1845. ist = input_streams[i];
  1846. for (j = 0; j < ist->nb_filters; j++) {
  1847. if (!filtergraph_is_simple(ist->filters[j]->graph)) {
  1848. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  1849. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  1850. ist->filters[j]->name);
  1851. if (nb_filtergraphs > 1)
  1852. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  1853. av_log(NULL, AV_LOG_INFO, "\n");
  1854. }
  1855. }
  1856. }
  1857. for (i = 0; i < nb_output_streams; i++) {
  1858. ost = output_streams[i];
  1859. if (ost->attachment_filename) {
  1860. /* an attached file */
  1861. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  1862. ost->attachment_filename, ost->file_index, ost->index);
  1863. continue;
  1864. }
  1865. if (ost->filter && !filtergraph_is_simple(ost->filter->graph)) {
  1866. /* output from a complex graph */
  1867. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  1868. if (nb_filtergraphs > 1)
  1869. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  1870. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  1871. ost->index, ost->enc ? ost->enc->name : "?");
  1872. continue;
  1873. }
  1874. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  1875. input_streams[ost->source_index]->file_index,
  1876. input_streams[ost->source_index]->st->index,
  1877. ost->file_index,
  1878. ost->index);
  1879. if (ost->sync_ist != input_streams[ost->source_index])
  1880. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  1881. ost->sync_ist->file_index,
  1882. ost->sync_ist->st->index);
  1883. if (ost->stream_copy)
  1884. av_log(NULL, AV_LOG_INFO, " (copy)");
  1885. else {
  1886. const AVCodec *in_codec = input_streams[ost->source_index]->dec;
  1887. const AVCodec *out_codec = ost->enc;
  1888. const char *decoder_name = "?";
  1889. const char *in_codec_name = "?";
  1890. const char *encoder_name = "?";
  1891. const char *out_codec_name = "?";
  1892. const AVCodecDescriptor *desc;
  1893. if (in_codec) {
  1894. decoder_name = in_codec->name;
  1895. desc = avcodec_descriptor_get(in_codec->id);
  1896. if (desc)
  1897. in_codec_name = desc->name;
  1898. if (!strcmp(decoder_name, in_codec_name))
  1899. decoder_name = "native";
  1900. }
  1901. if (out_codec) {
  1902. encoder_name = out_codec->name;
  1903. desc = avcodec_descriptor_get(out_codec->id);
  1904. if (desc)
  1905. out_codec_name = desc->name;
  1906. if (!strcmp(encoder_name, out_codec_name))
  1907. encoder_name = "native";
  1908. }
  1909. av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
  1910. in_codec_name, decoder_name,
  1911. out_codec_name, encoder_name);
  1912. }
  1913. av_log(NULL, AV_LOG_INFO, "\n");
  1914. }
  1915. if (ret) {
  1916. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  1917. return ret;
  1918. }
  1919. return 0;
  1920. }
  1921. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  1922. static int need_output(void)
  1923. {
  1924. int i;
  1925. for (i = 0; i < nb_output_streams; i++) {
  1926. OutputStream *ost = output_streams[i];
  1927. OutputFile *of = output_files[ost->file_index];
  1928. AVFormatContext *os = output_files[ost->file_index]->ctx;
  1929. if (ost->finished ||
  1930. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  1931. continue;
  1932. if (ost->frame_number >= ost->max_frames) {
  1933. int j;
  1934. for (j = 0; j < of->ctx->nb_streams; j++)
  1935. output_streams[of->ost_index + j]->finished = 1;
  1936. continue;
  1937. }
  1938. return 1;
  1939. }
  1940. return 0;
  1941. }
  1942. static InputFile *select_input_file(void)
  1943. {
  1944. InputFile *ifile = NULL;
  1945. int64_t ipts_min = INT64_MAX;
  1946. int i;
  1947. for (i = 0; i < nb_input_streams; i++) {
  1948. InputStream *ist = input_streams[i];
  1949. int64_t ipts = ist->last_dts;
  1950. if (ist->discard || input_files[ist->file_index]->eagain)
  1951. continue;
  1952. if (!input_files[ist->file_index]->eof_reached) {
  1953. if (ipts < ipts_min) {
  1954. ipts_min = ipts;
  1955. ifile = input_files[ist->file_index];
  1956. }
  1957. }
  1958. }
  1959. return ifile;
  1960. }
  1961. #if HAVE_PTHREADS
  1962. static void *input_thread(void *arg)
  1963. {
  1964. InputFile *f = arg;
  1965. int ret = 0;
  1966. while (!transcoding_finished && ret >= 0) {
  1967. AVPacket pkt;
  1968. ret = av_read_frame(f->ctx, &pkt);
  1969. if (ret == AVERROR(EAGAIN)) {
  1970. av_usleep(10000);
  1971. ret = 0;
  1972. continue;
  1973. } else if (ret < 0)
  1974. break;
  1975. pthread_mutex_lock(&f->fifo_lock);
  1976. while (!av_fifo_space(f->fifo))
  1977. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  1978. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  1979. pthread_mutex_unlock(&f->fifo_lock);
  1980. }
  1981. f->finished = 1;
  1982. return NULL;
  1983. }
  1984. static void free_input_threads(void)
  1985. {
  1986. int i;
  1987. if (nb_input_files == 1)
  1988. return;
  1989. transcoding_finished = 1;
  1990. for (i = 0; i < nb_input_files; i++) {
  1991. InputFile *f = input_files[i];
  1992. AVPacket pkt;
  1993. if (!f->fifo || f->joined)
  1994. continue;
  1995. pthread_mutex_lock(&f->fifo_lock);
  1996. while (av_fifo_size(f->fifo)) {
  1997. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  1998. av_packet_unref(&pkt);
  1999. }
  2000. pthread_cond_signal(&f->fifo_cond);
  2001. pthread_mutex_unlock(&f->fifo_lock);
  2002. pthread_join(f->thread, NULL);
  2003. f->joined = 1;
  2004. while (av_fifo_size(f->fifo)) {
  2005. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  2006. av_packet_unref(&pkt);
  2007. }
  2008. av_fifo_free(f->fifo);
  2009. }
  2010. }
  2011. static int init_input_threads(void)
  2012. {
  2013. int i, ret;
  2014. if (nb_input_files == 1)
  2015. return 0;
  2016. for (i = 0; i < nb_input_files; i++) {
  2017. InputFile *f = input_files[i];
  2018. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  2019. return AVERROR(ENOMEM);
  2020. pthread_mutex_init(&f->fifo_lock, NULL);
  2021. pthread_cond_init (&f->fifo_cond, NULL);
  2022. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  2023. return AVERROR(ret);
  2024. }
  2025. return 0;
  2026. }
  2027. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  2028. {
  2029. int ret = 0;
  2030. pthread_mutex_lock(&f->fifo_lock);
  2031. if (av_fifo_size(f->fifo)) {
  2032. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  2033. pthread_cond_signal(&f->fifo_cond);
  2034. } else {
  2035. if (f->finished)
  2036. ret = AVERROR_EOF;
  2037. else
  2038. ret = AVERROR(EAGAIN);
  2039. }
  2040. pthread_mutex_unlock(&f->fifo_lock);
  2041. return ret;
  2042. }
  2043. #endif
  2044. static int get_input_packet(InputFile *f, AVPacket *pkt)
  2045. {
  2046. if (f->rate_emu) {
  2047. int i;
  2048. for (i = 0; i < f->nb_streams; i++) {
  2049. InputStream *ist = input_streams[f->ist_index + i];
  2050. int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
  2051. int64_t now = av_gettime_relative() - ist->start;
  2052. if (pts > now)
  2053. return AVERROR(EAGAIN);
  2054. }
  2055. }
  2056. #if HAVE_PTHREADS
  2057. if (nb_input_files > 1)
  2058. return get_input_packet_mt(f, pkt);
  2059. #endif
  2060. return av_read_frame(f->ctx, pkt);
  2061. }
  2062. static int got_eagain(void)
  2063. {
  2064. int i;
  2065. for (i = 0; i < nb_input_files; i++)
  2066. if (input_files[i]->eagain)
  2067. return 1;
  2068. return 0;
  2069. }
  2070. static void reset_eagain(void)
  2071. {
  2072. int i;
  2073. for (i = 0; i < nb_input_files; i++)
  2074. input_files[i]->eagain = 0;
  2075. }
  2076. // set duration to max(tmp, duration) in a proper time base and return duration's time_base
  2077. static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
  2078. AVRational time_base)
  2079. {
  2080. int ret;
  2081. if (!*duration) {
  2082. *duration = tmp;
  2083. return tmp_time_base;
  2084. }
  2085. ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
  2086. if (ret < 0) {
  2087. *duration = tmp;
  2088. return tmp_time_base;
  2089. }
  2090. return time_base;
  2091. }
  2092. static int seek_to_start(InputFile *ifile, AVFormatContext *is)
  2093. {
  2094. InputStream *ist;
  2095. AVCodecContext *avctx;
  2096. int i, ret, has_audio = 0;
  2097. int64_t duration = 0;
  2098. ret = av_seek_frame(is, -1, is->start_time, 0);
  2099. if (ret < 0)
  2100. return ret;
  2101. for (i = 0; i < ifile->nb_streams; i++) {
  2102. ist = input_streams[ifile->ist_index + i];
  2103. avctx = ist->dec_ctx;
  2104. // flush decoders
  2105. if (ist->decoding_needed) {
  2106. process_input_packet(ist, NULL, 1);
  2107. avcodec_flush_buffers(avctx);
  2108. }
  2109. /* duration is the length of the last frame in a stream
  2110. * when audio stream is present we don't care about
  2111. * last video frame length because it's not defined exactly */
  2112. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
  2113. has_audio = 1;
  2114. }
  2115. for (i = 0; i < ifile->nb_streams; i++) {
  2116. ist = input_streams[ifile->ist_index + i];
  2117. avctx = ist->dec_ctx;
  2118. if (has_audio) {
  2119. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
  2120. AVRational sample_rate = {1, avctx->sample_rate};
  2121. duration = av_rescale_q(ist->nb_samples, sample_rate, ist->st->time_base);
  2122. } else
  2123. continue;
  2124. } else {
  2125. if (ist->framerate.num) {
  2126. duration = av_rescale_q(1, ist->framerate, ist->st->time_base);
  2127. } else if (ist->st->avg_frame_rate.num) {
  2128. duration = av_rescale_q(1, ist->st->avg_frame_rate, ist->st->time_base);
  2129. } else duration = 1;
  2130. }
  2131. if (!ifile->duration)
  2132. ifile->time_base = ist->st->time_base;
  2133. /* the total duration of the stream, max_pts - min_pts is
  2134. * the duration of the stream without the last frame */
  2135. duration += ist->max_pts - ist->min_pts;
  2136. ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
  2137. ifile->time_base);
  2138. }
  2139. if (ifile->loop > 0)
  2140. ifile->loop--;
  2141. return ret;
  2142. }
  2143. /*
  2144. * Read one packet from an input file and send it for
  2145. * - decoding -> lavfi (audio/video)
  2146. * - decoding -> encoding -> muxing (subtitles)
  2147. * - muxing (streamcopy)
  2148. *
  2149. * Return
  2150. * - 0 -- one packet was read and processed
  2151. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  2152. * this function should be called again
  2153. * - AVERROR_EOF -- this function should not be called again
  2154. */
  2155. static int process_input(void)
  2156. {
  2157. InputFile *ifile;
  2158. AVFormatContext *is;
  2159. InputStream *ist;
  2160. AVPacket pkt;
  2161. int ret, i, j;
  2162. int64_t duration;
  2163. /* select the stream that we must read now */
  2164. ifile = select_input_file();
  2165. /* if none, if is finished */
  2166. if (!ifile) {
  2167. if (got_eagain()) {
  2168. reset_eagain();
  2169. av_usleep(10000);
  2170. return AVERROR(EAGAIN);
  2171. }
  2172. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from.\n");
  2173. return AVERROR_EOF;
  2174. }
  2175. is = ifile->ctx;
  2176. ret = get_input_packet(ifile, &pkt);
  2177. if (ret == AVERROR(EAGAIN)) {
  2178. ifile->eagain = 1;
  2179. return ret;
  2180. }
  2181. if (ret < 0 && ifile->loop) {
  2182. ret = seek_to_start(ifile, is);
  2183. if(ret < 0)
  2184. av_log(NULL, AV_LOG_WARNING, "Seek to start failed.\n");
  2185. else
  2186. ret = get_input_packet(ifile, &pkt);
  2187. }
  2188. if (ret < 0) {
  2189. if (ret != AVERROR_EOF) {
  2190. print_error(is->filename, ret);
  2191. if (exit_on_error)
  2192. exit_program(1);
  2193. }
  2194. ifile->eof_reached = 1;
  2195. for (i = 0; i < ifile->nb_streams; i++) {
  2196. ist = input_streams[ifile->ist_index + i];
  2197. if (ist->decoding_needed)
  2198. process_input_packet(ist, NULL, 0);
  2199. /* mark all outputs that don't go through lavfi as finished */
  2200. for (j = 0; j < nb_output_streams; j++) {
  2201. OutputStream *ost = output_streams[j];
  2202. if (ost->source_index == ifile->ist_index + i &&
  2203. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  2204. finish_output_stream(ost);
  2205. }
  2206. }
  2207. return AVERROR(EAGAIN);
  2208. }
  2209. reset_eagain();
  2210. if (do_pkt_dump) {
  2211. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  2212. is->streams[pkt.stream_index]);
  2213. }
  2214. /* the following test is needed in case new streams appear
  2215. dynamically in stream : we ignore them */
  2216. if (pkt.stream_index >= ifile->nb_streams)
  2217. goto discard_packet;
  2218. ist = input_streams[ifile->ist_index + pkt.stream_index];
  2219. ist->data_size += pkt.size;
  2220. ist->nb_packets++;
  2221. if (ist->discard)
  2222. goto discard_packet;
  2223. /* add the stream-global side data to the first packet */
  2224. if (ist->nb_packets == 1)
  2225. for (i = 0; i < ist->st->nb_side_data; i++) {
  2226. AVPacketSideData *src_sd = &ist->st->side_data[i];
  2227. uint8_t *dst_data;
  2228. if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
  2229. continue;
  2230. if (ist->autorotate && src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
  2231. continue;
  2232. dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
  2233. if (!dst_data)
  2234. exit_program(1);
  2235. memcpy(dst_data, src_sd->data, src_sd->size);
  2236. }
  2237. if (pkt.dts != AV_NOPTS_VALUE)
  2238. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2239. if (pkt.pts != AV_NOPTS_VALUE)
  2240. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2241. if (pkt.pts != AV_NOPTS_VALUE)
  2242. pkt.pts *= ist->ts_scale;
  2243. if (pkt.dts != AV_NOPTS_VALUE)
  2244. pkt.dts *= ist->ts_scale;
  2245. if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  2246. ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
  2247. pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  2248. (is->iformat->flags & AVFMT_TS_DISCONT)) {
  2249. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2250. int64_t delta = pkt_dts - ist->next_dts;
  2251. if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
  2252. ifile->ts_offset -= delta;
  2253. av_log(NULL, AV_LOG_DEBUG,
  2254. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2255. delta, ifile->ts_offset);
  2256. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2257. if (pkt.pts != AV_NOPTS_VALUE)
  2258. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2259. }
  2260. }
  2261. duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
  2262. if (pkt.pts != AV_NOPTS_VALUE) {
  2263. pkt.pts += duration;
  2264. ist->max_pts = FFMAX(pkt.pts, ist->max_pts);
  2265. ist->min_pts = FFMIN(pkt.pts, ist->min_pts);
  2266. }
  2267. if (pkt.dts != AV_NOPTS_VALUE)
  2268. pkt.dts += duration;
  2269. process_input_packet(ist, &pkt, 0);
  2270. discard_packet:
  2271. av_packet_unref(&pkt);
  2272. return 0;
  2273. }
  2274. /*
  2275. * The following code is the main loop of the file converter
  2276. */
  2277. static int transcode(void)
  2278. {
  2279. int ret, i, need_input = 1;
  2280. AVFormatContext *os;
  2281. OutputStream *ost;
  2282. InputStream *ist;
  2283. int64_t timer_start;
  2284. ret = transcode_init();
  2285. if (ret < 0)
  2286. goto fail;
  2287. av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
  2288. term_init();
  2289. timer_start = av_gettime_relative();
  2290. #if HAVE_PTHREADS
  2291. if ((ret = init_input_threads()) < 0)
  2292. goto fail;
  2293. #endif
  2294. while (!received_sigterm) {
  2295. /* check if there's any stream where output is still needed */
  2296. if (!need_output()) {
  2297. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  2298. break;
  2299. }
  2300. /* read and process one input packet if needed */
  2301. if (need_input) {
  2302. ret = process_input();
  2303. if (ret == AVERROR_EOF)
  2304. need_input = 0;
  2305. }
  2306. ret = poll_filters();
  2307. if (ret < 0 && ret != AVERROR_EOF) {
  2308. char errbuf[128];
  2309. av_strerror(ret, errbuf, sizeof(errbuf));
  2310. av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
  2311. break;
  2312. }
  2313. /* dump report by using the output first video and audio streams */
  2314. print_report(0, timer_start);
  2315. }
  2316. #if HAVE_PTHREADS
  2317. free_input_threads();
  2318. #endif
  2319. /* at the end of stream, we must flush the decoder buffers */
  2320. for (i = 0; i < nb_input_streams; i++) {
  2321. ist = input_streams[i];
  2322. if (!input_files[ist->file_index]->eof_reached) {
  2323. process_input_packet(ist, NULL, 0);
  2324. }
  2325. }
  2326. poll_filters();
  2327. flush_encoders();
  2328. term_exit();
  2329. /* write the trailer if needed and close file */
  2330. for (i = 0; i < nb_output_files; i++) {
  2331. os = output_files[i]->ctx;
  2332. if (!output_files[i]->header_written) {
  2333. av_log(NULL, AV_LOG_ERROR,
  2334. "Nothing was written into output file %d (%s), because "
  2335. "at least one of its streams received no packets.\n",
  2336. i, os->filename);
  2337. continue;
  2338. }
  2339. av_write_trailer(os);
  2340. }
  2341. /* dump report by using the first video and audio streams */
  2342. print_report(1, timer_start);
  2343. /* close each encoder */
  2344. for (i = 0; i < nb_output_streams; i++) {
  2345. ost = output_streams[i];
  2346. if (ost->encoding_needed) {
  2347. av_freep(&ost->enc_ctx->stats_in);
  2348. }
  2349. }
  2350. /* close each decoder */
  2351. for (i = 0; i < nb_input_streams; i++) {
  2352. ist = input_streams[i];
  2353. if (ist->decoding_needed) {
  2354. avcodec_close(ist->dec_ctx);
  2355. if (ist->hwaccel_uninit)
  2356. ist->hwaccel_uninit(ist->dec_ctx);
  2357. }
  2358. }
  2359. av_buffer_unref(&hw_device_ctx);
  2360. hw_device_free_all();
  2361. /* finished ! */
  2362. ret = 0;
  2363. fail:
  2364. #if HAVE_PTHREADS
  2365. free_input_threads();
  2366. #endif
  2367. if (output_streams) {
  2368. for (i = 0; i < nb_output_streams; i++) {
  2369. ost = output_streams[i];
  2370. if (ost) {
  2371. if (ost->logfile) {
  2372. fclose(ost->logfile);
  2373. ost->logfile = NULL;
  2374. }
  2375. av_free(ost->forced_kf_pts);
  2376. av_dict_free(&ost->encoder_opts);
  2377. av_dict_free(&ost->resample_opts);
  2378. }
  2379. }
  2380. }
  2381. return ret;
  2382. }
  2383. static int64_t getutime(void)
  2384. {
  2385. #if HAVE_GETRUSAGE
  2386. struct rusage rusage;
  2387. getrusage(RUSAGE_SELF, &rusage);
  2388. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2389. #elif HAVE_GETPROCESSTIMES
  2390. HANDLE proc;
  2391. FILETIME c, e, k, u;
  2392. proc = GetCurrentProcess();
  2393. GetProcessTimes(proc, &c, &e, &k, &u);
  2394. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  2395. #else
  2396. return av_gettime_relative();
  2397. #endif
  2398. }
  2399. static int64_t getmaxrss(void)
  2400. {
  2401. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  2402. struct rusage rusage;
  2403. getrusage(RUSAGE_SELF, &rusage);
  2404. return (int64_t)rusage.ru_maxrss * 1024;
  2405. #elif HAVE_GETPROCESSMEMORYINFO
  2406. HANDLE proc;
  2407. PROCESS_MEMORY_COUNTERS memcounters;
  2408. proc = GetCurrentProcess();
  2409. memcounters.cb = sizeof(memcounters);
  2410. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  2411. return memcounters.PeakPagefileUsage;
  2412. #else
  2413. return 0;
  2414. #endif
  2415. }
  2416. int main(int argc, char **argv)
  2417. {
  2418. int i, ret;
  2419. int64_t ti;
  2420. register_exit(avconv_cleanup);
  2421. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2422. parse_loglevel(argc, argv, options);
  2423. avcodec_register_all();
  2424. #if CONFIG_AVDEVICE
  2425. avdevice_register_all();
  2426. #endif
  2427. avfilter_register_all();
  2428. av_register_all();
  2429. avformat_network_init();
  2430. show_banner();
  2431. /* parse options and open all input/output files */
  2432. ret = avconv_parse_options(argc, argv);
  2433. if (ret < 0)
  2434. exit_program(1);
  2435. if (nb_output_files <= 0 && nb_input_files == 0) {
  2436. show_usage();
  2437. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  2438. exit_program(1);
  2439. }
  2440. /* file converter / grab */
  2441. if (nb_output_files <= 0) {
  2442. fprintf(stderr, "At least one output file must be specified\n");
  2443. exit_program(1);
  2444. }
  2445. for (i = 0; i < nb_output_files; i++) {
  2446. if (strcmp(output_files[i]->ctx->oformat->name, "rtp"))
  2447. want_sdp = 0;
  2448. }
  2449. ti = getutime();
  2450. if (transcode() < 0)
  2451. exit_program(1);
  2452. ti = getutime() - ti;
  2453. if (do_benchmark) {
  2454. int maxrss = getmaxrss() / 1024;
  2455. printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
  2456. }
  2457. exit_program(0);
  2458. return 0;
  2459. }