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.

2913 lines
89KB

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