transcode_aac.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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
  22. * Simple audio converter
  23. *
  24. * @example transcode_aac.c
  25. * Convert an input audio file to AAC in an MP4 container using FFmpeg.
  26. * Formats other than MP4 are supported based on the output file extension.
  27. * @author Andreas Unterweger (dustsigns@gmail.com)
  28. */
  29. #include <stdio.h>
  30. #include "libavformat/avformat.h"
  31. #include "libavformat/avio.h"
  32. #include "libavcodec/avcodec.h"
  33. #include "libavutil/audio_fifo.h"
  34. #include "libavutil/avassert.h"
  35. #include "libavutil/avstring.h"
  36. #include "libavutil/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 later point to the audio samples of the corresponding
  401. * channels (although it may be NULL for interleaved formats).
  402. */
  403. if (!(*converted_input_samples = calloc(output_codec_context->ch_layout.nb_channels,
  404. sizeof(**converted_input_samples)))) {
  405. fprintf(stderr, "Could not allocate converted input sample pointers\n");
  406. return AVERROR(ENOMEM);
  407. }
  408. /* Allocate memory for the samples of all channels in one consecutive
  409. * block for convenience. */
  410. if ((error = av_samples_alloc(*converted_input_samples, NULL,
  411. output_codec_context->ch_layout.nb_channels,
  412. frame_size,
  413. output_codec_context->sample_fmt, 0)) < 0) {
  414. fprintf(stderr,
  415. "Could not allocate converted input samples (error '%s')\n",
  416. av_err2str(error));
  417. av_freep(&(*converted_input_samples)[0]);
  418. free(*converted_input_samples);
  419. return error;
  420. }
  421. return 0;
  422. }
  423. /**
  424. * Convert the input audio samples into the output sample format.
  425. * The conversion happens on a per-frame basis, the size of which is
  426. * specified by frame_size.
  427. * @param input_data Samples to be decoded. The dimensions are
  428. * channel (for multi-channel audio), sample.
  429. * @param[out] converted_data Converted samples. The dimensions are channel
  430. * (for multi-channel audio), sample.
  431. * @param frame_size Number of samples to be converted
  432. * @param resample_context Resample context for the conversion
  433. * @return Error code (0 if successful)
  434. */
  435. static int convert_samples(const uint8_t **input_data,
  436. uint8_t **converted_data, const int frame_size,
  437. SwrContext *resample_context)
  438. {
  439. int error;
  440. /* Convert the samples using the resampler. */
  441. if ((error = swr_convert(resample_context,
  442. converted_data, frame_size,
  443. input_data , frame_size)) < 0) {
  444. fprintf(stderr, "Could not convert input samples (error '%s')\n",
  445. av_err2str(error));
  446. return error;
  447. }
  448. return 0;
  449. }
  450. /**
  451. * Add converted input audio samples to the FIFO buffer for later processing.
  452. * @param fifo Buffer to add the samples to
  453. * @param converted_input_samples Samples to be added. The dimensions are channel
  454. * (for multi-channel audio), sample.
  455. * @param frame_size Number of samples to be converted
  456. * @return Error code (0 if successful)
  457. */
  458. static int add_samples_to_fifo(AVAudioFifo *fifo,
  459. uint8_t **converted_input_samples,
  460. const int frame_size)
  461. {
  462. int error;
  463. /* Make the FIFO as large as it needs to be to hold both,
  464. * the old and the new samples. */
  465. if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
  466. fprintf(stderr, "Could not reallocate FIFO\n");
  467. return error;
  468. }
  469. /* Store the new samples in the FIFO buffer. */
  470. if (av_audio_fifo_write(fifo, (void **)converted_input_samples,
  471. frame_size) < frame_size) {
  472. fprintf(stderr, "Could not write data to FIFO\n");
  473. return AVERROR_EXIT;
  474. }
  475. return 0;
  476. }
  477. /**
  478. * Read one audio frame from the input file, decode, convert and store
  479. * it in the FIFO buffer.
  480. * @param fifo Buffer used for temporary storage
  481. * @param input_format_context Format context of the input file
  482. * @param input_codec_context Codec context of the input file
  483. * @param output_codec_context Codec context of the output file
  484. * @param resampler_context Resample context for the conversion
  485. * @param[out] finished Indicates whether the end of file has
  486. * been reached and all data has been
  487. * decoded. If this flag is false,
  488. * there is more data to be decoded,
  489. * i.e., this function has to be called
  490. * again.
  491. * @return Error code (0 if successful)
  492. */
  493. static int read_decode_convert_and_store(AVAudioFifo *fifo,
  494. AVFormatContext *input_format_context,
  495. AVCodecContext *input_codec_context,
  496. AVCodecContext *output_codec_context,
  497. SwrContext *resampler_context,
  498. int *finished)
  499. {
  500. /* Temporary storage of the input samples of the frame read from the file. */
  501. AVFrame *input_frame = NULL;
  502. /* Temporary storage for the converted input samples. */
  503. uint8_t **converted_input_samples = NULL;
  504. int data_present;
  505. int ret = AVERROR_EXIT;
  506. /* Initialize temporary storage for one input frame. */
  507. if (init_input_frame(&input_frame))
  508. goto cleanup;
  509. /* Decode one frame worth of audio samples. */
  510. if (decode_audio_frame(input_frame, input_format_context,
  511. input_codec_context, &data_present, finished))
  512. goto cleanup;
  513. /* If we are at the end of the file and there are no more samples
  514. * in the decoder which are delayed, we are actually finished.
  515. * This must not be treated as an error. */
  516. if (*finished) {
  517. ret = 0;
  518. goto cleanup;
  519. }
  520. /* If there is decoded data, convert and store it. */
  521. if (data_present) {
  522. /* Initialize the temporary storage for the converted input samples. */
  523. if (init_converted_samples(&converted_input_samples, output_codec_context,
  524. input_frame->nb_samples))
  525. goto cleanup;
  526. /* Convert the input samples to the desired output sample format.
  527. * This requires a temporary storage provided by converted_input_samples. */
  528. if (convert_samples((const uint8_t**)input_frame->extended_data, converted_input_samples,
  529. input_frame->nb_samples, resampler_context))
  530. goto cleanup;
  531. /* Add the converted input samples to the FIFO buffer for later processing. */
  532. if (add_samples_to_fifo(fifo, converted_input_samples,
  533. input_frame->nb_samples))
  534. goto cleanup;
  535. ret = 0;
  536. }
  537. ret = 0;
  538. cleanup:
  539. if (converted_input_samples) {
  540. av_freep(&converted_input_samples[0]);
  541. free(converted_input_samples);
  542. }
  543. av_frame_free(&input_frame);
  544. return ret;
  545. }
  546. /**
  547. * Initialize one input frame for writing to the output file.
  548. * The frame will be exactly frame_size samples large.
  549. * @param[out] frame Frame to be initialized
  550. * @param output_codec_context Codec context of the output file
  551. * @param frame_size Size of the frame
  552. * @return Error code (0 if successful)
  553. */
  554. static int init_output_frame(AVFrame **frame,
  555. AVCodecContext *output_codec_context,
  556. int frame_size)
  557. {
  558. int error;
  559. /* Create a new frame to store the audio samples. */
  560. if (!(*frame = av_frame_alloc())) {
  561. fprintf(stderr, "Could not allocate output frame\n");
  562. return AVERROR_EXIT;
  563. }
  564. /* Set the frame's parameters, especially its size and format.
  565. * av_frame_get_buffer needs this to allocate memory for the
  566. * audio samples of the frame.
  567. * Default channel layouts based on the number of channels
  568. * are assumed for simplicity. */
  569. (*frame)->nb_samples = frame_size;
  570. av_channel_layout_copy(&(*frame)->ch_layout, &output_codec_context->ch_layout);
  571. (*frame)->format = output_codec_context->sample_fmt;
  572. (*frame)->sample_rate = output_codec_context->sample_rate;
  573. /* Allocate the samples of the created frame. This call will make
  574. * sure that the audio frame can hold as many samples as specified. */
  575. if ((error = av_frame_get_buffer(*frame, 0)) < 0) {
  576. fprintf(stderr, "Could not allocate output frame samples (error '%s')\n",
  577. av_err2str(error));
  578. av_frame_free(frame);
  579. return error;
  580. }
  581. return 0;
  582. }
  583. /* Global timestamp for the audio frames. */
  584. static int64_t pts = 0;
  585. /**
  586. * Encode one frame worth of audio to the output file.
  587. * @param frame Samples to be encoded
  588. * @param output_format_context Format context of the output file
  589. * @param output_codec_context Codec context of the output file
  590. * @param[out] data_present Indicates whether data has been
  591. * encoded
  592. * @return Error code (0 if successful)
  593. */
  594. static int encode_audio_frame(AVFrame *frame,
  595. AVFormatContext *output_format_context,
  596. AVCodecContext *output_codec_context,
  597. int *data_present)
  598. {
  599. /* Packet used for temporary storage. */
  600. AVPacket *output_packet;
  601. int error;
  602. error = init_packet(&output_packet);
  603. if (error < 0)
  604. return error;
  605. /* Set a timestamp based on the sample rate for the container. */
  606. if (frame) {
  607. frame->pts = pts;
  608. pts += frame->nb_samples;
  609. }
  610. *data_present = 0;
  611. /* Send the audio frame stored in the temporary packet to the encoder.
  612. * The output audio stream encoder is used to do this. */
  613. error = avcodec_send_frame(output_codec_context, frame);
  614. /* Check for errors, but proceed with fetching encoded samples if the
  615. * encoder signals that it has nothing more to encode. */
  616. if (error < 0 && error != AVERROR_EOF) {
  617. fprintf(stderr, "Could not send packet for encoding (error '%s')\n",
  618. av_err2str(error));
  619. goto cleanup;
  620. }
  621. /* Receive one encoded frame from the encoder. */
  622. error = avcodec_receive_packet(output_codec_context, output_packet);
  623. /* If the encoder asks for more data to be able to provide an
  624. * encoded frame, return indicating that no data is present. */
  625. if (error == AVERROR(EAGAIN)) {
  626. error = 0;
  627. goto cleanup;
  628. /* If the last frame has been encoded, stop encoding. */
  629. } else if (error == AVERROR_EOF) {
  630. error = 0;
  631. goto cleanup;
  632. } else if (error < 0) {
  633. fprintf(stderr, "Could not encode frame (error '%s')\n",
  634. av_err2str(error));
  635. goto cleanup;
  636. /* Default case: Return encoded data. */
  637. } else {
  638. *data_present = 1;
  639. }
  640. /* Write one audio frame from the temporary packet to the output file. */
  641. if (*data_present &&
  642. (error = av_write_frame(output_format_context, output_packet)) < 0) {
  643. fprintf(stderr, "Could not write frame (error '%s')\n",
  644. av_err2str(error));
  645. goto cleanup;
  646. }
  647. cleanup:
  648. av_packet_free(&output_packet);
  649. return error;
  650. }
  651. /**
  652. * Load one audio frame from the FIFO buffer, encode and write it to the
  653. * output file.
  654. * @param fifo Buffer used for temporary storage
  655. * @param output_format_context Format context of the output file
  656. * @param output_codec_context Codec context of the output file
  657. * @return Error code (0 if successful)
  658. */
  659. static int load_encode_and_write(AVAudioFifo *fifo,
  660. AVFormatContext *output_format_context,
  661. AVCodecContext *output_codec_context)
  662. {
  663. /* Temporary storage of the output samples of the frame written to the file. */
  664. AVFrame *output_frame;
  665. /* Use the maximum number of possible samples per frame.
  666. * If there is less than the maximum possible frame size in the FIFO
  667. * buffer use this number. Otherwise, use the maximum possible frame size. */
  668. const int frame_size = FFMIN(av_audio_fifo_size(fifo),
  669. output_codec_context->frame_size);
  670. int data_written;
  671. /* Initialize temporary storage for one output frame. */
  672. if (init_output_frame(&output_frame, output_codec_context, frame_size))
  673. return AVERROR_EXIT;
  674. /* Read as many samples from the FIFO buffer as required to fill the frame.
  675. * The samples are stored in the frame temporarily. */
  676. if (av_audio_fifo_read(fifo, (void **)output_frame->data, frame_size) < frame_size) {
  677. fprintf(stderr, "Could not read data from FIFO\n");
  678. av_frame_free(&output_frame);
  679. return AVERROR_EXIT;
  680. }
  681. /* Encode one frame worth of audio samples. */
  682. if (encode_audio_frame(output_frame, output_format_context,
  683. output_codec_context, &data_written)) {
  684. av_frame_free(&output_frame);
  685. return AVERROR_EXIT;
  686. }
  687. av_frame_free(&output_frame);
  688. return 0;
  689. }
  690. /**
  691. * Write the trailer of the output file container.
  692. * @param output_format_context Format context of the output file
  693. * @return Error code (0 if successful)
  694. */
  695. static int write_output_file_trailer(AVFormatContext *output_format_context)
  696. {
  697. int error;
  698. if ((error = av_write_trailer(output_format_context)) < 0) {
  699. fprintf(stderr, "Could not write output file trailer (error '%s')\n",
  700. av_err2str(error));
  701. return error;
  702. }
  703. return 0;
  704. }
  705. int main(int argc, char **argv)
  706. {
  707. AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
  708. AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
  709. SwrContext *resample_context = NULL;
  710. AVAudioFifo *fifo = NULL;
  711. int ret = AVERROR_EXIT;
  712. if (argc != 3) {
  713. fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
  714. exit(1);
  715. }
  716. /* Open the input file for reading. */
  717. if (open_input_file(argv[1], &input_format_context,
  718. &input_codec_context))
  719. goto cleanup;
  720. /* Open the output file for writing. */
  721. if (open_output_file(argv[2], input_codec_context,
  722. &output_format_context, &output_codec_context))
  723. goto cleanup;
  724. /* Initialize the resampler to be able to convert audio sample formats. */
  725. if (init_resampler(input_codec_context, output_codec_context,
  726. &resample_context))
  727. goto cleanup;
  728. /* Initialize the FIFO buffer to store audio samples to be encoded. */
  729. if (init_fifo(&fifo, output_codec_context))
  730. goto cleanup;
  731. /* Write the header of the output file container. */
  732. if (write_output_file_header(output_format_context))
  733. goto cleanup;
  734. /* Loop as long as we have input samples to read or output samples
  735. * to write; abort as soon as we have neither. */
  736. while (1) {
  737. /* Use the encoder's desired frame size for processing. */
  738. const int output_frame_size = output_codec_context->frame_size;
  739. int finished = 0;
  740. /* Make sure that there is one frame worth of samples in the FIFO
  741. * buffer so that the encoder can do its work.
  742. * Since the decoder's and the encoder's frame size may differ, we
  743. * need to FIFO buffer to store as many frames worth of input samples
  744. * that they make up at least one frame worth of output samples. */
  745. while (av_audio_fifo_size(fifo) < output_frame_size) {
  746. /* Decode one frame worth of audio samples, convert it to the
  747. * output sample format and put it into the FIFO buffer. */
  748. if (read_decode_convert_and_store(fifo, input_format_context,
  749. input_codec_context,
  750. output_codec_context,
  751. resample_context, &finished))
  752. goto cleanup;
  753. /* If we are at the end of the input file, we continue
  754. * encoding the remaining audio samples to the output file. */
  755. if (finished)
  756. break;
  757. }
  758. /* If we have enough samples for the encoder, we encode them.
  759. * At the end of the file, we pass the remaining samples to
  760. * the encoder. */
  761. while (av_audio_fifo_size(fifo) >= output_frame_size ||
  762. (finished && av_audio_fifo_size(fifo) > 0))
  763. /* Take one frame worth of audio samples from the FIFO buffer,
  764. * encode it and write it to the output file. */
  765. if (load_encode_and_write(fifo, output_format_context,
  766. output_codec_context))
  767. goto cleanup;
  768. /* If we are at the end of the input file and have encoded
  769. * all remaining samples, we can exit this loop and finish. */
  770. if (finished) {
  771. int data_written;
  772. /* Flush the encoder as it may have delayed frames. */
  773. do {
  774. if (encode_audio_frame(NULL, output_format_context,
  775. output_codec_context, &data_written))
  776. goto cleanup;
  777. } while (data_written);
  778. break;
  779. }
  780. }
  781. /* Write the trailer of the output file container. */
  782. if (write_output_file_trailer(output_format_context))
  783. goto cleanup;
  784. ret = 0;
  785. cleanup:
  786. if (fifo)
  787. av_audio_fifo_free(fifo);
  788. swr_free(&resample_context);
  789. if (output_codec_context)
  790. avcodec_free_context(&output_codec_context);
  791. if (output_format_context) {
  792. avio_closep(&output_format_context->pb);
  793. avformat_free_context(output_format_context);
  794. }
  795. if (input_codec_context)
  796. avcodec_free_context(&input_codec_context);
  797. if (input_format_context)
  798. avformat_close_input(&input_format_context);
  799. return ret;
  800. }