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.

2802 lines
89KB

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