transcoding.c 22 KB

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