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.

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