transcode_aac.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  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 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->ch_layout.nb_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->ch_layout.nb_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;
  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. av_channel_layout_copy(&(*frame)->ch_layout, &output_codec_context->ch_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. *data_present = 0;
  610. /* Send the audio frame stored in the temporary packet to the encoder.
  611. * The output audio stream encoder is used to do this. */
  612. error = avcodec_send_frame(output_codec_context, frame);
  613. /* Check for errors, but proceed with fetching encoded samples if the
  614. * encoder signals that it has nothing more to encode. */
  615. if (error < 0 && error != AVERROR_EOF) {
  616. fprintf(stderr, "Could not send packet for encoding (error '%s')\n",
  617. av_err2str(error));
  618. goto cleanup;
  619. }
  620. /* Receive one encoded frame from the encoder. */
  621. error = avcodec_receive_packet(output_codec_context, output_packet);
  622. /* If the encoder asks for more data to be able to provide an
  623. * encoded frame, return indicating that no data is present. */
  624. if (error == AVERROR(EAGAIN)) {
  625. error = 0;
  626. goto cleanup;
  627. /* If the last frame has been encoded, stop encoding. */
  628. } else if (error == AVERROR_EOF) {
  629. error = 0;
  630. goto cleanup;
  631. } else if (error < 0) {
  632. fprintf(stderr, "Could not encode frame (error '%s')\n",
  633. av_err2str(error));
  634. goto cleanup;
  635. /* Default case: Return encoded data. */
  636. } else {
  637. *data_present = 1;
  638. }
  639. /* Write one audio frame from the temporary packet to the output file. */
  640. if (*data_present &&
  641. (error = av_write_frame(output_format_context, output_packet)) < 0) {
  642. fprintf(stderr, "Could not write frame (error '%s')\n",
  643. av_err2str(error));
  644. goto cleanup;
  645. }
  646. cleanup:
  647. av_packet_free(&output_packet);
  648. return error;
  649. }
  650. /**
  651. * Load one audio frame from the FIFO buffer, encode and write it to the
  652. * output file.
  653. * @param fifo Buffer used for temporary storage
  654. * @param output_format_context Format context of the output file
  655. * @param output_codec_context Codec context of the output file
  656. * @return Error code (0 if successful)
  657. */
  658. static int load_encode_and_write(AVAudioFifo *fifo,
  659. AVFormatContext *output_format_context,
  660. AVCodecContext *output_codec_context)
  661. {
  662. /* Temporary storage of the output samples of the frame written to the file. */
  663. AVFrame *output_frame;
  664. /* Use the maximum number of possible samples per frame.
  665. * If there is less than the maximum possible frame size in the FIFO
  666. * buffer use this number. Otherwise, use the maximum possible frame size. */
  667. const int frame_size = FFMIN(av_audio_fifo_size(fifo),
  668. output_codec_context->frame_size);
  669. int data_written;
  670. /* Initialize temporary storage for one output frame. */
  671. if (init_output_frame(&output_frame, output_codec_context, frame_size))
  672. return AVERROR_EXIT;
  673. /* Read as many samples from the FIFO buffer as required to fill the frame.
  674. * The samples are stored in the frame temporarily. */
  675. if (av_audio_fifo_read(fifo, (void **)output_frame->data, frame_size) < frame_size) {
  676. fprintf(stderr, "Could not read data from FIFO\n");
  677. av_frame_free(&output_frame);
  678. return AVERROR_EXIT;
  679. }
  680. /* Encode one frame worth of audio samples. */
  681. if (encode_audio_frame(output_frame, output_format_context,
  682. output_codec_context, &data_written)) {
  683. av_frame_free(&output_frame);
  684. return AVERROR_EXIT;
  685. }
  686. av_frame_free(&output_frame);
  687. return 0;
  688. }
  689. /**
  690. * Write the trailer of the output file container.
  691. * @param output_format_context Format context of the output file
  692. * @return Error code (0 if successful)
  693. */
  694. static int write_output_file_trailer(AVFormatContext *output_format_context)
  695. {
  696. int error;
  697. if ((error = av_write_trailer(output_format_context)) < 0) {
  698. fprintf(stderr, "Could not write output file trailer (error '%s')\n",
  699. av_err2str(error));
  700. return error;
  701. }
  702. return 0;
  703. }
  704. int main(int argc, char **argv)
  705. {
  706. AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
  707. AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
  708. SwrContext *resample_context = NULL;
  709. AVAudioFifo *fifo = NULL;
  710. int ret = AVERROR_EXIT;
  711. if (argc != 3) {
  712. fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
  713. exit(1);
  714. }
  715. /* Open the input file for reading. */
  716. if (open_input_file(argv[1], &input_format_context,
  717. &input_codec_context))
  718. goto cleanup;
  719. /* Open the output file for writing. */
  720. if (open_output_file(argv[2], input_codec_context,
  721. &output_format_context, &output_codec_context))
  722. goto cleanup;
  723. /* Initialize the resampler to be able to convert audio sample formats. */
  724. if (init_resampler(input_codec_context, output_codec_context,
  725. &resample_context))
  726. goto cleanup;
  727. /* Initialize the FIFO buffer to store audio samples to be encoded. */
  728. if (init_fifo(&fifo, output_codec_context))
  729. goto cleanup;
  730. /* Write the header of the output file container. */
  731. if (write_output_file_header(output_format_context))
  732. goto cleanup;
  733. /* Loop as long as we have input samples to read or output samples
  734. * to write; abort as soon as we have neither. */
  735. while (1) {
  736. /* Use the encoder's desired frame size for processing. */
  737. const int output_frame_size = output_codec_context->frame_size;
  738. int finished = 0;
  739. /* Make sure that there is one frame worth of samples in the FIFO
  740. * buffer so that the encoder can do its work.
  741. * Since the decoder's and the encoder's frame size may differ, we
  742. * need to FIFO buffer to store as many frames worth of input samples
  743. * that they make up at least one frame worth of output samples. */
  744. while (av_audio_fifo_size(fifo) < output_frame_size) {
  745. /* Decode one frame worth of audio samples, convert it to the
  746. * output sample format and put it into the FIFO buffer. */
  747. if (read_decode_convert_and_store(fifo, input_format_context,
  748. input_codec_context,
  749. output_codec_context,
  750. resample_context, &finished))
  751. goto cleanup;
  752. /* If we are at the end of the input file, we continue
  753. * encoding the remaining audio samples to the output file. */
  754. if (finished)
  755. break;
  756. }
  757. /* If we have enough samples for the encoder, we encode them.
  758. * At the end of the file, we pass the remaining samples to
  759. * the encoder. */
  760. while (av_audio_fifo_size(fifo) >= output_frame_size ||
  761. (finished && av_audio_fifo_size(fifo) > 0))
  762. /* Take one frame worth of audio samples from the FIFO buffer,
  763. * encode it and write it to the output file. */
  764. if (load_encode_and_write(fifo, output_format_context,
  765. output_codec_context))
  766. goto cleanup;
  767. /* If we are at the end of the input file and have encoded
  768. * all remaining samples, we can exit this loop and finish. */
  769. if (finished) {
  770. int data_written;
  771. /* Flush the encoder as it may have delayed frames. */
  772. do {
  773. if (encode_audio_frame(NULL, output_format_context,
  774. output_codec_context, &data_written))
  775. goto cleanup;
  776. } while (data_written);
  777. break;
  778. }
  779. }
  780. /* Write the trailer of the output file container. */
  781. if (write_output_file_trailer(output_format_context))
  782. goto cleanup;
  783. ret = 0;
  784. cleanup:
  785. if (fifo)
  786. av_audio_fifo_free(fifo);
  787. swr_free(&resample_context);
  788. if (output_codec_context)
  789. avcodec_free_context(&output_codec_context);
  790. if (output_format_context) {
  791. avio_closep(&output_format_context->pb);
  792. avformat_free_context(output_format_context);
  793. }
  794. if (input_codec_context)
  795. avcodec_free_context(&input_codec_context);
  796. if (input_format_context)
  797. avformat_close_input(&input_format_context);
  798. return ret;
  799. }