transcode_aac.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  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. #include "common.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. AVCodec *input_codec;
  57. int error;
  58. /* Open the input file to read from it. */
  59. if ((error = avformat_open_input(input_format_context, filename, NULL, NULL)) < 0) {
  60. fprintf(stderr,
  61. "Could not open input file '%s' (error '%s')\n",
  62. filename,
  63. 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", 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,
  76. "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. /* Find a decoder for the audio stream. */
  82. if (!(input_codec = avcodec_find_decoder(
  83. (*input_format_context)->streams[0]->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, (*input_format_context)->streams[0]->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", av_err2str(error));
  105. avcodec_free_context(&avctx);
  106. avformat_close_input(input_format_context);
  107. return error;
  108. }
  109. /* Save the decoder context for easier access later. */
  110. *input_codec_context = avctx;
  111. return 0;
  112. }
  113. /**
  114. * Open an output file and the required encoder.
  115. * Also set some basic encoder parameters.
  116. * Some of these parameters are based on the input file's parameters.
  117. * @param filename File to be opened
  118. * @param input_codec_context Codec context of input file
  119. * @param[out] output_format_context Format context of output file
  120. * @param[out] output_codec_context Codec context of output file
  121. * @return Error code (0 if successful)
  122. */
  123. static int open_output_file(const char *filename,
  124. AVCodecContext *input_codec_context,
  125. AVFormatContext **output_format_context,
  126. AVCodecContext **output_codec_context)
  127. {
  128. AVCodecContext *avctx = NULL;
  129. AVIOContext *output_io_context = NULL;
  130. AVStream *stream = NULL;
  131. AVCodec *output_codec = NULL;
  132. int error;
  133. /* Open the output file to write to it. */
  134. if ((error = avio_open(&output_io_context, filename, AVIO_FLAG_WRITE)) < 0) {
  135. fprintf(stderr,
  136. "Could not open output file '%s' (error '%s')\n",
  137. filename,
  138. av_err2str(error));
  139. return error;
  140. }
  141. /* Create a new format context for the output container format. */
  142. if (!(*output_format_context = avformat_alloc_context())) {
  143. fprintf(stderr, "Could not allocate output format context\n");
  144. return AVERROR(ENOMEM);
  145. }
  146. /* Associate the output file (pointer) with the container format context. */
  147. (*output_format_context)->pb = output_io_context;
  148. /* Guess the desired container format based on the file extension. */
  149. if (!((*output_format_context)->oformat = av_guess_format(NULL, filename, NULL))) {
  150. fprintf(stderr, "Could not find output file format\n");
  151. goto cleanup;
  152. }
  153. if (!((*output_format_context)->url = av_strdup(filename))) {
  154. fprintf(stderr, "Could not allocate url.\n");
  155. error = AVERROR(ENOMEM);
  156. goto cleanup;
  157. }
  158. /* Find the encoder to be used by its name. */
  159. if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_AAC))) {
  160. fprintf(stderr, "Could not find an AAC encoder.\n");
  161. goto cleanup;
  162. }
  163. /* Create a new audio stream in the output file container. */
  164. if (!(stream = avformat_new_stream(*output_format_context, NULL))) {
  165. fprintf(stderr, "Could not create new stream\n");
  166. error = AVERROR(ENOMEM);
  167. goto cleanup;
  168. }
  169. avctx = avcodec_alloc_context3(output_codec);
  170. if (!avctx) {
  171. fprintf(stderr, "Could not allocate an encoding context\n");
  172. error = AVERROR(ENOMEM);
  173. goto cleanup;
  174. }
  175. /* Set the basic encoder parameters.
  176. * The input file's sample rate is used to avoid a sample rate conversion. */
  177. avctx->channels = OUTPUT_CHANNELS;
  178. avctx->channel_layout = av_get_default_channel_layout(OUTPUT_CHANNELS);
  179. avctx->sample_rate = input_codec_context->sample_rate;
  180. avctx->sample_fmt = output_codec->sample_fmts[0];
  181. avctx->bit_rate = OUTPUT_BIT_RATE;
  182. /* Allow the use of the experimental AAC encoder. */
  183. avctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
  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", 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 packet Packet to be initialized
  214. */
  215. static void init_packet(AVPacket *packet)
  216. {
  217. av_init_packet(packet);
  218. /* Set the packet data and size so that it is recognized as being empty. */
  219. packet->data = NULL;
  220. packet->size = 0;
  221. }
  222. /**
  223. * Initialize one audio frame for reading from the input file.
  224. * @param[out] frame Frame to be initialized
  225. * @return Error code (0 if successful)
  226. */
  227. static int init_input_frame(AVFrame **frame)
  228. {
  229. if (!(*frame = av_frame_alloc())) {
  230. fprintf(stderr, "Could not allocate input frame\n");
  231. return AVERROR(ENOMEM);
  232. }
  233. return 0;
  234. }
  235. /**
  236. * Initialize the audio resampler based on the input and output codec settings.
  237. * If the input and output sample formats differ, a conversion is required
  238. * libswresample takes care of this, but requires initialization.
  239. * @param input_codec_context Codec context of the input file
  240. * @param output_codec_context Codec context of the output file
  241. * @param[out] resample_context Resample context for the required conversion
  242. * @return Error code (0 if successful)
  243. */
  244. static int init_resampler(AVCodecContext *input_codec_context,
  245. AVCodecContext *output_codec_context,
  246. SwrContext **resample_context)
  247. {
  248. int error;
  249. /*
  250. * Create a resampler context for the conversion.
  251. * Set the conversion parameters.
  252. * Default channel layouts based on the number of channels
  253. * are assumed for simplicity (they are sometimes not detected
  254. * properly by the demuxer and/or decoder).
  255. */
  256. *resample_context
  257. = swr_alloc_set_opts(NULL,
  258. av_get_default_channel_layout(output_codec_context->channels),
  259. output_codec_context->sample_fmt,
  260. output_codec_context->sample_rate,
  261. av_get_default_channel_layout(input_codec_context->channels),
  262. input_codec_context->sample_fmt,
  263. input_codec_context->sample_rate,
  264. 0,
  265. NULL);
  266. if (!*resample_context) {
  267. fprintf(stderr, "Could not allocate resample context\n");
  268. return AVERROR(ENOMEM);
  269. }
  270. /*
  271. * Perform a sanity check so that the number of converted samples is
  272. * not greater than the number of samples to be converted.
  273. * If the sample rates differ, this case has to be handled differently
  274. */
  275. av_assert0(output_codec_context->sample_rate == input_codec_context->sample_rate);
  276. /* Open the resampler with the specified parameters. */
  277. if ((error = swr_init(*resample_context)) < 0) {
  278. fprintf(stderr, "Could not open resample context\n");
  279. swr_free(resample_context);
  280. return error;
  281. }
  282. return 0;
  283. }
  284. /**
  285. * Initialize a FIFO buffer for the audio samples to be encoded.
  286. * @param[out] fifo Sample buffer
  287. * @param output_codec_context Codec context of the output file
  288. * @return Error code (0 if successful)
  289. */
  290. static int init_fifo(AVAudioFifo **fifo, AVCodecContext *output_codec_context)
  291. {
  292. /* Create the FIFO buffer based on the specified output sample format. */
  293. if (!(*fifo = av_audio_fifo_alloc(output_codec_context->sample_fmt,
  294. output_codec_context->channels,
  295. 1))) {
  296. fprintf(stderr, "Could not allocate FIFO\n");
  297. return AVERROR(ENOMEM);
  298. }
  299. return 0;
  300. }
  301. /**
  302. * Write the header of the output file container.
  303. * @param output_format_context Format context of the output file
  304. * @return Error code (0 if successful)
  305. */
  306. static int write_output_file_header(AVFormatContext *output_format_context)
  307. {
  308. int error;
  309. if ((error = avformat_write_header(output_format_context, NULL)) < 0) {
  310. fprintf(stderr, "Could not write output file header (error '%s')\n", av_err2str(error));
  311. return error;
  312. }
  313. return 0;
  314. }
  315. /**
  316. * Decode one audio frame from the input file.
  317. * @param frame Audio frame to be decoded
  318. * @param input_format_context Format context of the input file
  319. * @param input_codec_context Codec context of the input file
  320. * @param[out] data_present Indicates whether data has been decoded
  321. * @param[out] finished Indicates whether the end of file has
  322. * been reached and all data has been
  323. * decoded. If this flag is false, there
  324. * is more data to be decoded, i.e., this
  325. * function has to be called again.
  326. * @return Error code (0 if successful)
  327. */
  328. static int decode_audio_frame(AVFrame *frame,
  329. AVFormatContext *input_format_context,
  330. AVCodecContext *input_codec_context,
  331. int *data_present,
  332. int *finished)
  333. {
  334. /* Packet used for temporary storage. */
  335. AVPacket input_packet;
  336. int error;
  337. init_packet(&input_packet);
  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", av_err2str(error));
  345. return error;
  346. }
  347. }
  348. /* Send the audio frame stored in the temporary packet to the decoder.
  349. * The input audio stream decoder is used to do this. */
  350. if ((error = avcodec_send_packet(input_codec_context, &input_packet)) < 0) {
  351. fprintf(stderr, "Could not send packet for decoding (error '%s')\n", av_err2str(error));
  352. return error;
  353. }
  354. /* Receive one frame from the decoder. */
  355. error = avcodec_receive_frame(input_codec_context, frame);
  356. /* If the decoder asks for more data to be able to decode a frame,
  357. * return indicating that no data is present. */
  358. if (error == AVERROR(EAGAIN)) {
  359. error = 0;
  360. goto cleanup;
  361. /* If the end of the input file is reached, stop decoding. */
  362. } else if (error == AVERROR_EOF) {
  363. *finished = 1;
  364. error = 0;
  365. goto cleanup;
  366. } else if (error < 0) {
  367. fprintf(stderr, "Could not decode frame (error '%s')\n", av_err2str(error));
  368. goto cleanup;
  369. /* Default case: Return decoded data. */
  370. } else {
  371. *data_present = 1;
  372. goto cleanup;
  373. }
  374. cleanup:
  375. av_packet_unref(&input_packet);
  376. return error;
  377. }
  378. /**
  379. * Initialize a temporary storage for the specified number of audio samples.
  380. * The conversion requires temporary storage due to the different format.
  381. * The number of audio samples to be allocated is specified in frame_size.
  382. * @param[out] converted_input_samples Array of converted samples. The
  383. * dimensions are reference, channel
  384. * (for multi-channel audio), sample.
  385. * @param output_codec_context Codec context of the output file
  386. * @param frame_size Number of samples to be converted in
  387. * each round
  388. * @return Error code (0 if successful)
  389. */
  390. static int init_converted_samples(uint8_t ***converted_input_samples,
  391. AVCodecContext *output_codec_context,
  392. int frame_size)
  393. {
  394. int error;
  395. /* Allocate as many pointers as there are audio channels.
  396. * Each pointer will later point to the audio samples of the corresponding
  397. * channels (although it may be NULL for interleaved formats).
  398. */
  399. if (!(*converted_input_samples = (uint8_t **) calloc(output_codec_context->channels,
  400. sizeof(**converted_input_samples)))) {
  401. fprintf(stderr, "Could not allocate converted input sample pointers\n");
  402. return AVERROR(ENOMEM);
  403. }
  404. /* Allocate memory for the samples of all channels in one consecutive
  405. * block for convenience. */
  406. if ((error = av_samples_alloc(*converted_input_samples,
  407. NULL,
  408. output_codec_context->channels,
  409. frame_size,
  410. output_codec_context->sample_fmt,
  411. 0))
  412. < 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,
  436. 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, converted_data, frame_size, input_data, frame_size))
  442. < 0) {
  443. fprintf(stderr, "Could not convert input samples (error '%s')\n", av_err2str(error));
  444. return error;
  445. }
  446. return 0;
  447. }
  448. /**
  449. * Add converted input audio samples to the FIFO buffer for later processing.
  450. * @param fifo Buffer to add the samples to
  451. * @param converted_input_samples Samples to be added. The dimensions are channel
  452. * (for multi-channel audio), sample.
  453. * @param frame_size Number of samples to be converted
  454. * @return Error code (0 if successful)
  455. */
  456. static int add_samples_to_fifo(AVAudioFifo *fifo,
  457. uint8_t **converted_input_samples,
  458. const int frame_size)
  459. {
  460. int error;
  461. /* Make the FIFO as large as it needs to be to hold both,
  462. * the old and the new samples. */
  463. if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
  464. fprintf(stderr, "Could not reallocate FIFO\n");
  465. return error;
  466. }
  467. /* Store the new samples in the FIFO buffer. */
  468. if (av_audio_fifo_write(fifo, (void **) converted_input_samples, frame_size) < frame_size) {
  469. fprintf(stderr, "Could not write data to FIFO\n");
  470. return AVERROR_EXIT;
  471. }
  472. return 0;
  473. }
  474. /**
  475. * Read one audio frame from the input file, decode, convert and store
  476. * it in the FIFO buffer.
  477. * @param fifo Buffer used for temporary storage
  478. * @param input_format_context Format context of the input file
  479. * @param input_codec_context Codec context of the input file
  480. * @param output_codec_context Codec context of the output file
  481. * @param resampler_context Resample context for the conversion
  482. * @param[out] finished Indicates whether the end of file has
  483. * been reached and all data has been
  484. * decoded. If this flag is false,
  485. * there is more data to be decoded,
  486. * i.e., this function has to be called
  487. * again.
  488. * @return Error code (0 if successful)
  489. */
  490. static int read_decode_convert_and_store(AVAudioFifo *fifo,
  491. AVFormatContext *input_format_context,
  492. AVCodecContext *input_codec_context,
  493. AVCodecContext *output_codec_context,
  494. SwrContext *resampler_context,
  495. int *finished)
  496. {
  497. /* Temporary storage of the input samples of the frame read from the file. */
  498. AVFrame *input_frame = NULL;
  499. /* Temporary storage for the converted input samples. */
  500. uint8_t **converted_input_samples = NULL;
  501. int data_present = 0;
  502. int ret = AVERROR_EXIT;
  503. /* Initialize temporary storage for one input frame. */
  504. if (init_input_frame(&input_frame))
  505. goto cleanup;
  506. /* Decode one frame worth of audio samples. */
  507. if (decode_audio_frame(input_frame,
  508. input_format_context,
  509. input_codec_context,
  510. &data_present,
  511. 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,
  524. output_codec_context,
  525. input_frame->nb_samples))
  526. goto cleanup;
  527. /* Convert the input samples to the desired output sample format.
  528. * This requires a temporary storage provided by converted_input_samples. */
  529. if (convert_samples((const uint8_t **) input_frame->extended_data,
  530. converted_input_samples,
  531. input_frame->nb_samples,
  532. resampler_context))
  533. goto cleanup;
  534. /* Add the converted input samples to the FIFO buffer for later processing. */
  535. if (add_samples_to_fifo(fifo, converted_input_samples, input_frame->nb_samples))
  536. goto cleanup;
  537. ret = 0;
  538. }
  539. ret = 0;
  540. cleanup:
  541. if (converted_input_samples) {
  542. av_freep(&converted_input_samples[0]);
  543. free(converted_input_samples);
  544. }
  545. av_frame_free(&input_frame);
  546. return ret;
  547. }
  548. /**
  549. * Initialize one input frame for writing to the output file.
  550. * The frame will be exactly frame_size samples large.
  551. * @param[out] frame Frame to be initialized
  552. * @param output_codec_context Codec context of the output file
  553. * @param frame_size Size of the frame
  554. * @return Error code (0 if successful)
  555. */
  556. static int init_output_frame(AVFrame **frame, AVCodecContext *output_codec_context, 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. (*frame)->channel_layout = output_codec_context->channel_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", 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. init_packet(&output_packet);
  602. /* Set a timestamp based on the sample rate for the container. */
  603. if (frame) {
  604. frame->pts = pts;
  605. pts += frame->nb_samples;
  606. }
  607. /* Send the audio frame stored in the temporary packet to the encoder.
  608. * The output audio stream encoder is used to do this. */
  609. error = avcodec_send_frame(output_codec_context, frame);
  610. /* The encoder signals that it has nothing more to encode. */
  611. if (error == AVERROR_EOF) {
  612. error = 0;
  613. goto cleanup;
  614. } else if (error < 0) {
  615. fprintf(stderr, "Could not send packet for encoding (error '%s')\n", av_err2str(error));
  616. return error;
  617. }
  618. /* Receive one encoded frame from the encoder. */
  619. error = avcodec_receive_packet(output_codec_context, &output_packet);
  620. /* If the encoder asks for more data to be able to provide an
  621. * encoded frame, return indicating that no data is present. */
  622. if (error == AVERROR(EAGAIN)) {
  623. error = 0;
  624. goto cleanup;
  625. /* If the last frame has been encoded, stop encoding. */
  626. } else if (error == AVERROR_EOF) {
  627. error = 0;
  628. goto cleanup;
  629. } else if (error < 0) {
  630. fprintf(stderr, "Could not encode frame (error '%s')\n", av_err2str(error));
  631. goto cleanup;
  632. /* Default case: Return encoded data. */
  633. } else {
  634. *data_present = 1;
  635. }
  636. /* Write one audio frame from the temporary packet to the output file. */
  637. if (*data_present && (error = av_write_frame(output_format_context, &output_packet)) < 0) {
  638. fprintf(stderr, "Could not write frame (error '%s')\n", 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), output_codec_context->frame_size);
  663. int data_written;
  664. /* Initialize temporary storage for one output frame. */
  665. if (init_output_frame(&output_frame, output_codec_context, frame_size))
  666. return AVERROR_EXIT;
  667. /* Read as many samples from the FIFO buffer as required to fill the frame.
  668. * The samples are stored in the frame temporarily. */
  669. if (av_audio_fifo_read(fifo, (void **) output_frame->data, frame_size) < frame_size) {
  670. fprintf(stderr, "Could not read data from FIFO\n");
  671. av_frame_free(&output_frame);
  672. return AVERROR_EXIT;
  673. }
  674. /* Encode one frame worth of audio samples. */
  675. if (encode_audio_frame(output_frame,
  676. output_format_context,
  677. output_codec_context,
  678. &data_written)) {
  679. av_frame_free(&output_frame);
  680. return AVERROR_EXIT;
  681. }
  682. av_frame_free(&output_frame);
  683. return 0;
  684. }
  685. /**
  686. * Write the trailer of the output file container.
  687. * @param output_format_context Format context of the output file
  688. * @return Error code (0 if successful)
  689. */
  690. static int write_output_file_trailer(AVFormatContext *output_format_context)
  691. {
  692. int error;
  693. if ((error = av_write_trailer(output_format_context)) < 0) {
  694. fprintf(stderr, "Could not write output file trailer (error '%s')\n", av_err2str(error));
  695. return error;
  696. }
  697. return 0;
  698. }
  699. int test_transcode()
  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. const char *inputfile = "WAS_2019-09-05_14_19_42_109.wav";
  711. const char *outputfile = "transcode.aac";
  712. /* Open the input file for reading. */
  713. if (open_input_file(inputfile, &input_format_context, &input_codec_context))
  714. goto cleanup;
  715. /* Open the output file for writing. */
  716. if (open_output_file(outputfile,
  717. input_codec_context,
  718. &output_format_context,
  719. &output_codec_context))
  720. goto cleanup;
  721. /* Initialize the resampler to be able to convert audio sample formats. */
  722. if (init_resampler(input_codec_context, output_codec_context, &resample_context))
  723. goto cleanup;
  724. /* Initialize the FIFO buffer to store audio samples to be encoded. */
  725. if (init_fifo(&fifo, output_codec_context))
  726. goto cleanup;
  727. /* Write the header of the output file container. */
  728. if (write_output_file_header(output_format_context))
  729. goto cleanup;
  730. /* Loop as long as we have input samples to read or output samples
  731. * to write; abort as soon as we have neither. */
  732. while (1) {
  733. /* Use the encoder's desired frame size for processing. */
  734. const int output_frame_size = output_codec_context->frame_size;
  735. int finished = 0;
  736. /* Make sure that there is one frame worth of samples in the FIFO
  737. * buffer so that the encoder can do its work.
  738. * Since the decoder's and the encoder's frame size may differ, we
  739. * need to FIFO buffer to store as many frames worth of input samples
  740. * that they make up at least one frame worth of output samples. */
  741. while (av_audio_fifo_size(fifo) < output_frame_size) {
  742. /* Decode one frame worth of audio samples, convert it to the
  743. * output sample format and put it into the FIFO buffer. */
  744. if (read_decode_convert_and_store(fifo,
  745. input_format_context,
  746. input_codec_context,
  747. output_codec_context,
  748. resample_context,
  749. &finished))
  750. goto cleanup;
  751. /* If we are at the end of the input file, we continue
  752. * encoding the remaining audio samples to the output file. */
  753. if (finished)
  754. break;
  755. }
  756. /* If we have enough samples for the encoder, we encode them.
  757. * At the end of the file, we pass the remaining samples to
  758. * the encoder. */
  759. while (av_audio_fifo_size(fifo) >= output_frame_size
  760. || (finished && av_audio_fifo_size(fifo) > 0))
  761. /* Take one frame worth of audio samples from the FIFO buffer,
  762. * encode it and write it to the output file. */
  763. if (load_encode_and_write(fifo, output_format_context, output_codec_context))
  764. goto cleanup;
  765. /* If we are at the end of the input file and have encoded
  766. * all remaining samples, we can exit this loop and finish. */
  767. if (finished) {
  768. int data_written;
  769. /* Flush the encoder as it may have delayed frames. */
  770. do {
  771. data_written = 0;
  772. if (encode_audio_frame(NULL,
  773. output_format_context,
  774. output_codec_context,
  775. &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. }
  801. int main1(int argc, char **argv)
  802. {
  803. AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
  804. AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
  805. SwrContext *resample_context = NULL;
  806. AVAudioFifo *fifo = NULL;
  807. int ret = AVERROR_EXIT;
  808. //if (argc != 3) {
  809. // fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
  810. // exit(1);
  811. //}
  812. const char *inputfile = "WAS_2019-09-05_14_19_42_109.wav";
  813. const char *outputfile = "transcode.aac";
  814. /* Open the input file for reading. */
  815. if (open_input_file(inputfile, &input_format_context, &input_codec_context))
  816. goto cleanup;
  817. /* Open the output file for writing. */
  818. if (open_output_file(outputfile,
  819. input_codec_context,
  820. &output_format_context,
  821. &output_codec_context))
  822. goto cleanup;
  823. /* Initialize the resampler to be able to convert audio sample formats. */
  824. if (init_resampler(input_codec_context, output_codec_context, &resample_context))
  825. goto cleanup;
  826. /* Initialize the FIFO buffer to store audio samples to be encoded. */
  827. if (init_fifo(&fifo, output_codec_context))
  828. goto cleanup;
  829. /* Write the header of the output file container. */
  830. if (write_output_file_header(output_format_context))
  831. goto cleanup;
  832. /* Loop as long as we have input samples to read or output samples
  833. * to write; abort as soon as we have neither. */
  834. while (1) {
  835. /* Use the encoder's desired frame size for processing. */
  836. const int output_frame_size = output_codec_context->frame_size;
  837. int finished = 0;
  838. /* Make sure that there is one frame worth of samples in the FIFO
  839. * buffer so that the encoder can do its work.
  840. * Since the decoder's and the encoder's frame size may differ, we
  841. * need to FIFO buffer to store as many frames worth of input samples
  842. * that they make up at least one frame worth of output samples. */
  843. while (av_audio_fifo_size(fifo) < output_frame_size) {
  844. /* Decode one frame worth of audio samples, convert it to the
  845. * output sample format and put it into the FIFO buffer. */
  846. if (read_decode_convert_and_store(fifo,
  847. input_format_context,
  848. input_codec_context,
  849. output_codec_context,
  850. resample_context,
  851. &finished))
  852. goto cleanup;
  853. /* If we are at the end of the input file, we continue
  854. * encoding the remaining audio samples to the output file. */
  855. if (finished)
  856. break;
  857. }
  858. /* If we have enough samples for the encoder, we encode them.
  859. * At the end of the file, we pass the remaining samples to
  860. * the encoder. */
  861. while (av_audio_fifo_size(fifo) >= output_frame_size
  862. || (finished && av_audio_fifo_size(fifo) > 0))
  863. /* Take one frame worth of audio samples from the FIFO buffer,
  864. * encode it and write it to the output file. */
  865. if (load_encode_and_write(fifo, output_format_context, output_codec_context))
  866. goto cleanup;
  867. /* If we are at the end of the input file and have encoded
  868. * all remaining samples, we can exit this loop and finish. */
  869. if (finished) {
  870. int data_written;
  871. /* Flush the encoder as it may have delayed frames. */
  872. do {
  873. data_written = 0;
  874. if (encode_audio_frame(NULL,
  875. output_format_context,
  876. output_codec_context,
  877. &data_written))
  878. goto cleanup;
  879. } while (data_written);
  880. break;
  881. }
  882. }
  883. /* Write the trailer of the output file container. */
  884. if (write_output_file_trailer(output_format_context))
  885. goto cleanup;
  886. ret = 0;
  887. cleanup:
  888. if (fifo)
  889. av_audio_fifo_free(fifo);
  890. swr_free(&resample_context);
  891. if (output_codec_context)
  892. avcodec_free_context(&output_codec_context);
  893. if (output_format_context) {
  894. avio_closep(&output_format_context->pb);
  895. avformat_free_context(output_format_context);
  896. }
  897. if (input_codec_context)
  898. avcodec_free_context(&input_codec_context);
  899. if (input_format_context)
  900. avformat_close_input(&input_format_context);
  901. return ret;
  902. }