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.

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