transcode_aac.c 33.8 KB
Newer Older
1
/*
2
 * Copyright (c) 2013-2018 Andreas Unterweger
3
 *
4
 * This file is part of FFmpeg.
5
 *
6
 * FFmpeg is free software; you can redistribute it and/or
7 8 9 10
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
11
 * FFmpeg is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 15 16
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
17
 * License along with FFmpeg; if not, write to the Free Software
18 19 20 21
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

/**
22
 * @file
23
 * Simple audio converter
24
 *
25
 * @example transcode_aac.c
26
 * Convert an input audio file to AAC in an MP4 container using FFmpeg.
27
 * Formats other than MP4 are supported based on the output file extension.
28 29 30 31 32 33 34 35 36 37 38
 * @author Andreas Unterweger (dustsigns@gmail.com)
 */

#include <stdio.h>

#include "libavformat/avformat.h"
#include "libavformat/avio.h"

#include "libavcodec/avcodec.h"

#include "libavutil/audio_fifo.h"
39
#include "libavutil/avassert.h"
40 41 42 43
#include "libavutil/avstring.h"
#include "libavutil/frame.h"
#include "libavutil/opt.h"

44
#include "libswresample/swresample.h"
45

46
/* The output bit rate in bit/s */
47
#define OUTPUT_BIT_RATE 96000
48
/* The number of output channels */
49 50
#define OUTPUT_CHANNELS 2

51 52 53 54 55 56 57
/**
 * Open an input file and the required decoder.
 * @param      filename             File to be opened
 * @param[out] input_format_context Format context of opened file
 * @param[out] input_codec_context  Codec context of opened file
 * @return Error code (0 if successful)
 */
58 59 60 61
static int open_input_file(const char *filename,
                           AVFormatContext **input_format_context,
                           AVCodecContext **input_codec_context)
{
62
    AVCodecContext *avctx;
63 64 65
    AVCodec *input_codec;
    int error;

66
    /* Open the input file to read from it. */
67 68 69
    if ((error = avformat_open_input(input_format_context, filename, NULL,
                                     NULL)) < 0) {
        fprintf(stderr, "Could not open input file '%s' (error '%s')\n",
70
                filename, av_err2str(error));
71 72 73 74
        *input_format_context = NULL;
        return error;
    }

75
    /* Get information on the input file (number of streams etc.). */
76 77
    if ((error = avformat_find_stream_info(*input_format_context, NULL)) < 0) {
        fprintf(stderr, "Could not open find stream info (error '%s')\n",
78
                av_err2str(error));
79 80 81 82
        avformat_close_input(input_format_context);
        return error;
    }

83
    /* Make sure that there is only one stream in the input file. */
84 85 86 87 88 89 90
    if ((*input_format_context)->nb_streams != 1) {
        fprintf(stderr, "Expected one audio input stream, but found %d\n",
                (*input_format_context)->nb_streams);
        avformat_close_input(input_format_context);
        return AVERROR_EXIT;
    }

91
    /* Find a decoder for the audio stream. */
92
    if (!(input_codec = avcodec_find_decoder((*input_format_context)->streams[0]->codecpar->codec_id))) {
93 94 95 96 97
        fprintf(stderr, "Could not find input codec\n");
        avformat_close_input(input_format_context);
        return AVERROR_EXIT;
    }

98
    /* Allocate a new decoding context. */
99 100 101 102 103 104 105
    avctx = avcodec_alloc_context3(input_codec);
    if (!avctx) {
        fprintf(stderr, "Could not allocate a decoding context\n");
        avformat_close_input(input_format_context);
        return AVERROR(ENOMEM);
    }

106
    /* Initialize the stream parameters with demuxer information. */
107 108 109 110 111 112 113
    error = avcodec_parameters_to_context(avctx, (*input_format_context)->streams[0]->codecpar);
    if (error < 0) {
        avformat_close_input(input_format_context);
        avcodec_free_context(&avctx);
        return error;
    }

114
    /* Open the decoder for the audio stream to use it later. */
115
    if ((error = avcodec_open2(avctx, input_codec, NULL)) < 0) {
116
        fprintf(stderr, "Could not open input codec (error '%s')\n",
117
                av_err2str(error));
118
        avcodec_free_context(&avctx);
119 120 121 122
        avformat_close_input(input_format_context);
        return error;
    }

123
    /* Save the decoder context for easier access later. */
124
    *input_codec_context = avctx;
125 126 127 128 129 130 131 132

    return 0;
}

