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.

2890 lines
88KB

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