transcoding.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. /*
  2. * Copyright (c) 2010 Nicolas George
  3. * Copyright (c) 2011 Stefano Sabatini
  4. * Copyright (c) 2014 Andrey Utkin
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. /**
  25. * @file
  26. * API example for demuxing, decoding, filtering, encoding and muxing
  27. * @example transcoding.c
  28. */
  29. #include <libavcodec/avcodec.h>
  30. #include <libavformat/avformat.h>
  31. #include <libavfilter/buffersink.h>
  32. #include <libavfilter/buffersrc.h>
  33. #include <libavutil/opt.h>
  34. #include <libavutil/pixdesc.h>
  35. static AVFormatContext *ifmt_ctx;
  36. static AVFormatContext *ofmt_ctx;
  37. typedef struct FilteringContext {
  38. AVFilterContext *buffersink_ctx;
  39. AVFilterContext *buffersrc_ctx;
  40. AVFilterGraph *filter_graph;
  41. } FilteringContext;
  42. static FilteringContext *filter_ctx;
  43. typedef struct StreamContext {
  44. AVCodecContext *dec_ctx;
  45. AVCodecContext *enc_ctx;
  46. } StreamContext;
  47. static StreamContext *stream_ctx;
  48. static int open_input_file(const char *filename)
  49. {
  50. int ret;
  51. unsigned int i;
  52. ifmt_ctx = NULL;
  53. if ((ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL)) < 0) {
  54. av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
  55. return ret;
  56. }
  57. if ((ret = avformat_find_stream_info(ifmt_ctx, NULL)) < 0) {
  58. av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
  59. return ret;
  60. }
  61. stream_ctx = av_mallocz_array(ifmt_ctx->nb_streams, sizeof(*stream_ctx));
  62. if (!stream_ctx)
  63. return AVERROR(ENOMEM);
  64. for (i = 0; i < ifmt_ctx->nb_streams; i++) {
  65. AVStream *stream = ifmt_ctx->streams[i];
  66. AVCodec *dec = avcodec_find_decoder(stream->codecpar->codec_id);
  67. AVCodecContext *codec_ctx;
  68. if (!dec) {
  69. av_log(NULL, AV_LOG_ERROR, "Failed to find decoder for stream #%u\n", i);
  70. return AVERROR_DECODER_NOT_FOUND;
  71. }
  72. codec_ctx = avcodec_alloc_context3(dec);
  73. if (!codec_ctx) {
  74. av_log(NULL, AV_LOG_ERROR, "Failed to allocate the decoder context for stream #%u\n", i);
  75. return AVERROR(ENOMEM);
  76. }
  77. ret = avcodec_parameters_to_context(codec_ctx, stream->codecpar);
  78. if (ret < 0) {
  79. av_log(NULL, AV_LOG_ERROR, "Failed to copy decoder parameters to input decoder context "
  80. "for stream #%u\n", i);
  81. return ret;
  82. }
  83. /* Reencode video & audio and remux subtitles etc. */
  84. if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
  85. || codec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  86. if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
  87. codec_ctx->framerate = av_guess_frame_rate(ifmt_ctx, stream, NULL);
  88. /* Open decoder */
  89. ret = avcodec_open2(codec_ctx, dec, NULL);
  90. if (ret < 0) {
  91. av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i);
  92. return ret;
  93. }
  94. }
  95. stream_ctx[i].dec_ctx = codec_ctx;
  96. }
  97. av_dump_format(ifmt_ctx, 0, filename, 0);
  98. return 0;
  99. }
  100. static int open_output_file(const char *filename)
  101. {
  102. AVStream *out_stream;
  103. AVStream *in_stream;
  104. AVCodecContext *dec_ctx, *enc_ctx;
  105. AVCodec *encoder;
  106. int ret;
  107. unsigned int i;
  108. ofmt_ctx = NULL;
  109. avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, filename);
  110. if (!ofmt_ctx) {
  111. av_log(NULL, AV_LOG_ERROR, "Could not create output context\n");
  112. return AVERROR_UNKNOWN;
  113. }
  114. for (i = 0; i < ifmt_ctx->nb_streams; i++) {
  115. out_stream = avformat_new_stream(ofmt_ctx, NULL);
  116. if (!out_stream) {
  117. av_log(NULL, AV_LOG_ERROR, "Failed allocating output stream\n");
  118. return AVERROR_UNKNOWN;
  119. }
  120. in_stream = ifmt_ctx->streams[i];
  121. dec_ctx = stream_ctx[i].dec_ctx;
  122. if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
  123. || dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  124. /* in this example, we choose transcoding to same codec */
  125. encoder = avcodec_find_encoder(dec_ctx->codec_id);
  126. if (!encoder) {
  127. av_log(NULL, AV_LOG_FATAL, "Necessary encoder not found\n");
  128. return AVERROR_INVALIDDATA;
  129. }
  130. enc_ctx = avcodec_alloc_context3(encoder);
  131. if (!enc_ctx) {
  132. av_log(NULL, AV_LOG_FATAL, "Failed to allocate the encoder context\n");
  133. return AVERROR(ENOMEM);
  134. }
  135. /* In this example, we transcode to same properties (picture size,
  136. * sample rate etc.). These properties can be changed for output
  137. * streams easily using filters */
  138. if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  139. enc_ctx->height = dec_ctx->height;
  140. enc_ctx->width = dec_ctx->width;
  141. enc_ctx->sample_aspect_ratio = dec_ctx->sample_aspect_ratio;
  142. /* take first format from list of supported formats */
  143. if (encoder->pix_fmts)
  144. enc_ctx->pix_fmt = encoder->pix_fmts[0];
  145. else
  146. enc_ctx->pix_fmt = dec_ctx->pix_fmt;
  147. /* video time_base can be set to whatever is handy and supported by encoder */
  148. enc_ctx->time_base = av_inv_q(dec_ctx->framerate);
  149. } else {
  150. enc_ctx->sample_rate = dec_ctx->sample_rate;
  151. enc_ctx->channel_layout = dec_ctx->channel_layout;
  152. enc_ctx->channels = av_get_channel_layout_nb_channels(enc_ctx->channel_layout);
  153. /* take first format from list of supported formats */
  154. enc_ctx->sample_fmt = encoder->sample_fmts[0];
  155. enc_ctx->time_base = (AVRational){1, enc_ctx->sample_rate};
  156. }
  157. if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
  158. enc_ctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  159. /* Third parameter can be used to pass settings to encoder */
  160. ret = avcodec_open2(enc_ctx, encoder, NULL);
  161. if (ret < 0) {
  162. av_log(NULL, AV_LOG_ERROR, "Cannot open video encoder for stream #%u\n", i);
  163. return ret;
  164. }
  165. ret = avcodec_parameters_from_context(out_stream->codecpar, enc_ctx);
  166. if (ret < 0) {
  167. av_log(NULL, AV_LOG_ERROR, "Failed to copy encoder parameters to output stream #%u\n", i);
  168. return ret;
  169. }
  170. out_stream->time_base = enc_ctx->time_base;
  171. stream_ctx[i].enc_ctx = enc_ctx;
  172. } else if (dec_ctx->codec_type == AVMEDIA_TYPE_UNKNOWN) {
  173. av_log(NULL, AV_LOG_FATAL, "Elementary stream #%d is of unknown type, cannot proceed\n", i);
  174. return AVERROR_INVALIDDATA;
  175. } else {
  176. /* if this stream must be remuxed */
  177. ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);
  178. if (ret < 0) {
  179. av_log(NULL, AV_LOG_ERROR, "Copying parameters for stream #%u failed\n", i);
  180. return ret;
  181. }
  182. out_stream->time_base = in_stream->time_base;
  183. }
  184. }
  185. av_dump_format(ofmt_ctx, 0, filename, 1);
  186. if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
  187. ret = avio_open(&ofmt_ctx->pb, filename, AVIO_FLAG_WRITE);
  188. if (ret < 0) {
  189. av_log(NULL, AV_LOG_ERROR, "Could not open output file '%s'", filename);
  190. return ret;
  191. }
  192. }
  193. /* init muxer, write output file header */
  194. ret = avformat_write_header(ofmt_ctx, NULL);
  195. if (ret < 0) {
  196. av_log(NULL, AV_LOG_ERROR, "Error occurred when opening output file\n");
  197. return ret;
  198. }
  199. return 0;
  200. }
  201. static int init_filter(FilteringContext* fctx, AVCodecContext *dec_ctx,
  202. AVCodecContext *enc_ctx, const char *filter_spec)
  203. {
  204. char args[512];
  205. int ret = 0;
  206. const AVFilter *buffersrc = NULL;
  207. const AVFilter *buffersink = NULL;
  208. AVFilterContext *buffersrc_ctx = NULL;
  209. AVFilterContext *buffersink_ctx = NULL;
  210. AVFilterInOut *outputs = avfilter_inout_alloc();
  211. AVFilterInOut *inputs = avfilter_inout_alloc();
  212. AVFilterGraph *filter_graph = avfilter_graph_alloc();
  213. if (!outputs || !inputs || !filter_graph) {
  214. ret = AVERROR(ENOMEM);
  215. goto end;
  216. }
  217. if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
  218. buffersrc = avfilter_get_by_name("buffer");
  219. buffersink = avfilter_get_by_name("buffersink");
  220. if (!buffersrc || !buffersink) {
  221. av_log(NULL, AV_LOG_ERROR, "filtering source or sink element not found\n");
  222. ret = AVERROR_UNKNOWN;
  223. goto end;
  224. }
  225. snprintf(args, sizeof(args),
  226. "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
  227. dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,
  228. dec_ctx->time_base.num, dec_ctx->time_base.den,
  229. dec_ctx->sample_aspect_ratio.num,
  230. dec_ctx->sample_aspect_ratio.den);
  231. ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
  232. args, NULL, filter_graph);
  233. if (ret < 0) {
  234. av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
  235. goto end;
  236. }
  237. ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
  238. NULL, NULL, filter_graph);
  239. if (ret < 0) {
  240. av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
  241. goto end;
  242. }
  243. ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
  244. (uint8_t*)&enc_ctx->pix_fmt, sizeof(enc_ctx->pix_fmt),
  245. AV_OPT_SEARCH_CHILDREN);
  246. if (ret < 0) {
  247. av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\n");
  248. goto end;
  249. }
  250. } else if (dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
  251. buffersrc = avfilter_get_by_name("abuffer");
  252. buffersink = avfilter_get_by_name("abuffersink");
  253. if (!buffersrc || !buffersink) {
  254. av_log(NULL, AV_LOG_ERROR, "filtering source or sink element not found\n");
  255. ret = AVERROR_UNKNOWN;
  256. goto end;
  257. }
  258. if (!dec_ctx->channel_layout)
  259. dec_ctx->channel_layout =
  260. av_get_default_channel_layout(dec_ctx->channels);
  261. snprintf(args, sizeof(args),
  262. "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=0x%"PRIx64,
  263. dec_ctx->time_base.num, dec_ctx->time_base.den, dec_ctx->sample_rate,
  264. av_get_sample_fmt_name(dec_ctx->sample_fmt),
  265. dec_ctx->channel_layout);
  266. ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
  267. args, NULL, filter_graph);
  268. if (ret < 0) {
  269. av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source\n");
  270. goto end;
  271. }
  272. ret = avfilter_graph_create_filter(&buffersink_ctx, buffersink, "out",
  273. NULL, NULL, filter_graph);
  274. if (ret < 0) {
  275. av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink\n");
  276. goto end;
  277. }
  278. ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
  279. (uint8_t*)&enc_ctx->sample_fmt, sizeof(enc_ctx->sample_fmt),
  280. AV_OPT_SEARCH_CHILDREN);
  281. if (ret < 0) {
  282. av_log(NULL, AV_LOG_ERROR, "Cannot set output sample format\n");
  283. goto end;
  284. }
  285. ret = av_opt_set_bin(buffersink_ctx, "channel_layouts",
  286. (uint8_t*)&enc_ctx->channel_layout,
  287. sizeof(enc_ctx->channel_layout), AV_OPT_SEARCH_CHILDREN);
  288. if (ret < 0) {
  289. av_log(NULL, AV_LOG_ERROR, "Cannot set output channel layout\n");
  290. goto end;
  291. }
  292. ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
  293. (uint8_t*)&enc_ctx->sample_rate, sizeof(enc_ctx->sample_rate),
  294. AV_OPT_SEARCH_CHILDREN);
  295. if (ret < 0) {
  296. av_log(NULL, AV_LOG_ERROR, "Cannot set output sample rate\n");
  297. goto end;
  298. }
  299. } else {
  300. ret = AVERROR_UNKNOWN;
  301. goto end;
  302. }
  303. /* Endpoints for the filter graph. */
  304. outputs->name = av_strdup("in");
  305. outputs->filter_ctx = buffersrc_ctx;
  306. outputs->pad_idx = 0;
  307. outputs->next = NULL;
  308. inputs->name = av_strdup("out");
  309. inputs->filter_ctx = buffersink_ctx;
  310. inputs->pad_idx = 0;
  311. inputs->next = NULL;
  312. if (!outputs->name || !inputs->name) {
  313. ret = AVERROR(ENOMEM);
  314. goto end;
  315. }
  316. if ((ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
  317. &inputs, &outputs, NULL)) < 0)
  318. goto end;
  319. if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
  320. goto end;
  321. /* Fill FilteringContext */
  322. fctx->buffersrc_ctx = buffersrc_ctx;
  323. fctx->buffersink_ctx = buffersink_ctx;
  324. fctx->filter_graph = filter_graph;
  325. end:
  326. avfilter_inout_free(&inputs);
  327. avfilter_inout_free(&outputs);
  328. return ret;
  329. }
  330. static int init_filters(void)
  331. {
  332. const char *filter_spec;
  333. unsigned int i;
  334. int ret;
  335. filter_ctx = av_malloc_array(ifmt_ctx->nb_streams, sizeof(*filter_ctx));
  336. if (!filter_ctx)
  337. return AVERROR(ENOMEM);
  338. for (i = 0; i < ifmt_ctx->nb_streams; i++) {
  339. filter_ctx[i].buffersrc_ctx = NULL;
  340. filter_ctx[i].buffersink_ctx = NULL;
  341. filter_ctx[i].filter_graph = NULL;
  342. if (!(ifmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO
  343. || ifmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO))
  344. continue;
  345. if (ifmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
  346. filter_spec = "null"; /* passthrough (dummy) filter for video */
  347. else
  348. filter_spec = "anull"; /* passthrough (dummy) filter for audio */
  349. ret = init_filter(&filter_ctx[i], stream_ctx[i].dec_ctx,
  350. stream_ctx[i].enc_ctx, filter_spec);
  351. if (ret)
  352. return ret;
  353. }
  354. return 0;
  355. }
  356. static int encode_write_frame(AVFrame *filt_frame, unsigned int stream_index, int *got_frame) {
  357. int ret;
  358. int got_frame_local;
  359. AVPacket enc_pkt;
  360. int (*enc_func)(AVCodecContext *, AVPacket *, const AVFrame *, int *) =
  361. (ifmt_ctx->streams[stream_index]->codecpar->codec_type ==
  362. AVMEDIA_TYPE_VIDEO) ? avcodec_encode_video2 : avcodec_encode_audio2;
  363. if (!got_frame)
  364. got_frame = &got_frame_local;
  365. av_log(NULL, AV_LOG_INFO, "Encoding frame\n");
  366. /* encode filtered frame */
  367. enc_pkt.data = NULL;
  368. enc_pkt.size = 0;
  369. av_init_packet(&enc_pkt);
  370. ret = enc_func(stream_ctx[stream_index].enc_ctx, &enc_pkt,
  371. filt_frame, got_frame);
  372. av_frame_free(&filt_frame);
  373. if (ret < 0)
  374. return ret;
  375. if (!(*got_frame))
  376. return 0;
  377. /* prepare packet for muxing */
  378. enc_pkt.stream_index = stream_index;
  379. av_packet_rescale_ts(&enc_pkt,
  380. stream_ctx[stream_index].enc_ctx->time_base,
  381. ofmt_ctx->streams[stream_index]->time_base);
  382. av_log(NULL, AV_LOG_DEBUG, "Muxing frame\n");
  383. /* mux encoded frame */
  384. ret = av_interleaved_write_frame(ofmt_ctx, &enc_pkt);
  385. return ret;
  386. }
  387. static int filter_encode_write_frame(AVFrame *frame, unsigned int stream_index)
  388. {
  389. int ret;
  390. AVFrame *filt_frame;
  391. av_log(NULL, AV_LOG_INFO, "Pushing decoded frame to filters\n");
  392. /* push the decoded frame into the filtergraph */
  393. ret = av_buffersrc_add_frame_flags(filter_ctx[stream_index].buffersrc_ctx,
  394. frame, 0);
  395. if (ret < 0) {
  396. av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
  397. return ret;
  398. }
  399. /* pull filtered frames from the filtergraph */
  400. while (1) {
  401. filt_frame = av_frame_alloc();
  402. if (!filt_frame) {
  403. ret = AVERROR(ENOMEM);
  404. break;
  405. }
  406. av_log(NULL, AV_LOG_INFO, "Pulling filtered frame from filters\n");
  407. ret = av_buffersink_get_frame(filter_ctx[stream_index].buffersink_ctx,
  408. filt_frame);
  409. if (ret < 0) {
  410. /* if no more frames for output - returns AVERROR(EAGAIN)
  411. * if flushed and no more frames for output - returns AVERROR_EOF
  412. * rewrite retcode to 0 to show it as normal procedure completion
  413. */
  414. if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
  415. ret = 0;
  416. av_frame_free(&filt_frame);
  417. break;
  418. }
  419. filt_frame->pict_type = AV_PICTURE_TYPE_NONE;
  420. ret = encode_write_frame(filt_frame, stream_index, NULL);
  421. if (ret < 0)
  422. break;
  423. }
  424. return ret;
  425. }
  426. static int flush_encoder(unsigned int stream_index)
  427. {
  428. int ret;
  429. int got_frame;
  430. if (!(stream_ctx[stream_index].enc_ctx->codec->capabilities &
  431. AV_CODEC_CAP_DELAY))
  432. return 0;
  433. while (1) {
  434. av_log(NULL, AV_LOG_INFO, "Flushing stream #%u encoder\n", stream_index);
  435. ret = encode_write_frame(NULL, stream_index, &got_frame);
  436. if (ret < 0)
  437. break;
  438. if (!got_frame)
  439. return 0;
  440. }
  441. return ret;
  442. }
  443. int main(int argc, char **argv)
  444. {
  445. int ret;
  446. AVPacket packet = { .data = NULL, .size = 0 };
  447. AVFrame *frame = NULL;
  448. enum AVMediaType type;
  449. unsigned int stream_index;
  450. unsigned int i;
  451. int got_frame;
  452. int (*dec_func)(AVCodecContext *, AVFrame *, int *, const AVPacket *);
  453. if (argc != 3) {
  454. av_log(NULL, AV_LOG_ERROR, "Usage: %s <input file> <output file>\n", argv[0]);
  455. return 1;
  456. }
  457. if ((ret = open_input_file(argv[1])) < 0)
  458. goto end;
  459. if ((ret = open_output_file(argv[2])) < 0)
  460. goto end;
  461. if ((ret = init_filters()) < 0)
  462. goto end;
  463. /* read all packets */
  464. while (1) {
  465. if ((ret = av_read_frame(ifmt_ctx, &packet)) < 0)
  466. break;
  467. stream_index = packet.stream_index;
  468. type = ifmt_ctx->streams[packet.stream_index]->codecpar->codec_type;
  469. av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n",
  470. stream_index);
  471. if (filter_ctx[stream_index].filter_graph) {
  472. av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
  473. frame = av_frame_alloc();
  474. if (!frame) {
  475. ret = AVERROR(ENOMEM);
  476. break;
  477. }
  478. av_packet_rescale_ts(&packet,
  479. ifmt_ctx->streams[stream_index]->time_base,
  480. stream_ctx[stream_index].dec_ctx->time_base);
  481. dec_func = (type == AVMEDIA_TYPE_VIDEO) ? avcodec_decode_video2 :
  482. avcodec_decode_audio4;
  483. ret = dec_func(stream_ctx[stream_index].dec_ctx, frame,
  484. &got_frame, &packet);
  485. if (ret < 0) {
  486. av_frame_free(&frame);
  487. av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
  488. break;
  489. }
  490. if (got_frame) {
  491. frame->pts = frame->best_effort_timestamp;
  492. ret = filter_encode_write_frame(frame, stream_index);
  493. av_frame_free(&frame);
  494. if (ret < 0)
  495. goto end;
  496. } else {
  497. av_frame_free(&frame);
  498. }
  499. } else {
  500. /* remux this frame without reencoding */
  501. av_packet_rescale_ts(&packet,
  502. ifmt_ctx->streams[stream_index]->time_base,
  503. ofmt_ctx->streams[stream_index]->time_base);
  504. ret = av_interleaved_write_frame(ofmt_ctx, &packet);
  505. if (ret < 0)
  506. goto end;
  507. }
  508. av_packet_unref(&packet);
  509. }
  510. /* flush filters and encoders */
  511. for (i = 0; i < ifmt_ctx->nb_streams; i++) {
  512. /* flush filter */
  513. if (!filter_ctx[i].filter_graph)
  514. continue;
  515. ret = filter_encode_write_frame(NULL, i);
  516. if (ret < 0) {
  517. av_log(NULL, AV_LOG_ERROR, "Flushing filter failed\n");
  518. goto end;
  519. }
  520. /* flush encoder */
  521. ret = flush_encoder(i);
  522. if (ret < 0) {
  523. av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n");
  524. goto end;
  525. }
  526. }
  527. av_write_trailer(ofmt_ctx);
  528. end:
  529. av_packet_unref(&packet);
  530. av_frame_free(&frame);
  531. for (i = 0; i < ifmt_ctx->nb_streams; i++) {
  532. avcodec_free_context(&stream_ctx[i].dec_ctx);
  533. if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && stream_ctx[i].enc_ctx)
  534. avcodec_free_context(&stream_ctx[i].enc_ctx);
  535. if (filter_ctx && filter_ctx[i].filter_graph)
  536. avfilter_graph_free(&filter_ctx[i].filter_graph);
  537. }
  538. av_free(filter_ctx);
  539. av_free(stream_ctx);
  540. avformat_close_input(&ifmt_ctx);
  541. if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
  542. avio_closep(&ofmt_ctx->pb);
  543. avformat_free_context(ofmt_ctx);
  544. if (ret < 0)
  545. av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret));
  546. return ret ? 1 : 0;
  547. }