/**
 * Open an output file and the required encoder.
 * Also set some basic encoder parameters.
 * Some of these parameters are based on the input file's parameters.
133 134 135 136 137
 * @param      filename              File to be opened
 * @param      input_codec_context   Codec context of input file
 * @param[out] output_format_context Format context of output file
 * @param[out] output_codec_context  Codec context of output file
 * @return Error code (0 if successful)
138 139 140 141 142 143
 */
static int open_output_file(const char *filename,
                            AVCodecContext *input_codec_context,
                            AVFormatContext **output_format_context,
                            AVCodecContext **output_codec_context)
{
144
    AVCodecContext *avctx          = NULL;
145 146 147 148 149
    AVIOContext *output_io_context = NULL;
    AVStream *stream               = NULL;
    AVCodec *output_codec          = NULL;
    int error;

150
    /* Open the output file to write to it. */
151 152 153
    if ((error = avio_open(&output_io_context, filename,
                           AVIO_FLAG_WRITE)) < 0) {
        fprintf(stderr, "Could not open output file '%s' (error '%s')\n",
154
                filename, av_err2str(error));
155 156 157
        return error;
    }

158
    /* Create a new format context for the output container format. */
159 160 161 162 163
    if (!(*output_format_context = avformat_alloc_context())) {
        fprintf(stderr, "Could not allocate output format context\n");
        return AVERROR(ENOMEM);
    }

164
    /* Associate the output file (pointer) with the container format context. */
165 166
    (*output_format_context)->pb = output_io_context;

167
    /* Guess the desired container format based on the file extension. */
168 169 170 171 172 173
    if (!((*output_format_context)->oformat = av_guess_format(NULL, filename,
                                                              NULL))) {
        fprintf(stderr, "Could not find output file format\n");
        goto cleanup;
    }

174 175 176 177 178
    if (!((*output_format_context)->url = av_strdup(filename))) {
        fprintf(stderr, "Could not allocate url.\n");
        error = AVERROR(ENOMEM);
        goto cleanup;
    }
179

180
    /* Find the encoder to be used by its name. */
181 182 183 184 185
    if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_AAC))) {
        fprintf(stderr, "Could not find an AAC encoder.\n");
        goto cleanup;
    }

186
    /* Create a new audio stream in the output file container. */
187
    if (!(stream = avformat_new_stream(*output_format_context, NULL))) {
188 189 190 191 192
        fprintf(stderr, "Could not create new stream\n");
        error = AVERROR(ENOMEM);
        goto cleanup;
    }

193 194 195 196 197 198
    avctx = avcodec_alloc_context3(output_codec);
    if (!avctx) {
        fprintf(stderr, "Could not allocate an encoding context\n");
        error = AVERROR(ENOMEM);
        goto cleanup;
    }
199

200 201
    /* Set the basic encoder parameters.
     * The input file's sample rate is used to avoid a sample rate conversion. */
202 203 204 205 206
    avctx->channels       = OUTPUT_CHANNELS;
    avctx->channel_layout = av_get_default_channel_layout(OUTPUT_CHANNELS);
    avctx->sample_rate    = input_codec_context->sample_rate;
    avctx->sample_fmt     = output_codec->sample_fmts[0];
    avctx->bit_rate       = OUTPUT_BIT_RATE;
207

208
    /* Allow the use of the experimental AAC encoder. */
209
    avctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
210

211
    /* Set the sample rate for the container. */
212 213 214
    stream->time_base.den = input_codec_context->sample_rate;
    stream->time_base.num = 1;

215 216
    /* Some container formats (like MP4) require global headers to be present.
     * Mark the encoder so that it behaves accordingly. */
217
    if ((*output_format_context)->oformat->flags & AVFMT_GLOBALHEADER)
218
        avctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
219

220
    /* Open the encoder for the audio stream to use it later. */
221
    if ((error = avcodec_open2(avctx, output_codec, NULL)) < 0) {
222
        fprintf(stderr, "Could not open output codec (error '%s')\n",
223
                av_err2str(error));
224 225 226
        goto cleanup;
    }

