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.

773 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 48000
  37. /** The number of output channels */
  38. #define OUTPUT_CHANNELS 2
  39. /** The audio sample output format */
  40. #define OUTPUT_SAMPLE_FORMAT AV_SAMPLE_FMT_S16
  41. /**
  42. * Convert an error code into a text message.
  43. * @param error Error code to be converted
  44. * @return Corresponding error text (not thread-safe)
  45. */
  46. static char *const get_error_text(const int error)
  47. {
  48. static char error_buffer[255];
  49. av_strerror(error, error_buffer, sizeof(error_buffer));
  50. return error_buffer;
  51. }
  52. /** Open an input file and the required decoder. */
  53. static int open_input_file(const char *filename,
  54. AVFormatContext **input_format_context,
  55. AVCodecContext **input_codec_context)
  56. {
  57. AVCodec *input_codec;
  58. int error;
  59. /** Open the input file to read from it. */
  60. if ((error = avformat_open_input(input_format_context, filename, NULL,
  61. NULL)) < 0) {
  62. fprintf(stderr, "Could not open input file '%s' (error '%s')\n",
  63. filename, get_error_text(error));
  64. *input_format_context = NULL;
  65. return error;
  66. }
  67. /** Get information on the input file (number of streams etc.). */
  68. if ((error = avformat_find_stream_info(*input_format_context, NULL)) < 0) {
  69. fprintf(stderr, "Could not open find stream info (error '%s')\n",
  70. get_error_text(error));
  71. avformat_close_input(input_format_context);
  72. return error;
  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. /** Find a decoder for the audio stream. */
  82. if (!(input_codec = avcodec_find_decoder((*input_format_context)->streams[0]->codec->codec_id))) {
  83. fprintf(stderr, "Could not find input codec\n");
  84. avformat_close_input(input_format_context);
  85. return AVERROR_EXIT;
  86. }
  87. /** Open the decoder for the audio stream to use it later. */
  88. if ((error = avcodec_open2((*input_format_context)->streams[0]->codec,
  89. input_codec, NULL)) < 0) {
  90. fprintf(stderr, "Could not open input codec (error '%s')\n",
  91. get_error_text(error));
  92. avformat_close_input(input_format_context);
  93. return error;
  94. }
  95. /** Save the decoder context for easier access later. */
  96. *input_codec_context = (*input_format_context)->streams[0]->codec;
  97. return 0;
  98. }
  99. /**
  100. * Open an output file and the required encoder.
  101. * Also set some basic encoder parameters.
  102. * Some of these parameters are based on the input file's parameters.
  103. */
  104. static int open_output_file(const char *filename,
  105. AVCodecContext *input_codec_context,
  106. AVFormatContext **output_format_context,
  107. AVCodecContext **output_codec_context)
  108. {
  109. AVIOContext *output_io_context = NULL;
  110. AVStream *stream = NULL;
  111. AVCodec *output_codec = NULL;
  112. int error;
  113. /** Open the output file to write to it. */
  114. if ((error = avio_open(&output_io_context, filename,
  115. AVIO_FLAG_WRITE)) < 0) {
  116. fprintf(stderr, "Could not open output file '%s' (error '%s')\n",
  117. filename, get_error_text(error));
  118. return error;
  119. }
  120. /** Create a new format context for the output container format. */
  121. if (!(*output_format_context = avformat_alloc_context())) {
  122. fprintf(stderr, "Could not allocate output format context\n");
  123. return AVERROR(ENOMEM);
  124. }
  125. /** Associate the output file (pointer) with the container format context. */
  126. (*output_format_context)->pb = output_io_context;
  127. /** Guess the desired container format based on the file extension. */
  128. if (!((*output_format_context)->oformat = av_guess_format(NULL, filename,
  129. NULL))) {
  130. fprintf(stderr, "Could not find output file format\n");
  131. goto cleanup;
  132. }
  133. av_strlcpy((*output_format_context)->filename, filename,
  134. sizeof((*output_format_context)->filename));
  135. /** Find the encoder to be used by its name. */
  136. if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_AAC))) {
  137. fprintf(stderr, "Could not find an AAC encoder.\n");
  138. goto cleanup;
  139. }
  140. /** Create a new audio stream in the output file container. */
  141. if (!(stream = avformat_new_stream(*output_format_context, output_codec))) {
  142. fprintf(stderr, "Could not create new stream\n");
  143. error = AVERROR(ENOMEM);
  144. goto cleanup;
  145. }
  146. /** Save the encoder context for easiert access later. */
  147. *output_codec_context = stream->codec;
  148. /**
  149. * Set the basic encoder parameters.
  150. * The input file's sample rate is used to avoid a sample rate conversion.
  151. */
  152. (*output_codec_context)->channels = OUTPUT_CHANNELS;
  153. (*output_codec_context)->channel_layout = av_get_default_channel_layout(OUTPUT_CHANNELS);
  154. (*output_codec_context)->sample_rate = input_codec_context->sample_rate;
  155. (*output_codec_context)->sample_fmt = AV_SAMPLE_FMT_S16;
  156. (*output_codec_context)->bit_rate = OUTPUT_BIT_RATE;
  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)
  243. {
  244. /** Create the FIFO buffer based on the specified output sample format. */
  245. if (!(*fifo = av_audio_fifo_alloc(OUTPUT_SAMPLE_FORMAT, OUTPUT_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 the 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(uint8_t **input_data,
  348. uint8_t **converted_data, const int frame_size,
  349. AVAudioResampleContext *resample_context)
  350. {
  351. int error;
  352. /** Convert the samples using the resampler. */
  353. if ((error = avresample_convert(resample_context, converted_data, 0,
  354. frame_size, input_data, 0, frame_size)) < 0) {
  355. fprintf(stderr, "Could not convert input samples (error '%s')\n",
  356. get_error_text(error));
  357. return error;
  358. }
  359. /**
  360. * Perform a sanity check so that the number of converted samples is
  361. * not greater than the number of samples to be converted.
  362. * If the sample rates differ, this case has to be handled differently
  363. */
  364. if (avresample_available(resample_context)) {
  365. fprintf(stderr, "Converted samples left over\n");
  366. return AVERROR_EXIT;
  367. }
  368. return 0;
  369. }
  370. /** Add converted input audio samples to the FIFO buffer for later processing. */
  371. static int add_samples_to_fifo(AVAudioFifo *fifo,
  372. uint8_t **converted_input_samples,
  373. const int frame_size)
  374. {
  375. int error;
  376. /**
  377. * Make the FIFO as large as it needs to be to hold both,
  378. * the old and the new samples.
  379. */
  380. if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
  381. fprintf(stderr, "Could not reallocate FIFO\n");
  382. return error;
  383. }
  384. /** Store the new samples in the FIFO buffer. */
  385. if (av_audio_fifo_write(fifo, (void **)converted_input_samples,
  386. frame_size) < frame_size) {
  387. fprintf(stderr, "Could not write data to FIFO\n");
  388. return AVERROR_EXIT;
  389. }
  390. return 0;
  391. }
  392. /**
  393. * Read one audio frame from the input file, decodes, converts and stores
  394. * it in the FIFO buffer.
  395. */
  396. static int read_decode_convert_and_store(AVAudioFifo *fifo,
  397. AVFormatContext *input_format_context,
  398. AVCodecContext *input_codec_context,
  399. AVCodecContext *output_codec_context,
  400. AVAudioResampleContext *resampler_context,
  401. int *finished)
  402. {
  403. /** Temporary storage of the input samples of the frame read from the file. */
  404. AVFrame *input_frame = NULL;
  405. /** Temporary storage for the converted input samples. */
  406. uint8_t **converted_input_samples = NULL;
  407. int data_present;
  408. int ret = AVERROR_EXIT;
  409. /** Initialize temporary storage for one input frame. */
  410. if (init_input_frame(&input_frame))
  411. goto cleanup;
  412. /** Decode one frame worth of audio samples. */
  413. if (decode_audio_frame(input_frame, input_format_context,
  414. input_codec_context, &data_present, finished))
  415. goto cleanup;
  416. /**
  417. * If we are at the end of the file and there are no more samples
  418. * in the decoder which are delayed, we are actually finished.
  419. * This must not be treated as an error.
  420. */
  421. if (*finished && !data_present) {
  422. ret = 0;
  423. goto cleanup;
  424. }
  425. /** If there is decoded data, convert and store it */
  426. if (data_present) {
  427. /** Initialize the temporary storage for the converted input samples. */
  428. if (init_converted_samples(&converted_input_samples, output_codec_context,
  429. input_frame->nb_samples))
  430. goto cleanup;
  431. /**
  432. * Convert the input samples to the desired output sample format.
  433. * This requires a temporary storage provided by converted_input_samples.
  434. */
  435. if (convert_samples(input_frame->extended_data, converted_input_samples,
  436. input_frame->nb_samples, resampler_context))
  437. goto cleanup;
  438. /** Add the converted input samples to the FIFO buffer for later processing. */
  439. if (add_samples_to_fifo(fifo, converted_input_samples,
  440. input_frame->nb_samples))
  441. goto cleanup;
  442. ret = 0;
  443. }
  444. ret = 0;
  445. cleanup:
  446. if (converted_input_samples) {
  447. av_freep(&converted_input_samples[0]);
  448. free(converted_input_samples);
  449. }
  450. av_frame_free(&input_frame);
  451. return ret;
  452. }
  453. /**
  454. * Initialize one input frame for writing to the output file.
  455. * The frame will be exactly frame_size samples large.
  456. */
  457. static int init_output_frame(AVFrame **frame,
  458. AVCodecContext *output_codec_context,
  459. int frame_size)
  460. {
  461. int error;
  462. /** Create a new frame to store the audio samples. */
  463. if (!(*frame = av_frame_alloc())) {
  464. fprintf(stderr, "Could not allocate output frame\n");
  465. return AVERROR_EXIT;
  466. }
  467. /**
  468. * Set the frame's parameters, especially its size and format.
  469. * av_frame_get_buffer needs this to allocate memory for the
  470. * audio samples of the frame.
  471. * Default channel layouts based on the number of channels
  472. * are assumed for simplicity.
  473. */
  474. (*frame)->nb_samples = frame_size;
  475. (*frame)->channel_layout = output_codec_context->channel_layout;
  476. (*frame)->format = output_codec_context->sample_fmt;
  477. (*frame)->sample_rate = output_codec_context->sample_rate;
  478. /**
  479. * Allocate the samples of the created frame. This call will make
  480. * sure that the audio frame can hold as many samples as specified.
  481. */
  482. if ((error = av_frame_get_buffer(*frame, 0)) < 0) {
  483. fprintf(stderr, "Could allocate output frame samples (error '%s')\n",
  484. get_error_text(error));
  485. av_frame_free(frame);
  486. return error;
  487. }
  488. return 0;
  489. }
  490. /** Encode one frame worth of audio to the output file. */
  491. static int encode_audio_frame(AVFrame *frame,
  492. AVFormatContext *output_format_context,
  493. AVCodecContext *output_codec_context,
  494. int *data_present)
  495. {
  496. /** Packet used for temporary storage. */
  497. AVPacket output_packet;
  498. int error;
  499. init_packet(&output_packet);
  500. /**
  501. * Encode the audio frame and store it in the temporary packet.
  502. * The output audio stream encoder is used to do this.
  503. */
  504. if ((error = avcodec_encode_audio2(output_codec_context, &output_packet,
  505. frame, data_present)) < 0) {
  506. fprintf(stderr, "Could not encode frame (error '%s')\n",
  507. get_error_text(error));
  508. av_free_packet(&output_packet);
  509. return error;
  510. }
  511. /** Write one audio frame from the temporary packet to the output file. */
  512. if (*data_present) {
  513. if ((error = av_write_frame(output_format_context, &output_packet)) < 0) {
  514. fprintf(stderr, "Could not write frame (error '%s')\n",
  515. get_error_text(error));
  516. av_free_packet(&output_packet);
  517. return error;
  518. }
  519. av_free_packet(&output_packet);
  520. }
  521. return 0;
  522. }
  523. /**
  524. * Load one audio frame from the FIFO buffer, encode and write it to the
  525. * output file.
  526. */
  527. static int load_encode_and_write(AVAudioFifo *fifo,
  528. AVFormatContext *output_format_context,
  529. AVCodecContext *output_codec_context)
  530. {
  531. /** Temporary storage of the output samples of the frame written to the file. */
  532. AVFrame *output_frame;
  533. /**
  534. * Use the maximum number of possible samples per frame.
  535. * If there is less than the maximum possible frame size in the FIFO
  536. * buffer use this number. Otherwise, use the maximum possible frame size
  537. */
  538. const int frame_size = FFMIN(av_audio_fifo_size(fifo),
  539. output_codec_context->frame_size);
  540. int data_written;
  541. /** Initialize temporary storage for one output frame. */
  542. if (init_output_frame(&output_frame, output_codec_context, frame_size))
  543. return AVERROR_EXIT;
  544. /**
  545. * Read as many samples from the FIFO buffer as required to fill the frame.
  546. * The samples are stored in the frame temporarily.
  547. */
  548. if (av_audio_fifo_read(fifo, (void **)output_frame->data, frame_size) < frame_size) {
  549. fprintf(stderr, "Could not read data from FIFO\n");
  550. av_frame_free(&output_frame);
  551. return AVERROR_EXIT;
  552. }
  553. /** Encode one frame worth of audio samples. */
  554. if (encode_audio_frame(output_frame, output_format_context,
  555. output_codec_context, &data_written)) {
  556. av_frame_free(&output_frame);
  557. return AVERROR_EXIT;
  558. }
  559. av_frame_free(&output_frame);
  560. return 0;
  561. }
  562. /** Write the trailer of the output file container. */
  563. static int write_output_file_trailer(AVFormatContext *output_format_context)
  564. {
  565. int error;
  566. if ((error = av_write_trailer(output_format_context)) < 0) {
  567. fprintf(stderr, "Could not write output file trailer (error '%s')\n",
  568. get_error_text(error));
  569. return error;
  570. }
  571. return 0;
  572. }
  573. /** Convert an audio file to an AAC file in an MP4 container. */
  574. int main(int argc, char **argv)
  575. {
  576. AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
  577. AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
  578. AVAudioResampleContext *resample_context = NULL;
  579. AVAudioFifo *fifo = NULL;
  580. int ret = AVERROR_EXIT;
  581. if (argc < 3) {
  582. fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
  583. exit(1);
  584. }
  585. /** Register all codecs and formats so that they can be used. */
  586. av_register_all();
  587. /** Open the input file for reading. */
  588. if (open_input_file(argv[1], &input_format_context,
  589. &input_codec_context))
  590. goto cleanup;
  591. /** Open the output file for writing. */
  592. if (open_output_file(argv[2], input_codec_context,
  593. &output_format_context, &output_codec_context))
  594. goto cleanup;
  595. /** Initialize the resampler to be able to convert audio sample formats. */
  596. if (init_resampler(input_codec_context, output_codec_context,
  597. &resample_context))
  598. goto cleanup;
  599. /** Initialize the FIFO buffer to store audio samples to be encoded. */
  600. if (init_fifo(&fifo))
  601. goto cleanup;
  602. /** Write the header of the output file container. */
  603. if (write_output_file_header(output_format_context))
  604. goto cleanup;
  605. /**
  606. * Loop as long as we have input samples to read or output samples
  607. * to write; abort as soon as we have neither.
  608. */
  609. while (1) {
  610. /** Use the encoder's desired frame size for processing. */
  611. const int output_frame_size = output_codec_context->frame_size;
  612. int finished = 0;
  613. /**
  614. * Make sure that there is one frame worth of samples in the FIFO
  615. * buffer so that the encoder can do its work.
  616. * Since the decoder's and the encoder's frame size may differ, we
  617. * need to FIFO buffer to store as many frames worth of input samples
  618. * that they make up at least one frame worth of output samples.
  619. */
  620. while (av_audio_fifo_size(fifo) < output_frame_size) {
  621. /**
  622. * Decode one frame worth of audio samples, convert it to the
  623. * output sample format and put it into the FIFO buffer.
  624. */
  625. if (read_decode_convert_and_store(fifo, input_format_context,
  626. input_codec_context,
  627. output_codec_context,
  628. resample_context, &finished))
  629. goto cleanup;
  630. /**
  631. * If we are at the end of the input file, we continue
  632. * encoding the remaining audio samples to the output file.
  633. */
  634. if (finished)
  635. break;
  636. }
  637. /**
  638. * If we have enough samples for the encoder, we encode them.
  639. * At the end of the file, we pass the remaining samples to
  640. * the encoder.
  641. */
  642. while (av_audio_fifo_size(fifo) >= output_frame_size ||
  643. (finished && av_audio_fifo_size(fifo) > 0))
  644. /**
  645. * Take one frame worth of audio samples from the FIFO buffer,
  646. * encode it and write it to the output file.
  647. */
  648. if (load_encode_and_write(fifo, output_format_context,
  649. output_codec_context))
  650. goto cleanup;
  651. /**
  652. * If we are at the end of the input file and have encoded
  653. * all remaining samples, we can exit this loop and finish.
  654. */
  655. if (finished) {
  656. int data_written;
  657. /** Flush the encoder as it may have delayed frames. */
  658. do {
  659. if (encode_audio_frame(NULL, output_format_context,
  660. output_codec_context, &data_written))
  661. goto cleanup;
  662. } while (data_written);
  663. break;
  664. }
  665. }
  666. /** Write the trailer of the output file container. */
  667. if (write_output_file_trailer(output_format_context))
  668. goto cleanup;
  669. ret = 0;
  670. cleanup:
  671. if (fifo)
  672. av_audio_fifo_free(fifo);
  673. if (resample_context) {
  674. avresample_close(resample_context);
  675. avresample_free(&resample_context);
  676. }
  677. if (output_codec_context)
  678. avcodec_close(output_codec_context);
  679. if (output_format_context) {
  680. avio_close(output_format_context->pb);
  681. avformat_free_context(output_format_context);
  682. }
  683. if (input_codec_context)
  684. avcodec_close(input_codec_context);
  685. if (input_format_context)
  686. avformat_close_input(&input_format_context);
  687. return ret;
  688. }