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.

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