227 228 229 230 231 232
    error = avcodec_parameters_from_context(stream->codecpar, avctx);
    if (error < 0) {
        fprintf(stderr, "Could not initialize stream parameters\n");
        goto cleanup;
    }

233
    /* Save the encoder context for easier access later. */
234 235
    *output_codec_context = avctx;

236 237 238
    return 0;

cleanup:
239
    avcodec_free_context(&avctx);
240
    avio_closep(&(*output_format_context)->pb);
241 242 243 244 245
    avformat_free_context(*output_format_context);
    *output_format_context = NULL;
    return error < 0 ? error : AVERROR_EXIT;
}

246 247 248 249
/**
 * Initialize one data packet for reading or writing.
 * @param packet Packet to be initialized
 */
250 251 252
static void init_packet(AVPacket *packet)
{
    av_init_packet(packet);
253
    /* Set the packet data and size so that it is recognized as being empty. */
254 255 256 257
    packet->data = NULL;
    packet->size = 0;
}

258 259 260 261 262
/**
 * Initialize one audio frame for reading from the input file.
 * @param[out] frame Frame to be initialized
 * @return Error code (0 if successful)
 */
263 264 265 266 267 268 269 270 271 272 273 274
static int init_input_frame(AVFrame **frame)
{
    if (!(*frame = av_frame_alloc())) {
        fprintf(stderr, "Could not allocate input frame\n");
        return AVERROR(ENOMEM);
    }
    return 0;
}

/**
 * Initialize the audio resampler based on the input and output codec settings.
 * If the input and output sample formats differ, a conversion is required
275
 * libswresample takes care of this, but requires initialization.
276 277 278 279
 * @param      input_codec_context  Codec context of the input file
 * @param      output_codec_context Codec context of the output file
 * @param[out] resample_context     Resample context for the required conversion
 * @return Error code (0 if successful)
280 281 282
 */
static int init_resampler(AVCodecContext *input_codec_context,
                          AVCodecContext *output_codec_context,
283
                          SwrContext **resample_context)
284 285 286
{
        int error;

James Almer's avatar
James Almer committed
287
        /*
288
         * Create a resampler context for the conversion.
289 290 291 292 293
         * Set the conversion parameters.
         * Default channel layouts based on the number of channels
         * are assumed for simplicity (they are sometimes not detected
         * properly by the demuxer and/or decoder).
         */
294 295 296 297 298 299 300 301 302 303 304 305
        *resample_context = swr_alloc_set_opts(NULL,
                                              av_get_default_channel_layout(output_codec_context->channels),
                                              output_codec_context->sample_fmt,
                                              output_codec_context->sample_rate,
                                              av_get_default_channel_layout(input_codec_context->channels),
                                              input_codec_context->sample_fmt,
                                              input_codec_context->sample_rate,
                                              0, NULL);
        if (!*resample_context) {
            fprintf(stderr, "Could not allocate resample context\n");
            return AVERROR(ENOMEM);
        }
James Almer's avatar
James Almer committed
306
        /*
307 308 309 310 311
        * Perform a sanity check so that the number of converted samples is
        * not greater than the number of samples to be converted.
        * If the sample rates differ, this case has to be handled differently
        */
        av_assert0(output_codec_context->sample_rate == input_codec_context->sample_rate);
312

313
        /* Open the resampler with the specified parameters. */
314
        if ((error = swr_init(*resample_context)) < 0) {
315
            fprintf(stderr, "Could not open resample context\n");
316
            swr_free(resample_context);
317 318 319 320 321
            return error;
        }
    return 0;
}

322 323 324 325 326 327
/**
 * Initialize a FIFO buffer for the audio samples to be encoded.
 * @param[out] fifo                 Sample buffer
 * @param      output_codec_context Codec context of the output file
 * @return Error code (0 if successful)
 */
328
static int init_fifo(AVAudioFifo **fifo, AVCodecContext *output_codec_context)
329
{
330
    /* Create the FIFO buffer based on the specified output sample format. */
331 332
    if (!(*fifo = av_audio_fifo_alloc(output_codec_context->sample_fmt,
                                      output_codec_context->channels, 1))) {
333 334 335 336 337 338
        fprintf(stderr, "Could not allocate FIFO\n");
        return AVERROR(ENOMEM);
    }
    return 0;
}

