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.

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