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.

849 lines
33KB

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