339 340 341 342 343
/**
 * Write the header of the output file container.
 * @param output_format_context Format context of the output file
 * @return Error code (0 if successful)
 */
344 345 346 347 348
static int write_output_file_header(AVFormatContext *output_format_context)
{
    int error;
    if ((error = avformat_write_header(output_format_context, NULL)) < 0) {
        fprintf(stderr, "Could not write output file header (error '%s')\n",
349
                av_err2str(error));
350 351 352 353 354
        return error;
    }
    return 0;
}

355 356 357 358 359 360 361 362 363 364 365 366 367
/**
 * Decode one audio frame from the input file.
 * @param      frame                Audio frame to be decoded
 * @param      input_format_context Format context of the input file
 * @param      input_codec_context  Codec context of the input file
 * @param[out] data_present         Indicates whether data has been decoded
 * @param[out] finished             Indicates whether the end of file has
 *                                  been reached and all data has been
 *                                  decoded. If this flag is false, there
 *                                  is more data to be decoded, i.e., this
 *                                  function has to be called again.
 * @return Error code (0 if successful)
 */
368 369 370 371 372
static int decode_audio_frame(AVFrame *frame,
                              AVFormatContext *input_format_context,
                              AVCodecContext *input_codec_context,
                              int *data_present, int *finished)
{
373
    /* Packet used for temporary storage. */
374 375 376 377
    AVPacket input_packet;
    int error;
    init_packet(&input_packet);

378
    /* Read one audio frame from the input file into a temporary packet. */
379
    if ((error = av_read_frame(input_format_context, &input_packet)) < 0) {
James Almer's avatar
James Almer committed
380
        /* If we are at the end of the file, flush the decoder below. */
381 382 383 384
        if (error == AVERROR_EOF)
            *finished = 1;
        else {
            fprintf(stderr, "Could not read frame (error '%s')\n",
385
                    av_err2str(error));
386 387 388 389
            return error;
        }
    }

390 391 392 393
    /* Send the audio frame stored in the temporary packet to the decoder.
     * The input audio stream decoder is used to do this. */
    if ((error = avcodec_send_packet(input_codec_context, &input_packet)) < 0) {
        fprintf(stderr, "Could not send packet for decoding (error '%s')\n",
394
                av_err2str(error));
395 396 397
        return error;
    }

398 399 400 401 402 403 404 405 406 407 408 409 410 411
    /* Receive one frame from the decoder. */
    error = avcodec_receive_frame(input_codec_context, frame);
    /* If the decoder asks for more data to be able to decode a frame,
     * return indicating that no data is present. */
    if (error == AVERROR(EAGAIN)) {
        error = 0;
        goto cleanup;
    /* If the end of the input file is reached, stop decoding. */
    } else if (error == AVERROR_EOF) {
        *finished = 1;
        error = 0;
        goto cleanup;
    } else if (error < 0) {
        fprintf(stderr, "Could not decode frame (error '%s')\n",
James Almer's avatar
James Almer committed
412
                av_err2str(error));
413 414 415 416 417 418 419 420
        goto cleanup;
    /* Default case: Return decoded data. */
    } else {
        *data_present = 1;
        goto cleanup;
    }

cleanup:
421
    av_packet_unref(&input_packet);
422
    return error;
423 424 425 426 427 428
}

/**
 * Initialize a temporary storage for the specified number of audio samples.
 * The conversion requires temporary storage due to the different format.
 * The number of audio samples to be allocated is specified in frame_size.
429 430 431 432 433 434 435
 * @param[out] converted_input_samples Array of converted samples. The
 *                                     dimensions are reference, channel
 *                                     (for multi-channel audio), sample.
 * @param      output_codec_context    Codec context of the output file
 * @param      frame_size              Number of samples to be converted in
 *                                     each round
 * @return Error code (0 if successful)
436 437 438 439 440 441 442
 */
