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.

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