FFmpeg 8.0.1
Loading...
Searching...
No Matches
transcode.c
Go to the documentation of this file.
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/**
26 * @file demuxing, decoding, filtering, encoding and muxing API usage example
27 * @example transcode.c
28 *
29 * Convert input to output file, applying some hard-coded filter-graph on both
30 * audio and video streams.
31 */
32
33#include <libavcodec/avcodec.h>
38#include <libavutil/mem.h>
39#include <libavutil/opt.h>
40#include <libavutil/pixdesc.h>
41
53
61
62static int open_input_file(const char *filename)
63{
64 int ret;
65 unsigned int i;
66
67 ifmt_ctx = NULL;
68 if ((ret = avformat_open_input(&ifmt_ctx, filename, NULL, NULL)) < 0) {
69 av_log(NULL, AV_LOG_ERROR, "Cannot open input file\n");
70 return ret;
71 }
72
73 if ((ret = avformat_find_stream_info(ifmt_ctx, NULL)) < 0) {
74 av_log(NULL, AV_LOG_ERROR, "Cannot find stream information\n");
75 return ret;
76 }
77
78 stream_ctx = av_calloc(ifmt_ctx->nb_streams, sizeof(*stream_ctx));
79 if (!stream_ctx)
80 return AVERROR(ENOMEM);
81
82 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
83 AVStream *stream = ifmt_ctx->streams[i];
84 const AVCodec *dec = avcodec_find_decoder(stream->codecpar->codec_id);
85 AVCodecContext *codec_ctx;
86 if (!dec) {
87 av_log(NULL, AV_LOG_ERROR, "Failed to find decoder for stream #%u\n", i);
89 }
90 codec_ctx = avcodec_alloc_context3(dec);
91 if (!codec_ctx) {
92 av_log(NULL, AV_LOG_ERROR, "Failed to allocate the decoder context for stream #%u\n", i);
93 return AVERROR(ENOMEM);
94 }
95 ret = avcodec_parameters_to_context(codec_ctx, stream->codecpar);
96 if (ret < 0) {
97 av_log(NULL, AV_LOG_ERROR, "Failed to copy decoder parameters to input decoder context "
98 "for stream #%u\n", i);
99 return ret;
100 }
101
102 /* Inform the decoder about the timebase for the packet timestamps.
103 * This is highly recommended, but not mandatory. */
104 codec_ctx->pkt_timebase = stream->time_base;
105
106 /* Reencode video & audio and remux subtitles etc. */
107 if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
108 || codec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
109 if (codec_ctx->codec_type == AVMEDIA_TYPE_VIDEO)
110 codec_ctx->framerate = av_guess_frame_rate(ifmt_ctx, stream, NULL);
111 /* Open decoder */
112 ret = avcodec_open2(codec_ctx, dec, NULL);
113 if (ret < 0) {
114 av_log(NULL, AV_LOG_ERROR, "Failed to open decoder for stream #%u\n", i);
115 return ret;
116 }
117 }
118 stream_ctx[i].dec_ctx = codec_ctx;
119
120 stream_ctx[i].dec_frame = av_frame_alloc();
121 if (!stream_ctx[i].dec_frame)
122 return AVERROR(ENOMEM);
123 }
124
125 av_dump_format(ifmt_ctx, 0, filename, 0);
126 return 0;
127}
128
129static int open_output_file(const char *filename)
130{
131 AVStream *out_stream;
132 AVStream *in_stream;
133 AVCodecContext *dec_ctx, *enc_ctx;
134 const AVCodec *encoder;
135 int ret;
136 unsigned int i;
137
138 ofmt_ctx = NULL;
139 avformat_alloc_output_context2(&ofmt_ctx, NULL, NULL, filename);
140 if (!ofmt_ctx) {
141 av_log(NULL, AV_LOG_ERROR, "Could not create output context\n");
142 return AVERROR_UNKNOWN;
143 }
144
145
146 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
147 out_stream = avformat_new_stream(ofmt_ctx, NULL);
148 if (!out_stream) {
149 av_log(NULL, AV_LOG_ERROR, "Failed allocating output stream\n");
150 return AVERROR_UNKNOWN;
151 }
152
153 in_stream = ifmt_ctx->streams[i];
154 dec_ctx = stream_ctx[i].dec_ctx;
155
156 if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO
157 || dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
158 /* in this example, we choose transcoding to same codec */
159 encoder = avcodec_find_encoder(dec_ctx->codec_id);
160 if (!encoder) {
161 av_log(NULL, AV_LOG_FATAL, "Necessary encoder not found\n");
162 return AVERROR_INVALIDDATA;
163 }
164 enc_ctx = avcodec_alloc_context3(encoder);
165 if (!enc_ctx) {
166 av_log(NULL, AV_LOG_FATAL, "Failed to allocate the encoder context\n");
167 return AVERROR(ENOMEM);
168 }
169
170 /* In this example, we transcode to same properties (picture size,
171 * sample rate etc.). These properties can be changed for output
172 * streams easily using filters */
173 if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
174 const enum AVPixelFormat *pix_fmts = NULL;
175
176 enc_ctx->height = dec_ctx->height;
177 enc_ctx->width = dec_ctx->width;
178 enc_ctx->sample_aspect_ratio = dec_ctx->sample_aspect_ratio;
179
182 (const void**)&pix_fmts, NULL);
183
184 /* take first format from list of supported formats */
185 enc_ctx->pix_fmt = (ret >= 0 && pix_fmts) ?
186 pix_fmts[0] : dec_ctx->pix_fmt;
187
188 /* video time_base can be set to whatever is handy and supported by encoder */
189 enc_ctx->time_base = av_inv_q(dec_ctx->framerate);
190 } else {
191 const enum AVSampleFormat *sample_fmts = NULL;
192
193 enc_ctx->sample_rate = dec_ctx->sample_rate;
194 ret = av_channel_layout_copy(&enc_ctx->ch_layout, &dec_ctx->ch_layout);
195 if (ret < 0)
196 return ret;
197
200 (const void**)&sample_fmts, NULL);
201
202 /* take first format from list of supported formats */
203 enc_ctx->sample_fmt = (ret >= 0 && sample_fmts) ?
204 sample_fmts[0] : dec_ctx->sample_fmt;
205
206 enc_ctx->time_base = (AVRational){1, enc_ctx->sample_rate};
207 }
208
209 if (ofmt_ctx->oformat->flags & AVFMT_GLOBALHEADER)
211
212 /* Third parameter can be used to pass settings to encoder */
213 ret = avcodec_open2(enc_ctx, encoder, NULL);
214 if (ret < 0) {
215 av_log(NULL, AV_LOG_ERROR, "Cannot open %s encoder for stream #%u\n", encoder->name, i);
216 return ret;
217 }
218 ret = avcodec_parameters_from_context(out_stream->codecpar, enc_ctx);
219 if (ret < 0) {
220 av_log(NULL, AV_LOG_ERROR, "Failed to copy encoder parameters to output stream #%u\n", i);
221 return ret;
222 }
223
224 out_stream->time_base = enc_ctx->time_base;
225 stream_ctx[i].enc_ctx = enc_ctx;
226 } else if (dec_ctx->codec_type == AVMEDIA_TYPE_UNKNOWN) {
227 av_log(NULL, AV_LOG_FATAL, "Elementary stream #%d is of unknown type, cannot proceed\n", i);
228 return AVERROR_INVALIDDATA;
229 } else {
230 /* if this stream must be remuxed */
231 ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar);
232 if (ret < 0) {
233 av_log(NULL, AV_LOG_ERROR, "Copying parameters for stream #%u failed\n", i);
234 return ret;
235 }
236 out_stream->time_base = in_stream->time_base;
237 }
238
239 }
240 av_dump_format(ofmt_ctx, 0, filename, 1);
241
242 if (!(ofmt_ctx->oformat->flags & AVFMT_NOFILE)) {
243 ret = avio_open(&ofmt_ctx->pb, filename, AVIO_FLAG_WRITE);
244 if (ret < 0) {
245 av_log(NULL, AV_LOG_ERROR, "Could not open output file '%s'", filename);
246 return ret;
247 }
248 }
249
250 /* init muxer, write output file header */
251 ret = avformat_write_header(ofmt_ctx, NULL);
252 if (ret < 0) {
253 av_log(NULL, AV_LOG_ERROR, "Error occurred when opening output file\n");
254 return ret;
255 }
256
257 return 0;
258}
259
261 AVCodecContext *enc_ctx, const char *filter_spec)
262{
263 char args[512];
264 int ret = 0;
265 const AVFilter *buffersrc = NULL;
266 const AVFilter *buffersink = NULL;
272
273 if (!outputs || !inputs || !filter_graph) {
274 ret = AVERROR(ENOMEM);
275 goto end;
276 }
277
278 if (dec_ctx->codec_type == AVMEDIA_TYPE_VIDEO) {
279 buffersrc = avfilter_get_by_name("buffer");
280 buffersink = avfilter_get_by_name("buffersink");
281 if (!buffersrc || !buffersink) {
282 av_log(NULL, AV_LOG_ERROR, "filtering source or sink element not found\n");
283 ret = AVERROR_UNKNOWN;
284 goto end;
285 }
286
287 snprintf(args, sizeof(args),
288 "video_size=%dx%d:pix_fmt=%d:time_base=%d/%d:pixel_aspect=%d/%d",
289 dec_ctx->width, dec_ctx->height, dec_ctx->pix_fmt,
290 dec_ctx->pkt_timebase.num, dec_ctx->pkt_timebase.den,
291 dec_ctx->sample_aspect_ratio.num,
292 dec_ctx->sample_aspect_ratio.den);
293
294 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
295 args, NULL, filter_graph);
296 if (ret < 0) {
297 av_log(NULL, AV_LOG_ERROR, "Cannot create buffer source\n");
298 goto end;
299 }
300
302 if (!buffersink_ctx) {
303 av_log(NULL, AV_LOG_ERROR, "Cannot create buffer sink\n");
304 ret = AVERROR(ENOMEM);
305 goto end;
306 }
307
308 ret = av_opt_set_bin(buffersink_ctx, "pix_fmts",
309 (uint8_t*)&enc_ctx->pix_fmt, sizeof(enc_ctx->pix_fmt),
311 if (ret < 0) {
312 av_log(NULL, AV_LOG_ERROR, "Cannot set output pixel format\n");
313 goto end;
314 }
315
317 if (ret < 0) {
318 av_log(NULL, AV_LOG_ERROR, "Cannot initialize buffer sink\n");
319 goto end;
320 }
321 } else if (dec_ctx->codec_type == AVMEDIA_TYPE_AUDIO) {
322 char buf[64];
323 buffersrc = avfilter_get_by_name("abuffer");
324 buffersink = avfilter_get_by_name("abuffersink");
325 if (!buffersrc || !buffersink) {
326 av_log(NULL, AV_LOG_ERROR, "filtering source or sink element not found\n");
327 ret = AVERROR_UNKNOWN;
328 goto end;
329 }
330
331 if (dec_ctx->ch_layout.order == AV_CHANNEL_ORDER_UNSPEC)
332 av_channel_layout_default(&dec_ctx->ch_layout, dec_ctx->ch_layout.nb_channels);
333 av_channel_layout_describe(&dec_ctx->ch_layout, buf, sizeof(buf));
334 snprintf(args, sizeof(args),
335 "time_base=%d/%d:sample_rate=%d:sample_fmt=%s:channel_layout=%s",
336 dec_ctx->pkt_timebase.num, dec_ctx->pkt_timebase.den, dec_ctx->sample_rate,
337 av_get_sample_fmt_name(dec_ctx->sample_fmt),
338 buf);
339 ret = avfilter_graph_create_filter(&buffersrc_ctx, buffersrc, "in",
340 args, NULL, filter_graph);
341 if (ret < 0) {
342 av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer source\n");
343 goto end;
344 }
345
347 if (!buffersink_ctx) {
348 av_log(NULL, AV_LOG_ERROR, "Cannot create audio buffer sink\n");
349 ret = AVERROR(ENOMEM);
350 goto end;
351 }
352
353 ret = av_opt_set_bin(buffersink_ctx, "sample_fmts",
354 (uint8_t*)&enc_ctx->sample_fmt, sizeof(enc_ctx->sample_fmt),
356 if (ret < 0) {
357 av_log(NULL, AV_LOG_ERROR, "Cannot set output sample format\n");
358 goto end;
359 }
360
361 av_channel_layout_describe(&enc_ctx->ch_layout, buf, sizeof(buf));
362 ret = av_opt_set(buffersink_ctx, "ch_layouts",
364 if (ret < 0) {
365 av_log(NULL, AV_LOG_ERROR, "Cannot set output channel layout\n");
366 goto end;
367 }
368
369 ret = av_opt_set_bin(buffersink_ctx, "sample_rates",
370 (uint8_t*)&enc_ctx->sample_rate, sizeof(enc_ctx->sample_rate),
372 if (ret < 0) {
373 av_log(NULL, AV_LOG_ERROR, "Cannot set output sample rate\n");
374 goto end;
375 }
376
377 if (enc_ctx->frame_size > 0)
379
381 if (ret < 0) {
382 av_log(NULL, AV_LOG_ERROR, "Cannot initialize audio buffer sink\n");
383 goto end;
384 }
385 } else {
386 ret = AVERROR_UNKNOWN;
387 goto end;
388 }
389
390 /* Endpoints for the filter graph. */
391 outputs->name = av_strdup("in");
392 outputs->filter_ctx = buffersrc_ctx;
393 outputs->pad_idx = 0;
394 outputs->next = NULL;
395
396 inputs->name = av_strdup("out");
397 inputs->filter_ctx = buffersink_ctx;
398 inputs->pad_idx = 0;
399 inputs->next = NULL;
400
401 if (!outputs->name || !inputs->name) {
402 ret = AVERROR(ENOMEM);
403 goto end;
404 }
405
406 if ((ret = avfilter_graph_parse_ptr(filter_graph, filter_spec,
407 &inputs, &outputs, NULL)) < 0)
408 goto end;
409
410 if ((ret = avfilter_graph_config(filter_graph, NULL)) < 0)
411 goto end;
412
413 /* Fill FilteringContext */
417
418end:
419 avfilter_inout_free(&inputs);
420 avfilter_inout_free(&outputs);
421
422 return ret;
423}
424
425static int init_filters(void)
426{
427 const char *filter_spec;
428 unsigned int i;
429 int ret;
430 filter_ctx = av_malloc_array(ifmt_ctx->nb_streams, sizeof(*filter_ctx));
431 if (!filter_ctx)
432 return AVERROR(ENOMEM);
433
434 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
435 filter_ctx[i].buffersrc_ctx = NULL;
436 filter_ctx[i].buffersink_ctx = NULL;
437 filter_ctx[i].filter_graph = NULL;
438 if (!(ifmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO
439 || ifmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO))
440 continue;
441
442
443 if (ifmt_ctx->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)
444 filter_spec = "null"; /* passthrough (dummy) filter for video */
445 else
446 filter_spec = "anull"; /* passthrough (dummy) filter for audio */
448 stream_ctx[i].enc_ctx, filter_spec);
449 if (ret)
450 return ret;
451
452 filter_ctx[i].enc_pkt = av_packet_alloc();
453 if (!filter_ctx[i].enc_pkt)
454 return AVERROR(ENOMEM);
455
456 filter_ctx[i].filtered_frame = av_frame_alloc();
457 if (!filter_ctx[i].filtered_frame)
458 return AVERROR(ENOMEM);
459 }
460 return 0;
461}
462
463static int encode_write_frame(unsigned int stream_index, int flush)
464{
465 StreamContext *stream = &stream_ctx[stream_index];
466 FilteringContext *filter = &filter_ctx[stream_index];
467 AVFrame *filt_frame = flush ? NULL : filter->filtered_frame;
468 AVPacket *enc_pkt = filter->enc_pkt;
469 int ret;
470
471 av_log(NULL, AV_LOG_INFO, "Encoding frame\n");
472 /* encode filtered frame */
473 av_packet_unref(enc_pkt);
474
475 if (filt_frame && filt_frame->pts != AV_NOPTS_VALUE)
476 filt_frame->pts = av_rescale_q(filt_frame->pts, filt_frame->time_base,
477 stream->enc_ctx->time_base);
478
479 ret = avcodec_send_frame(stream->enc_ctx, filt_frame);
480
481 if (ret < 0)
482 return ret;
483
484 while (ret >= 0) {
485 ret = avcodec_receive_packet(stream->enc_ctx, enc_pkt);
486
487 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
488 return 0;
489
490 /* prepare packet for muxing */
491 enc_pkt->stream_index = stream_index;
492 av_packet_rescale_ts(enc_pkt,
493 stream->enc_ctx->time_base,
494 ofmt_ctx->streams[stream_index]->time_base);
495
496 av_log(NULL, AV_LOG_DEBUG, "Muxing frame\n");
497 /* mux encoded frame */
498 ret = av_interleaved_write_frame(ofmt_ctx, enc_pkt);
499 }
500
501 return ret;
502}
503
504static int filter_encode_write_frame(AVFrame *frame, unsigned int stream_index)
505{
506 FilteringContext *filter = &filter_ctx[stream_index];
507 int ret;
508
509 av_log(NULL, AV_LOG_INFO, "Pushing decoded frame to filters\n");
510 /* push the decoded frame into the filtergraph */
512 frame, 0);
513 if (ret < 0) {
514 av_log(NULL, AV_LOG_ERROR, "Error while feeding the filtergraph\n");
515 return ret;
516 }
517
518 /* pull filtered frames from the filtergraph */
519 while (1) {
520 av_log(NULL, AV_LOG_INFO, "Pulling filtered frame from filters\n");
522 filter->filtered_frame);
523 if (ret < 0) {
524 /* if no more frames for output - returns AVERROR(EAGAIN)
525 * if flushed and no more frames for output - returns AVERROR_EOF
526 * rewrite retcode to 0 to show it as normal procedure completion
527 */
528 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
529 ret = 0;
530 break;
531 }
532
535 ret = encode_write_frame(stream_index, 0);
537 if (ret < 0)
538 break;
539 }
540
541 return ret;
542}
543
544static int flush_encoder(unsigned int stream_index)
545{
546 if (!(stream_ctx[stream_index].enc_ctx->codec->capabilities &
548 return 0;
549
550 av_log(NULL, AV_LOG_INFO, "Flushing stream #%u encoder\n", stream_index);
551 return encode_write_frame(stream_index, 1);
552}
553
554int main(int argc, char **argv)
555{
556 int ret;
557 AVPacket *packet = NULL;
558 unsigned int stream_index;
559 unsigned int i;
560
561 if (argc != 3) {
562 av_log(NULL, AV_LOG_ERROR, "Usage: %s <input file> <output file>\n", argv[0]);
563 return 1;
564 }
565
566 if ((ret = open_input_file(argv[1])) < 0)
567 goto end;
568 if ((ret = open_output_file(argv[2])) < 0)
569 goto end;
570 if ((ret = init_filters()) < 0)
571 goto end;
572 if (!(packet = av_packet_alloc()))
573 goto end;
574
575 /* read all packets */
576 while (1) {
577 if ((ret = av_read_frame(ifmt_ctx, packet)) < 0)
578 break;
579 stream_index = packet->stream_index;
580 av_log(NULL, AV_LOG_DEBUG, "Demuxer gave frame of stream_index %u\n",
581 stream_index);
582
583 if (filter_ctx[stream_index].filter_graph) {
584 StreamContext *stream = &stream_ctx[stream_index];
585
586 av_log(NULL, AV_LOG_DEBUG, "Going to reencode&filter the frame\n");
587
588 ret = avcodec_send_packet(stream->dec_ctx, packet);
589 if (ret < 0) {
590 av_log(NULL, AV_LOG_ERROR, "Decoding failed\n");
591 break;
592 }
593
594 while (ret >= 0) {
595 ret = avcodec_receive_frame(stream->dec_ctx, stream->dec_frame);
596 if (ret == AVERROR_EOF || ret == AVERROR(EAGAIN))
597 break;
598 else if (ret < 0)
599 goto end;
600
601 stream->dec_frame->pts = stream->dec_frame->best_effort_timestamp;
602 ret = filter_encode_write_frame(stream->dec_frame, stream_index);
603 if (ret < 0)
604 goto end;
605 }
606 } else {
607 /* remux this frame without reencoding */
609 ifmt_ctx->streams[stream_index]->time_base,
610 ofmt_ctx->streams[stream_index]->time_base);
611
613 if (ret < 0)
614 goto end;
615 }
616 av_packet_unref(packet);
617 }
618
619 /* flush decoders, filters and encoders */
620 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
621 StreamContext *stream;
622
623 if (!filter_ctx[i].filter_graph)
624 continue;
625
626 stream = &stream_ctx[i];
627
628 av_log(NULL, AV_LOG_INFO, "Flushing stream %u decoder\n", i);
629
630 /* flush decoder */
631 ret = avcodec_send_packet(stream->dec_ctx, NULL);
632 if (ret < 0) {
633 av_log(NULL, AV_LOG_ERROR, "Flushing decoding failed\n");
634 goto end;
635 }
636
637 while (ret >= 0) {
638 ret = avcodec_receive_frame(stream->dec_ctx, stream->dec_frame);
639 if (ret == AVERROR_EOF)
640 break;
641 else if (ret < 0)
642 goto end;
643
644 stream->dec_frame->pts = stream->dec_frame->best_effort_timestamp;
645 ret = filter_encode_write_frame(stream->dec_frame, i);
646 if (ret < 0)
647 goto end;
648 }
649
650 /* flush filter */
651 ret = filter_encode_write_frame(NULL, i);
652 if (ret < 0) {
653 av_log(NULL, AV_LOG_ERROR, "Flushing filter failed\n");
654 goto end;
655 }
656
657 /* flush encoder */
658 ret = flush_encoder(i);
659 if (ret < 0) {
660 av_log(NULL, AV_LOG_ERROR, "Flushing encoder failed\n");
661 goto end;
662 }
663 }
664
666end:
667 av_packet_free(&packet);
668 for (i = 0; i < ifmt_ctx->nb_streams; i++) {
670 if (ofmt_ctx && ofmt_ctx->nb_streams > i && ofmt_ctx->streams[i] && stream_ctx[i].enc_ctx)
671 avcodec_free_context(&stream_ctx[i].enc_ctx);
674 av_packet_free(&filter_ctx[i].enc_pkt);
675 av_frame_free(&filter_ctx[i].filtered_frame);
676 }
677
678 av_frame_free(&stream_ctx[i].dec_frame);
679 }
683 if (ofmt_ctx && !(ofmt_ctx->oformat->flags & AVFMT_NOFILE))
684 avio_closep(&ofmt_ctx->pb);
686
687 if (ret < 0)
688 av_log(NULL, AV_LOG_ERROR, "Error occurred: %s\n", av_err2str(ret));
689
690 return ret ? 1 : 0;
691}
Libavcodec external API header.
Main libavformat public API header.
#define AVFMT_NOFILE
Demuxer will use avio_open, no opened file should be provided by the caller.
Definition avformat.h:468
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition avformat.h:477
int avformat_alloc_output_context2(AVFormatContext **ctx, const AVOutputFormat *oformat, const char *format_name, const char *filename)
Allocate an AVFormatContext for an output format.
int avio_open(AVIOContext **s, const char *url, int flags)
Create and initialize a AVIOContext for accessing the resource indicated by url.
#define AVIO_FLAG_WRITE
write-only
Definition avio.h:618
int avio_closep(AVIOContext **s)
Close the resource accessed by the AVIOContext *s, free it and set the pointer pointing to it to NULL...
int main(int argc, char *argv[])
memory buffer sink API for audio and video
Memory buffer source API.
Public libavutil channel layout APIs header.
AVFilterGraph * filter_graph
AVFilterContext * buffersink_ctx
AVFilterContext * buffersrc_ctx
static int open_input_file(const char *filename)
static AVCodecContext * dec_ctx
static AVFrame * frame
int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
Definition codec.h:76
int avcodec_parameters_from_context(struct AVCodecParameters *par, const AVCodecContext *codec)
Fill the parameters struct based on the values from the supplied codec context.
int avcodec_parameters_copy(AVCodecParameters *dst, const AVCodecParameters *src)
Copy the contents of src to dst.
const AVCodec * avcodec_find_decoder(enum AVCodecID id)
Find a registered decoder with a matching codec ID.
int avcodec_parameters_to_context(AVCodecContext *codec, const struct AVCodecParameters *par)
Fill the codec context based on the values from the supplied codec parameters.
const AVCodec * avcodec_find_encoder(enum AVCodecID id)
Find a registered encoder with a matching codec ID.
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
Definition avcodec.h:318
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer.
int avcodec_receive_frame(AVCodecContext *avctx, AVFrame *frame)
Return decoded output data from a decoder or encoder (when the AV_CODEC_FLAG_RECON_FRAME flag is used...
int avcodec_send_packet(AVCodecContext *avctx, const AVPacket *avpkt)
Supply raw packet data as input to a decoder.
int avcodec_receive_packet(AVCodecContext *avctx, AVPacket *avpkt)
Read encoded data from the encoder.
int avcodec_send_frame(AVCodecContext *avctx, const AVFrame *frame)
Supply a raw video or audio frame to the encoder.
int avcodec_get_supported_config(const AVCodecContext *avctx, const AVCodec *codec, enum AVCodecConfig config, unsigned flags, const void **out_configs, int *out_num_configs)
Retrieve a list of all supported values for a given configuration type.
@ AV_CODEC_CONFIG_PIX_FORMAT
AVPixelFormat, terminated by AV_PIX_FMT_NONE.
Definition avcodec.h:2524
@ AV_CODEC_CONFIG_SAMPLE_FORMAT
AVSampleFormat, terminated by AV_SAMPLE_FMT_NONE.
Definition avcodec.h:2527
void av_packet_free(AVPacket **pkt)
Free the packet, if the packet is reference counted, it will be unreferenced first.
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
AVPacket * av_packet_alloc(void)
Allocate an AVPacket and set its fields to default values.
void av_packet_rescale_ts(AVPacket *pkt, AVRational tb_src, AVRational tb_dst)
Convert valid timing fields (timestamps / durations) in a packet from one timebase to another.
AVStream * avformat_new_stream(AVFormatContext *s, const struct AVCodec *c)
Add a new stream to a media file.
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
int avformat_open_input(AVFormatContext **ps, const char *url, const AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
av_warn_unused_result int avformat_write_header(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and write the stream header to an output media file.
int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file ensuring correct interleaving.
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
AVRational av_guess_frame_rate(AVFormatContext *ctx, AVStream *stream, struct AVFrame *frame)
Guess the frame rate, based on both the container and codec information.
void av_dump_format(AVFormatContext *ic, int index, const char *url, int is_output)
Print detailed information about the input or output format, such as duration, bitrate,...
AVRational av_buffersink_get_time_base(const AVFilterContext *ctx)
void av_buffersink_set_frame_size(AVFilterContext *ctx, unsigned frame_size)
Set the frame size for an audio buffer sink.
int av_buffersink_get_frame(AVFilterContext *ctx, AVFrame *frame)
Get a frame with filtered data from sink and put it in frame.
av_warn_unused_result int av_buffersrc_add_frame_flags(AVFilterContext *buffer_src, AVFrame *frame, int flags)
Add a frame to the buffer source.
int avfilter_graph_config(AVFilterGraph *graphctx, void *log_ctx)
Check validity and configure all the links and formats in the graph.
const AVFilter * avfilter_get_by_name(const char *name)
Get a filter definition matching the given name.
void avfilter_inout_free(AVFilterInOut **inout)
Free the supplied list of AVFilterInOut and set *inout to NULL.
int avfilter_graph_parse_ptr(AVFilterGraph *graph, const char *filters, AVFilterInOut **inputs, AVFilterInOut **outputs, void *log_ctx)
Add a graph described by a string to a graph.
AVFilterContext * avfilter_graph_alloc_filter(AVFilterGraph *graph, const AVFilter *filter, const char *name)
Create a new filter instance in a filter graph.
void avfilter_graph_free(AVFilterGraph **graph)
Free a graph, destroy its links, and set *graph to NULL.
int avfilter_init_dict(AVFilterContext *ctx, AVDictionary **options)
Initialize a filter with the supplied dictionary of options.
int avfilter_graph_create_filter(AVFilterContext **filt_ctx, const AVFilter *filt, const char *name, const char *args, void *opaque, AVFilterGraph *graph_ctx)
A convenience wrapper that allocates and initializes a filter in a single step.
AVFilterInOut * avfilter_inout_alloc(void)
Allocate a single AVFilterInOut entry.
AVFilterGraph * avfilter_graph_alloc(void)
Allocate a filter graph.
void av_channel_layout_default(AVChannelLayout *ch_layout, int nb_channels)
Get the default channel layout for a given number of channels.
int av_channel_layout_describe(const AVChannelLayout *channel_layout, char *buf, size_t buf_size)
Get a human-readable string describing the channel layout properties.
int av_channel_layout_copy(AVChannelLayout *dst, const AVChannelLayout *src)
Make a copy of a channel layout.
@ AV_CHANNEL_ORDER_UNSPEC
Only the channel count is specified, without any further information about the channel order.
#define AVERROR_DECODER_NOT_FOUND
Decoder not found.
Definition error.h:54
#define AVERROR_UNKNOWN
Unknown error, typically from an external library.
Definition error.h:73
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition error.h:122
#define AVERROR(e)
Definition error.h:45
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition log.h:204
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
void av_log(void *avcl, int level, const char *fmt,...) av_printf_format(3
Send the specified message to the log if the level is less than or equal to the current av_log_level.
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition rational.h:159
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq) av_const
Rescale a 64-bit integer by 2 rational numbers.
void av_free(void *ptr)
Free a memory block which has been allocated with a function of av_malloc() or av_realloc() family.
char * av_strdup(const char *s) av_malloc_attrib
Duplicate a string.
void * av_calloc(size_t nmemb, size_t size) av_malloc_attrib
Allocate a memory block for an array with av_mallocz().
void * av_malloc_array(size_t nmemb, size_t size)
Allocate a memory block for an array with av_malloc().
@ AVMEDIA_TYPE_AUDIO
Definition avutil.h:201
@ AVMEDIA_TYPE_VIDEO
Definition avutil.h:200
@ AVMEDIA_TYPE_UNKNOWN
Usually treated as AVMEDIA_TYPE_DATA.
Definition avutil.h:199
@ AV_PICTURE_TYPE_NONE
Undefined.
Definition avutil.h:277
const char * av_get_sample_fmt_name(enum AVSampleFormat sample_fmt)
Return the name of sample_fmt, or NULL if sample_fmt is not recognized.
AVSampleFormat
Audio sample formats.
Definition samplefmt.h:55
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition avutil.h:247
#define AV_OPT_SEARCH_CHILDREN
Search in possible children of the given object first.
Definition opt.h:605
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
int av_opt_set_bin(void *obj, const char *name, const uint8_t *val, int size, int search_flags)
Memory handling functions.
AVOptions.
AVPixelFormat
Pixel format.
Definition pixfmt.h:71
main external API structure.
Definition avcodec.h:431
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition avcodec.h:631
int width
picture width / height.
Definition avcodec.h:592
AVChannelLayout ch_layout
Audio channel layout.
Definition avcodec.h:1039
enum AVSampleFormat sample_fmt
audio sample format
Definition avcodec.h:1031
AVRational pkt_timebase
Timebase in which pkt_dts/pts and AVPacket.dts/pts are expressed.
Definition avcodec.h:542
enum AVMediaType codec_type
Definition avcodec.h:439
AVRational framerate
Definition avcodec.h:551
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
Definition avcodec.h:616
int sample_rate
samples per second
Definition avcodec.h:1024
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avcodec.h:535
int flags
AV_CODEC_FLAG_*.
Definition avcodec.h:488
int frame_size
Number of samples per channel in an audio frame.
Definition avcodec.h:1051
enum AVCodecID codec_id
Specific type of the encoded data (the codec used).
Definition codec_par.h:55
AVCodec.
Definition codec.h:172
const char * name
Name of the codec implementation.
Definition codec.h:179
An instance of a filter.
Definition avfilter.h:269
A linked-list of the inputs/outputs of the filter chain.
Definition avfilter.h:739
AVFilterContext * filter_ctx
filter context associated to this input/output
Definition avfilter.h:744
int pad_idx
index of the filt_ctx pad to use for linking
Definition avfilter.h:747
char * name
unique name for this input/output in the list
Definition avfilter.h:741
struct AVFilterInOut * next
next input/input in the list, NULL if this is the last
Definition avfilter.h:750
Filter definition.
Definition avfilter.h:211
Format I/O context.
Definition avformat.h:1264
This structure describes decoded (raw) audio or video data.
Definition frame.h:421
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition frame.h:523
int64_t best_effort_timestamp
frame timestamp estimated using various heuristics, in stream time base
Definition frame.h:692
AVRational time_base
Time base for the timestamps in this frame.
Definition frame.h:538
enum AVPictureType pict_type
Picture type of the frame.
Definition frame.h:513
This structure stores compressed data.
Definition packet.h:529
int stream_index
Definition packet.h:554
Rational number (pair of numerator and denominator).
Definition rational.h:58
Stream structure.
Definition avformat.h:744
AVCodecParameters * codecpar
Codec parameters associated with this stream.
Definition avformat.h:767
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition avformat.h:783
AVPacket * enc_pkt
Definition transcode.c:49
AVFilterContext * buffersrc_ctx
Definition transcode.c:46
AVFilterContext * buffersink_ctx
Definition transcode.c:45
AVFilterGraph * filter_graph
Definition transcode.c:47
AVFrame * filtered_frame
Definition transcode.c:50
AVFrame * dec_frame
Definition transcode.c:58
AVCodecContext * dec_ctx
Definition transcode.c:55
AVCodecContext * enc_ctx
Definition transcode.c:56
static int init_filters(void)
Definition transcode.c:425
static StreamContext * stream_ctx
Definition transcode.c:60
static int encode_write_frame(unsigned int stream_index, int flush)
Definition transcode.c:463
static AVFormatContext * ifmt_ctx
Definition transcode.c:42
static int filter_encode_write_frame(AVFrame *frame, unsigned int stream_index)
Definition transcode.c:504
static int init_filter(FilteringContext *fctx, AVCodecContext *dec_ctx, AVCodecContext *enc_ctx, const char *filter_spec)
Definition transcode.c:260
static FilteringContext * filter_ctx
Definition transcode.c:52
static AVFormatContext * ofmt_ctx
Definition transcode.c:43
static int flush_encoder(unsigned int stream_index)
Definition transcode.c:544
static int open_output_file(const char *filename, AVCodecContext *input_codec_context, AVFormatContext **output_format_context, AVCodecContext **output_codec_context)
Open an output file and the required encoder.