static int init_converted_samples(uint8_t ***converted_input_samples,
                                  AVCodecContext *output_codec_context,
                                  int frame_size)
{
    int error;

443
    /* Allocate as many pointers as there are audio channels.
444 445 446 447 448 449 450 451 452
     * Each pointer will later point to the audio samples of the corresponding
     * channels (although it may be NULL for interleaved formats).
     */
    if (!(*converted_input_samples = calloc(output_codec_context->channels,
                                            sizeof(**converted_input_samples)))) {
        fprintf(stderr, "Could not allocate converted input sample pointers\n");
        return AVERROR(ENOMEM);
    }

453 454
    /* Allocate memory for the samples of all channels in one consecutive
     * block for convenience. */
455 456 457 458 459 460
    if ((error = av_samples_alloc(*converted_input_samples, NULL,
                                  output_codec_context->channels,
                                  frame_size,
                                  output_codec_context->sample_fmt, 0)) < 0) {
        fprintf(stderr,
                "Could not allocate converted input samples (error '%s')\n",
461
                av_err2str(error));
462 463 464 465 466 467 468 469 470
        av_freep(&(*converted_input_samples)[0]);
        free(*converted_input_samples);
        return error;
    }
    return 0;
}

/**
 * Convert the input audio samples into the output sample format.
471 472 473 474 475 476 477 478 479
 * The conversion happens on a per-frame basis, the size of which is
 * specified by frame_size.
 * @param      input_data       Samples to be decoded. The dimensions are
 *                              channel (for multi-channel audio), sample.
 * @param[out] converted_data   Converted samples. The dimensions are channel
 *                              (for multi-channel audio), sample.
 * @param      frame_size       Number of samples to be converted
 * @param      resample_context Resample context for the conversion
 * @return Error code (0 if successful)
480
 */
481
static int convert_samples(const uint8_t **input_data,
482
                           uint8_t **converted_data, const int frame_size,
483
                           SwrContext *resample_context)
484 485 486
{
    int error;

487
    /* Convert the samples using the resampler. */
488 489 490
    if ((error = swr_convert(resample_context,
                             converted_data, frame_size,
                             input_data    , frame_size)) < 0) {
491
        fprintf(stderr, "Could not convert input samples (error '%s')\n",
492
                av_err2str(error));
493 494 495 496 497 498
        return error;
    }

    return 0;
}

499 500 501 502 503 504 505 506
/**
 * Add converted input audio samples to the FIFO buffer for later processing.
 * @param fifo                    Buffer to add the samples to
 * @param converted_input_samples Samples to be added. The dimensions are channel
 *                                (for multi-channel audio), sample.
 * @param frame_size              Number of samples to be converted
 * @return Error code (0 if successful)
 */
507 508 509 510 511 512
static int add_samples_to_fifo(AVAudioFifo *fifo,
                               uint8_t **converted_input_samples,
                               const int frame_size)
{
    int error;

513 514
    /* Make the FIFO as large as it needs to be to hold both,
     * the old and the new samples. */
515 516 517 518 519
    if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
        fprintf(stderr, "Could not reallocate FIFO\n");
        return error;
    }

520
    /* Store the new samples in the FIFO buffer. */
521 522 523 524 525 526 527 528 529
    if (av_audio_fifo_write(fifo, (void **)converted_input_samples,
                            frame_size) < frame_size) {
        fprintf(stderr, "Could not write data to FIFO\n");
        return AVERROR_EXIT;
    }
    return 0;
}

/**
530
 * Read one audio frame from the input file, decode, convert and store
531
 * it in the FIFO buffer.
532 533 534 535
 * @param      fifo                 Buffer used for temporary storage
 * @param      input_format_context Format context of the input file
 * @param      input_codec_context  Codec context of the input file
 * @param      output_codec_context Codec context of the output file
James Almer's avatar
James Almer committed
536
 * @param      resampler_context    Resample context for the conversion
537 538 539 540 541 542 543
 * @param[out] finished             Indicates whether the end of file has
 *                                  been reached and all data has been
 *                                  decoded. If this flag is false,
 *                                  there is more data to be decoded,
 *                                  i.e., this function has to be called
 *                                  again.
 * @return Error code (0 if successful)
544 545 546 547 548
 */
