You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

820 lines
29KB

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