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.

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