static int read_decode_convert_and_store(AVAudioFifo *fifo,
                                         AVFormatContext *input_format_context,
                                         AVCodecContext *input_codec_context,
                                         AVCodecContext *output_codec_context,
549
                                         SwrContext *resampler_context,
550 551
                                         int *finished)
{
552
    /* Temporary storage of the input samples of the frame read from the file. */
553
    AVFrame *input_frame = NULL;
554
    /* Temporary storage for the converted input samples. */
555
    uint8_t **converted_input_samples = NULL;
556
    int data_present = 0;
557 558
    int ret = AVERROR_EXIT;

559
    /* Initialize temporary storage for one input frame. */
560 561
    if (init_input_frame(&input_frame))
        goto cleanup;
562
    /* Decode one frame worth of audio samples. */
563 564 565
    if (decode_audio_frame(input_frame, input_format_context,
                           input_codec_context, &data_present, finished))
        goto cleanup;
566
    /* If we are at the end of the file and there are no more samples
567
     * in the decoder which are delayed, we are actually finished.
568
     * This must not be treated as an error. */
569
    if (*finished) {
570 571 572
        ret = 0;
        goto cleanup;
    }
573
    /* If there is decoded data, convert and store it. */
574
    if (data_present) {
575
        /* Initialize the temporary storage for the converted input samples. */
576 577 578 579
        if (init_converted_samples(&converted_input_samples, output_codec_context,
                                   input_frame->nb_samples))
            goto cleanup;

580 581
        /* Convert the input samples to the desired output sample format.
         * This requires a temporary storage provided by converted_input_samples. */
582
        if (convert_samples((const uint8_t**)input_frame->extended_data, converted_input_samples,
583 584 585
                            input_frame->nb_samples, resampler_context))
            goto cleanup;

586
        /* Add the converted input samples to the FIFO buffer for later processing. */
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
        if (add_samples_to_fifo(fifo, converted_input_samples,
                                input_frame->nb_samples))
            goto cleanup;
        ret = 0;
    }
    ret = 0;

cleanup:
    if (converted_input_samples) {
        av_freep(&converted_input_samples[0]);
        free(converted_input_samples);
    }
    av_frame_free(&input_frame);

    return ret;
}

/**
 * Initialize one input frame for writing to the output file.
 * The frame will be exactly frame_size samples large.
607 608 609 610
 * @param[out] frame                Frame to be initialized
 * @param      output_codec_context Codec context of the output file
 * @param      frame_size           Size of the frame
 * @return Error code (0 if successful)
611 612 613 614 615 616 617
 */
static int init_output_frame(AVFrame **frame,
                             AVCodecContext *output_codec_context,
                             int frame_size)
{
    int error;

618
    /* Create a new frame to store the audio samples. */
619 620 621 622 623
    if (!(*frame = av_frame_alloc())) {
        fprintf(stderr, "Could not allocate output frame\n");
        return AVERROR_EXIT;
    }

624
    /* Set the frame's parameters, especially its size and format.
625 626 627
     * av_frame_get_buffer needs this to allocate memory for the
     * audio samples of the frame.
     * Default channel layouts based on the number of channels
628
     * are assumed for simplicity. */
629 630 631 632 633
    (*frame)->nb_samples     = frame_size;
    (*frame)->channel_layout = output_codec_context->channel_layout;
    (*frame)->format         = output_codec_context->sample_fmt;
    (*frame)->sample_rate    = output_codec_context->sample_rate;

634 635
    /* Allocate the samples of the created frame. This call will make
     * sure that the audio frame can hold as many samples as specified. */
636
    if ((error = av_frame_get_buffer(*frame, 0)) < 0) {
637
        fprintf(stderr, "Could not allocate output frame samples (error '%s')\n",
638
                av_err2str(error));
639 640 641 642 643 644 645
        av_frame_free(frame);
        return error;
    }

    return 0;
}

646
/* Global timestamp for the audio frames. */
647 648
static int64_t pts = 0;

649 650 651 652 653 654
/**
 * Encode one frame worth of audio to the output file.
 * @param      frame                 Samples to be encoded
 * @param      output_format_context Format context of the output file
 * @param      output_codec_context  Codec context of the output file
 * @param[out] data_present          Indicates whether data has been
655
 *                                   encoded
656 657
 * @return Error code (0 if successful)
 */
