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