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.

2695 lines
86KB

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