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.

872 lines
34KB

  1. /*
  2. * Copyright (c) 2013-2017 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. /* Decode the audio frame stored in the temporary packet.
  355. * The input audio stream decoder is used to do this.
  356. * If we are at the end of the file, pass an empty packet to the decoder
  357. * to flush it. */
  358. if ((error = avcodec_decode_audio4(input_codec_context, frame,
  359. data_present, &input_packet)) < 0) {
  360. fprintf(stderr, "Could not decode frame (error '%s')\n",
  361. get_error_text(error));
  362. av_packet_unref(&input_packet);
  363. return error;
  364. }
  365. /* If the decoder has not been flushed completely, we are not finished,
  366. * so that this function has to be called again. */
  367. if (*finished && *data_present)
  368. *finished = 0;
  369. av_packet_unref(&input_packet);
  370. return 0;
  371. }
  372. /**
  373. * Initialize a temporary storage for the specified number of audio samples.
  374. * The conversion requires temporary storage due to the different format.
  375. * The number of audio samples to be allocated is specified in frame_size.
  376. * @param[out] converted_input_samples Array of converted samples. The
  377. * dimensions are reference, channel
  378. * (for multi-channel audio), sample.
  379. * @param output_codec_context Codec context of the output file
  380. * @param frame_size Number of samples to be converted in
  381. * each round
  382. * @return Error code (0 if successful)
  383. */
  384. static int init_converted_samples(uint8_t ***converted_input_samples,
  385. AVCodecContext *output_codec_context,
  386. int frame_size)
  387. {
  388. int error;
  389. /* Allocate as many pointers as there are audio channels.
  390. * Each pointer will later point to the audio samples of the corresponding
  391. * channels (although it may be NULL for interleaved formats).
  392. */
  393. if (!(*converted_input_samples = calloc(output_codec_context->channels,
  394. sizeof(**converted_input_samples)))) {
  395. fprintf(stderr, "Could not allocate converted input sample pointers\n");
  396. return AVERROR(ENOMEM);
  397. }
  398. /* Allocate memory for the samples of all channels in one consecutive
  399. * block for convenience. */
  400. if ((error = av_samples_alloc(*converted_input_samples, NULL,
  401. output_codec_context->channels,
  402. frame_size,
  403. output_codec_context->sample_fmt, 0)) < 0) {
  404. fprintf(stderr,
  405. "Could not allocate converted input samples (error '%s')\n",
  406. get_error_text(error));
  407. av_freep(&(*converted_input_samples)[0]);
  408. free(*converted_input_samples);
  409. return error;
  410. }
  411. return 0;
  412. }
  413. /**
  414. * Convert the input audio samples into the output sample format.
  415. * The conversion happens on a per-frame basis, the size of which is
  416. * specified by frame_size.
  417. * @param input_data Samples to be decoded. The dimensions are
  418. * channel (for multi-channel audio), sample.
  419. * @param[out] converted_data Converted samples. The dimensions are channel
  420. * (for multi-channel audio), sample.
  421. * @param frame_size Number of samples to be converted
  422. * @param resample_context Resample context for the conversion
  423. * @return Error code (0 if successful)
  424. */
  425. static int convert_samples(uint8_t **input_data,
  426. uint8_t **converted_data, const int frame_size,
  427. AVAudioResampleContext *resample_context)
  428. {
  429. int error;
  430. /* Convert the samples using the resampler. */
  431. if ((error = avresample_convert(resample_context, converted_data, 0,
  432. frame_size, input_data, 0, frame_size)) < 0) {
  433. fprintf(stderr, "Could not convert input samples (error '%s')\n",
  434. get_error_text(error));
  435. return error;
  436. }
  437. /* Perform a sanity check so that the number of converted samples is
  438. * not greater than the number of samples to be converted.
  439. * If the sample rates differ, this case has to be handled differently. */
  440. if (avresample_available(resample_context)) {
  441. fprintf(stderr, "Converted samples left over\n");
  442. return AVERROR_EXIT;
  443. }
  444. return 0;
  445. }
  446. /**
  447. * Add converted input audio samples to the FIFO buffer for later processing.
  448. * @param fifo Buffer to add the samples to
  449. * @param converted_input_samples Samples to be added. The dimensions are channel
  450. * (for multi-channel audio), sample.
  451. * @param frame_size Number of samples to be converted
  452. * @return Error code (0 if successful)
  453. */
  454. static int add_samples_to_fifo(AVAudioFifo *fifo,
  455. uint8_t **converted_input_samples,
  456. const int frame_size)
  457. {
  458. int error;
  459. /* Make the FIFO as large as it needs to be to hold both,
  460. * the old and the new samples. */
  461. if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
  462. fprintf(stderr, "Could not reallocate FIFO\n");
  463. return error;
  464. }
  465. /* Store the new samples in the FIFO buffer. */
  466. if (av_audio_fifo_write(fifo, (void **)converted_input_samples,
  467. frame_size) < frame_size) {
  468. fprintf(stderr, "Could not write data to FIFO\n");
  469. return AVERROR_EXIT;
  470. }
  471. return 0;
  472. }
  473. /**
  474. * Read one audio frame from the input file, decode, convert and store
  475. * it in the FIFO buffer.
  476. * @param fifo Buffer used for temporary storage
  477. * @param input_format_context Format context of the input file
  478. * @param input_codec_context Codec context of the input file
  479. * @param output_codec_context Codec context of the output file
  480. * @param resample_context Resample context for the conversion
  481. * @param[out] finished Indicates whether the end of file has
  482. * been reached and all data has been
  483. * decoded. If this flag is false,
  484. * there is more data to be decoded,
  485. * i.e., this function has to be called
  486. * again.
  487. * @return Error code (0 if successful)
  488. */
  489. static int read_decode_convert_and_store(AVAudioFifo *fifo,
  490. AVFormatContext *input_format_context,
  491. AVCodecContext *input_codec_context,
  492. AVCodecContext *output_codec_context,
  493. AVAudioResampleContext *resample_context,
  494. int *finished)
  495. {
  496. /* Temporary storage of the input samples of the frame read from the file. */
  497. AVFrame *input_frame = NULL;
  498. /* Temporary storage for the converted input samples. */
  499. uint8_t **converted_input_samples = NULL;
  500. int data_present;
  501. int ret = AVERROR_EXIT;
  502. /* Initialize temporary storage for one input frame. */
  503. if (init_input_frame(&input_frame))
  504. goto cleanup;
  505. /* Decode one frame worth of audio samples. */
  506. if (decode_audio_frame(input_frame, input_format_context,
  507. input_codec_context, &data_present, finished))
  508. goto cleanup;
  509. /* If we are at the end of the file and there are no more samples
  510. * in the decoder which are delayed, we are actually finished.
  511. * This must not be treated as an error. */
  512. if (*finished && !data_present) {
  513. ret = 0;
  514. goto cleanup;
  515. }
  516. /* If there is decoded data, convert and store it. */
  517. if (data_present) {
  518. /* Initialize the temporary storage for the converted input samples. */
  519. if (init_converted_samples(&converted_input_samples, output_codec_context,
  520. input_frame->nb_samples))
  521. goto cleanup;
  522. /* Convert the input samples to the desired output sample format.
  523. * This requires a temporary storage provided by converted_input_samples. */
  524. if (convert_samples(input_frame->extended_data, converted_input_samples,
  525. input_frame->nb_samples, resample_context))
  526. goto cleanup;
  527. /* Add the converted input samples to the FIFO buffer for later processing. */
  528. if (add_samples_to_fifo(fifo, converted_input_samples,
  529. input_frame->nb_samples))
  530. goto cleanup;
  531. ret = 0;
  532. }
  533. ret = 0;
  534. cleanup:
  535. if (converted_input_samples) {
  536. av_freep(&converted_input_samples[0]);
  537. free(converted_input_samples);
  538. }
  539. av_frame_free(&input_frame);
  540. return ret;
  541. }
  542. /**
  543. * Initialize one input frame for writing to the output file.
  544. * The frame will be exactly frame_size samples large.
  545. * @param[out] frame Frame to be initialized
  546. * @param output_codec_context Codec context of the output file
  547. * @param frame_size Size of the frame
  548. * @return Error code (0 if successful)
  549. */
  550. static int init_output_frame(AVFrame **frame,
  551. AVCodecContext *output_codec_context,
  552. int frame_size)
  553. {
  554. int error;
  555. /* Create a new frame to store the audio samples. */
  556. if (!(*frame = av_frame_alloc())) {
  557. fprintf(stderr, "Could not allocate output frame\n");
  558. return AVERROR_EXIT;
  559. }
  560. /* Set the frame's parameters, especially its size and format.
  561. * av_frame_get_buffer needs this to allocate memory for the
  562. * audio samples of the frame.
  563. * Default channel layouts based on the number of channels
  564. * are assumed for simplicity. */
  565. (*frame)->nb_samples = frame_size;
  566. (*frame)->channel_layout = output_codec_context->channel_layout;
  567. (*frame)->format = output_codec_context->sample_fmt;
  568. (*frame)->sample_rate = output_codec_context->sample_rate;
  569. /* Allocate the samples of the created frame. This call will make
  570. * sure that the audio frame can hold as many samples as specified. */
  571. if ((error = av_frame_get_buffer(*frame, 0)) < 0) {
  572. fprintf(stderr, "Could not allocate output frame samples (error '%s')\n",
  573. get_error_text(error));
  574. av_frame_free(frame);
  575. return error;
  576. }
  577. return 0;
  578. }
  579. /* Global timestamp for the audio frames. */
  580. static int64_t pts = 0;
  581. /**
  582. * Encode one frame worth of audio to the output file.
  583. * @param frame Samples to be encoded
  584. * @param output_format_context Format context of the output file
  585. * @param output_codec_context Codec context of the output file
  586. * @param[out] data_present Indicates whether data has been
  587. * decoded
  588. * @return Error code (0 if successful)
  589. */
  590. static int encode_audio_frame(AVFrame *frame,
  591. AVFormatContext *output_format_context,
  592. AVCodecContext *output_codec_context,
  593. int *data_present)
  594. {
  595. /* Packet used for temporary storage. */
  596. AVPacket output_packet;
  597. int error;
  598. init_packet(&output_packet);
  599. /* Set a timestamp based on the sample rate for the container. */
  600. if (frame) {
  601. frame->pts = pts;
  602. pts += frame->nb_samples;
  603. }
  604. /* Encode the audio frame and store it in the temporary packet.
  605. * The output audio stream encoder is used to do this. */
  606. if ((error = avcodec_encode_audio2(output_codec_context, &output_packet,
  607. frame, data_present)) < 0) {
  608. fprintf(stderr, "Could not encode frame (error '%s')\n",
  609. get_error_text(error));
  610. av_packet_unref(&output_packet);
  611. return error;
  612. }
  613. /* Write one audio frame from the temporary packet to the output file. */
  614. if (*data_present) {
  615. if ((error = av_write_frame(output_format_context, &output_packet)) < 0) {
  616. fprintf(stderr, "Could not write frame (error '%s')\n",
  617. get_error_text(error));
  618. av_packet_unref(&output_packet);
  619. return error;
  620. }
  621. av_packet_unref(&output_packet);
  622. }
  623. return 0;
  624. }
  625. /**
  626. * Load one audio frame from the FIFO buffer, encode and write it to the
  627. * output file.
  628. * @param fifo Buffer used for temporary storage
  629. * @param output_format_context Format context of the output file
  630. * @param output_codec_context Codec context of the output file
  631. * @return Error code (0 if successful)
  632. */
  633. static int load_encode_and_write(AVAudioFifo *fifo,
  634. AVFormatContext *output_format_context,
  635. AVCodecContext *output_codec_context)
  636. {
  637. /* Temporary storage of the output samples of the frame written to the file. */
  638. AVFrame *output_frame;
  639. /* Use the maximum number of possible samples per frame.
  640. * If there is less than the maximum possible frame size in the FIFO
  641. * buffer use this number. Otherwise, use the maximum possible frame size. */
  642. const int frame_size = FFMIN(av_audio_fifo_size(fifo),
  643. output_codec_context->frame_size);
  644. int data_written;
  645. /* Initialize temporary storage for one output frame. */
  646. if (init_output_frame(&output_frame, output_codec_context, frame_size))
  647. return AVERROR_EXIT;
  648. /* Read as many samples from the FIFO buffer as required to fill the frame.
  649. * The samples are stored in the frame temporarily. */
  650. if (av_audio_fifo_read(fifo, (void **)output_frame->data, frame_size) < frame_size) {
  651. fprintf(stderr, "Could not read data from FIFO\n");
  652. av_frame_free(&output_frame);
  653. return AVERROR_EXIT;
  654. }
  655. /* Encode one frame worth of audio samples. */
  656. if (encode_audio_frame(output_frame, output_format_context,
  657. output_codec_context, &data_written)) {
  658. av_frame_free(&output_frame);
  659. return AVERROR_EXIT;
  660. }
  661. av_frame_free(&output_frame);
  662. return 0;
  663. }
  664. /**
  665. * Write the trailer of the output file container.
  666. * @param output_format_context Format context of the output file
  667. * @return Error code (0 if successful)
  668. */
  669. static int write_output_file_trailer(AVFormatContext *output_format_context)
  670. {
  671. int error;
  672. if ((error = av_write_trailer(output_format_context)) < 0) {
  673. fprintf(stderr, "Could not write output file trailer (error '%s')\n",
  674. get_error_text(error));
  675. return error;
  676. }
  677. return 0;
  678. }
  679. int main(int argc, char **argv)
  680. {
  681. AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
  682. AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
  683. AVAudioResampleContext *resample_context = NULL;
  684. AVAudioFifo *fifo = NULL;
  685. int ret = AVERROR_EXIT;
  686. if (argc != 3) {
  687. fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
  688. exit(1);
  689. }
  690. /* Register all codecs and formats so that they can be used. */
  691. av_register_all();
  692. /* Open the input file for reading. */
  693. if (open_input_file(argv[1], &input_format_context,
  694. &input_codec_context))
  695. goto cleanup;
  696. /* Open the output file for writing. */
  697. if (open_output_file(argv[2], input_codec_context,
  698. &output_format_context, &output_codec_context))
  699. goto cleanup;
  700. /* Initialize the resampler to be able to convert audio sample formats. */
  701. if (init_resampler(input_codec_context, output_codec_context,
  702. &resample_context))
  703. goto cleanup;
  704. /* Initialize the FIFO buffer to store audio samples to be encoded. */
  705. if (init_fifo(&fifo, output_codec_context))
  706. goto cleanup;
  707. /* Write the header of the output file container. */
  708. if (write_output_file_header(output_format_context))
  709. goto cleanup;
  710. /* Loop as long as we have input samples to read or output samples
  711. * to write; abort as soon as we have neither. */
  712. while (1) {
  713. /* Use the encoder's desired frame size for processing. */
  714. const int output_frame_size = output_codec_context->frame_size;
  715. int finished = 0;
  716. /* Make sure that there is one frame worth of samples in the FIFO
  717. * buffer so that the encoder can do its work.
  718. * Since the decoder's and the encoder's frame size may differ, we
  719. * need to FIFO buffer to store as many frames worth of input samples
  720. * that they make up at least one frame worth of output samples. */
  721. while (av_audio_fifo_size(fifo) < output_frame_size) {
  722. /* Decode one frame worth of audio samples, convert it to the
  723. * output sample format and put it into the FIFO buffer. */
  724. if (read_decode_convert_and_store(fifo, input_format_context,
  725. input_codec_context,
  726. output_codec_context,
  727. resample_context, &finished))
  728. goto cleanup;
  729. /* If we are at the end of the input file, we continue
  730. * encoding the remaining audio samples to the output file. */
  731. if (finished)
  732. break;
  733. }
  734. /* If we have enough samples for the encoder, we encode them.
  735. * At the end of the file, we pass the remaining samples to
  736. * the encoder. */
  737. while (av_audio_fifo_size(fifo) >= output_frame_size ||
  738. (finished && av_audio_fifo_size(fifo) > 0))
  739. /* Take one frame worth of audio samples from the FIFO buffer,
  740. * encode it and write it to the output file. */
  741. if (load_encode_and_write(fifo, output_format_context,
  742. output_codec_context))
  743. goto cleanup;
  744. /* If we are at the end of the input file and have encoded
  745. * all remaining samples, we can exit this loop and finish. */
  746. if (finished) {
  747. int data_written;
  748. /* Flush the encoder as it may have delayed frames. */
  749. do {
  750. if (encode_audio_frame(NULL, output_format_context,
  751. output_codec_context, &data_written))
  752. goto cleanup;
  753. } while (data_written);
  754. break;
  755. }
  756. }
  757. /* Write the trailer of the output file container. */
  758. if (write_output_file_trailer(output_format_context))
  759. goto cleanup;
  760. ret = 0;
  761. cleanup:
  762. if (fifo)
  763. av_audio_fifo_free(fifo);
  764. if (resample_context) {
  765. avresample_close(resample_context);
  766. avresample_free(&resample_context);
  767. }
  768. if (output_codec_context)
  769. avcodec_free_context(&output_codec_context);
  770. if (output_format_context) {
  771. avio_close(output_format_context->pb);
  772. avformat_free_context(output_format_context);
  773. }
  774. if (input_codec_context)
  775. avcodec_free_context(&input_codec_context);
  776. if (input_format_context)
  777. avformat_close_input(&input_format_context);
  778. return ret;
  779. }