]> git.sesse.net Git - ffmpeg/blob - doc/examples/transcode_aac.c
Merge commit '89de5157b1cbe7807d3ec1d51bd56a75e98c002e'
[ffmpeg] / doc / examples / transcode_aac.c
1 /*
2  * This file is part of FFmpeg.
3  *
4  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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 simple audio converter
21  * Convert an input audio file to AAC in an MP4 container using FFmpeg.
22  * @author Andreas Unterweger (dustsigns@gmail.com)
23  */
24
25 #include <stdio.h>
26
27 #include "libavformat/avformat.h"
28 #include "libavformat/avio.h"
29
30 #include "libavcodec/avcodec.h"
31
32 #include "libavutil/audio_fifo.h"
33 #include "libavutil/avassert.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/frame.h"
36 #include "libavutil/opt.h"
37
38 #include "libswresample/swresample.h"
39
40 /** The output bit rate in kbit/s */
41 #define OUTPUT_BIT_RATE 48000
42 /** The number of output channels */
43 #define OUTPUT_CHANNELS 2
44 /** The audio sample output format */
45 #define OUTPUT_SAMPLE_FORMAT AV_SAMPLE_FMT_S16
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 easiert 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     = AV_SAMPLE_FMT_S16;
180     (*output_codec_context)->bit_rate       = OUTPUT_BIT_RATE;
181
182     /**
183      * Some container formats (like MP4) require global headers to be present
184      * Mark the encoder so that it behaves accordingly.
185      */
186     if ((*output_format_context)->oformat->flags & AVFMT_GLOBALHEADER)
187         (*output_codec_context)->flags |= CODEC_FLAG_GLOBAL_HEADER;
188
189     /** Open the encoder for the audio stream to use it later. */
190     if ((error = avcodec_open2(*output_codec_context, output_codec, NULL)) < 0) {
191         fprintf(stderr, "Could not open output codec (error '%s')\n",
192                 get_error_text(error));
193         goto cleanup;
194     }
195
196     return 0;
197
198 cleanup:
199     avio_close((*output_format_context)->pb);
200     avformat_free_context(*output_format_context);
201     *output_format_context = NULL;
202     return error < 0 ? error : AVERROR_EXIT;
203 }
204
205 /** Initialize one data packet for reading or writing. */
206 static void init_packet(AVPacket *packet)
207 {
208     av_init_packet(packet);
209     /** Set the packet data and size so that it is recognized as being empty. */
210     packet->data = NULL;
211     packet->size = 0;
212 }
213
214 /** Initialize one audio frame for reading from the input file */
215 static int init_input_frame(AVFrame **frame)
216 {
217     if (!(*frame = av_frame_alloc())) {
218         fprintf(stderr, "Could not allocate input frame\n");
219         return AVERROR(ENOMEM);
220     }
221     return 0;
222 }
223
224 /**
225  * Initialize the audio resampler based on the input and output codec settings.
226  * If the input and output sample formats differ, a conversion is required
227  * libswresample takes care of this, but requires initialization.
228  */
229 static int init_resampler(AVCodecContext *input_codec_context,
230                           AVCodecContext *output_codec_context,
231                           SwrContext **resample_context)
232 {
233         int error;
234
235         /**
236          * Create a resampler context for the conversion.
237          * Set the conversion parameters.
238          * Default channel layouts based on the number of channels
239          * are assumed for simplicity (they are sometimes not detected
240          * properly by the demuxer and/or decoder).
241          */
242         *resample_context = swr_alloc_set_opts(NULL,
243                                               av_get_default_channel_layout(output_codec_context->channels),
244                                               output_codec_context->sample_fmt,
245                                               output_codec_context->sample_rate,
246                                               av_get_default_channel_layout(input_codec_context->channels),
247                                               input_codec_context->sample_fmt,
248                                               input_codec_context->sample_rate,
249                                               0, NULL);
250         if (!*resample_context) {
251             fprintf(stderr, "Could not allocate resample context\n");
252             return AVERROR(ENOMEM);
253         }
254         /**
255         * Perform a sanity check so that the number of converted samples is
256         * not greater than the number of samples to be converted.
257         * If the sample rates differ, this case has to be handled differently
258         */
259         av_assert0(output_codec_context->sample_rate == input_codec_context->sample_rate);
260
261         /** Open the resampler with the specified parameters. */
262         if ((error = swr_init(*resample_context)) < 0) {
263             fprintf(stderr, "Could not open resample context\n");
264             swr_free(resample_context);
265             return error;
266         }
267     return 0;
268 }
269
270 /** Initialize a FIFO buffer for the audio samples to be encoded. */
271 static int init_fifo(AVAudioFifo **fifo)
272 {
273     /** Create the FIFO buffer based on the specified output sample format. */
274     if (!(*fifo = av_audio_fifo_alloc(OUTPUT_SAMPLE_FORMAT, OUTPUT_CHANNELS, 1))) {
275         fprintf(stderr, "Could not allocate FIFO\n");
276         return AVERROR(ENOMEM);
277     }
278     return 0;
279 }
280
281 /** Write the header of the output file container. */
282 static int write_output_file_header(AVFormatContext *output_format_context)
283 {
284     int error;
285     if ((error = avformat_write_header(output_format_context, NULL)) < 0) {
286         fprintf(stderr, "Could not write output file header (error '%s')\n",
287                 get_error_text(error));
288         return error;
289     }
290     return 0;
291 }
292
293 /** Decode one audio frame from the input file. */
294 static int decode_audio_frame(AVFrame *frame,
295                               AVFormatContext *input_format_context,
296                               AVCodecContext *input_codec_context,
297                               int *data_present, int *finished)
298 {
299     /** Packet used for temporary storage. */
300     AVPacket input_packet;
301     int error;
302     init_packet(&input_packet);
303
304     /** Read one audio frame from the input file into a temporary packet. */
305     if ((error = av_read_frame(input_format_context, &input_packet)) < 0) {
306         /** If we are the the end of the file, flush the decoder below. */
307         if (error == AVERROR_EOF)
308             *finished = 1;
309         else {
310             fprintf(stderr, "Could not read frame (error '%s')\n",
311                     get_error_text(error));
312             return error;
313         }
314     }
315
316     /**
317      * Decode the audio frame stored in the temporary packet.
318      * The input audio stream decoder is used to do this.
319      * If we are at the end of the file, pass an empty packet to the decoder
320      * to flush it.
321      */
322     if ((error = avcodec_decode_audio4(input_codec_context, frame,
323                                        data_present, &input_packet)) < 0) {
324         fprintf(stderr, "Could not decode frame (error '%s')\n",
325                 get_error_text(error));
326         av_free_packet(&input_packet);
327         return error;
328     }
329
330     /**
331      * If the decoder has not been flushed completely, we are not finished,
332      * so that this function has to be called again.
333      */
334     if (*finished && *data_present)
335         *finished = 0;
336     av_free_packet(&input_packet);
337     return 0;
338 }
339
340 /**
341  * Initialize a temporary storage for the specified number of audio samples.
342  * The conversion requires temporary storage due to the different format.
343  * The number of audio samples to be allocated is specified in frame_size.
344  */
345 static int init_converted_samples(uint8_t ***converted_input_samples,
346                                   AVCodecContext *output_codec_context,
347                                   int frame_size)
348 {
349     int error;
350
351     /**
352      * Allocate as many pointers as there are audio channels.
353      * Each pointer will later point to the audio samples of the corresponding
354      * channels (although it may be NULL for interleaved formats).
355      */
356     if (!(*converted_input_samples = calloc(output_codec_context->channels,
357                                             sizeof(**converted_input_samples)))) {
358         fprintf(stderr, "Could not allocate converted input sample pointers\n");
359         return AVERROR(ENOMEM);
360     }
361
362     /**
363      * Allocate memory for the samples of all channels in one consecutive
364      * block for convenience.
365      */
366     if ((error = av_samples_alloc(*converted_input_samples, NULL,
367                                   output_codec_context->channels,
368                                   frame_size,
369                                   output_codec_context->sample_fmt, 0)) < 0) {
370         fprintf(stderr,
371                 "Could not allocate converted input samples (error '%s')\n",
372                 get_error_text(error));
373         av_freep(&(*converted_input_samples)[0]);
374         free(*converted_input_samples);
375         return error;
376     }
377     return 0;
378 }
379
380 /**
381  * Convert the input audio samples into the output sample format.
382  * The conversion happens on a per-frame basis, the size of which is specified
383  * by frame_size.
384  */
385 static int convert_samples(const uint8_t **input_data,
386                            uint8_t **converted_data, const int frame_size,
387                            SwrContext *resample_context)
388 {
389     int error;
390
391     /** Convert the samples using the resampler. */
392     if ((error = swr_convert(resample_context,
393                              converted_data, frame_size,
394                              input_data    , frame_size)) < 0) {
395         fprintf(stderr, "Could not convert input samples (error '%s')\n",
396                 get_error_text(error));
397         return error;
398     }
399
400     return 0;
401 }
402
403 /** Add converted input audio samples to the FIFO buffer for later processing. */
404 static int add_samples_to_fifo(AVAudioFifo *fifo,
405                                uint8_t **converted_input_samples,
406                                const int frame_size)
407 {
408     int error;
409
410     /**
411      * Make the FIFO as large as it needs to be to hold both,
412      * the old and the new samples.
413      */
414     if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
415         fprintf(stderr, "Could not reallocate FIFO\n");
416         return error;
417     }
418
419     /** Store the new samples in the FIFO buffer. */
420     if (av_audio_fifo_write(fifo, (void **)converted_input_samples,
421                             frame_size) < frame_size) {
422         fprintf(stderr, "Could not write data to FIFO\n");
423         return AVERROR_EXIT;
424     }
425     return 0;
426 }
427
428 /**
429  * Read one audio frame from the input file, decodes, converts and stores
430  * it in the FIFO buffer.
431  */
432 static int read_decode_convert_and_store(AVAudioFifo *fifo,
433                                          AVFormatContext *input_format_context,
434                                          AVCodecContext *input_codec_context,
435                                          AVCodecContext *output_codec_context,
436                                          SwrContext *resampler_context,
437                                          int *finished)
438 {
439     /** Temporary storage of the input samples of the frame read from the file. */
440     AVFrame *input_frame = NULL;
441     /** Temporary storage for the converted input samples. */
442     uint8_t **converted_input_samples = NULL;
443     int data_present;
444     int ret = AVERROR_EXIT;
445
446     /** Initialize temporary storage for one input frame. */
447     if (init_input_frame(&input_frame))
448         goto cleanup;
449     /** Decode one frame worth of audio samples. */
450     if (decode_audio_frame(input_frame, input_format_context,
451                            input_codec_context, &data_present, finished))
452         goto cleanup;
453     /**
454      * If we are at the end of the file and there are no more samples
455      * in the decoder which are delayed, we are actually finished.
456      * This must not be treated as an error.
457      */
458     if (*finished && !data_present) {
459         ret = 0;
460         goto cleanup;
461     }
462     /** If there is decoded data, convert and store it */
463     if (data_present) {
464         /** Initialize the temporary storage for the converted input samples. */
465         if (init_converted_samples(&converted_input_samples, output_codec_context,
466                                    input_frame->nb_samples))
467             goto cleanup;
468
469         /**
470          * Convert the input samples to the desired output sample format.
471          * This requires a temporary storage provided by converted_input_samples.
472          */
473         if (convert_samples((const uint8_t**)input_frame->extended_data, converted_input_samples,
474                             input_frame->nb_samples, resampler_context))
475             goto cleanup;
476
477         /** Add the converted input samples to the FIFO buffer for later processing. */
478         if (add_samples_to_fifo(fifo, converted_input_samples,
479                                 input_frame->nb_samples))
480             goto cleanup;
481         ret = 0;
482     }
483     ret = 0;
484
485 cleanup:
486     if (converted_input_samples) {
487         av_freep(&converted_input_samples[0]);
488         free(converted_input_samples);
489     }
490     av_frame_free(&input_frame);
491
492     return ret;
493 }
494
495 /**
496  * Initialize one input frame for writing to the output file.
497  * The frame will be exactly frame_size samples large.
498  */
499 static int init_output_frame(AVFrame **frame,
500                              AVCodecContext *output_codec_context,
501                              int frame_size)
502 {
503     int error;
504
505     /** Create a new frame to store the audio samples. */
506     if (!(*frame = av_frame_alloc())) {
507         fprintf(stderr, "Could not allocate output frame\n");
508         return AVERROR_EXIT;
509     }
510
511     /**
512      * Set the frame's parameters, especially its size and format.
513      * av_frame_get_buffer needs this to allocate memory for the
514      * audio samples of the frame.
515      * Default channel layouts based on the number of channels
516      * are assumed for simplicity.
517      */
518     (*frame)->nb_samples     = frame_size;
519     (*frame)->channel_layout = output_codec_context->channel_layout;
520     (*frame)->format         = output_codec_context->sample_fmt;
521     (*frame)->sample_rate    = output_codec_context->sample_rate;
522
523     /**
524      * Allocate the samples of the created frame. This call will make
525      * sure that the audio frame can hold as many samples as specified.
526      */
527     if ((error = av_frame_get_buffer(*frame, 0)) < 0) {
528         fprintf(stderr, "Could allocate output frame samples (error '%s')\n",
529                 get_error_text(error));
530         av_frame_free(frame);
531         return error;
532     }
533
534     return 0;
535 }
536
537 /** Encode one frame worth of audio to the output file. */
538 static int encode_audio_frame(AVFrame *frame,
539                               AVFormatContext *output_format_context,
540                               AVCodecContext *output_codec_context,
541                               int *data_present)
542 {
543     /** Packet used for temporary storage. */
544     AVPacket output_packet;
545     int error;
546     init_packet(&output_packet);
547
548     /**
549      * Encode the audio frame and store it in the temporary packet.
550      * The output audio stream encoder is used to do this.
551      */
552     if ((error = avcodec_encode_audio2(output_codec_context, &output_packet,
553                                        frame, data_present)) < 0) {
554         fprintf(stderr, "Could not encode frame (error '%s')\n",
555                 get_error_text(error));
556         av_free_packet(&output_packet);
557         return error;
558     }
559
560     /** Write one audio frame from the temporary packet to the output file. */
561     if (*data_present) {
562         if ((error = av_write_frame(output_format_context, &output_packet)) < 0) {
563             fprintf(stderr, "Could not write frame (error '%s')\n",
564                     get_error_text(error));
565             av_free_packet(&output_packet);
566             return error;
567         }
568
569         av_free_packet(&output_packet);
570     }
571
572     return 0;
573 }
574
575 /**
576  * Load one audio frame from the FIFO buffer, encode and write it to the
577  * output file.
578  */
579 static int load_encode_and_write(AVAudioFifo *fifo,
580                                  AVFormatContext *output_format_context,
581                                  AVCodecContext *output_codec_context)
582 {
583     /** Temporary storage of the output samples of the frame written to the file. */
584     AVFrame *output_frame;
585     /**
586      * Use the maximum number of possible samples per frame.
587      * If there is less than the maximum possible frame size in the FIFO
588      * buffer use this number. Otherwise, use the maximum possible frame size
589      */
590     const int frame_size = FFMIN(av_audio_fifo_size(fifo),
591                                  output_codec_context->frame_size);
592     int data_written;
593
594     /** Initialize temporary storage for one output frame. */
595     if (init_output_frame(&output_frame, output_codec_context, frame_size))
596         return AVERROR_EXIT;
597
598     /**
599      * Read as many samples from the FIFO buffer as required to fill the frame.
600      * The samples are stored in the frame temporarily.
601      */
602     if (av_audio_fifo_read(fifo, (void **)output_frame->data, frame_size) < frame_size) {
603         fprintf(stderr, "Could not read data from FIFO\n");
604         av_frame_free(&output_frame);
605         return AVERROR_EXIT;
606     }
607
608     /** Encode one frame worth of audio samples. */
609     if (encode_audio_frame(output_frame, output_format_context,
610                            output_codec_context, &data_written)) {
611         av_frame_free(&output_frame);
612         return AVERROR_EXIT;
613     }
614     av_frame_free(&output_frame);
615     return 0;
616 }
617
618 /** Write the trailer of the output file container. */
619 static int write_output_file_trailer(AVFormatContext *output_format_context)
620 {
621     int error;
622     if ((error = av_write_trailer(output_format_context)) < 0) {
623         fprintf(stderr, "Could not write output file trailer (error '%s')\n",
624                 get_error_text(error));
625         return error;
626     }
627     return 0;
628 }
629
630 /** Convert an audio file to an AAC file in an MP4 container. */
631 int main(int argc, char **argv)
632 {
633     AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
634     AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
635     SwrContext *resample_context = NULL;
636     AVAudioFifo *fifo = NULL;
637     int ret = AVERROR_EXIT;
638
639     if (argc < 3) {
640         fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
641         exit(1);
642     }
643
644     /** Register all codecs and formats so that they can be used. */
645     av_register_all();
646     /** Open the input file for reading. */
647     if (open_input_file(argv[1], &input_format_context,
648                         &input_codec_context))
649         goto cleanup;
650     /** Open the output file for writing. */
651     if (open_output_file(argv[2], input_codec_context,
652                          &output_format_context, &output_codec_context))
653         goto cleanup;
654     /** Initialize the resampler to be able to convert audio sample formats. */
655     if (init_resampler(input_codec_context, output_codec_context,
656                        &resample_context))
657         goto cleanup;
658     /** Initialize the FIFO buffer to store audio samples to be encoded. */
659     if (init_fifo(&fifo))
660         goto cleanup;
661     /** Write the header of the output file container. */
662     if (write_output_file_header(output_format_context))
663         goto cleanup;
664
665     /**
666      * Loop as long as we have input samples to read or output samples
667      * to write; abort as soon as we have neither.
668      */
669     while (1) {
670         /** Use the encoder's desired frame size for processing. */
671         const int output_frame_size = output_codec_context->frame_size;
672         int finished                = 0;
673
674         /**
675          * Make sure that there is one frame worth of samples in the FIFO
676          * buffer so that the encoder can do its work.
677          * Since the decoder's and the encoder's frame size may differ, we
678          * need to FIFO buffer to store as many frames worth of input samples
679          * that they make up at least one frame worth of output samples.
680          */
681         while (av_audio_fifo_size(fifo) < output_frame_size) {
682             /**
683              * Decode one frame worth of audio samples, convert it to the
684              * output sample format and put it into the FIFO buffer.
685              */
686             if (read_decode_convert_and_store(fifo, input_format_context,
687                                               input_codec_context,
688                                               output_codec_context,
689                                               resample_context, &finished))
690                 goto cleanup;
691
692             /**
693              * If we are at the end of the input file, we continue
694              * encoding the remaining audio samples to the output file.
695              */
696             if (finished)
697                 break;
698         }
699
700         /**
701          * If we have enough samples for the encoder, we encode them.
702          * At the end of the file, we pass the remaining samples to
703          * the encoder.
704          */
705         while (av_audio_fifo_size(fifo) >= output_frame_size ||
706                (finished && av_audio_fifo_size(fifo) > 0))
707             /**
708              * Take one frame worth of audio samples from the FIFO buffer,
709              * encode it and write it to the output file.
710              */
711             if (load_encode_and_write(fifo, output_format_context,
712                                       output_codec_context))
713                 goto cleanup;
714
715         /**
716          * If we are at the end of the input file and have encoded
717          * all remaining samples, we can exit this loop and finish.
718          */
719         if (finished) {
720             int data_written;
721             /** Flush the encoder as it may have delayed frames. */
722             do {
723                 if (encode_audio_frame(NULL, output_format_context,
724                                        output_codec_context, &data_written))
725                     goto cleanup;
726             } while (data_written);
727             break;
728         }
729     }
730
731     /** Write the trailer of the output file container. */
732     if (write_output_file_trailer(output_format_context))
733         goto cleanup;
734     ret = 0;
735
736 cleanup:
737     if (fifo)
738         av_audio_fifo_free(fifo);
739     swr_free(&resample_context);
740     if (output_codec_context)
741         avcodec_close(output_codec_context);
742     if (output_format_context) {
743         avio_close(output_format_context->pb);
744         avformat_free_context(output_format_context);
745     }
746     if (input_codec_context)
747         avcodec_close(input_codec_context);
748     if (input_format_context)
749         avformat_close_input(&input_format_context);
750
751     return ret;
752 }