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.

771 lines
28KB

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