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.

2910 lines
89KB

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