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.

2986 lines
92KB

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