be86fe5d3ba6da853b802f28d48f1dfd2d83e40f
[libav.git] / doc / examples / transcode_aac.c
1 /*
2 * This file is part of Libav.
3 *
4 * Libav is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * Libav is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with Libav; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 */
18
19 /**
20 * @file
21 * simple audio converter
22 *
23 * @example transcode_aac.c
24 * Convert an input audio file to AAC in an MP4 container using Libav.
25 * @author Andreas Unterweger (dustsigns@gmail.com)
26 */
27
28 #include <stdio.h>
29
30 #include "libavformat/avformat.h"
31 #include "libavformat/avio.h"
32
33 #include "libavcodec/avcodec.h"
34
35 #include "libavutil/audio_fifo.h"
36 #include "libavutil/avstring.h"
37 #include "libavutil/frame.h"
38 #include "libavutil/opt.h"
39
40 #include "libavresample/avresample.h"
41
42 /** The output bit rate in kbit/s */
43 #define OUTPUT_BIT_RATE 96000
44 /** The number of output channels */
45 #define OUTPUT_CHANNELS 2
46
47 /**
48 * Convert an error code into a text message.
49 * @param error Error code to be converted
50 * @return Corresponding error text (not thread-safe)
51 */
52 static char *const get_error_text(const int error)
53 {
54 static char error_buffer[255];
55 av_strerror(error, error_buffer, sizeof(error_buffer));
56 return error_buffer;
57 }
58
59 /** Open an input file and the required decoder. */
60 static int open_input_file(const char *filename,
61 AVFormatContext **input_format_context,
62 AVCodecContext **input_codec_context)
63 {
64 AVCodecContext *avctx;
65 AVCodec *input_codec;
66 int error;
67
68 /** Open the input file to read from it. */
69 if ((error = avformat_open_input(input_format_context, filename, NULL,
70 NULL)) < 0) {
71 fprintf(stderr, "Could not open input file '%s' (error '%s')\n",
72 filename, get_error_text(error));
73 *input_format_context = NULL;
74 return error;
75 }
76
77 /** Get information on the input file (number of streams etc.). */
78 if ((error = avformat_find_stream_info(*input_format_context, NULL)) < 0) {
79 fprintf(stderr, "Could not open find stream info (error '%s')\n",
80 get_error_text(error));
81 avformat_close_input(input_format_context);
82 return error;
83 }
84
85 /** Make sure that there is only one stream in the input file. */
86 if ((*input_format_context)->nb_streams != 1) {
87 fprintf(stderr, "Expected one audio input stream, but found %d\n",
88 (*input_format_context)->nb_streams);
89 avformat_close_input(input_format_context);
90 return AVERROR_EXIT;
91 }
92
93 /** Find a decoder for the audio stream. */
94 if (!(input_codec = avcodec_find_decoder((*input_format_context)->streams[0]->codecpar->codec_id))) {
95 fprintf(stderr, "Could not find input codec\n");
96 avformat_close_input(input_format_context);
97 return AVERROR_EXIT;
98 }
99
100 /** allocate a new decoding context */
101 avctx = avcodec_alloc_context3(input_codec);
102 if (!avctx) {
103 fprintf(stderr, "Could not allocate a decoding context\n");
104 avformat_close_input(input_format_context);
105 return AVERROR(ENOMEM);
106 }
107
108 /** initialize the stream parameters with demuxer information */
109 error = avcodec_parameters_to_context(avctx, (*input_format_context)->streams[0]->codecpar);
110 if (error < 0) {
111 avformat_close_input(input_format_context);
112 avcodec_free_context(&avctx);
113 return error;
114 }
115
116 /** Open the decoder for the audio stream to use it later. */
117 if ((error = avcodec_open2(avctx, input_codec, NULL)) < 0) {
118 fprintf(stderr, "Could not open input codec (error '%s')\n",
119 get_error_text(error));
120 avcodec_free_context(&avctx);
121 avformat_close_input(input_format_context);
122 return error;
123 }
124
125 /** Save the decoder context for easier access later. */
126 *input_codec_context = avctx;
127
128 return 0;
129 }
130
131 /**
132 * Open an output file and the required encoder.
133 * Also set some basic encoder parameters.
134 * Some of these parameters are based on the input file's parameters.
135 */
136 static int open_output_file(const char *filename,
137 AVCodecContext *input_codec_context,
138 AVFormatContext **output_format_context,
139 AVCodecContext **output_codec_context)
140 {
141 AVCodecContext *avctx = NULL;
142 AVIOContext *output_io_context = NULL;
143 AVStream *stream = NULL;
144 AVCodec *output_codec = NULL;
145 int error;
146
147 /** Open the output file to write to it. */
148 if ((error = avio_open(&output_io_context, filename,
149 AVIO_FLAG_WRITE)) < 0) {
150 fprintf(stderr, "Could not open output file '%s' (error '%s')\n",
151 filename, get_error_text(error));
152 return error;
153 }
154
155 /** Create a new format context for the output container format. */
156 if (!(*output_format_context = avformat_alloc_context())) {
157 fprintf(stderr, "Could not allocate output format context\n");
158 return AVERROR(ENOMEM);
159 }
160
161 /** Associate the output file (pointer) with the container format context. */
162 (*output_format_context)->pb = output_io_context;
163
164 /** Guess the desired container format based on the file extension. */
165 if (!((*output_format_context)->oformat = av_guess_format(NULL, filename,
166 NULL))) {
167 fprintf(stderr, "Could not find output file format\n");
168 goto cleanup;
169 }
170
171 av_strlcpy((*output_format_context)->filename, filename,
172 sizeof((*output_format_context)->filename));
173
174 /** Find the encoder to be used by its name. */
175 if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_AAC))) {
176 fprintf(stderr, "Could not find an AAC encoder.\n");
177 goto cleanup;
178 }
179
180 /** Create a new audio stream in the output file container. */
181 if (!(stream = avformat_new_stream(*output_format_context, NULL))) {
182 fprintf(stderr, "Could not create new stream\n");
183 error = AVERROR(ENOMEM);
184 goto cleanup;
185 }
186
187 avctx = avcodec_alloc_context3(output_codec);
188 if (!avctx) {
189 fprintf(stderr, "Could not allocate an encoding context\n");
190 error = AVERROR(ENOMEM);
191 goto cleanup;
192 }
193
194 /**
195 * Set the basic encoder parameters.
196 * The input file's sample rate is used to avoid a sample rate conversion.
197 */
198 avctx->channels = OUTPUT_CHANNELS;
199 avctx->channel_layout = av_get_default_channel_layout(OUTPUT_CHANNELS);
200 avctx->sample_rate = input_codec_context->sample_rate;
201 avctx->sample_fmt = output_codec->sample_fmts[0];
202 avctx->bit_rate = OUTPUT_BIT_RATE;
203
204 /** Allow the use of the experimental AAC encoder */
205 avctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
206
207 /** Set the sample rate for the container. */
208 stream->time_base.den = input_codec_context->sample_rate;
209 stream->time_base.num = 1;
210
211 /**
212 * Some container formats (like MP4) require global headers to be present
213 * Mark the encoder so that it behaves accordingly.
214 */
215 if ((*output_format_context)->oformat->flags & AVFMT_GLOBALHEADER)
216 avctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
217
218 /** Open the encoder for the audio stream to use it later. */
219 if ((error = avcodec_open2(avctx, output_codec, NULL)) < 0) {
220 fprintf(stderr, "Could not open output codec (error '%s')\n",
221 get_error_text(error));
222 goto cleanup;
223 }
224
225 error = avcodec_parameters_from_context(stream->codecpar, avctx);
226 if (error < 0) {
227 fprintf(stderr, "Could not initialize stream parameters\n");
228 goto cleanup;
229 }
230
231 /** Save the encoder context for easier access later. */
232 *output_codec_context = avctx;
233
234 return 0;
235
236 cleanup:
237 avcodec_free_context(&avctx);
238 avio_close((*output_format_context)->pb);
239 avformat_free_context(*output_format_context);
240 *output_format_context = NULL;
241 return error < 0 ? error : AVERROR_EXIT;
242 }
243
244 /** Initialize one data packet for reading or writing. */
245 static void init_packet(AVPacket *packet)
246 {
247 av_init_packet(packet);
248 /** Set the packet data and size so that it is recognized as being empty. */
249 packet->data = NULL;
250 packet->size = 0;
251 }
252
253 /** Initialize one audio frame for reading from the input file */
254 static int init_input_frame(AVFrame **frame)
255 {
256 if (!(*frame = av_frame_alloc())) {
257 fprintf(stderr, "Could not allocate input frame\n");
258 return AVERROR(ENOMEM);
259 }
260 return 0;
261 }
262
263 /**
264 * Initialize the audio resampler based on the input and output codec settings.
265 * If the input and output sample formats differ, a conversion is required
266 * libavresample takes care of this, but requires initialization.
267 */
268 static int init_resampler(AVCodecContext *input_codec_context,
269 AVCodecContext *output_codec_context,
270 AVAudioResampleContext **resample_context)
271 {
272 /**
273 * Only initialize the resampler if it is necessary, i.e.,
274 * if and only if the sample formats differ.
275 */
276 if (input_codec_context->sample_fmt != output_codec_context->sample_fmt ||
277 input_codec_context->channels != output_codec_context->channels) {
278 int error;
279
280 /** Create a resampler context for the conversion. */
281 if (!(*resample_context = avresample_alloc_context())) {
282 fprintf(stderr, "Could not allocate resample context\n");
283 return AVERROR(ENOMEM);
284 }
285
286 /**
287 * Set the conversion parameters.
288 * Default channel layouts based on the number of channels
289 * are assumed for simplicity (they are sometimes not detected
290 * properly by the demuxer and/or decoder).
291 */
292 av_opt_set_int(*resample_context, "in_channel_layout",
293 av_get_default_channel_layout(input_codec_context->channels), 0);
294 av_opt_set_int(*resample_context, "out_channel_layout",
295 av_get_default_channel_layout(output_codec_context->channels), 0);
296 av_opt_set_int(*resample_context, "in_sample_rate",
297 input_codec_context->sample_rate, 0);
298 av_opt_set_int(*resample_context, "out_sample_rate",
299 output_codec_context->sample_rate, 0);
300 av_opt_set_int(*resample_context, "in_sample_fmt",
301 input_codec_context->sample_fmt, 0);
302 av_opt_set_int(*resample_context, "out_sample_fmt",
303 output_codec_context->sample_fmt, 0);
304
305 /** Open the resampler with the specified parameters. */
306 if ((error = avresample_open(*resample_context)) < 0) {
307 fprintf(stderr, "Could not open resample context\n");
308 avresample_free(resample_context);
309 return error;
310 }
311 }
312 return 0;
313 }
314
315 /** Initialize a FIFO buffer for the audio samples to be encoded. */
316 static int init_fifo(AVAudioFifo **fifo, AVCodecContext *output_codec_context)
317 {
318 /** Create the FIFO buffer based on the specified output sample format. */
319 if (!(*fifo = av_audio_fifo_alloc(output_codec_context->sample_fmt,
320 output_codec_context->channels, 1))) {
321 fprintf(stderr, "Could not allocate FIFO\n");
322 return AVERROR(ENOMEM);
323 }
324 return 0;
325 }
326
327 /** Write the header of the output file container. */
328 static int write_output_file_header(AVFormatContext *output_format_context)
329 {
330 int error;
331 if ((error = avformat_write_header(output_format_context, NULL)) < 0) {
332 fprintf(stderr, "Could not write output file header (error '%s')\n",
333 get_error_text(error));
334 return error;
335 }
336 return 0;
337 }
338
339 /** Decode one audio frame from the input file. */
340 static int decode_audio_frame(AVFrame *frame,
341 AVFormatContext *input_format_context,
342 AVCodecContext *input_codec_context,
343 int *data_present, int *finished)
344 {
345 /** Packet used for temporary storage. */
346 AVPacket input_packet;
347 int error;
348 init_packet(&input_packet);
349
350 /** Read one audio frame from the input file into a temporary packet. */
351 if ((error = av_read_frame(input_format_context, &input_packet)) < 0) {
352 /** If we are the the end of the file, flush the decoder below. */
353 if (error == AVERROR_EOF)
354 *finished = 1;
355 else {
356 fprintf(stderr, "Could not read frame (error '%s')\n",
357 get_error_text(error));
358 return error;
359 }
360 }
361
362 /**
363 * Decode the audio frame stored in the temporary packet.
364 * The input audio stream decoder is used to do this.
365 * If we are at the end of the file, pass an empty packet to the decoder
366 * to flush it.
367 */
368 if ((error = avcodec_decode_audio4(input_codec_context, frame,
369 data_present, &input_packet)) < 0) {
370 fprintf(stderr, "Could not decode frame (error '%s')\n",
371 get_error_text(error));
372 av_packet_unref(&input_packet);
373 return error;
374 }
375
376 /**
377 * If the decoder has not been flushed completely, we are not finished,
378 * so that this function has to be called again.
379 */
380 if (*finished && *data_present)
381 *finished = 0;
382 av_packet_unref(&input_packet);
383 return 0;
384 }
385
386 /**
387 * Initialize a temporary storage for the specified number of audio samples.
388 * The conversion requires temporary storage due to the different format.
389 * The number of audio samples to be allocated is specified in frame_size.
390 */
391 static int init_converted_samples(uint8_t ***converted_input_samples,
392 AVCodecContext *output_codec_context,
393 int frame_size)
394 {
395 int error;
396
397 /**
398 * Allocate as many pointers as there are audio channels.
399 * Each pointer will later point to the audio samples of the corresponding
400 * channels (although it may be NULL for interleaved formats).
401 */
402 if (!(*converted_input_samples = calloc(output_codec_context->channels,
403 sizeof(**converted_input_samples)))) {
404 fprintf(stderr, "Could not allocate converted input sample pointers\n");
405 return AVERROR(ENOMEM);
406 }
407
408 /**
409 * Allocate memory for the samples of all channels in one consecutive
410 * block for convenience.
411 */
412 if ((error = av_samples_alloc(*converted_input_samples, NULL,
413 output_codec_context->channels,
414 frame_size,
415 output_codec_context->sample_fmt, 0)) < 0) {
416 fprintf(stderr,
417 "Could not allocate converted input samples (error '%s')\n",
418 get_error_text(error));
419 av_freep(&(*converted_input_samples)[0]);
420 free(*converted_input_samples);
421 return error;
422 }
423 return 0;
424 }
425
426 /**
427 * Convert the input audio samples into the output sample format.
428 * The conversion happens on a per-frame basis, the size of which is specified
429 * by frame_size.
430 */
431 static int convert_samples(uint8_t **input_data,
432 uint8_t **converted_data, const int frame_size,
433 AVAudioResampleContext *resample_context)
434 {
435 int error;
436
437 /** Convert the samples using the resampler. */
438 if ((error = avresample_convert(resample_context, converted_data, 0,
439 frame_size, input_data, 0, frame_size)) < 0) {
440 fprintf(stderr, "Could not convert input samples (error '%s')\n",
441 get_error_text(error));
442 return error;
443 }
444
445 /**
446 * Perform a sanity check so that the number of converted samples is
447 * not greater than the number of samples to be converted.
448 * If the sample rates differ, this case has to be handled differently
449 */
450 if (avresample_available(resample_context)) {
451 fprintf(stderr, "Converted samples left over\n");
452 return AVERROR_EXIT;
453 }
454
455 return 0;
456 }
457
458 /** Add converted input audio samples to the FIFO buffer for later processing. */
459 static int add_samples_to_fifo(AVAudioFifo *fifo,
460 uint8_t **converted_input_samples,
461 const int frame_size)
462 {
463 int error;
464
465 /**
466 * Make the FIFO as large as it needs to be to hold both,
467 * the old and the new samples.
468 */
469 if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
470 fprintf(stderr, "Could not reallocate FIFO\n");
471 return error;
472 }
473
474 /** Store the new samples in the FIFO buffer. */
475 if (av_audio_fifo_write(fifo, (void **)converted_input_samples,
476 frame_size) < frame_size) {
477 fprintf(stderr, "Could not write data to FIFO\n");
478 return AVERROR_EXIT;
479 }
480 return 0;
481 }
482
483 /**
484 * Read one audio frame from the input file, decodes, converts and stores
485 * it in the FIFO buffer.
486 */
487 static int read_decode_convert_and_store(AVAudioFifo *fifo,
488 AVFormatContext *input_format_context,
489 AVCodecContext *input_codec_context,
490 AVCodecContext *output_codec_context,
491 AVAudioResampleContext *resampler_context,
492 int *finished)
493 {
494 /** Temporary storage of the input samples of the frame read from the file. */
495 AVFrame *input_frame = NULL;
496 /** Temporary storage for the converted input samples. */
497 uint8_t **converted_input_samples = NULL;
498 int data_present;
499 int ret = AVERROR_EXIT;
500
501 /** Initialize temporary storage for one input frame. */
502 if (init_input_frame(&input_frame))
503 goto cleanup;
504 /** Decode one frame worth of audio samples. */
505 if (decode_audio_frame(input_frame, input_format_context,
506 input_codec_context, &data_present, finished))
507 goto cleanup;
508 /**
509 * If we are at the end of the file and there are no more samples
510 * in the decoder which are delayed, we are actually finished.
511 * This must not be treated as an error.
512 */
513 if (*finished && !data_present) {
514 ret = 0;
515 goto cleanup;
516 }
517 /** If there is decoded data, convert and store it */
518 if (data_present) {
519 /** Initialize the temporary storage for the converted input samples. */
520 if (init_converted_samples(&converted_input_samples, output_codec_context,
521 input_frame->nb_samples))
522 goto cleanup;
523
524 /**
525 * Convert the input samples to the desired output sample format.
526 * This requires a temporary storage provided by converted_input_samples.
527 */
528 if (convert_samples(input_frame->extended_data, converted_input_samples,
529 input_frame->nb_samples, resampler_context))
530 goto cleanup;
531
532 /** Add the converted input samples to the FIFO buffer for later processing. */
533 if (add_samples_to_fifo(fifo, converted_input_samples,
534 input_frame->nb_samples))
535 goto cleanup;
536 ret = 0;
537 }
538 ret = 0;
539
540 cleanup:
541 if (converted_input_samples) {
542 av_freep(&converted_input_samples[0]);
543 free(converted_input_samples);
544 }
545 av_frame_free(&input_frame);
546
547 return ret;
548 }
549
550 /**
551 * Initialize one input frame for writing to the output file.
552 * The frame will be exactly frame_size samples large.
553 */
554 static int init_output_frame(AVFrame **frame,
555 AVCodecContext *output_codec_context,
556 int frame_size)
557 {
558 int error;
559
560 /** Create a new frame to store the audio samples. */
561 if (!(*frame = av_frame_alloc())) {
562 fprintf(stderr, "Could not allocate output frame\n");
563 return AVERROR_EXIT;
564 }
565
566 /**
567 * Set the frame's parameters, especially its size and format.
568 * av_frame_get_buffer needs this to allocate memory for the
569 * audio samples of the frame.
570 * Default channel layouts based on the number of channels
571 * are assumed for simplicity.
572 */
573 (*frame)->nb_samples = frame_size;
574 (*frame)->channel_layout = output_codec_context->channel_layout;
575 (*frame)->format = output_codec_context->sample_fmt;
576 (*frame)->sample_rate = output_codec_context->sample_rate;
577
578 /**
579 * Allocate the samples of the created frame. This call will make
580 * sure that the audio frame can hold as many samples as specified.
581 */
582 if ((error = av_frame_get_buffer(*frame, 0)) < 0) {
583 fprintf(stderr, "Could allocate output frame samples (error '%s')\n",
584 get_error_text(error));
585 av_frame_free(frame);
586 return error;
587 }
588
589 return 0;
590 }
591
592 /** Global timestamp for the audio frames */
593 static int64_t pts = 0;
594
595 /** Encode one frame worth of audio to the output file. */
596 static int encode_audio_frame(AVFrame *frame,
597 AVFormatContext *output_format_context,
598 AVCodecContext *output_codec_context,
599 int *data_present)
600 {
601 /** Packet used for temporary storage. */
602 AVPacket output_packet;
603 int error;
604 init_packet(&output_packet);
605
606 /** Set a timestamp based on the sample rate for the container. */
607 if (frame) {
608 frame->pts = pts;
609 pts += frame->nb_samples;
610 }
611
612 /**
613 * Encode the audio frame and store it in the temporary packet.
614 * The output audio stream encoder is used to do this.
615 */
616 if ((error = avcodec_encode_audio2(output_codec_context, &output_packet,
617 frame, data_present)) < 0) {
618 fprintf(stderr, "Could not encode frame (error '%s')\n",
619 get_error_text(error));
620 av_packet_unref(&output_packet);
621 return error;
622 }
623
624 /** Write one audio frame from the temporary packet to the output file. */
625 if (*data_present) {
626 if ((error = av_write_frame(output_format_context, &output_packet)) < 0) {
627 fprintf(stderr, "Could not write frame (error '%s')\n",
628 get_error_text(error));
629 av_packet_unref(&output_packet);
630 return error;
631 }
632
633 av_packet_unref(&output_packet);
634 }
635
636 return 0;
637 }
638
639 /**
640 * Load one audio frame from the FIFO buffer, encode and write it to the
641 * output file.
642 */
643 static int load_encode_and_write(AVAudioFifo *fifo,
644 AVFormatContext *output_format_context,
645 AVCodecContext *output_codec_context)
646 {
647 /** Temporary storage of the output samples of the frame written to the file. */
648 AVFrame *output_frame;
649 /**
650 * Use the maximum number of possible samples per frame.
651 * If there is less than the maximum possible frame size in the FIFO
652 * buffer use this number. Otherwise, use the maximum possible frame size
653 */
654 const int frame_size = FFMIN(av_audio_fifo_size(fifo),
655 output_codec_context->frame_size);
656 int data_written;
657
658 /** Initialize temporary storage for one output frame. */
659 if (init_output_frame(&output_frame, output_codec_context, frame_size))
660 return AVERROR_EXIT;
661
662 /**
663 * Read as many samples from the FIFO buffer as required to fill the frame.
664 * The samples are stored in the frame temporarily.
665 */
666 if (av_audio_fifo_read(fifo, (void **)output_frame->data, frame_size) < frame_size) {
667 fprintf(stderr, "Could not read data from FIFO\n");
668 av_frame_free(&output_frame);
669 return AVERROR_EXIT;
670 }
671
672 /** Encode one frame worth of audio samples. */
673 if (encode_audio_frame(output_frame, output_format_context,
674 output_codec_context, &data_written)) {
675 av_frame_free(&output_frame);
676 return AVERROR_EXIT;
677 }
678 av_frame_free(&output_frame);
679 return 0;
680 }
681
682 /** Write the trailer of the output file container. */
683 static int write_output_file_trailer(AVFormatContext *output_format_context)
684 {
685 int error;
686 if ((error = av_write_trailer(output_format_context)) < 0) {
687 fprintf(stderr, "Could not write output file trailer (error '%s')\n",
688 get_error_text(error));
689 return error;
690 }
691 return 0;
692 }
693
694 /** Convert an audio file to an AAC file in an MP4 container. */
695 int main(int argc, char **argv)
696 {
697 AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
698 AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
699 AVAudioResampleContext *resample_context = NULL;
700 AVAudioFifo *fifo = NULL;
701 int ret = AVERROR_EXIT;
702
703 if (argc < 3) {
704 fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
705 exit(1);
706 }
707
708 /** Register all codecs and formats so that they can be used. */
709 av_register_all();
710 /** Open the input file for reading. */
711 if (open_input_file(argv[1], &input_format_context,
712 &input_codec_context))
713 goto cleanup;
714 /** Open the output file for writing. */
715 if (open_output_file(argv[2], input_codec_context,
716 &output_format_context, &output_codec_context))
717 goto cleanup;
718 /** Initialize the resampler to be able to convert audio sample formats. */
719 if (init_resampler(input_codec_context, output_codec_context,
720 &resample_context))
721 goto cleanup;
722 /** Initialize the FIFO buffer to store audio samples to be encoded. */
723 if (init_fifo(&fifo, output_codec_context))
724 goto cleanup;
725 /** Write the header of the output file container. */
726 if (write_output_file_header(output_format_context))
727 goto cleanup;
728
729 /**
730 * Loop as long as we have input samples to read or output samples
731 * to write; abort as soon as we have neither.
732 */
733 while (1) {
734 /** Use the encoder's desired frame size for processing. */
735 const int output_frame_size = output_codec_context->frame_size;
736 int finished = 0;
737
738 /**
739 * Make sure that there is one frame worth of samples in the FIFO
740 * buffer so that the encoder can do its work.
741 * Since the decoder's and the encoder's frame size may differ, we
742 * need to FIFO buffer to store as many frames worth of input samples
743 * that they make up at least one frame worth of output samples.
744 */
745 while (av_audio_fifo_size(fifo) < output_frame_size) {
746 /**
747 * Decode one frame worth of audio samples, convert it to the
748 * output sample format and put it into the FIFO buffer.
749 */
750 if (read_decode_convert_and_store(fifo, input_format_context,
751 input_codec_context,
752 output_codec_context,
753 resample_context, &finished))
754 goto cleanup;
755
756 /**
757 * If we are at the end of the input file, we continue
758 * encoding the remaining audio samples to the output file.
759 */
760 if (finished)
761 break;
762 }
763
764 /**
765 * If we have enough samples for the encoder, we encode them.
766 * At the end of the file, we pass the remaining samples to
767 * the encoder.
768 */
769 while (av_audio_fifo_size(fifo) >= output_frame_size ||
770 (finished && av_audio_fifo_size(fifo) > 0))
771 /**
772 * Take one frame worth of audio samples from the FIFO buffer,
773 * encode it and write it to the output file.
774 */
775 if (load_encode_and_write(fifo, output_format_context,
776 output_codec_context))
777 goto cleanup;
778
779 /**
780 * If we are at the end of the input file and have encoded
781 * all remaining samples, we can exit this loop and finish.
782 */
783 if (finished) {
784 int data_written;
785 /** Flush the encoder as it may have delayed frames. */
786 do {
787 if (encode_audio_frame(NULL, output_format_context,
788 output_codec_context, &data_written))
789 goto cleanup;
790 } while (data_written);
791 break;
792 }
793 }
794
795 /** Write the trailer of the output file container. */
796 if (write_output_file_trailer(output_format_context))
797 goto cleanup;
798 ret = 0;
799
800 cleanup:
801 if (fifo)
802 av_audio_fifo_free(fifo);
803 if (resample_context) {
804 avresample_close(resample_context);
805 avresample_free(&resample_context);
806 }
807 if (output_codec_context)
808 avcodec_free_context(&output_codec_context);
809 if (output_format_context) {
810 avio_close(output_format_context->pb);
811 avformat_free_context(output_format_context);
812 }
813 if (input_codec_context)
814 avcodec_free_context(&input_codec_context);
815 if (input_format_context)
816 avformat_close_input(&input_format_context);
817
818 return ret;
819 }