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.

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