658 659 660 661 662
static int encode_audio_frame(AVFrame *frame,
                              AVFormatContext *output_format_context,
                              AVCodecContext *output_codec_context,
                              int *data_present)
{
663
    /* Packet used for temporary storage. */
664 665 666 667
    AVPacket output_packet;
    int error;
    init_packet(&output_packet);

668
    /* Set a timestamp based on the sample rate for the container. */
669 670 671 672 673
    if (frame) {
        frame->pts = pts;
        pts += frame->nb_samples;
    }

674
    /* Send the audio frame stored in the temporary packet to the encoder.
675
     * The output audio stream encoder is used to do this. */
676 677 678 679 680 681 682
    error = avcodec_send_frame(output_codec_context, frame);
    /* The encoder signals that it has nothing more to encode. */
    if (error == AVERROR_EOF) {
        error = 0;
        goto cleanup;
    } else if (error < 0) {
        fprintf(stderr, "Could not send packet for encoding (error '%s')\n",
683
                av_err2str(error));
684 685 686
        return error;
    }

687 688 689 690 691 692 693 694 695 696 697 698 699
    /* Receive one encoded frame from the encoder. */
    error = avcodec_receive_packet(output_codec_context, &output_packet);
    /* If the encoder asks for more data to be able to provide an
     * encoded frame, return indicating that no data is present. */
    if (error == AVERROR(EAGAIN)) {
        error = 0;
        goto cleanup;
    /* If the last frame has been encoded, stop encoding. */
    } else if (error == AVERROR_EOF) {
        error = 0;
        goto cleanup;
    } else if (error < 0) {
        fprintf(stderr, "Could not encode frame (error '%s')\n",
James Almer's avatar
James Almer committed
700
                av_err2str(error));
701 702 703 704 705
        goto cleanup;
    /* Default case: Return encoded data. */
    } else {
        *data_present = 1;
    }
706

707 708 709 710
    /* Write one audio frame from the temporary packet to the output file. */
    if (*data_present &&
        (error = av_write_frame(output_format_context, &output_packet)) < 0) {
        fprintf(stderr, "Could not write frame (error '%s')\n",
James Almer's avatar
James Almer committed
711
                av_err2str(error));
712
        goto cleanup;
713 714
    }

715 716 717
cleanup:
    av_packet_unref(&output_packet);
    return error;
718 719 720 721 722
}

/**
 * Load one audio frame from the FIFO buffer, encode and write it to the
 * output file.
723 724 725 726
 * @param fifo                  Buffer used for temporary storage
 * @param output_format_context Format context of the output file
 * @param output_codec_context  Codec context of the output file
 * @return Error code (0 if successful)
727 728 729 730 731
 */
static int load_encode_and_write(AVAudioFifo *fifo,
                                 AVFormatContext *output_format_context,
                                 AVCodecContext *output_codec_context)
{
732
    /* Temporary storage of the output samples of the frame written to the file. */
733
    AVFrame *output_frame;
734
    /* Use the maximum number of possible samples per frame.
735
     * If there is less than the maximum possible frame size in the FIFO
736
     * buffer use this number. Otherwise, use the maximum possible frame size. */
737 738 739 740
    const int frame_size = FFMIN(av_audio_fifo_size(fifo),
                                 output_codec_context->frame_size);
    int data_written;

741
    /* Initialize temporary storage for one output frame. */
742 743 744
    if (init_output_frame(&output_frame, output_codec_context, frame_size))
        return AVERROR_EXIT;

745 746
    /* Read as many samples from the FIFO buffer as required to fill the frame.
     * The samples are stored in the frame temporarily. */
747 748 749 750 751 752
    if (av_audio_fifo_read(fifo, (void **)output_frame->data, frame_size) < frame_size) {
        fprintf(stderr, "Could not read data from FIFO\n");
        av_frame_free(&output_frame);
        return AVERROR_EXIT;
    }

753
    /* Encode one frame worth of audio samples. */
754 755 756 757 758 759 760 761 762
    if (encode_audio_frame(output_frame, output_format_context,
                           output_codec_context, &data_written)) {
        av_frame_free(&output_frame);
        return AVERROR_EXIT;
    }
    av_frame_free(&output_frame);
    return 0;
}

763 764 765 766 767
/**
 * Write the trailer of the output file container.
 * @param output_format_context Format context of the output file
 * @return Error code (0 if successful)
 */
