transcode_aac.c 34 KB

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