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.

2850 lines
90KB

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