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.

2899 lines
88KB

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