transcode_aac.c 33 KB

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