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.

909 lines
35KB

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