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.

2840 lines
88KB

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