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.

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