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.

894 lines
34KB

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