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.

2851 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. int got_packet;
  837. av_init_packet(&pkt);
  838. pkt.data = NULL;
  839. pkt.size = 0;
  840. ret = avcodec_receive_packet(enc, &pkt);
  841. if (ret < 0 && ret != AVERROR_EOF) {
  842. av_log(NULL, AV_LOG_FATAL, "%s encoding failed\n", desc);
  843. exit_program(1);
  844. }
  845. if (ost->logfile && enc->stats_out) {
  846. fprintf(ost->logfile, "%s", enc->stats_out);
  847. }
  848. if (ret == AVERROR_EOF) {
  849. stop_encoding = 1;
  850. break;
  851. }
  852. av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);
  853. output_packet(os, &pkt, ost);
  854. }
  855. if (stop_encoding)
  856. break;
  857. }
  858. }
  859. }
  860. /*
  861. * Check whether a packet from ist should be written into ost at this time
  862. */
  863. static int check_output_constraints(InputStream *ist, OutputStream *ost)
  864. {
  865. OutputFile *of = output_files[ost->file_index];
  866. int ist_index = input_files[ist->file_index]->ist_index + ist->st->index;
  867. if (ost->source_index != ist_index)
  868. return 0;
  869. if (of->start_time != AV_NOPTS_VALUE && ist->last_dts < of->start_time)
  870. return 0;
  871. return 1;
  872. }
  873. static void do_streamcopy(InputStream *ist, OutputStream *ost, const AVPacket *pkt)
  874. {
  875. OutputFile *of = output_files[ost->file_index];
  876. InputFile *f = input_files [ist->file_index];
  877. int64_t start_time = (of->start_time == AV_NOPTS_VALUE) ? 0 : of->start_time;
  878. int64_t ost_tb_start_time = av_rescale_q(start_time, AV_TIME_BASE_Q, ost->st->time_base);
  879. AVPacket opkt;
  880. av_init_packet(&opkt);
  881. if ((!ost->frame_number && !(pkt->flags & AV_PKT_FLAG_KEY)) &&
  882. !ost->copy_initial_nonkeyframes)
  883. return;
  884. if (of->recording_time != INT64_MAX &&
  885. ist->last_dts >= of->recording_time + start_time) {
  886. ost->finished = 1;
  887. return;
  888. }
  889. if (f->recording_time != INT64_MAX) {
  890. start_time = f->ctx->start_time;
  891. if (f->start_time != AV_NOPTS_VALUE)
  892. start_time += f->start_time;
  893. if (ist->last_dts >= f->recording_time + start_time) {
  894. ost->finished = 1;
  895. return;
  896. }
  897. }
  898. /* force the input stream PTS */
  899. if (ost->enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
  900. ost->sync_opts++;
  901. if (pkt->pts != AV_NOPTS_VALUE)
  902. opkt.pts = av_rescale_q(pkt->pts, ist->st->time_base, ost->st->time_base) - ost_tb_start_time;
  903. else
  904. opkt.pts = AV_NOPTS_VALUE;
  905. if (pkt->dts == AV_NOPTS_VALUE)
  906. opkt.dts = av_rescale_q(ist->last_dts, AV_TIME_BASE_Q, ost->st->time_base);
  907. else
  908. opkt.dts = av_rescale_q(pkt->dts, ist->st->time_base, ost->st->time_base);
  909. opkt.dts -= ost_tb_start_time;
  910. opkt.duration = av_rescale_q(pkt->duration, ist->st->time_base, ost->st->time_base);
  911. opkt.flags = pkt->flags;
  912. // FIXME remove the following 2 lines they shall be replaced by the bitstream filters
  913. if ( ost->enc_ctx->codec_id != AV_CODEC_ID_H264
  914. && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG1VIDEO
  915. && ost->enc_ctx->codec_id != AV_CODEC_ID_MPEG2VIDEO
  916. && ost->enc_ctx->codec_id != AV_CODEC_ID_VC1
  917. ) {
  918. if (av_parser_change(ost->parser, ost->st->codec,
  919. &opkt.data, &opkt.size,
  920. pkt->data, pkt->size,
  921. pkt->flags & AV_PKT_FLAG_KEY)) {
  922. opkt.buf = av_buffer_create(opkt.data, opkt.size, av_buffer_default_free, NULL, 0);
  923. if (!opkt.buf)
  924. exit_program(1);
  925. }
  926. } else {
  927. opkt.data = pkt->data;
  928. opkt.size = pkt->size;
  929. }
  930. output_packet(of->ctx, &opkt, ost);
  931. }
  932. // This does not quite work like avcodec_decode_audio4/avcodec_decode_video2.
  933. // There is the following difference: if you got a frame, you must call
  934. // it again with pkt=NULL. pkt==NULL is treated differently from pkt.size==0
  935. // (pkt==NULL means get more output, pkt.size==0 is a flush/drain packet)
  936. static int decode(AVCodecContext *avctx, AVFrame *frame, int *got_frame, AVPacket *pkt)
  937. {
  938. int ret;
  939. *got_frame = 0;
  940. if (pkt) {
  941. ret = avcodec_send_packet(avctx, pkt);
  942. // In particular, we don't expect AVERROR(EAGAIN), because we read all
  943. // decoded frames with avcodec_receive_frame() until done.
  944. if (ret < 0)
  945. return ret == AVERROR_EOF ? 0 : ret;
  946. }
  947. ret = avcodec_receive_frame(avctx, frame);
  948. if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF)
  949. return ret;
  950. if (ret >= 0)
  951. *got_frame = 1;
  952. return 0;
  953. }
  954. int guess_input_channel_layout(InputStream *ist)
  955. {
  956. AVCodecContext *dec = ist->dec_ctx;
  957. if (!dec->channel_layout) {
  958. char layout_name[256];
  959. dec->channel_layout = av_get_default_channel_layout(dec->channels);
  960. if (!dec->channel_layout)
  961. return 0;
  962. av_get_channel_layout_string(layout_name, sizeof(layout_name),
  963. dec->channels, dec->channel_layout);
  964. av_log(NULL, AV_LOG_WARNING, "Guessed Channel Layout for Input Stream "
  965. "#%d.%d : %s\n", ist->file_index, ist->st->index, layout_name);
  966. }
  967. return 1;
  968. }
  969. static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)
  970. {
  971. AVFrame *decoded_frame, *f;
  972. AVCodecContext *avctx = ist->dec_ctx;
  973. int i, ret, err = 0, resample_changed;
  974. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  975. return AVERROR(ENOMEM);
  976. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  977. return AVERROR(ENOMEM);
  978. decoded_frame = ist->decoded_frame;
  979. ret = decode(avctx, decoded_frame, got_output, pkt);
  980. if (!*got_output || ret < 0)
  981. return ret;
  982. ist->samples_decoded += decoded_frame->nb_samples;
  983. ist->frames_decoded++;
  984. /* if the decoder provides a pts, use it instead of the last packet pts.
  985. the decoder could be delaying output by a packet or more. */
  986. if (decoded_frame->pts != AV_NOPTS_VALUE)
  987. ist->next_dts = decoded_frame->pts;
  988. else if (pkt && pkt->pts != AV_NOPTS_VALUE) {
  989. decoded_frame->pts = pkt->pts;
  990. }
  991. resample_changed = ist->resample_sample_fmt != decoded_frame->format ||
  992. ist->resample_channels != avctx->channels ||
  993. ist->resample_channel_layout != decoded_frame->channel_layout ||
  994. ist->resample_sample_rate != decoded_frame->sample_rate;
  995. if (resample_changed) {
  996. char layout1[64], layout2[64];
  997. if (!guess_input_channel_layout(ist)) {
  998. av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "
  999. "layout for Input Stream #%d.%d\n", ist->file_index,
  1000. ist->st->index);
  1001. exit_program(1);
  1002. }
  1003. decoded_frame->channel_layout = avctx->channel_layout;
  1004. av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,
  1005. ist->resample_channel_layout);
  1006. av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,
  1007. decoded_frame->channel_layout);
  1008. av_log(NULL, AV_LOG_INFO,
  1009. "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",
  1010. ist->file_index, ist->st->index,
  1011. ist->resample_sample_rate, av_get_sample_fmt_name(ist->resample_sample_fmt),
  1012. ist->resample_channels, layout1,
  1013. decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),
  1014. avctx->channels, layout2);
  1015. ist->resample_sample_fmt = decoded_frame->format;
  1016. ist->resample_sample_rate = decoded_frame->sample_rate;
  1017. ist->resample_channel_layout = decoded_frame->channel_layout;
  1018. ist->resample_channels = avctx->channels;
  1019. for (i = 0; i < nb_filtergraphs; i++)
  1020. if (ist_in_filtergraph(filtergraphs[i], ist) &&
  1021. configure_filtergraph(filtergraphs[i]) < 0) {
  1022. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1023. exit_program(1);
  1024. }
  1025. }
  1026. if (decoded_frame->pts != AV_NOPTS_VALUE)
  1027. decoded_frame->pts = av_rescale_q(decoded_frame->pts,
  1028. ist->st->time_base,
  1029. (AVRational){1, avctx->sample_rate});
  1030. ist->nb_samples = decoded_frame->nb_samples;
  1031. for (i = 0; i < ist->nb_filters; i++) {
  1032. if (i < ist->nb_filters - 1) {
  1033. f = ist->filter_frame;
  1034. err = av_frame_ref(f, decoded_frame);
  1035. if (err < 0)
  1036. break;
  1037. } else
  1038. f = decoded_frame;
  1039. err = av_buffersrc_add_frame(ist->filters[i]->filter, f);
  1040. if (err < 0)
  1041. break;
  1042. }
  1043. av_frame_unref(ist->filter_frame);
  1044. av_frame_unref(decoded_frame);
  1045. return err < 0 ? err : ret;
  1046. }
  1047. static int decode_video(InputStream *ist, AVPacket *pkt, int *got_output)
  1048. {
  1049. AVFrame *decoded_frame, *f;
  1050. int i, ret = 0, err = 0, resample_changed;
  1051. if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))
  1052. return AVERROR(ENOMEM);
  1053. if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))
  1054. return AVERROR(ENOMEM);
  1055. decoded_frame = ist->decoded_frame;
  1056. ret = decode(ist->dec_ctx, decoded_frame, got_output, pkt);
  1057. if (!*got_output || ret < 0)
  1058. return ret;
  1059. ist->frames_decoded++;
  1060. if (ist->hwaccel_retrieve_data && decoded_frame->format == ist->hwaccel_pix_fmt) {
  1061. err = ist->hwaccel_retrieve_data(ist->dec_ctx, decoded_frame);
  1062. if (err < 0)
  1063. goto fail;
  1064. }
  1065. ist->hwaccel_retrieved_pix_fmt = decoded_frame->format;
  1066. decoded_frame->pts = guess_correct_pts(&ist->pts_ctx, decoded_frame->pkt_pts,
  1067. decoded_frame->pkt_dts);
  1068. if (ist->st->sample_aspect_ratio.num)
  1069. decoded_frame->sample_aspect_ratio = ist->st->sample_aspect_ratio;
  1070. resample_changed = ist->resample_width != decoded_frame->width ||
  1071. ist->resample_height != decoded_frame->height ||
  1072. ist->resample_pix_fmt != decoded_frame->format;
  1073. if (resample_changed) {
  1074. av_log(NULL, AV_LOG_INFO,
  1075. "Input stream #%d:%d frame changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",
  1076. ist->file_index, ist->st->index,
  1077. ist->resample_width, ist->resample_height, av_get_pix_fmt_name(ist->resample_pix_fmt),
  1078. decoded_frame->width, decoded_frame->height, av_get_pix_fmt_name(decoded_frame->format));
  1079. ret = poll_filters();
  1080. if (ret < 0 && ret != AVERROR_EOF) {
  1081. char errbuf[128];
  1082. av_strerror(ret, errbuf, sizeof(errbuf));
  1083. av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
  1084. }
  1085. ist->resample_width = decoded_frame->width;
  1086. ist->resample_height = decoded_frame->height;
  1087. ist->resample_pix_fmt = decoded_frame->format;
  1088. for (i = 0; i < nb_filtergraphs; i++)
  1089. if (ist_in_filtergraph(filtergraphs[i], ist) &&
  1090. configure_filtergraph(filtergraphs[i]) < 0) {
  1091. av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");
  1092. exit_program(1);
  1093. }
  1094. }
  1095. for (i = 0; i < ist->nb_filters; i++) {
  1096. if (i < ist->nb_filters - 1) {
  1097. f = ist->filter_frame;
  1098. err = av_frame_ref(f, decoded_frame);
  1099. if (err < 0)
  1100. break;
  1101. } else
  1102. f = decoded_frame;
  1103. err = av_buffersrc_add_frame(ist->filters[i]->filter, f);
  1104. if (err < 0)
  1105. break;
  1106. }
  1107. fail:
  1108. av_frame_unref(ist->filter_frame);
  1109. av_frame_unref(decoded_frame);
  1110. return err < 0 ? err : ret;
  1111. }
  1112. static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)
  1113. {
  1114. AVSubtitle subtitle;
  1115. int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,
  1116. &subtitle, got_output, pkt);
  1117. if (ret < 0)
  1118. return ret;
  1119. if (!*got_output)
  1120. return ret;
  1121. ist->frames_decoded++;
  1122. for (i = 0; i < nb_output_streams; i++) {
  1123. OutputStream *ost = output_streams[i];
  1124. if (!check_output_constraints(ist, ost) || !ost->encoding_needed)
  1125. continue;
  1126. do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);
  1127. }
  1128. avsubtitle_free(&subtitle);
  1129. return ret;
  1130. }
  1131. static int send_filter_eof(InputStream *ist)
  1132. {
  1133. int i, ret;
  1134. for (i = 0; i < ist->nb_filters; i++) {
  1135. ret = av_buffersrc_add_frame(ist->filters[i]->filter, NULL);
  1136. if (ret < 0)
  1137. return ret;
  1138. }
  1139. return 0;
  1140. }
  1141. /* pkt = NULL means EOF (needed to flush decoder buffers) */
  1142. static void process_input_packet(InputStream *ist, const AVPacket *pkt, int no_eof)
  1143. {
  1144. int i;
  1145. int repeating = 0;
  1146. AVPacket avpkt;
  1147. if (ist->next_dts == AV_NOPTS_VALUE)
  1148. ist->next_dts = ist->last_dts;
  1149. if (!pkt) {
  1150. /* EOF handling */
  1151. av_init_packet(&avpkt);
  1152. avpkt.data = NULL;
  1153. avpkt.size = 0;
  1154. } else {
  1155. avpkt = *pkt;
  1156. }
  1157. if (pkt && pkt->dts != AV_NOPTS_VALUE)
  1158. ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);
  1159. // while we have more to decode or while the decoder did output something on EOF
  1160. while (ist->decoding_needed && (!pkt || avpkt.size > 0)) {
  1161. int ret = 0;
  1162. int got_output = 0;
  1163. if (!repeating)
  1164. ist->last_dts = ist->next_dts;
  1165. switch (ist->dec_ctx->codec_type) {
  1166. case AVMEDIA_TYPE_AUDIO:
  1167. ret = decode_audio (ist, repeating ? NULL : &avpkt, &got_output);
  1168. break;
  1169. case AVMEDIA_TYPE_VIDEO:
  1170. ret = decode_video (ist, repeating ? NULL : &avpkt, &got_output);
  1171. if (repeating && !got_output)
  1172. ;
  1173. else if (pkt && pkt->duration)
  1174. ist->next_dts += av_rescale_q(pkt->duration, ist->st->time_base, AV_TIME_BASE_Q);
  1175. else if (ist->st->avg_frame_rate.num)
  1176. ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),
  1177. AV_TIME_BASE_Q);
  1178. else if (ist->dec_ctx->framerate.num != 0) {
  1179. int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 :
  1180. ist->dec_ctx->ticks_per_frame;
  1181. ist->next_dts += av_rescale_q(ticks, ist->dec_ctx->framerate, AV_TIME_BASE_Q);
  1182. }
  1183. break;
  1184. case AVMEDIA_TYPE_SUBTITLE:
  1185. if (repeating)
  1186. break;
  1187. ret = transcode_subtitles(ist, &avpkt, &got_output);
  1188. break;
  1189. default:
  1190. return;
  1191. }
  1192. if (ret < 0) {
  1193. av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d\n",
  1194. ist->file_index, ist->st->index);
  1195. if (exit_on_error)
  1196. exit_program(1);
  1197. break;
  1198. }
  1199. if (!got_output)
  1200. break;
  1201. repeating = 1;
  1202. }
  1203. /* after flushing, send an EOF on all the filter inputs attached to the stream */
  1204. /* except when looping we need to flush but not to send an EOF */
  1205. if (!pkt && ist->decoding_needed && !no_eof) {
  1206. int ret = send_filter_eof(ist);
  1207. if (ret < 0) {
  1208. av_log(NULL, AV_LOG_FATAL, "Error marking filters as finished\n");
  1209. exit_program(1);
  1210. }
  1211. }
  1212. /* handle stream copy */
  1213. if (!ist->decoding_needed) {
  1214. ist->last_dts = ist->next_dts;
  1215. switch (ist->dec_ctx->codec_type) {
  1216. case AVMEDIA_TYPE_AUDIO:
  1217. ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /
  1218. ist->dec_ctx->sample_rate;
  1219. break;
  1220. case AVMEDIA_TYPE_VIDEO:
  1221. if (ist->dec_ctx->framerate.num != 0) {
  1222. int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;
  1223. ist->next_dts += ((int64_t)AV_TIME_BASE *
  1224. ist->dec_ctx->framerate.den * ticks) /
  1225. ist->dec_ctx->framerate.num;
  1226. }
  1227. break;
  1228. }
  1229. }
  1230. for (i = 0; pkt && i < nb_output_streams; i++) {
  1231. OutputStream *ost = output_streams[i];
  1232. if (!check_output_constraints(ist, ost) || ost->encoding_needed)
  1233. continue;
  1234. do_streamcopy(ist, ost, pkt);
  1235. }
  1236. return;
  1237. }
  1238. static void print_sdp(void)
  1239. {
  1240. char sdp[16384];
  1241. int i;
  1242. AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);
  1243. if (!avc)
  1244. exit_program(1);
  1245. for (i = 0; i < nb_output_files; i++)
  1246. avc[i] = output_files[i]->ctx;
  1247. av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));
  1248. printf("SDP:\n%s\n", sdp);
  1249. fflush(stdout);
  1250. av_freep(&avc);
  1251. }
  1252. static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt)
  1253. {
  1254. int i;
  1255. for (i = 0; hwaccels[i].name; i++)
  1256. if (hwaccels[i].pix_fmt == pix_fmt)
  1257. return &hwaccels[i];
  1258. return NULL;
  1259. }
  1260. static enum AVPixelFormat get_format(AVCodecContext *s, const enum AVPixelFormat *pix_fmts)
  1261. {
  1262. InputStream *ist = s->opaque;
  1263. const enum AVPixelFormat *p;
  1264. int ret;
  1265. for (p = pix_fmts; *p != -1; p++) {
  1266. const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p);
  1267. const HWAccel *hwaccel;
  1268. if (!(desc->flags & AV_PIX_FMT_FLAG_HWACCEL))
  1269. break;
  1270. hwaccel = get_hwaccel(*p);
  1271. if (!hwaccel ||
  1272. (ist->active_hwaccel_id && ist->active_hwaccel_id != hwaccel->id) ||
  1273. (ist->hwaccel_id != HWACCEL_AUTO && ist->hwaccel_id != hwaccel->id))
  1274. continue;
  1275. ret = hwaccel->init(s);
  1276. if (ret < 0) {
  1277. if (ist->hwaccel_id == hwaccel->id) {
  1278. av_log(NULL, AV_LOG_FATAL,
  1279. "%s hwaccel requested for input stream #%d:%d, "
  1280. "but cannot be initialized.\n", hwaccel->name,
  1281. ist->file_index, ist->st->index);
  1282. return AV_PIX_FMT_NONE;
  1283. }
  1284. continue;
  1285. }
  1286. ist->active_hwaccel_id = hwaccel->id;
  1287. ist->hwaccel_pix_fmt = *p;
  1288. break;
  1289. }
  1290. return *p;
  1291. }
  1292. static int get_buffer(AVCodecContext *s, AVFrame *frame, int flags)
  1293. {
  1294. InputStream *ist = s->opaque;
  1295. if (ist->hwaccel_get_buffer && frame->format == ist->hwaccel_pix_fmt)
  1296. return ist->hwaccel_get_buffer(s, frame, flags);
  1297. return avcodec_default_get_buffer2(s, frame, flags);
  1298. }
  1299. static int init_input_stream(int ist_index, char *error, int error_len)
  1300. {
  1301. int ret;
  1302. InputStream *ist = input_streams[ist_index];
  1303. if (ist->decoding_needed) {
  1304. AVCodec *codec = ist->dec;
  1305. if (!codec) {
  1306. snprintf(error, error_len, "Decoder (codec id %d) not found for input stream #%d:%d",
  1307. ist->dec_ctx->codec_id, ist->file_index, ist->st->index);
  1308. return AVERROR(EINVAL);
  1309. }
  1310. ist->dec_ctx->opaque = ist;
  1311. ist->dec_ctx->get_format = get_format;
  1312. ist->dec_ctx->get_buffer2 = get_buffer;
  1313. ist->dec_ctx->thread_safe_callbacks = 1;
  1314. av_opt_set_int(ist->dec_ctx, "refcounted_frames", 1, 0);
  1315. if (!av_dict_get(ist->decoder_opts, "threads", NULL, 0))
  1316. av_dict_set(&ist->decoder_opts, "threads", "auto", 0);
  1317. if ((ret = avcodec_open2(ist->dec_ctx, codec, &ist->decoder_opts)) < 0) {
  1318. char errbuf[128];
  1319. if (ret == AVERROR_EXPERIMENTAL)
  1320. abort_codec_experimental(codec, 0);
  1321. av_strerror(ret, errbuf, sizeof(errbuf));
  1322. snprintf(error, error_len,
  1323. "Error while opening decoder for input stream "
  1324. "#%d:%d : %s",
  1325. ist->file_index, ist->st->index, errbuf);
  1326. return ret;
  1327. }
  1328. assert_avoptions(ist->decoder_opts);
  1329. }
  1330. 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;
  1331. ist->next_dts = AV_NOPTS_VALUE;
  1332. init_pts_correction(&ist->pts_ctx);
  1333. return 0;
  1334. }
  1335. static InputStream *get_input_stream(OutputStream *ost)
  1336. {
  1337. if (ost->source_index >= 0)
  1338. return input_streams[ost->source_index];
  1339. if (ost->filter) {
  1340. FilterGraph *fg = ost->filter->graph;
  1341. int i;
  1342. for (i = 0; i < fg->nb_inputs; i++)
  1343. if (fg->inputs[i]->ist->dec_ctx->codec_type == ost->enc_ctx->codec_type)
  1344. return fg->inputs[i]->ist;
  1345. }
  1346. return NULL;
  1347. }
  1348. static int init_output_bsfs(OutputStream *ost)
  1349. {
  1350. AVBSFContext *ctx;
  1351. int i, ret;
  1352. if (!ost->nb_bitstream_filters)
  1353. return 0;
  1354. ost->bsf_ctx = av_mallocz_array(ost->nb_bitstream_filters, sizeof(*ost->bsf_ctx));
  1355. if (!ost->bsf_ctx)
  1356. return AVERROR(ENOMEM);
  1357. for (i = 0; i < ost->nb_bitstream_filters; i++) {
  1358. ret = av_bsf_alloc(ost->bitstream_filters[i], &ctx);
  1359. if (ret < 0) {
  1360. av_log(NULL, AV_LOG_ERROR, "Error allocating a bistream filter context\n");
  1361. return ret;
  1362. }
  1363. ost->bsf_ctx[i] = ctx;
  1364. ret = avcodec_parameters_copy(ctx->par_in,
  1365. i ? ost->bsf_ctx[i - 1]->par_out : ost->st->codecpar);
  1366. if (ret < 0)
  1367. return ret;
  1368. ctx->time_base_in = i ? ost->bsf_ctx[i - 1]->time_base_out : ost->st->time_base;
  1369. ret = av_bsf_init(ctx);
  1370. if (ret < 0) {
  1371. av_log(NULL, AV_LOG_ERROR, "Error initializing bistream filter: %s\n",
  1372. ost->bitstream_filters[i]->name);
  1373. return ret;
  1374. }
  1375. }
  1376. ctx = ost->bsf_ctx[ost->nb_bitstream_filters - 1];
  1377. ret = avcodec_parameters_copy(ost->st->codecpar, ctx->par_out);
  1378. if (ret < 0)
  1379. return ret;
  1380. ost->st->time_base = ctx->time_base_out;
  1381. return 0;
  1382. }
  1383. static int init_output_stream(OutputStream *ost, char *error, int error_len)
  1384. {
  1385. int ret = 0;
  1386. if (ost->encoding_needed) {
  1387. AVCodec *codec = ost->enc;
  1388. AVCodecContext *dec = NULL;
  1389. InputStream *ist;
  1390. if ((ist = get_input_stream(ost)))
  1391. dec = ist->dec_ctx;
  1392. if (dec && dec->subtitle_header) {
  1393. ost->enc_ctx->subtitle_header = av_malloc(dec->subtitle_header_size);
  1394. if (!ost->enc_ctx->subtitle_header)
  1395. return AVERROR(ENOMEM);
  1396. memcpy(ost->enc_ctx->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);
  1397. ost->enc_ctx->subtitle_header_size = dec->subtitle_header_size;
  1398. }
  1399. if (!av_dict_get(ost->encoder_opts, "threads", NULL, 0))
  1400. av_dict_set(&ost->encoder_opts, "threads", "auto", 0);
  1401. if (ost->filter && ost->filter->filter->inputs[0]->hw_frames_ctx) {
  1402. ost->enc_ctx->hw_frames_ctx = av_buffer_ref(ost->filter->filter->inputs[0]->hw_frames_ctx);
  1403. if (!ost->enc_ctx->hw_frames_ctx)
  1404. return AVERROR(ENOMEM);
  1405. }
  1406. if ((ret = avcodec_open2(ost->enc_ctx, codec, &ost->encoder_opts)) < 0) {
  1407. if (ret == AVERROR_EXPERIMENTAL)
  1408. abort_codec_experimental(codec, 1);
  1409. snprintf(error, error_len,
  1410. "Error while opening encoder for output stream #%d:%d - "
  1411. "maybe incorrect parameters such as bit_rate, rate, width or height",
  1412. ost->file_index, ost->index);
  1413. return ret;
  1414. }
  1415. assert_avoptions(ost->encoder_opts);
  1416. if (ost->enc_ctx->bit_rate && ost->enc_ctx->bit_rate < 1000)
  1417. av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."
  1418. "It takes bits/s as argument, not kbits/s\n");
  1419. ret = avcodec_parameters_from_context(ost->st->codecpar, ost->enc_ctx);
  1420. if (ret < 0) {
  1421. av_log(NULL, AV_LOG_FATAL,
  1422. "Error initializing the output stream codec context.\n");
  1423. exit_program(1);
  1424. }
  1425. /*
  1426. * FIXME: this is only so that the bitstream filters and parsers (that still
  1427. * work with a codec context) get the parameter values.
  1428. * This should go away with the new BSF/parser API.
  1429. */
  1430. ret = avcodec_copy_context(ost->st->codec, ost->enc_ctx);
  1431. if (ret < 0)
  1432. return ret;
  1433. if (ost->enc_ctx->nb_coded_side_data) {
  1434. int i;
  1435. ost->st->side_data = av_realloc_array(NULL, ost->enc_ctx->nb_coded_side_data,
  1436. sizeof(*ost->st->side_data));
  1437. if (!ost->st->side_data)
  1438. return AVERROR(ENOMEM);
  1439. for (i = 0; i < ost->enc_ctx->nb_coded_side_data; i++) {
  1440. const AVPacketSideData *sd_src = &ost->enc_ctx->coded_side_data[i];
  1441. AVPacketSideData *sd_dst = &ost->st->side_data[i];
  1442. sd_dst->data = av_malloc(sd_src->size);
  1443. if (!sd_dst->data)
  1444. return AVERROR(ENOMEM);
  1445. memcpy(sd_dst->data, sd_src->data, sd_src->size);
  1446. sd_dst->size = sd_src->size;
  1447. sd_dst->type = sd_src->type;
  1448. ost->st->nb_side_data++;
  1449. }
  1450. }
  1451. ost->st->time_base = ost->enc_ctx->time_base;
  1452. } else {
  1453. ret = av_opt_set_dict(ost->enc_ctx, &ost->encoder_opts);
  1454. if (ret < 0)
  1455. return ret;
  1456. /*
  1457. * FIXME: this is only so that the bitstream filters and parsers (that still
  1458. * work with a codec context) get the parameter values.
  1459. * This should go away with the new BSF/parser API.
  1460. */
  1461. ret = avcodec_parameters_to_context(ost->st->codec, ost->st->codecpar);
  1462. if (ret < 0)
  1463. return ret;
  1464. }
  1465. /* initialize bitstream filters for the output stream
  1466. * needs to be done here, because the codec id for streamcopy is not
  1467. * known until now */
  1468. ret = init_output_bsfs(ost);
  1469. if (ret < 0)
  1470. return ret;
  1471. return ret;
  1472. }
  1473. static void parse_forced_key_frames(char *kf, OutputStream *ost,
  1474. AVCodecContext *avctx)
  1475. {
  1476. char *p;
  1477. int n = 1, i;
  1478. int64_t t;
  1479. for (p = kf; *p; p++)
  1480. if (*p == ',')
  1481. n++;
  1482. ost->forced_kf_count = n;
  1483. ost->forced_kf_pts = av_malloc(sizeof(*ost->forced_kf_pts) * n);
  1484. if (!ost->forced_kf_pts) {
  1485. av_log(NULL, AV_LOG_FATAL, "Could not allocate forced key frames array.\n");
  1486. exit_program(1);
  1487. }
  1488. p = kf;
  1489. for (i = 0; i < n; i++) {
  1490. char *next = strchr(p, ',');
  1491. if (next)
  1492. *next++ = 0;
  1493. t = parse_time_or_die("force_key_frames", p, 1);
  1494. ost->forced_kf_pts[i] = av_rescale_q(t, AV_TIME_BASE_Q, avctx->time_base);
  1495. p = next;
  1496. }
  1497. }
  1498. static void set_encoder_id(OutputFile *of, OutputStream *ost)
  1499. {
  1500. AVDictionaryEntry *e;
  1501. uint8_t *encoder_string;
  1502. int encoder_string_len;
  1503. int format_flags = 0;
  1504. e = av_dict_get(of->opts, "fflags", NULL, 0);
  1505. if (e) {
  1506. const AVOption *o = av_opt_find(of->ctx, "fflags", NULL, 0, 0);
  1507. if (!o)
  1508. return;
  1509. av_opt_eval_flags(of->ctx, o, e->value, &format_flags);
  1510. }
  1511. encoder_string_len = sizeof(LIBAVCODEC_IDENT) + strlen(ost->enc->name) + 2;
  1512. encoder_string = av_mallocz(encoder_string_len);
  1513. if (!encoder_string)
  1514. exit_program(1);
  1515. if (!(format_flags & AVFMT_FLAG_BITEXACT))
  1516. av_strlcpy(encoder_string, LIBAVCODEC_IDENT " ", encoder_string_len);
  1517. av_strlcat(encoder_string, ost->enc->name, encoder_string_len);
  1518. av_dict_set(&ost->st->metadata, "encoder", encoder_string,
  1519. AV_DICT_DONT_STRDUP_VAL | AV_DICT_DONT_OVERWRITE);
  1520. }
  1521. static int transcode_init(void)
  1522. {
  1523. int ret = 0, i, j, k;
  1524. AVFormatContext *oc;
  1525. OutputStream *ost;
  1526. InputStream *ist;
  1527. char error[1024];
  1528. int want_sdp = 1;
  1529. /* init framerate emulation */
  1530. for (i = 0; i < nb_input_files; i++) {
  1531. InputFile *ifile = input_files[i];
  1532. if (ifile->rate_emu)
  1533. for (j = 0; j < ifile->nb_streams; j++)
  1534. input_streams[j + ifile->ist_index]->start = av_gettime_relative();
  1535. }
  1536. /* for each output stream, we compute the right encoding parameters */
  1537. for (i = 0; i < nb_output_streams; i++) {
  1538. ost = output_streams[i];
  1539. oc = output_files[ost->file_index]->ctx;
  1540. ist = get_input_stream(ost);
  1541. if (ost->attachment_filename)
  1542. continue;
  1543. if (ist) {
  1544. ost->st->disposition = ist->st->disposition;
  1545. }
  1546. if (ost->stream_copy) {
  1547. AVCodecParameters *par_dst = ost->st->codecpar;
  1548. AVCodecParameters *par_src = ist->st->codecpar;
  1549. AVRational sar;
  1550. uint64_t extra_size;
  1551. av_assert0(ist && !ost->filter);
  1552. extra_size = (uint64_t)par_src->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE;
  1553. if (extra_size > INT_MAX) {
  1554. return AVERROR(EINVAL);
  1555. }
  1556. /* if stream_copy is selected, no need to decode or encode */
  1557. par_dst->codec_id = par_src->codec_id;
  1558. par_dst->codec_type = par_src->codec_type;
  1559. if (!par_dst->codec_tag) {
  1560. if (!oc->oformat->codec_tag ||
  1561. av_codec_get_id (oc->oformat->codec_tag, par_src->codec_tag) == par_dst->codec_id ||
  1562. av_codec_get_tag(oc->oformat->codec_tag, par_src->codec_id) <= 0)
  1563. par_dst->codec_tag = par_src->codec_tag;
  1564. }
  1565. par_dst->bit_rate = par_src->bit_rate;
  1566. par_dst->field_order = par_src->field_order;
  1567. par_dst->chroma_location = par_src->chroma_location;
  1568. par_dst->extradata = av_mallocz(extra_size);
  1569. if (!par_dst->extradata) {
  1570. return AVERROR(ENOMEM);
  1571. }
  1572. memcpy(par_dst->extradata, par_src->extradata, par_src->extradata_size);
  1573. par_dst->extradata_size = par_src->extradata_size;
  1574. ost->st->time_base = ist->st->time_base;
  1575. if (ist->st->nb_side_data) {
  1576. ost->st->side_data = av_realloc_array(NULL, ist->st->nb_side_data,
  1577. sizeof(*ist->st->side_data));
  1578. if (!ost->st->side_data)
  1579. return AVERROR(ENOMEM);
  1580. for (j = 0; j < ist->st->nb_side_data; j++) {
  1581. const AVPacketSideData *sd_src = &ist->st->side_data[j];
  1582. AVPacketSideData *sd_dst = &ost->st->side_data[j];
  1583. sd_dst->data = av_malloc(sd_src->size);
  1584. if (!sd_dst->data)
  1585. return AVERROR(ENOMEM);
  1586. memcpy(sd_dst->data, sd_src->data, sd_src->size);
  1587. sd_dst->size = sd_src->size;
  1588. sd_dst->type = sd_src->type;
  1589. ost->st->nb_side_data++;
  1590. }
  1591. }
  1592. ost->parser = av_parser_init(par_dst->codec_id);
  1593. switch (par_dst->codec_type) {
  1594. case AVMEDIA_TYPE_AUDIO:
  1595. if (audio_volume != 256) {
  1596. av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");
  1597. exit_program(1);
  1598. }
  1599. par_dst->channel_layout = par_src->channel_layout;
  1600. par_dst->sample_rate = par_src->sample_rate;
  1601. par_dst->channels = par_src->channels;
  1602. par_dst->block_align = par_src->block_align;
  1603. break;
  1604. case AVMEDIA_TYPE_VIDEO:
  1605. par_dst->format = par_src->format;
  1606. par_dst->width = par_src->width;
  1607. par_dst->height = par_src->height;
  1608. if (ost->frame_aspect_ratio)
  1609. sar = av_d2q(ost->frame_aspect_ratio * par_dst->height / par_dst->width, 255);
  1610. else if (ist->st->sample_aspect_ratio.num)
  1611. sar = ist->st->sample_aspect_ratio;
  1612. else
  1613. sar = par_src->sample_aspect_ratio;
  1614. ost->st->sample_aspect_ratio = par_dst->sample_aspect_ratio = sar;
  1615. break;
  1616. case AVMEDIA_TYPE_SUBTITLE:
  1617. par_dst->width = par_src->width;
  1618. par_dst->height = par_src->height;
  1619. break;
  1620. case AVMEDIA_TYPE_DATA:
  1621. case AVMEDIA_TYPE_ATTACHMENT:
  1622. break;
  1623. default:
  1624. abort();
  1625. }
  1626. } else {
  1627. AVCodecContext *enc_ctx = ost->enc_ctx;
  1628. AVCodecContext *dec_ctx = NULL;
  1629. if (!ost->enc) {
  1630. /* should only happen when a default codec is not present. */
  1631. snprintf(error, sizeof(error), "Automatic encoder selection "
  1632. "failed for output stream #%d:%d. Default encoder for "
  1633. "format %s is probably disabled. Please choose an "
  1634. "encoder manually.\n", ost->file_index, ost->index,
  1635. oc->oformat->name);
  1636. ret = AVERROR(EINVAL);
  1637. goto dump_format;
  1638. }
  1639. set_encoder_id(output_files[ost->file_index], ost);
  1640. if (ist) {
  1641. dec_ctx = ist->dec_ctx;
  1642. enc_ctx->bits_per_raw_sample = dec_ctx->bits_per_raw_sample;
  1643. enc_ctx->chroma_sample_location = dec_ctx->chroma_sample_location;
  1644. }
  1645. /*
  1646. * We want CFR output if and only if one of those is true:
  1647. * 1) user specified output framerate with -r
  1648. * 2) user specified -vsync cfr
  1649. * 3) output format is CFR and the user didn't force vsync to
  1650. * something else than CFR
  1651. *
  1652. * in such a case, set ost->frame_rate
  1653. */
  1654. if (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO &&
  1655. !ost->frame_rate.num && ist &&
  1656. (video_sync_method == VSYNC_CFR ||
  1657. (video_sync_method == VSYNC_AUTO &&
  1658. !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {
  1659. if (ist->framerate.num)
  1660. ost->frame_rate = ist->framerate;
  1661. else if (ist->st->avg_frame_rate.num)
  1662. ost->frame_rate = ist->st->avg_frame_rate;
  1663. else {
  1664. av_log(NULL, AV_LOG_WARNING, "Constant framerate requested "
  1665. "for the output stream #%d:%d, but no information "
  1666. "about the input framerate is available. Falling "
  1667. "back to a default value of 25fps. Use the -r option "
  1668. "if you want a different framerate.\n",
  1669. ost->file_index, ost->index);
  1670. ost->frame_rate = (AVRational){ 25, 1 };
  1671. }
  1672. if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {
  1673. int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);
  1674. ost->frame_rate = ost->enc->supported_framerates[idx];
  1675. }
  1676. }
  1677. #if CONFIG_LIBMFX
  1678. if (qsv_transcode_init(ost))
  1679. exit_program(1);
  1680. #endif
  1681. if (!ost->filter &&
  1682. (enc_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  1683. enc_ctx->codec_type == AVMEDIA_TYPE_AUDIO)) {
  1684. FilterGraph *fg;
  1685. fg = init_simple_filtergraph(ist, ost);
  1686. if (configure_filtergraph(fg)) {
  1687. av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");
  1688. exit_program(1);
  1689. }
  1690. }
  1691. switch (enc_ctx->codec_type) {
  1692. case AVMEDIA_TYPE_AUDIO:
  1693. enc_ctx->sample_fmt = ost->filter->filter->inputs[0]->format;
  1694. enc_ctx->sample_rate = ost->filter->filter->inputs[0]->sample_rate;
  1695. enc_ctx->channel_layout = ost->filter->filter->inputs[0]->channel_layout;
  1696. enc_ctx->channels = av_get_channel_layout_nb_channels(enc_ctx->channel_layout);
  1697. enc_ctx->time_base = (AVRational){ 1, enc_ctx->sample_rate };
  1698. break;
  1699. case AVMEDIA_TYPE_VIDEO:
  1700. enc_ctx->time_base = ost->filter->filter->inputs[0]->time_base;
  1701. enc_ctx->width = ost->filter->filter->inputs[0]->w;
  1702. enc_ctx->height = ost->filter->filter->inputs[0]->h;
  1703. enc_ctx->sample_aspect_ratio = ost->st->sample_aspect_ratio =
  1704. ost->frame_aspect_ratio ? // overridden by the -aspect cli option
  1705. av_d2q(ost->frame_aspect_ratio * enc_ctx->height/enc_ctx->width, 255) :
  1706. ost->filter->filter->inputs[0]->sample_aspect_ratio;
  1707. enc_ctx->pix_fmt = ost->filter->filter->inputs[0]->format;
  1708. ost->st->avg_frame_rate = ost->frame_rate;
  1709. if (dec_ctx &&
  1710. (enc_ctx->width != dec_ctx->width ||
  1711. enc_ctx->height != dec_ctx->height ||
  1712. enc_ctx->pix_fmt != dec_ctx->pix_fmt)) {
  1713. enc_ctx->bits_per_raw_sample = 0;
  1714. }
  1715. if (ost->forced_keyframes)
  1716. parse_forced_key_frames(ost->forced_keyframes, ost,
  1717. ost->enc_ctx);
  1718. break;
  1719. case AVMEDIA_TYPE_SUBTITLE:
  1720. enc_ctx->time_base = (AVRational){1, 1000};
  1721. break;
  1722. default:
  1723. abort();
  1724. break;
  1725. }
  1726. }
  1727. }
  1728. /* init input streams */
  1729. for (i = 0; i < nb_input_streams; i++)
  1730. if ((ret = init_input_stream(i, error, sizeof(error))) < 0)
  1731. goto dump_format;
  1732. /* open each encoder */
  1733. for (i = 0; i < nb_output_streams; i++) {
  1734. ret = init_output_stream(output_streams[i], error, sizeof(error));
  1735. if (ret < 0)
  1736. goto dump_format;
  1737. }
  1738. /* discard unused programs */
  1739. for (i = 0; i < nb_input_files; i++) {
  1740. InputFile *ifile = input_files[i];
  1741. for (j = 0; j < ifile->ctx->nb_programs; j++) {
  1742. AVProgram *p = ifile->ctx->programs[j];
  1743. int discard = AVDISCARD_ALL;
  1744. for (k = 0; k < p->nb_stream_indexes; k++)
  1745. if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {
  1746. discard = AVDISCARD_DEFAULT;
  1747. break;
  1748. }
  1749. p->discard = discard;
  1750. }
  1751. }
  1752. /* open files and write file headers */
  1753. for (i = 0; i < nb_output_files; i++) {
  1754. oc = output_files[i]->ctx;
  1755. oc->interrupt_callback = int_cb;
  1756. if ((ret = avformat_write_header(oc, &output_files[i]->opts)) < 0) {
  1757. char errbuf[128];
  1758. av_strerror(ret, errbuf, sizeof(errbuf));
  1759. snprintf(error, sizeof(error),
  1760. "Could not write header for output file #%d "
  1761. "(incorrect codec parameters ?): %s",
  1762. i, errbuf);
  1763. ret = AVERROR(EINVAL);
  1764. goto dump_format;
  1765. }
  1766. assert_avoptions(output_files[i]->opts);
  1767. if (strcmp(oc->oformat->name, "rtp")) {
  1768. want_sdp = 0;
  1769. }
  1770. }
  1771. dump_format:
  1772. /* dump the file output parameters - cannot be done before in case
  1773. of stream copy */
  1774. for (i = 0; i < nb_output_files; i++) {
  1775. av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);
  1776. }
  1777. /* dump the stream mapping */
  1778. av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");
  1779. for (i = 0; i < nb_input_streams; i++) {
  1780. ist = input_streams[i];
  1781. for (j = 0; j < ist->nb_filters; j++) {
  1782. if (ist->filters[j]->graph->graph_desc) {
  1783. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d (%s) -> %s",
  1784. ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",
  1785. ist->filters[j]->name);
  1786. if (nb_filtergraphs > 1)
  1787. av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);
  1788. av_log(NULL, AV_LOG_INFO, "\n");
  1789. }
  1790. }
  1791. }
  1792. for (i = 0; i < nb_output_streams; i++) {
  1793. ost = output_streams[i];
  1794. if (ost->attachment_filename) {
  1795. /* an attached file */
  1796. av_log(NULL, AV_LOG_INFO, " File %s -> Stream #%d:%d\n",
  1797. ost->attachment_filename, ost->file_index, ost->index);
  1798. continue;
  1799. }
  1800. if (ost->filter && ost->filter->graph->graph_desc) {
  1801. /* output from a complex graph */
  1802. av_log(NULL, AV_LOG_INFO, " %s", ost->filter->name);
  1803. if (nb_filtergraphs > 1)
  1804. av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);
  1805. av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,
  1806. ost->index, ost->enc ? ost->enc->name : "?");
  1807. continue;
  1808. }
  1809. av_log(NULL, AV_LOG_INFO, " Stream #%d:%d -> #%d:%d",
  1810. input_streams[ost->source_index]->file_index,
  1811. input_streams[ost->source_index]->st->index,
  1812. ost->file_index,
  1813. ost->index);
  1814. if (ost->sync_ist != input_streams[ost->source_index])
  1815. av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",
  1816. ost->sync_ist->file_index,
  1817. ost->sync_ist->st->index);
  1818. if (ost->stream_copy)
  1819. av_log(NULL, AV_LOG_INFO, " (copy)");
  1820. else {
  1821. const AVCodec *in_codec = input_streams[ost->source_index]->dec;
  1822. const AVCodec *out_codec = ost->enc;
  1823. const char *decoder_name = "?";
  1824. const char *in_codec_name = "?";
  1825. const char *encoder_name = "?";
  1826. const char *out_codec_name = "?";
  1827. const AVCodecDescriptor *desc;
  1828. if (in_codec) {
  1829. decoder_name = in_codec->name;
  1830. desc = avcodec_descriptor_get(in_codec->id);
  1831. if (desc)
  1832. in_codec_name = desc->name;
  1833. if (!strcmp(decoder_name, in_codec_name))
  1834. decoder_name = "native";
  1835. }
  1836. if (out_codec) {
  1837. encoder_name = out_codec->name;
  1838. desc = avcodec_descriptor_get(out_codec->id);
  1839. if (desc)
  1840. out_codec_name = desc->name;
  1841. if (!strcmp(encoder_name, out_codec_name))
  1842. encoder_name = "native";
  1843. }
  1844. av_log(NULL, AV_LOG_INFO, " (%s (%s) -> %s (%s))",
  1845. in_codec_name, decoder_name,
  1846. out_codec_name, encoder_name);
  1847. }
  1848. av_log(NULL, AV_LOG_INFO, "\n");
  1849. }
  1850. if (ret) {
  1851. av_log(NULL, AV_LOG_ERROR, "%s\n", error);
  1852. return ret;
  1853. }
  1854. if (want_sdp) {
  1855. print_sdp();
  1856. }
  1857. return 0;
  1858. }
  1859. /* Return 1 if there remain streams where more output is wanted, 0 otherwise. */
  1860. static int need_output(void)
  1861. {
  1862. int i;
  1863. for (i = 0; i < nb_output_streams; i++) {
  1864. OutputStream *ost = output_streams[i];
  1865. OutputFile *of = output_files[ost->file_index];
  1866. AVFormatContext *os = output_files[ost->file_index]->ctx;
  1867. if (ost->finished ||
  1868. (os->pb && avio_tell(os->pb) >= of->limit_filesize))
  1869. continue;
  1870. if (ost->frame_number >= ost->max_frames) {
  1871. int j;
  1872. for (j = 0; j < of->ctx->nb_streams; j++)
  1873. output_streams[of->ost_index + j]->finished = 1;
  1874. continue;
  1875. }
  1876. return 1;
  1877. }
  1878. return 0;
  1879. }
  1880. static InputFile *select_input_file(void)
  1881. {
  1882. InputFile *ifile = NULL;
  1883. int64_t ipts_min = INT64_MAX;
  1884. int i;
  1885. for (i = 0; i < nb_input_streams; i++) {
  1886. InputStream *ist = input_streams[i];
  1887. int64_t ipts = ist->last_dts;
  1888. if (ist->discard || input_files[ist->file_index]->eagain)
  1889. continue;
  1890. if (!input_files[ist->file_index]->eof_reached) {
  1891. if (ipts < ipts_min) {
  1892. ipts_min = ipts;
  1893. ifile = input_files[ist->file_index];
  1894. }
  1895. }
  1896. }
  1897. return ifile;
  1898. }
  1899. #if HAVE_PTHREADS
  1900. static void *input_thread(void *arg)
  1901. {
  1902. InputFile *f = arg;
  1903. int ret = 0;
  1904. while (!transcoding_finished && ret >= 0) {
  1905. AVPacket pkt;
  1906. ret = av_read_frame(f->ctx, &pkt);
  1907. if (ret == AVERROR(EAGAIN)) {
  1908. av_usleep(10000);
  1909. ret = 0;
  1910. continue;
  1911. } else if (ret < 0)
  1912. break;
  1913. pthread_mutex_lock(&f->fifo_lock);
  1914. while (!av_fifo_space(f->fifo))
  1915. pthread_cond_wait(&f->fifo_cond, &f->fifo_lock);
  1916. av_fifo_generic_write(f->fifo, &pkt, sizeof(pkt), NULL);
  1917. pthread_mutex_unlock(&f->fifo_lock);
  1918. }
  1919. f->finished = 1;
  1920. return NULL;
  1921. }
  1922. static void free_input_threads(void)
  1923. {
  1924. int i;
  1925. if (nb_input_files == 1)
  1926. return;
  1927. transcoding_finished = 1;
  1928. for (i = 0; i < nb_input_files; i++) {
  1929. InputFile *f = input_files[i];
  1930. AVPacket pkt;
  1931. if (!f->fifo || f->joined)
  1932. continue;
  1933. pthread_mutex_lock(&f->fifo_lock);
  1934. while (av_fifo_size(f->fifo)) {
  1935. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  1936. av_packet_unref(&pkt);
  1937. }
  1938. pthread_cond_signal(&f->fifo_cond);
  1939. pthread_mutex_unlock(&f->fifo_lock);
  1940. pthread_join(f->thread, NULL);
  1941. f->joined = 1;
  1942. while (av_fifo_size(f->fifo)) {
  1943. av_fifo_generic_read(f->fifo, &pkt, sizeof(pkt), NULL);
  1944. av_packet_unref(&pkt);
  1945. }
  1946. av_fifo_free(f->fifo);
  1947. }
  1948. }
  1949. static int init_input_threads(void)
  1950. {
  1951. int i, ret;
  1952. if (nb_input_files == 1)
  1953. return 0;
  1954. for (i = 0; i < nb_input_files; i++) {
  1955. InputFile *f = input_files[i];
  1956. if (!(f->fifo = av_fifo_alloc(8*sizeof(AVPacket))))
  1957. return AVERROR(ENOMEM);
  1958. pthread_mutex_init(&f->fifo_lock, NULL);
  1959. pthread_cond_init (&f->fifo_cond, NULL);
  1960. if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))
  1961. return AVERROR(ret);
  1962. }
  1963. return 0;
  1964. }
  1965. static int get_input_packet_mt(InputFile *f, AVPacket *pkt)
  1966. {
  1967. int ret = 0;
  1968. pthread_mutex_lock(&f->fifo_lock);
  1969. if (av_fifo_size(f->fifo)) {
  1970. av_fifo_generic_read(f->fifo, pkt, sizeof(*pkt), NULL);
  1971. pthread_cond_signal(&f->fifo_cond);
  1972. } else {
  1973. if (f->finished)
  1974. ret = AVERROR_EOF;
  1975. else
  1976. ret = AVERROR(EAGAIN);
  1977. }
  1978. pthread_mutex_unlock(&f->fifo_lock);
  1979. return ret;
  1980. }
  1981. #endif
  1982. static int get_input_packet(InputFile *f, AVPacket *pkt)
  1983. {
  1984. if (f->rate_emu) {
  1985. int i;
  1986. for (i = 0; i < f->nb_streams; i++) {
  1987. InputStream *ist = input_streams[f->ist_index + i];
  1988. int64_t pts = av_rescale(ist->last_dts, 1000000, AV_TIME_BASE);
  1989. int64_t now = av_gettime_relative() - ist->start;
  1990. if (pts > now)
  1991. return AVERROR(EAGAIN);
  1992. }
  1993. }
  1994. #if HAVE_PTHREADS
  1995. if (nb_input_files > 1)
  1996. return get_input_packet_mt(f, pkt);
  1997. #endif
  1998. return av_read_frame(f->ctx, pkt);
  1999. }
  2000. static int got_eagain(void)
  2001. {
  2002. int i;
  2003. for (i = 0; i < nb_input_files; i++)
  2004. if (input_files[i]->eagain)
  2005. return 1;
  2006. return 0;
  2007. }
  2008. static void reset_eagain(void)
  2009. {
  2010. int i;
  2011. for (i = 0; i < nb_input_files; i++)
  2012. input_files[i]->eagain = 0;
  2013. }
  2014. // set duration to max(tmp, duration) in a proper time base and return duration's time_base
  2015. static AVRational duration_max(int64_t tmp, int64_t *duration, AVRational tmp_time_base,
  2016. AVRational time_base)
  2017. {
  2018. int ret;
  2019. if (!*duration) {
  2020. *duration = tmp;
  2021. return tmp_time_base;
  2022. }
  2023. ret = av_compare_ts(*duration, time_base, tmp, tmp_time_base);
  2024. if (ret < 0) {
  2025. *duration = tmp;
  2026. return tmp_time_base;
  2027. }
  2028. return time_base;
  2029. }
  2030. static int seek_to_start(InputFile *ifile, AVFormatContext *is)
  2031. {
  2032. InputStream *ist;
  2033. AVCodecContext *avctx;
  2034. int i, ret, has_audio = 0;
  2035. int64_t duration = 0;
  2036. ret = av_seek_frame(is, -1, is->start_time, 0);
  2037. if (ret < 0)
  2038. return ret;
  2039. for (i = 0; i < ifile->nb_streams; i++) {
  2040. ist = input_streams[ifile->ist_index + i];
  2041. avctx = ist->dec_ctx;
  2042. // flush decoders
  2043. if (ist->decoding_needed) {
  2044. process_input_packet(ist, NULL, 1);
  2045. avcodec_flush_buffers(avctx);
  2046. }
  2047. /* duration is the length of the last frame in a stream
  2048. * when audio stream is present we don't care about
  2049. * last video frame length because it's not defined exactly */
  2050. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples)
  2051. has_audio = 1;
  2052. }
  2053. for (i = 0; i < ifile->nb_streams; i++) {
  2054. ist = input_streams[ifile->ist_index + i];
  2055. avctx = ist->dec_ctx;
  2056. if (has_audio) {
  2057. if (avctx->codec_type == AVMEDIA_TYPE_AUDIO && ist->nb_samples) {
  2058. AVRational sample_rate = {1, avctx->sample_rate};
  2059. duration = av_rescale_q(ist->nb_samples, sample_rate, ist->st->time_base);
  2060. } else
  2061. continue;
  2062. } else {
  2063. if (ist->framerate.num) {
  2064. duration = av_rescale_q(1, ist->framerate, ist->st->time_base);
  2065. } else if (ist->st->avg_frame_rate.num) {
  2066. duration = av_rescale_q(1, ist->st->avg_frame_rate, ist->st->time_base);
  2067. } else duration = 1;
  2068. }
  2069. if (!ifile->duration)
  2070. ifile->time_base = ist->st->time_base;
  2071. /* the total duration of the stream, max_pts - min_pts is
  2072. * the duration of the stream without the last frame */
  2073. duration += ist->max_pts - ist->min_pts;
  2074. ifile->time_base = duration_max(duration, &ifile->duration, ist->st->time_base,
  2075. ifile->time_base);
  2076. }
  2077. if (ifile->loop > 0)
  2078. ifile->loop--;
  2079. return ret;
  2080. }
  2081. /*
  2082. * Read one packet from an input file and send it for
  2083. * - decoding -> lavfi (audio/video)
  2084. * - decoding -> encoding -> muxing (subtitles)
  2085. * - muxing (streamcopy)
  2086. *
  2087. * Return
  2088. * - 0 -- one packet was read and processed
  2089. * - AVERROR(EAGAIN) -- no packets were available for selected file,
  2090. * this function should be called again
  2091. * - AVERROR_EOF -- this function should not be called again
  2092. */
  2093. static int process_input(void)
  2094. {
  2095. InputFile *ifile;
  2096. AVFormatContext *is;
  2097. InputStream *ist;
  2098. AVPacket pkt;
  2099. int ret, i, j;
  2100. int64_t duration;
  2101. /* select the stream that we must read now */
  2102. ifile = select_input_file();
  2103. /* if none, if is finished */
  2104. if (!ifile) {
  2105. if (got_eagain()) {
  2106. reset_eagain();
  2107. av_usleep(10000);
  2108. return AVERROR(EAGAIN);
  2109. }
  2110. av_log(NULL, AV_LOG_VERBOSE, "No more inputs to read from.\n");
  2111. return AVERROR_EOF;
  2112. }
  2113. is = ifile->ctx;
  2114. ret = get_input_packet(ifile, &pkt);
  2115. if (ret == AVERROR(EAGAIN)) {
  2116. ifile->eagain = 1;
  2117. return ret;
  2118. }
  2119. if (ret < 0 && ifile->loop) {
  2120. if ((ret = seek_to_start(ifile, is)) < 0)
  2121. return ret;
  2122. ret = get_input_packet(ifile, &pkt);
  2123. }
  2124. if (ret < 0) {
  2125. if (ret != AVERROR_EOF) {
  2126. print_error(is->filename, ret);
  2127. if (exit_on_error)
  2128. exit_program(1);
  2129. }
  2130. ifile->eof_reached = 1;
  2131. for (i = 0; i < ifile->nb_streams; i++) {
  2132. ist = input_streams[ifile->ist_index + i];
  2133. if (ist->decoding_needed)
  2134. process_input_packet(ist, NULL, 0);
  2135. /* mark all outputs that don't go through lavfi as finished */
  2136. for (j = 0; j < nb_output_streams; j++) {
  2137. OutputStream *ost = output_streams[j];
  2138. if (ost->source_index == ifile->ist_index + i &&
  2139. (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))
  2140. finish_output_stream(ost);
  2141. }
  2142. }
  2143. return AVERROR(EAGAIN);
  2144. }
  2145. reset_eagain();
  2146. if (do_pkt_dump) {
  2147. av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,
  2148. is->streams[pkt.stream_index]);
  2149. }
  2150. /* the following test is needed in case new streams appear
  2151. dynamically in stream : we ignore them */
  2152. if (pkt.stream_index >= ifile->nb_streams)
  2153. goto discard_packet;
  2154. ist = input_streams[ifile->ist_index + pkt.stream_index];
  2155. ist->data_size += pkt.size;
  2156. ist->nb_packets++;
  2157. if (ist->discard)
  2158. goto discard_packet;
  2159. /* add the stream-global side data to the first packet */
  2160. if (ist->nb_packets == 1)
  2161. for (i = 0; i < ist->st->nb_side_data; i++) {
  2162. AVPacketSideData *src_sd = &ist->st->side_data[i];
  2163. uint8_t *dst_data;
  2164. if (av_packet_get_side_data(&pkt, src_sd->type, NULL))
  2165. continue;
  2166. if (ist->autorotate && src_sd->type == AV_PKT_DATA_DISPLAYMATRIX)
  2167. continue;
  2168. dst_data = av_packet_new_side_data(&pkt, src_sd->type, src_sd->size);
  2169. if (!dst_data)
  2170. exit_program(1);
  2171. memcpy(dst_data, src_sd->data, src_sd->size);
  2172. }
  2173. if (pkt.dts != AV_NOPTS_VALUE)
  2174. pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2175. if (pkt.pts != AV_NOPTS_VALUE)
  2176. pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);
  2177. if (pkt.pts != AV_NOPTS_VALUE)
  2178. pkt.pts *= ist->ts_scale;
  2179. if (pkt.dts != AV_NOPTS_VALUE)
  2180. pkt.dts *= ist->ts_scale;
  2181. if ((ist->dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO ||
  2182. ist->dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) &&
  2183. pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&
  2184. (is->iformat->flags & AVFMT_TS_DISCONT)) {
  2185. int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);
  2186. int64_t delta = pkt_dts - ist->next_dts;
  2187. if ((FFABS(delta) > 1LL * dts_delta_threshold * AV_TIME_BASE || pkt_dts + 1 < ist->last_dts) && !copy_ts) {
  2188. ifile->ts_offset -= delta;
  2189. av_log(NULL, AV_LOG_DEBUG,
  2190. "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",
  2191. delta, ifile->ts_offset);
  2192. pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2193. if (pkt.pts != AV_NOPTS_VALUE)
  2194. pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);
  2195. }
  2196. }
  2197. duration = av_rescale_q(ifile->duration, ifile->time_base, ist->st->time_base);
  2198. if (pkt.pts != AV_NOPTS_VALUE) {
  2199. pkt.pts += duration;
  2200. ist->max_pts = FFMAX(pkt.pts, ist->max_pts);
  2201. ist->min_pts = FFMIN(pkt.pts, ist->min_pts);
  2202. }
  2203. if (pkt.dts != AV_NOPTS_VALUE)
  2204. pkt.dts += duration;
  2205. process_input_packet(ist, &pkt, 0);
  2206. discard_packet:
  2207. av_packet_unref(&pkt);
  2208. return 0;
  2209. }
  2210. /*
  2211. * The following code is the main loop of the file converter
  2212. */
  2213. static int transcode(void)
  2214. {
  2215. int ret, i, need_input = 1;
  2216. AVFormatContext *os;
  2217. OutputStream *ost;
  2218. InputStream *ist;
  2219. int64_t timer_start;
  2220. ret = transcode_init();
  2221. if (ret < 0)
  2222. goto fail;
  2223. av_log(NULL, AV_LOG_INFO, "Press ctrl-c to stop encoding\n");
  2224. term_init();
  2225. timer_start = av_gettime_relative();
  2226. #if HAVE_PTHREADS
  2227. if ((ret = init_input_threads()) < 0)
  2228. goto fail;
  2229. #endif
  2230. while (!received_sigterm) {
  2231. /* check if there's any stream where output is still needed */
  2232. if (!need_output()) {
  2233. av_log(NULL, AV_LOG_VERBOSE, "No more output streams to write to, finishing.\n");
  2234. break;
  2235. }
  2236. /* read and process one input packet if needed */
  2237. if (need_input) {
  2238. ret = process_input();
  2239. if (ret == AVERROR_EOF)
  2240. need_input = 0;
  2241. }
  2242. ret = poll_filters();
  2243. if (ret < 0 && ret != AVERROR_EOF) {
  2244. char errbuf[128];
  2245. av_strerror(ret, errbuf, sizeof(errbuf));
  2246. av_log(NULL, AV_LOG_ERROR, "Error while filtering: %s\n", errbuf);
  2247. break;
  2248. }
  2249. /* dump report by using the output first video and audio streams */
  2250. print_report(0, timer_start);
  2251. }
  2252. #if HAVE_PTHREADS
  2253. free_input_threads();
  2254. #endif
  2255. /* at the end of stream, we must flush the decoder buffers */
  2256. for (i = 0; i < nb_input_streams; i++) {
  2257. ist = input_streams[i];
  2258. if (!input_files[ist->file_index]->eof_reached && ist->decoding_needed) {
  2259. process_input_packet(ist, NULL, 0);
  2260. }
  2261. }
  2262. poll_filters();
  2263. flush_encoders();
  2264. term_exit();
  2265. /* write the trailer if needed and close file */
  2266. for (i = 0; i < nb_output_files; i++) {
  2267. os = output_files[i]->ctx;
  2268. av_write_trailer(os);
  2269. }
  2270. /* dump report by using the first video and audio streams */
  2271. print_report(1, timer_start);
  2272. /* close each encoder */
  2273. for (i = 0; i < nb_output_streams; i++) {
  2274. ost = output_streams[i];
  2275. if (ost->encoding_needed) {
  2276. av_freep(&ost->enc_ctx->stats_in);
  2277. }
  2278. }
  2279. /* close each decoder */
  2280. for (i = 0; i < nb_input_streams; i++) {
  2281. ist = input_streams[i];
  2282. if (ist->decoding_needed) {
  2283. avcodec_close(ist->dec_ctx);
  2284. if (ist->hwaccel_uninit)
  2285. ist->hwaccel_uninit(ist->dec_ctx);
  2286. }
  2287. }
  2288. av_buffer_unref(&hw_device_ctx);
  2289. /* finished ! */
  2290. ret = 0;
  2291. fail:
  2292. #if HAVE_PTHREADS
  2293. free_input_threads();
  2294. #endif
  2295. if (output_streams) {
  2296. for (i = 0; i < nb_output_streams; i++) {
  2297. ost = output_streams[i];
  2298. if (ost) {
  2299. if (ost->logfile) {
  2300. fclose(ost->logfile);
  2301. ost->logfile = NULL;
  2302. }
  2303. av_free(ost->forced_kf_pts);
  2304. av_dict_free(&ost->encoder_opts);
  2305. av_dict_free(&ost->resample_opts);
  2306. }
  2307. }
  2308. }
  2309. return ret;
  2310. }
  2311. static int64_t getutime(void)
  2312. {
  2313. #if HAVE_GETRUSAGE
  2314. struct rusage rusage;
  2315. getrusage(RUSAGE_SELF, &rusage);
  2316. return (rusage.ru_utime.tv_sec * 1000000LL) + rusage.ru_utime.tv_usec;
  2317. #elif HAVE_GETPROCESSTIMES
  2318. HANDLE proc;
  2319. FILETIME c, e, k, u;
  2320. proc = GetCurrentProcess();
  2321. GetProcessTimes(proc, &c, &e, &k, &u);
  2322. return ((int64_t) u.dwHighDateTime << 32 | u.dwLowDateTime) / 10;
  2323. #else
  2324. return av_gettime_relative();
  2325. #endif
  2326. }
  2327. static int64_t getmaxrss(void)
  2328. {
  2329. #if HAVE_GETRUSAGE && HAVE_STRUCT_RUSAGE_RU_MAXRSS
  2330. struct rusage rusage;
  2331. getrusage(RUSAGE_SELF, &rusage);
  2332. return (int64_t)rusage.ru_maxrss * 1024;
  2333. #elif HAVE_GETPROCESSMEMORYINFO
  2334. HANDLE proc;
  2335. PROCESS_MEMORY_COUNTERS memcounters;
  2336. proc = GetCurrentProcess();
  2337. memcounters.cb = sizeof(memcounters);
  2338. GetProcessMemoryInfo(proc, &memcounters, sizeof(memcounters));
  2339. return memcounters.PeakPagefileUsage;
  2340. #else
  2341. return 0;
  2342. #endif
  2343. }
  2344. int main(int argc, char **argv)
  2345. {
  2346. int ret;
  2347. int64_t ti;
  2348. register_exit(avconv_cleanup);
  2349. av_log_set_flags(AV_LOG_SKIP_REPEATED);
  2350. parse_loglevel(argc, argv, options);
  2351. avcodec_register_all();
  2352. #if CONFIG_AVDEVICE
  2353. avdevice_register_all();
  2354. #endif
  2355. avfilter_register_all();
  2356. av_register_all();
  2357. avformat_network_init();
  2358. show_banner();
  2359. /* parse options and open all input/output files */
  2360. ret = avconv_parse_options(argc, argv);
  2361. if (ret < 0)
  2362. exit_program(1);
  2363. if (nb_output_files <= 0 && nb_input_files == 0) {
  2364. show_usage();
  2365. av_log(NULL, AV_LOG_WARNING, "Use -h to get full help or, even better, run 'man %s'\n", program_name);
  2366. exit_program(1);
  2367. }
  2368. /* file converter / grab */
  2369. if (nb_output_files <= 0) {
  2370. fprintf(stderr, "At least one output file must be specified\n");
  2371. exit_program(1);
  2372. }
  2373. ti = getutime();
  2374. if (transcode() < 0)
  2375. exit_program(1);
  2376. ti = getutime() - ti;
  2377. if (do_benchmark) {
  2378. int maxrss = getmaxrss() / 1024;
  2379. printf("bench: utime=%0.3fs maxrss=%ikB\n", ti / 1000000.0, maxrss);
  2380. }
  2381. exit_program(0);
  2382. return 0;
  2383. }