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.

2723 lines
87KB

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