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.

775 lines
28KB

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