768 769 770 771 772
static int write_output_file_trailer(AVFormatContext *output_format_context)
{
    int error;
    if ((error = av_write_trailer(output_format_context)) < 0) {
        fprintf(stderr, "Could not write output file trailer (error '%s')\n",
773
                av_err2str(error));
774 775 776 777 778 779 780 781 782
        return error;
    }
    return 0;
}

int main(int argc, char **argv)
{
    AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
    AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
783
    SwrContext *resample_context = NULL;
784 785 786
    AVAudioFifo *fifo = NULL;
    int ret = AVERROR_EXIT;

787
    if (argc != 3) {
788 789 790 791
        fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
        exit(1);
    }

792
    /* Open the input file for reading. */
793 794 795
    if (open_input_file(argv[1], &input_format_context,
                        &input_codec_context))
        goto cleanup;
796
    /* Open the output file for writing. */
797 798 799
    if (open_output_file(argv[2], input_codec_context,
                         &output_format_context, &output_codec_context))
        goto cleanup;
800
    /* Initialize the resampler to be able to convert audio sample formats. */
801 802 803
    if (init_resampler(input_codec_context, output_codec_context,
                       &resample_context))
        goto cleanup;
804
    /* Initialize the FIFO buffer to store audio samples to be encoded. */
805
    if (init_fifo(&fifo, output_codec_context))
806
        goto cleanup;
807
    /* Write the header of the output file container. */
808 809 810
    if (write_output_file_header(output_format_context))
        goto cleanup;

811 812
    /* Loop as long as we have input samples to read or output samples
     * to write; abort as soon as we have neither. */
813
    while (1) {
814
        /* Use the encoder's desired frame size for processing. */
815 816 817
        const int output_frame_size = output_codec_context->frame_size;
        int finished                = 0;

818
        /* Make sure that there is one frame worth of samples in the FIFO
819 820 821
         * buffer so that the encoder can do its work.
         * Since the decoder's and the encoder's frame size may differ, we
         * need to FIFO buffer to store as many frames worth of input samples
822
         * that they make up at least one frame worth of output samples. */
823
        while (av_audio_fifo_size(fifo) < output_frame_size) {
824 825
            /* Decode one frame worth of audio samples, convert it to the
             * output sample format and put it into the FIFO buffer. */
826 827 828 829 830 831
            if (read_decode_convert_and_store(fifo, input_format_context,
                                              input_codec_context,
                                              output_codec_context,
                                              resample_context, &finished))
                goto cleanup;

832 833
            /* If we are at the end of the input file, we continue
             * encoding the remaining audio samples to the output file. */
834 835 836 837
            if (finished)
                break;
        }

838
        /* If we have enough samples for the encoder, we encode them.
839
         * At the end of the file, we pass the remaining samples to
840
         * the encoder. */
841 842
        while (av_audio_fifo_size(fifo) >= output_frame_size ||
               (finished && av_audio_fifo_size(fifo) > 0))
843 844
            /* Take one frame worth of audio samples from the FIFO buffer,
             * encode it and write it to the output file. */
845 846 847 848
            if (load_encode_and_write(fifo, output_format_context,
                                      output_codec_context))
                goto cleanup;

849 850
        /* If we are at the end of the input file and have encoded
         * all remaining samples, we can exit this loop and finish. */
851 852
        if (finished) {
            int data_written;
853
            /* Flush the encoder as it may have delayed frames. */
854
            do {
855
                data_written = 0;
856 857 858 859 860 861 862 863
                if (encode_audio_frame(NULL, output_format_context,
                                       output_codec_context, &data_written))
                    goto cleanup;
            } while (data_written);
            break;
        }
    }

864
    /* Write the trailer of the output file container. */
865 866 867 868 869 870 871
    if (write_output_file_trailer(output_format_context))
        goto cleanup;
    ret = 0;

cleanup:
    if (fifo)
        av_audio_fifo_free(fifo);
872
    swr_free(&resample_context);
873
    if (output_codec_context)
874
        avcodec_free_context(&output_codec_context);
875
    if (output_format_context) {
876
        avio_closep(&output_format_context->pb);
877 878 879
        avformat_free_context(output_format_context);
    }
    if (input_codec_context)
880
        avcodec_free_context(&input_codec_context);
881 882 883 884 885
    if (input_format_context)
        avformat_close_input(&input_format_context);

    return ret;
}