2 * This file is part of FFmpeg.
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.
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.
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
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)
27 #include "libavformat/avformat.h"
28 #include "libavformat/avio.h"
30 #include "libavcodec/avcodec.h"
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"
38 #include "libswresample/swresample.h"
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
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)
52 static char *const get_error_text(const int error)
54 static char error_buffer[255];
55 av_strerror(error, error_buffer, sizeof(error_buffer));
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)
67 /** Open the input file to read from it. */
68 if ((error = avformat_open_input(input_format_context, filename, NULL,
70 fprintf(stderr, "Could not open input file '%s' (error '%s')\n",
71 filename, get_error_text(error));
72 *input_format_context = NULL;
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);
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);
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);
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);
108 /** Save the decoder context for easier access later. */
109 *input_codec_context = (*input_format_context)->streams[0]->codec;
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.
119 static int open_output_file(const char *filename,
120 AVCodecContext *input_codec_context,
121 AVFormatContext **output_format_context,
122 AVCodecContext **output_codec_context)
124 AVIOContext *output_io_context = NULL;
125 AVStream *stream = NULL;
126 AVCodec *output_codec = NULL;
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));
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);
143 /** Associate the output file (pointer) with the container format context. */
144 (*output_format_context)->pb = output_io_context;
146 /** Guess the desired container format based on the file extension. */
147 if (!((*output_format_context)->oformat = av_guess_format(NULL, filename,
149 fprintf(stderr, "Could not find output file format\n");
153 av_strlcpy((*output_format_context)->filename, filename,
154 sizeof((*output_format_context)->filename));
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");
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);
169 /** Save the encoder context for easiert access later. */
170 *output_codec_context = stream->codec;
173 * Set the basic encoder parameters.
174 * The input file's sample rate is used to avoid a sample rate conversion.
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;
183 * Some container formats (like MP4) require global headers to be present
184 * Mark the encoder so that it behaves accordingly.
186 if ((*output_format_context)->oformat->flags & AVFMT_GLOBALHEADER)
187 (*output_codec_context)->flags |= CODEC_FLAG_GLOBAL_HEADER;
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));
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;
205 /** Initialize one data packet for reading or writing. */
206 static void init_packet(AVPacket *packet)
208 av_init_packet(packet);
209 /** Set the packet data and size so that it is recognized as being empty. */
214 /** Initialize one audio frame for reading from the input file */
215 static int init_input_frame(AVFrame **frame)
217 if (!(*frame = av_frame_alloc())) {
218 fprintf(stderr, "Could not allocate input frame\n");
219 return AVERROR(ENOMEM);
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.
229 static int init_resampler(AVCodecContext *input_codec_context,
230 AVCodecContext *output_codec_context,
231 SwrContext **resample_context)
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).
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,
250 if (!*resample_context) {
251 fprintf(stderr, "Could not allocate resample context\n");
252 return AVERROR(ENOMEM);
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
259 av_assert0(output_codec_context->sample_rate == input_codec_context->sample_rate);
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);
270 /** Initialize a FIFO buffer for the audio samples to be encoded. */
271 static int init_fifo(AVAudioFifo **fifo)
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);
281 /** Write the header of the output file container. */
282 static int write_output_file_header(AVFormatContext *output_format_context)
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));
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)
299 /** Packet used for temporary storage. */
300 AVPacket input_packet;
302 init_packet(&input_packet);
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)
310 fprintf(stderr, "Could not read frame (error '%s')\n",
311 get_error_text(error));
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
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);
331 * If the decoder has not been flushed completely, we are not finished,
332 * so that this function has to be called again.
334 if (*finished && *data_present)
336 av_free_packet(&input_packet);
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.
345 static int init_converted_samples(uint8_t ***converted_input_samples,
346 AVCodecContext *output_codec_context,
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).
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);
363 * Allocate memory for the samples of all channels in one consecutive
364 * block for convenience.
366 if ((error = av_samples_alloc(*converted_input_samples, NULL,
367 output_codec_context->channels,
369 output_codec_context->sample_fmt, 0)) < 0) {
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);
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
385 static int convert_samples(const uint8_t **input_data,
386 uint8_t **converted_data, const int frame_size,
387 SwrContext *resample_context)
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));
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)
411 * Make the FIFO as large as it needs to be to hold both,
412 * the old and the new samples.
414 if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
415 fprintf(stderr, "Could not reallocate FIFO\n");
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");
429 * Read one audio frame from the input file, decodes, converts and stores
430 * it in the FIFO buffer.
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,
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;
444 int ret = AVERROR_EXIT;
446 /** Initialize temporary storage for one input frame. */
447 if (init_input_frame(&input_frame))
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))
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.
458 if (*finished && !data_present) {
462 /** If there is decoded data, convert and store it */
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))
470 * Convert the input samples to the desired output sample format.
471 * This requires a temporary storage provided by converted_input_samples.
473 if (convert_samples((const uint8_t**)input_frame->extended_data, converted_input_samples,
474 input_frame->nb_samples, resampler_context))
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))
486 if (converted_input_samples) {
487 av_freep(&converted_input_samples[0]);
488 free(converted_input_samples);
490 av_frame_free(&input_frame);
496 * Initialize one input frame for writing to the output file.
497 * The frame will be exactly frame_size samples large.
499 static int init_output_frame(AVFrame **frame,
500 AVCodecContext *output_codec_context,
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");
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.
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;
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.
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);
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,
543 /** Packet used for temporary storage. */
544 AVPacket output_packet;
546 init_packet(&output_packet);
549 * Encode the audio frame and store it in the temporary packet.
550 * The output audio stream encoder is used to do this.
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);
560 /** Write one audio frame from the temporary packet to the output file. */
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);
569 av_free_packet(&output_packet);
576 * Load one audio frame from the FIFO buffer, encode and write it to the
579 static int load_encode_and_write(AVAudioFifo *fifo,
580 AVFormatContext *output_format_context,
581 AVCodecContext *output_codec_context)
583 /** Temporary storage of the output samples of the frame written to the file. */
584 AVFrame *output_frame;
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
590 const int frame_size = FFMIN(av_audio_fifo_size(fifo),
591 output_codec_context->frame_size);
594 /** Initialize temporary storage for one output frame. */
595 if (init_output_frame(&output_frame, output_codec_context, frame_size))
599 * Read as many samples from the FIFO buffer as required to fill the frame.
600 * The samples are stored in the frame temporarily.
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);
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);
614 av_frame_free(&output_frame);
618 /** Write the trailer of the output file container. */
619 static int write_output_file_trailer(AVFormatContext *output_format_context)
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));
630 /** Convert an audio file to an AAC file in an MP4 container. */
631 int main(int argc, char **argv)
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;
640 fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
644 /** Register all codecs and formats so that they can be used. */
646 /** Open the input file for reading. */
647 if (open_input_file(argv[1], &input_format_context,
648 &input_codec_context))
650 /** Open the output file for writing. */
651 if (open_output_file(argv[2], input_codec_context,
652 &output_format_context, &output_codec_context))
654 /** Initialize the resampler to be able to convert audio sample formats. */
655 if (init_resampler(input_codec_context, output_codec_context,
658 /** Initialize the FIFO buffer to store audio samples to be encoded. */
659 if (init_fifo(&fifo))
661 /** Write the header of the output file container. */
662 if (write_output_file_header(output_format_context))
666 * Loop as long as we have input samples to read or output samples
667 * to write; abort as soon as we have neither.
670 /** Use the encoder's desired frame size for processing. */
671 const int output_frame_size = output_codec_context->frame_size;
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.
681 while (av_audio_fifo_size(fifo) < output_frame_size) {
683 * Decode one frame worth of audio samples, convert it to the
684 * output sample format and put it into the FIFO buffer.
686 if (read_decode_convert_and_store(fifo, input_format_context,
688 output_codec_context,
689 resample_context, &finished))
693 * If we are at the end of the input file, we continue
694 * encoding the remaining audio samples to the output file.
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
705 while (av_audio_fifo_size(fifo) >= output_frame_size ||
706 (finished && av_audio_fifo_size(fifo) > 0))
708 * Take one frame worth of audio samples from the FIFO buffer,
709 * encode it and write it to the output file.
711 if (load_encode_and_write(fifo, output_format_context,
712 output_codec_context))
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.
721 /** Flush the encoder as it may have delayed frames. */
723 if (encode_audio_frame(NULL, output_format_context,
724 output_codec_context, &data_written))
726 } while (data_written);
731 /** Write the trailer of the output file container. */
732 if (write_output_file_trailer(output_format_context))
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);
746 if (input_codec_context)
747 avcodec_close(input_codec_context);
748 if (input_format_context)
749 avformat_close_input(&input_format_context);