transcode_aac.c 33 KB

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