FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
transcode_aac.c
Go to the documentation of this file.
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
21  * simple audio converter
22  *
23  * @example transcode_aac.c
24  * Convert an input audio file to AAC in an MP4 container using FFmpeg.
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/avassert.h"
37 #include "libavutil/avstring.h"
38 #include "libavutil/frame.h"
39 #include "libavutil/opt.h"
40 
42 
43 /** The output bit rate in kbit/s */
44 #define OUTPUT_BIT_RATE 96000
45 /** The number of output channels */
46 #define OUTPUT_CHANNELS 2
47 
48 /** Open an input file and the required decoder. */
49 static int open_input_file(const char *filename,
50  AVFormatContext **input_format_context,
51  AVCodecContext **input_codec_context)
52 {
53  AVCodecContext *avctx;
54  AVCodec *input_codec;
55  int error;
56 
57  /** Open the input file to read from it. */
58  if ((error = avformat_open_input(input_format_context, filename, NULL,
59  NULL)) < 0) {
60  fprintf(stderr, "Could not open input file '%s' (error '%s')\n",
61  filename, av_err2str(error));
62  *input_format_context = NULL;
63  return error;
64  }
65 
66  /** Get information on the input file (number of streams etc.). */
67  if ((error = avformat_find_stream_info(*input_format_context, NULL)) < 0) {
68  fprintf(stderr, "Could not open find stream info (error '%s')\n",
69  av_err2str(error));
70  avformat_close_input(input_format_context);
71  return error;
72  }
73 
74  /** Make sure that there is only one stream in the input file. */
75  if ((*input_format_context)->nb_streams != 1) {
76  fprintf(stderr, "Expected one audio input stream, but found %d\n",
77  (*input_format_context)->nb_streams);
78  avformat_close_input(input_format_context);
79  return AVERROR_EXIT;
80  }
81 
82  /** Find a decoder for the audio stream. */
83  if (!(input_codec = avcodec_find_decoder((*input_format_context)->streams[0]->codecpar->codec_id))) {
84  fprintf(stderr, "Could not find input codec\n");
85  avformat_close_input(input_format_context);
86  return AVERROR_EXIT;
87  }
88 
89  /** allocate a new decoding context */
90  avctx = avcodec_alloc_context3(input_codec);
91  if (!avctx) {
92  fprintf(stderr, "Could not allocate a decoding context\n");
93  avformat_close_input(input_format_context);
94  return AVERROR(ENOMEM);
95  }
96 
97  /** initialize the stream parameters with demuxer information */
98  error = avcodec_parameters_to_context(avctx, (*input_format_context)->streams[0]->codecpar);
99  if (error < 0) {
100  avformat_close_input(input_format_context);
101  avcodec_free_context(&avctx);
102  return error;
103  }
104 
105  /** Open the decoder for the audio stream to use it later. */
106  if ((error = avcodec_open2(avctx, input_codec, NULL)) < 0) {
107  fprintf(stderr, "Could not open input codec (error '%s')\n",
108  av_err2str(error));
109  avcodec_free_context(&avctx);
110  avformat_close_input(input_format_context);
111  return error;
112  }
113 
114  /** Save the decoder context for easier access later. */
115  *input_codec_context = avctx;
116 
117  return 0;
118 }
119 
120 /**
121  * Open an output file and the required encoder.
122  * Also set some basic encoder parameters.
123  * Some of these parameters are based on the input file's parameters.
124  */
125 static int open_output_file(const char *filename,
126  AVCodecContext *input_codec_context,
127  AVFormatContext **output_format_context,
128  AVCodecContext **output_codec_context)
129 {
130  AVCodecContext *avctx = NULL;
131  AVIOContext *output_io_context = NULL;
132  AVStream *stream = NULL;
133  AVCodec *output_codec = NULL;
134  int error;
135 
136  /** Open the output file to write to it. */
137  if ((error = avio_open(&output_io_context, filename,
138  AVIO_FLAG_WRITE)) < 0) {
139  fprintf(stderr, "Could not open output file '%s' (error '%s')\n",
140  filename, av_err2str(error));
141  return error;
142  }
143 
144  /** Create a new format context for the output container format. */
145  if (!(*output_format_context = avformat_alloc_context())) {
146  fprintf(stderr, "Could not allocate output format context\n");
147  return AVERROR(ENOMEM);
148  }
149 
150  /** Associate the output file (pointer) with the container format context. */
151  (*output_format_context)->pb = output_io_context;
152 
153  /** Guess the desired container format based on the file extension. */
154  if (!((*output_format_context)->oformat = av_guess_format(NULL, filename,
155  NULL))) {
156  fprintf(stderr, "Could not find output file format\n");
157  goto cleanup;
158  }
159 
160  av_strlcpy((*output_format_context)->filename, filename,
161  sizeof((*output_format_context)->filename));
162 
163  /** Find the encoder to be used by its name. */
164  if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_AAC))) {
165  fprintf(stderr, "Could not find an AAC encoder.\n");
166  goto cleanup;
167  }
168 
169  /** Create a new audio stream in the output file container. */
170  if (!(stream = avformat_new_stream(*output_format_context, NULL))) {
171  fprintf(stderr, "Could not create new stream\n");
172  error = AVERROR(ENOMEM);
173  goto cleanup;
174  }
175 
176  avctx = avcodec_alloc_context3(output_codec);
177  if (!avctx) {
178  fprintf(stderr, "Could not allocate an encoding context\n");
179  error = AVERROR(ENOMEM);
180  goto cleanup;
181  }
182 
183  /**
184  * Set the basic encoder parameters.
185  * The input file's sample rate is used to avoid a sample rate conversion.
186  */
187  avctx->channels = OUTPUT_CHANNELS;
189  avctx->sample_rate = input_codec_context->sample_rate;
190  avctx->sample_fmt = output_codec->sample_fmts[0];
191  avctx->bit_rate = OUTPUT_BIT_RATE;
192 
193  /** Allow the use of the experimental AAC encoder */
195 
196  /** Set the sample rate for the container. */
197  stream->time_base.den = input_codec_context->sample_rate;
198  stream->time_base.num = 1;
199 
200  /**
201  * Some container formats (like MP4) require global headers to be present
202  * Mark the encoder so that it behaves accordingly.
203  */
204  if ((*output_format_context)->oformat->flags & AVFMT_GLOBALHEADER)
206 
207  /** Open the encoder for the audio stream to use it later. */
208  if ((error = avcodec_open2(avctx, output_codec, NULL)) < 0) {
209  fprintf(stderr, "Could not open output codec (error '%s')\n",
210  av_err2str(error));
211  goto cleanup;
212  }
213 
214  error = avcodec_parameters_from_context(stream->codecpar, avctx);
215  if (error < 0) {
216  fprintf(stderr, "Could not initialize stream parameters\n");
217  goto cleanup;
218  }
219 
220  /** Save the encoder context for easier access later. */
221  *output_codec_context = avctx;
222 
223  return 0;
224 
225 cleanup:
226  avcodec_free_context(&avctx);
227  avio_closep(&(*output_format_context)->pb);
228  avformat_free_context(*output_format_context);
229  *output_format_context = NULL;
230  return error < 0 ? error : AVERROR_EXIT;
231 }
232 
233 /** Initialize one data packet for reading or writing. */
234 static void init_packet(AVPacket *packet)
235 {
236  av_init_packet(packet);
237  /** Set the packet data and size so that it is recognized as being empty. */
238  packet->data = NULL;
239  packet->size = 0;
240 }
241 
242 /** Initialize one audio frame for reading from the input file */
244 {
245  if (!(*frame = av_frame_alloc())) {
246  fprintf(stderr, "Could not allocate input frame\n");
247  return AVERROR(ENOMEM);
248  }
249  return 0;
250 }
251 
252 /**
253  * Initialize the audio resampler based on the input and output codec settings.
254  * If the input and output sample formats differ, a conversion is required
255  * libswresample takes care of this, but requires initialization.
256  */
257 static int init_resampler(AVCodecContext *input_codec_context,
258  AVCodecContext *output_codec_context,
259  SwrContext **resample_context)
260 {
261  int error;
262 
263  /**
264  * Create a resampler context for the conversion.
265  * Set the conversion parameters.
266  * Default channel layouts based on the number of channels
267  * are assumed for simplicity (they are sometimes not detected
268  * properly by the demuxer and/or decoder).
269  */
270  *resample_context = swr_alloc_set_opts(NULL,
271  av_get_default_channel_layout(output_codec_context->channels),
272  output_codec_context->sample_fmt,
273  output_codec_context->sample_rate,
274  av_get_default_channel_layout(input_codec_context->channels),
275  input_codec_context->sample_fmt,
276  input_codec_context->sample_rate,
277  0, NULL);
278  if (!*resample_context) {
279  fprintf(stderr, "Could not allocate resample context\n");
280  return AVERROR(ENOMEM);
281  }
282  /**
283  * Perform a sanity check so that the number of converted samples is
284  * not greater than the number of samples to be converted.
285  * If the sample rates differ, this case has to be handled differently
286  */
287  av_assert0(output_codec_context->sample_rate == input_codec_context->sample_rate);
288 
289  /** Open the resampler with the specified parameters. */
290  if ((error = swr_init(*resample_context)) < 0) {
291  fprintf(stderr, "Could not open resample context\n");
292  swr_free(resample_context);
293  return error;
294  }
295  return 0;
296 }
297 
298 /** Initialize a FIFO buffer for the audio samples to be encoded. */
299 static int init_fifo(AVAudioFifo **fifo, AVCodecContext *output_codec_context)
300 {
301  /** Create the FIFO buffer based on the specified output sample format. */
302  if (!(*fifo = av_audio_fifo_alloc(output_codec_context->sample_fmt,
303  output_codec_context->channels, 1))) {
304  fprintf(stderr, "Could not allocate FIFO\n");
305  return AVERROR(ENOMEM);
306  }
307  return 0;
308 }
309 
310 /** Write the header of the output file container. */
311 static int write_output_file_header(AVFormatContext *output_format_context)
312 {
313  int error;
314  if ((error = avformat_write_header(output_format_context, NULL)) < 0) {
315  fprintf(stderr, "Could not write output file header (error '%s')\n",
316  av_err2str(error));
317  return error;
318  }
319  return 0;
320 }
321 
322 /** Decode one audio frame from the input file. */
324  AVFormatContext *input_format_context,
325  AVCodecContext *input_codec_context,
326  int *data_present, int *finished)
327 {
328  /** Packet used for temporary storage. */
329  AVPacket input_packet;
330  int error;
331  init_packet(&input_packet);
332 
333  /** Read one audio frame from the input file into a temporary packet. */
334  if ((error = av_read_frame(input_format_context, &input_packet)) < 0) {
335  /** If we are at the end of the file, flush the decoder below. */
336  if (error == AVERROR_EOF)
337  *finished = 1;
338  else {
339  fprintf(stderr, "Could not read frame (error '%s')\n",
340  av_err2str(error));
341  return error;
342  }
343  }
344 
345  /**
346  * Decode the audio frame stored in the temporary packet.
347  * The input audio stream decoder is used to do this.
348  * If we are at the end of the file, pass an empty packet to the decoder
349  * to flush it.
350  */
351  if ((error = avcodec_decode_audio4(input_codec_context, frame,
352  data_present, &input_packet)) < 0) {
353  fprintf(stderr, "Could not decode frame (error '%s')\n",
354  av_err2str(error));
355  av_packet_unref(&input_packet);
356  return error;
357  }
358 
359  /**
360  * If the decoder has not been flushed completely, we are not finished,
361  * so that this function has to be called again.
362  */
363  if (*finished && *data_present)
364  *finished = 0;
365  av_packet_unref(&input_packet);
366  return 0;
367 }
368 
369 /**
370  * Initialize a temporary storage for the specified number of audio samples.
371  * The conversion requires temporary storage due to the different format.
372  * The number of audio samples to be allocated is specified in frame_size.
373  */
374 static int init_converted_samples(uint8_t ***converted_input_samples,
375  AVCodecContext *output_codec_context,
376  int frame_size)
377 {
378  int error;
379 
380  /**
381  * Allocate as many pointers as there are audio channels.
382  * Each pointer will later point to the audio samples of the corresponding
383  * channels (although it may be NULL for interleaved formats).
384  */
385  if (!(*converted_input_samples = calloc(output_codec_context->channels,
386  sizeof(**converted_input_samples)))) {
387  fprintf(stderr, "Could not allocate converted input sample pointers\n");
388  return AVERROR(ENOMEM);
389  }
390 
391  /**
392  * Allocate memory for the samples of all channels in one consecutive
393  * block for convenience.
394  */
395  if ((error = av_samples_alloc(*converted_input_samples, NULL,
396  output_codec_context->channels,
397  frame_size,
398  output_codec_context->sample_fmt, 0)) < 0) {
399  fprintf(stderr,
400  "Could not allocate converted input samples (error '%s')\n",
401  av_err2str(error));
402  av_freep(&(*converted_input_samples)[0]);
403  free(*converted_input_samples);
404  return error;
405  }
406  return 0;
407 }
408 
409 /**
410  * Convert the input audio samples into the output sample format.
411  * The conversion happens on a per-frame basis, the size of which is specified
412  * by frame_size.
413  */
414 static int convert_samples(const uint8_t **input_data,
415  uint8_t **converted_data, const int frame_size,
416  SwrContext *resample_context)
417 {
418  int error;
419 
420  /** Convert the samples using the resampler. */
421  if ((error = swr_convert(resample_context,
422  converted_data, frame_size,
423  input_data , frame_size)) < 0) {
424  fprintf(stderr, "Could not convert input samples (error '%s')\n",
425  av_err2str(error));
426  return error;
427  }
428 
429  return 0;
430 }
431 
432 /** Add converted input audio samples to the FIFO buffer for later processing. */
434  uint8_t **converted_input_samples,
435  const int frame_size)
436 {
437  int error;
438 
439  /**
440  * Make the FIFO as large as it needs to be to hold both,
441  * the old and the new samples.
442  */
443  if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
444  fprintf(stderr, "Could not reallocate FIFO\n");
445  return error;
446  }
447 
448  /** Store the new samples in the FIFO buffer. */
449  if (av_audio_fifo_write(fifo, (void **)converted_input_samples,
450  frame_size) < frame_size) {
451  fprintf(stderr, "Could not write data to FIFO\n");
452  return AVERROR_EXIT;
453  }
454  return 0;
455 }
456 
457 /**
458  * Read one audio frame from the input file, decodes, converts and stores
459  * it in the FIFO buffer.
460  */
462  AVFormatContext *input_format_context,
463  AVCodecContext *input_codec_context,
464  AVCodecContext *output_codec_context,
465  SwrContext *resampler_context,
466  int *finished)
467 {
468  /** Temporary storage of the input samples of the frame read from the file. */
469  AVFrame *input_frame = NULL;
470  /** Temporary storage for the converted input samples. */
471  uint8_t **converted_input_samples = NULL;
472  int data_present;
473  int ret = AVERROR_EXIT;
474 
475  /** Initialize temporary storage for one input frame. */
476  if (init_input_frame(&input_frame))
477  goto cleanup;
478  /** Decode one frame worth of audio samples. */
479  if (decode_audio_frame(input_frame, input_format_context,
480  input_codec_context, &data_present, finished))
481  goto cleanup;
482  /**
483  * If we are at the end of the file and there are no more samples
484  * in the decoder which are delayed, we are actually finished.
485  * This must not be treated as an error.
486  */
487  if (*finished && !data_present) {
488  ret = 0;
489  goto cleanup;
490  }
491  /** If there is decoded data, convert and store it */
492  if (data_present) {
493  /** Initialize the temporary storage for the converted input samples. */
494  if (init_converted_samples(&converted_input_samples, output_codec_context,
495  input_frame->nb_samples))
496  goto cleanup;
497 
498  /**
499  * Convert the input samples to the desired output sample format.
500  * This requires a temporary storage provided by converted_input_samples.
501  */
502  if (convert_samples((const uint8_t**)input_frame->extended_data, converted_input_samples,
503  input_frame->nb_samples, resampler_context))
504  goto cleanup;
505 
506  /** Add the converted input samples to the FIFO buffer for later processing. */
507  if (add_samples_to_fifo(fifo, converted_input_samples,
508  input_frame->nb_samples))
509  goto cleanup;
510  ret = 0;
511  }
512  ret = 0;
513 
514 cleanup:
515  if (converted_input_samples) {
516  av_freep(&converted_input_samples[0]);
517  free(converted_input_samples);
518  }
519  av_frame_free(&input_frame);
520 
521  return ret;
522 }
523 
524 /**
525  * Initialize one input frame for writing to the output file.
526  * The frame will be exactly frame_size samples large.
527  */
529  AVCodecContext *output_codec_context,
530  int frame_size)
531 {
532  int error;
533 
534  /** Create a new frame to store the audio samples. */
535  if (!(*frame = av_frame_alloc())) {
536  fprintf(stderr, "Could not allocate output frame\n");
537  return AVERROR_EXIT;
538  }
539 
540  /**
541  * Set the frame's parameters, especially its size and format.
542  * av_frame_get_buffer needs this to allocate memory for the
543  * audio samples of the frame.
544  * Default channel layouts based on the number of channels
545  * are assumed for simplicity.
546  */
547  (*frame)->nb_samples = frame_size;
548  (*frame)->channel_layout = output_codec_context->channel_layout;
549  (*frame)->format = output_codec_context->sample_fmt;
550  (*frame)->sample_rate = output_codec_context->sample_rate;
551 
552  /**
553  * Allocate the samples of the created frame. This call will make
554  * sure that the audio frame can hold as many samples as specified.
555  */
556  if ((error = av_frame_get_buffer(*frame, 0)) < 0) {
557  fprintf(stderr, "Could not allocate output frame samples (error '%s')\n",
558  av_err2str(error));
559  av_frame_free(frame);
560  return error;
561  }
562 
563  return 0;
564 }
565 
566 /** Global timestamp for the audio frames */
567 static int64_t pts = 0;
568 
569 /** Encode one frame worth of audio to the output file. */
571  AVFormatContext *output_format_context,
572  AVCodecContext *output_codec_context,
573  int *data_present)
574 {
575  /** Packet used for temporary storage. */
577  int error;
578  init_packet(&output_packet);
579 
580  /** Set a timestamp based on the sample rate for the container. */
581  if (frame) {
582  frame->pts = pts;
583  pts += frame->nb_samples;
584  }
585 
586  /**
587  * Encode the audio frame and store it in the temporary packet.
588  * The output audio stream encoder is used to do this.
589  */
590  if ((error = avcodec_encode_audio2(output_codec_context, &output_packet,
591  frame, data_present)) < 0) {
592  fprintf(stderr, "Could not encode frame (error '%s')\n",
593  av_err2str(error));
594  av_packet_unref(&output_packet);
595  return error;
596  }
597 
598  /** Write one audio frame from the temporary packet to the output file. */
599  if (*data_present) {
600  if ((error = av_write_frame(output_format_context, &output_packet)) < 0) {
601  fprintf(stderr, "Could not write frame (error '%s')\n",
602  av_err2str(error));
603  av_packet_unref(&output_packet);
604  return error;
605  }
606 
607  av_packet_unref(&output_packet);
608  }
609 
610  return 0;
611 }
612 
613 /**
614  * Load one audio frame from the FIFO buffer, encode and write it to the
615  * output file.
616  */
618  AVFormatContext *output_format_context,
619  AVCodecContext *output_codec_context)
620 {
621  /** Temporary storage of the output samples of the frame written to the file. */
623  /**
624  * Use the maximum number of possible samples per frame.
625  * If there is less than the maximum possible frame size in the FIFO
626  * buffer use this number. Otherwise, use the maximum possible frame size
627  */
628  const int frame_size = FFMIN(av_audio_fifo_size(fifo),
629  output_codec_context->frame_size);
630  int data_written;
631 
632  /** Initialize temporary storage for one output frame. */
633  if (init_output_frame(&output_frame, output_codec_context, frame_size))
634  return AVERROR_EXIT;
635 
636  /**
637  * Read as many samples from the FIFO buffer as required to fill the frame.
638  * The samples are stored in the frame temporarily.
639  */
640  if (av_audio_fifo_read(fifo, (void **)output_frame->data, frame_size) < frame_size) {
641  fprintf(stderr, "Could not read data from FIFO\n");
642  av_frame_free(&output_frame);
643  return AVERROR_EXIT;
644  }
645 
646  /** Encode one frame worth of audio samples. */
647  if (encode_audio_frame(output_frame, output_format_context,
648  output_codec_context, &data_written)) {
649  av_frame_free(&output_frame);
650  return AVERROR_EXIT;
651  }
652  av_frame_free(&output_frame);
653  return 0;
654 }
655 
656 /** Write the trailer of the output file container. */
657 static int write_output_file_trailer(AVFormatContext *output_format_context)
658 {
659  int error;
660  if ((error = av_write_trailer(output_format_context)) < 0) {
661  fprintf(stderr, "Could not write output file trailer (error '%s')\n",
662  av_err2str(error));
663  return error;
664  }
665  return 0;
666 }
667 
668 /** Convert an audio file to an AAC file in an MP4 container. */
669 int main(int argc, char **argv)
670 {
671  AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
672  AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
673  SwrContext *resample_context = NULL;
674  AVAudioFifo *fifo = NULL;
675  int ret = AVERROR_EXIT;
676 
677  if (argc < 3) {
678  fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
679  exit(1);
680  }
681 
682  /** Register all codecs and formats so that they can be used. */
683  av_register_all();
684  /** Open the input file for reading. */
685  if (open_input_file(argv[1], &input_format_context,
686  &input_codec_context))
687  goto cleanup;
688  /** Open the output file for writing. */
689  if (open_output_file(argv[2], input_codec_context,
690  &output_format_context, &output_codec_context))
691  goto cleanup;
692  /** Initialize the resampler to be able to convert audio sample formats. */
693  if (init_resampler(input_codec_context, output_codec_context,
694  &resample_context))
695  goto cleanup;
696  /** Initialize the FIFO buffer to store audio samples to be encoded. */
697  if (init_fifo(&fifo, output_codec_context))
698  goto cleanup;
699  /** Write the header of the output file container. */
700  if (write_output_file_header(output_format_context))
701  goto cleanup;
702 
703  /**
704  * Loop as long as we have input samples to read or output samples
705  * to write; abort as soon as we have neither.
706  */
707  while (1) {
708  /** Use the encoder's desired frame size for processing. */
709  const int output_frame_size = output_codec_context->frame_size;
710  int finished = 0;
711 
712  /**
713  * Make sure that there is one frame worth of samples in the FIFO
714  * buffer so that the encoder can do its work.
715  * Since the decoder's and the encoder's frame size may differ, we
716  * need to FIFO buffer to store as many frames worth of input samples
717  * that they make up at least one frame worth of output samples.
718  */
719  while (av_audio_fifo_size(fifo) < output_frame_size) {
720  /**
721  * Decode one frame worth of audio samples, convert it to the
722  * output sample format and put it into the FIFO buffer.
723  */
724  if (read_decode_convert_and_store(fifo, input_format_context,
725  input_codec_context,
726  output_codec_context,
727  resample_context, &finished))
728  goto cleanup;
729 
730  /**
731  * If we are at the end of the input file, we continue
732  * encoding the remaining audio samples to the output file.
733  */
734  if (finished)
735  break;
736  }
737 
738  /**
739  * If we have enough samples for the encoder, we encode them.
740  * At the end of the file, we pass the remaining samples to
741  * the encoder.
742  */
743  while (av_audio_fifo_size(fifo) >= output_frame_size ||
744  (finished && av_audio_fifo_size(fifo) > 0))
745  /**
746  * Take one frame worth of audio samples from the FIFO buffer,
747  * encode it and write it to the output file.
748  */
749  if (load_encode_and_write(fifo, output_format_context,
750  output_codec_context))
751  goto cleanup;
752 
753  /**
754  * If we are at the end of the input file and have encoded
755  * all remaining samples, we can exit this loop and finish.
756  */
757  if (finished) {
758  int data_written;
759  /** Flush the encoder as it may have delayed frames. */
760  do {
761  if (encode_audio_frame(NULL, output_format_context,
762  output_codec_context, &data_written))
763  goto cleanup;
764  } while (data_written);
765  break;
766  }
767  }
768 
769  /** Write the trailer of the output file container. */
770  if (write_output_file_trailer(output_format_context))
771  goto cleanup;
772  ret = 0;
773 
774 cleanup:
775  if (fifo)
776  av_audio_fifo_free(fifo);
777  swr_free(&resample_context);
778  if (output_codec_context)
779  avcodec_free_context(&output_codec_context);
780  if (output_format_context) {
781  avio_closep(&output_format_context->pb);
782  avformat_free_context(output_format_context);
783  }
784  if (input_codec_context)
785  avcodec_free_context(&input_codec_context);
786  if (input_format_context)
787  avformat_close_input(&input_format_context);
788 
789  return ret;
790 }
int avio_open(AVIOContext **s, const char *url, int flags)
Create and initialize a AVIOContext for accessing the resource indicated by url.
Definition: aviobuf.c:1076
#define FF_COMPLIANCE_EXPERIMENTAL
Allow nonstandardized experimental things.
Definition: avcodec.h:2986
#define NULL
Definition: coverity.c:32
static void output_packet(OutputFile *of, AVPacket *pkt, OutputStream *ost, int eof)
Definition: ffmpeg.c:828
Bytestream IO Context.
Definition: avio.h:161
AVAudioFifo * av_audio_fifo_alloc(enum AVSampleFormat sample_fmt, int channels, int nb_samples)
Allocate an AVAudioFifo.
Definition: audio_fifo.c:59
Buffered I/O operations.
int av_audio_fifo_read(AVAudioFifo *af, void **data, int nb_samples)
Read data from an AVAudioFifo.
Definition: audio_fifo.c:181
This structure describes decoded (raw) audio or video data.
Definition: frame.h:201
AVCodec * avcodec_find_encoder(enum AVCodecID id)
Find a registered encoder with a matching codec ID.
Definition: utils.c:1256
int main(int argc, char **argv)
Convert an audio file to an AAC file in an MP4 container.
int av_write_frame(AVFormatContext *s, AVPacket *pkt)
Write a packet to an output media file.
Definition: mux.c:927
int64_t bit_rate
the average bitrate
Definition: avcodec.h:1826
void av_audio_fifo_free(AVAudioFifo *af)
Free an AVAudioFifo.
Definition: audio_fifo.c:45
int num
Numerator.
Definition: rational.h:59
int size
Definition: avcodec.h:1680
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:661
attribute_deprecated int avcodec_encode_audio2(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr)
Encode a frame of audio.
Definition: encode.c:118
attribute_deprecated int avcodec_decode_audio4(AVCodecContext *avctx, AVFrame *frame, int *got_frame_ptr, const AVPacket *avpkt)
Decode the audio frame of size avpkt->size from avpkt->data into frame.
Definition: decode.c:837
AVCodec.
Definition: avcodec.h:3739
static void init_packet(AVPacket *packet)
Initialize one data packet for reading or writing.
static int init_resampler(AVCodecContext *input_codec_context, AVCodecContext *output_codec_context, SwrContext **resample_context)
Initialize the audio resampler based on the input and output codec settings.
static int open_input_file(const char *filename, AVFormatContext **input_format_context, AVCodecContext **input_codec_context)
Open an input file and the required decoder.
Definition: transcode_aac.c:49
Format I/O context.
Definition: avformat.h:1349
static int encode_audio_frame(AVFrame *frame, AVFormatContext *output_format_context, AVCodecContext *output_codec_context, int *data_present)
Encode one frame worth of audio to the output file.
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:2531
uint8_t
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:150
AVOptions.
static int read_decode_convert_and_store(AVAudioFifo *fifo, AVFormatContext *input_format_context, AVCodecContext *input_codec_context, AVCodecContext *output_codec_context, SwrContext *resampler_context, int *finished)
Read one audio frame from the input file, decodes, converts and stores it in the FIFO buffer...
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:294
static int convert_samples(const uint8_t **input_data, uint8_t **converted_data, const int frame_size, SwrContext *resample_context)
Convert the input audio samples into the output sample format.
AVStream * avformat_new_stream(AVFormatContext *s, const AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:4367
int avcodec_parameters_to_context(AVCodecContext *codec, const AVCodecParameters *par)
Fill the codec context based on the values from the supplied codec parameters.
Definition: utils.c:2354
static AVFrame * frame
AVFormatContext * avformat_alloc_context(void)
Allocate an AVFormatContext.
Definition: options.c:144
static void input_data(MLPEncodeContext *ctx, void *samples)
Wrapper function for inputting data in two different bit-depths.
Definition: mlpenc.c:1275
uint8_t * data
Definition: avcodec.h:1679
#define AVERROR_EOF
End of file.
Definition: error.h:55
static int init_input_frame(AVFrame **frame)
Initialize one audio frame for reading from the input file.
libswresample public header
static int write_output_file_header(AVFormatContext *output_format_context)
Write the header of the output file container.
#define AVERROR(e)
Definition: error.h:43
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:163
The libswresample context.
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:1856
simple assert() macros that are a bit more flexible than ISO C assert().
static int load_encode_and_write(AVAudioFifo *fifo, AVFormatContext *output_format_context, AVCodecContext *output_codec_context)
Load one audio frame from the FIFO buffer, encode and write it to the output file.
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:83
reference-counted frame API
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:2574
Context for an Audio FIFO Buffer.
Definition: audio_fifo.c:34
int av_audio_fifo_size(AVAudioFifo *af)
Get the current number of samples in the AVAudioFifo available for reading.
Definition: audio_fifo.c:228
int av_audio_fifo_realloc(AVAudioFifo *af, int nb_samples)
Reallocate an AVAudioFifo.
Definition: audio_fifo.c:96
av_warn_unused_result int avformat_write_header(AVFormatContext *s, AVDictionary **options)
Allocate the stream private data and write the stream header to an output media file.
Definition: mux.c:528
#define FFMIN(a, b)
Definition: common.h:96
static int open_output_file(const char *filename, AVCodecContext *input_codec_context, AVFormatContext **output_format_context, AVCodecContext **output_codec_context)
Open an output file and the required encoder.
AVCodecContext * avcodec_alloc_context3(const AVCodec *codec)
Allocate an AVCodecContext and set its fields to default values.
Definition: options.c:157
static int decode_audio_frame(AVFrame *frame, AVFormatContext *input_format_context, AVCodecContext *input_codec_context, int *data_present, int *finished)
Decode one audio frame from the input file.
#define AVFMT_GLOBALHEADER
Format wants global header.
Definition: avformat.h:485
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: error.h:119
struct SwrContext * swr_alloc_set_opts(struct SwrContext *s, int64_t out_ch_layout, enum AVSampleFormat out_sample_fmt, int out_sample_rate, int64_t in_ch_layout, enum AVSampleFormat in_sample_fmt, int in_sample_rate, int log_offset, void *log_ctx)
Allocate SwrContext if needed and set/reset common parameters.
Definition: swresample.c:59
AVOutputFormat * av_guess_format(const char *short_name, const char *filename, const char *mime_type)
Return the output format in the list of registered output formats which best matches the provided par...
Definition: format.c:98
static int add_samples_to_fifo(AVAudioFifo *fifo, uint8_t **converted_input_samples, const int frame_size)
Add converted input audio samples to the FIFO buffer for later processing.
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition: error.h:56
static void error(const char *err)
Stream structure.
Definition: avformat.h:889
int frame_size
Number of samples per channel in an audio frame.
Definition: avcodec.h:2543
int av_samples_alloc(uint8_t **audio_data, int *linesize, int nb_channels, int nb_samples, enum AVSampleFormat sample_fmt, int align)
Allocate a samples buffer for nb_samples samples, and fill data pointers and linesize accordingly...
Definition: samplefmt.c:173
int frame_size
Definition: mxfenc.c:1896
static int init_fifo(AVAudioFifo **fifo, AVCodecContext *output_codec_context)
Initialize a FIFO buffer for the audio samples to be encoded.
Libavcodec external API header.
void avcodec_free_context(AVCodecContext **avctx)
Free the codec context and everything associated with it and write NULL to the provided pointer...
Definition: options.c:172
#define OUTPUT_BIT_RATE
The output bit rate in kbit/s.
Definition: transcode_aac.c:44
int sample_rate
samples per second
Definition: avcodec.h:2523
main external API structure.
Definition: avcodec.h:1761
AVCodec * avcodec_find_decoder(enum AVCodecID id)
Find a registered decoder with a matching codec ID.
Definition: utils.c:1275
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:618
av_cold void swr_free(SwrContext **ss)
Free the given SwrContext and set the pointer to NULL.
Definition: swresample.c:137
static int output_frame(H264Context *h, AVFrame *dst, H264Picture *srcp)
Definition: h264dec.c:846
int avcodec_parameters_from_context(AVCodecParameters *par, const AVCodecContext *codec)
Fill the parameters struct based on the values from the supplied codec context.
Definition: utils.c:2297
int avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
Initialize the AVCodecContext to use the given AVCodec.
Definition: utils.c:627
void avformat_free_context(AVFormatContext *s)
Free an AVFormatContext and all its streams.
Definition: utils.c:4302
int attribute_align_arg swr_convert(struct SwrContext *s, uint8_t *out_arg[SWR_CH_MAX], int out_count, const uint8_t *in_arg[SWR_CH_MAX], int in_count)
Definition: swresample.c:706
int av_read_frame(AVFormatContext *s, AVPacket *pkt)
Return the next frame of a stream.
Definition: utils.c:1713
int av_frame_get_buffer(AVFrame *frame, int align)
Allocate new buffer(s) for audio or video data.
Definition: frame.c:283
static int64_t pts
Global timestamp for the audio frames.
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:215
int av_audio_fifo_write(AVAudioFifo *af, void **data, int nb_samples)
Write data to an AVAudioFifo.
Definition: audio_fifo.c:112
#define OUTPUT_CHANNELS
The number of output channels.
Definition: transcode_aac.c:46
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
Definition: avcodec.h:925
Main libavformat public API header.
int avformat_find_stream_info(AVFormatContext *ic, AVDictionary **options)
Read packets of a media file to get stream information.
Definition: utils.c:3498
static int write_output_file_trailer(AVFormatContext *output_format_context)
Write the trailer of the output file container.
void av_init_packet(AVPacket *pkt)
Initialize optional fields of a packet with default values.
Definition: avpacket.c:33
int den
Denominator.
Definition: rational.h:60
void avformat_close_input(AVFormatContext **s)
Close an opened input AVFormatContext.
Definition: utils.c:4339
Audio FIFO Buffer.
int channels
number of audio channels
Definition: avcodec.h:2524
int avformat_open_input(AVFormatContext **ps, const char *url, AVInputFormat *fmt, AVDictionary **options)
Open an input stream and read the header.
Definition: utils.c:510
int64_t av_get_default_channel_layout(int nb_channels)
Return default channel layout for a given number of channels.
int av_write_trailer(AVFormatContext *s)
Write the stream trailer to an output media file and free the file private data.
Definition: mux.c:1301
#define av_freep(p)
static int init_converted_samples(uint8_t ***converted_input_samples, AVCodecContext *output_codec_context, int frame_size)
Initialize a temporary storage for the specified number of audio samples.
AVCodecParameters * codecpar
Definition: avformat.h:1252
enum AVSampleFormat * sample_fmts
array of supported sample formats, or NULL if unknown, array is terminated by -1
Definition: avcodec.h:3762
static int init_output_frame(AVFrame **frame, AVCodecContext *output_codec_context, int frame_size)
Initialize one input frame for writing to the output file.
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avformat.h:926
uint8_t ** extended_data
pointers to the data planes/channels.
Definition: frame.h:248
This structure stores compressed data.
Definition: avcodec.h:1656
void av_register_all(void)
Initialize libavformat and register all the muxers, demuxers and protocols.
Definition: allformats.c:390
int avio_closep(AVIOContext **s)
Close the resource accessed by the AVIOContext *s, free it and set the pointer pointing to it to NULL...
Definition: aviobuf.c:1137
int nb_samples
number of audio samples (per channel) described by this frame
Definition: frame.h:267
int strict_std_compliance
strictly follow the standard (MPEG-4, ...).
Definition: avcodec.h:2981
av_cold int swr_init(struct SwrContext *s)
Initialize context after user parameters have been set.
Definition: swresample.c:152
static av_cold void cleanup(FlashSV2Context *s)
Definition: flashsv2enc.c:127