transcode_aac.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  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,
  60. NULL)) < 0) {
  61. fprintf(stderr, "Could not open input file '%s' (error '%s')\n",
  62. filename, av_err2str(error));
  63. *input_format_context = NULL;
  64. return error;
  65. }
  66. /* Get information on the input file (number of streams etc.). */
  67. if ((error = avformat_find_stream_info(*input_format_context, NULL)) < 0) {
  68. fprintf(stderr, "Could not open find stream info (error '%s')\n",
  69. av_err2str(error));
  70. avformat_close_input(input_format_context);
  71. return error;
  72. }
  73. /* Make sure that there is only one stream in the input file. */
  74. if ((*input_format_context)->nb_streams != 1) {
  75. fprintf(stderr, "Expected one audio input stream, but found %d\n",
  76. (*input_format_context)->nb_streams);
  77. avformat_close_input(input_format_context);
  78. return AVERROR_EXIT;
  79. }
  80. /* Find a decoder for the audio stream. */
  81. if (!(input_codec = avcodec_find_decoder((*input_format_context)->streams[0]->codecpar->codec_id))) {
  82. fprintf(stderr, "Could not find input codec\n");
  83. avformat_close_input(input_format_context);
  84. return AVERROR_EXIT;
  85. }
  86. /* Allocate a new decoding context. */
  87. avctx = avcodec_alloc_context3(input_codec);
  88. if (!avctx) {
  89. fprintf(stderr, "Could not allocate a decoding context\n");
  90. avformat_close_input(input_format_context);
  91. return AVERROR(ENOMEM);
  92. }
  93. /* Initialize the stream parameters with demuxer information. */
  94. error = avcodec_parameters_to_context(avctx, (*input_format_context)->streams[0]->codecpar);
  95. if (error < 0) {
  96. avformat_close_input(input_format_context);
  97. avcodec_free_context(&avctx);
  98. return error;
  99. }
  100. /* Open the decoder for the audio stream to use it later. */
  101. if ((error = avcodec_open2(avctx, input_codec, NULL)) < 0) {
  102. fprintf(stderr, "Could not open input codec (error '%s')\n",
  103. av_err2str(error));
  104. avcodec_free_context(&avctx);
  105. avformat_close_input(input_format_context);
  106. return error;
  107. }
  108. /* Save the decoder context for easier access later. */
  109. *input_codec_context = avctx;
  110. return 0;
  111. }
  112. /**
  113. * Open an output file and the required encoder.
  114. * Also set some basic encoder parameters.
  115. * Some of these parameters are based on the input file's parameters.
  116. * @param filename File to be opened
  117. * @param input_codec_context Codec context of input file
  118. * @param[out] output_format_context Format context of output file
  119. * @param[out] output_codec_context Codec context of output file
  120. * @return Error code (0 if successful)
  121. */
  122. static int open_output_file(const char *filename,
  123. AVCodecContext *input_codec_context,
  124. AVFormatContext **output_format_context,
  125. AVCodecContext **output_codec_context)
  126. {
  127. AVCodecContext *avctx = NULL;
  128. AVIOContext *output_io_context = NULL;
  129. AVStream *stream = NULL;
  130. AVCodec *output_codec = NULL;
  131. int error;
  132. /* Open the output file to write to it. */
  133. if ((error = avio_open(&output_io_context, filename,
  134. AVIO_FLAG_WRITE)) < 0) {
  135. fprintf(stderr, "Could not open output file '%s' (error '%s')\n",
  136. filename, av_err2str(error));
  137. return error;
  138. }
  139. /* Create a new format context for the output container format. */
  140. if (!(*output_format_context = avformat_alloc_context())) {
  141. fprintf(stderr, "Could not allocate output format context\n");
  142. return AVERROR(ENOMEM);
  143. }
  144. /* Associate the output file (pointer) with the container format context. */
  145. (*output_format_context)->pb = output_io_context;
  146. /* Guess the desired container format based on the file extension. */
  147. if (!((*output_format_context)->oformat = av_guess_format(NULL, filename,
  148. NULL))) {
  149. fprintf(stderr, "Could not find output file format\n");
  150. goto cleanup;
  151. }
  152. if (!((*output_format_context)->url = av_strdup(filename))) {
  153. fprintf(stderr, "Could not allocate url.\n");
  154. error = AVERROR(ENOMEM);
  155. goto cleanup;
  156. }
  157. /* Find the encoder to be used by its name. */
  158. if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_AAC))) {
  159. fprintf(stderr, "Could not find an AAC encoder.\n");
  160. goto cleanup;
  161. }
  162. /* Create a new audio stream in the output file container. */
  163. if (!(stream = avformat_new_stream(*output_format_context, NULL))) {
  164. fprintf(stderr, "Could not create new stream\n");
  165. error = AVERROR(ENOMEM);
  166. goto cleanup;
  167. }
  168. avctx = avcodec_alloc_context3(output_codec);
  169. if (!avctx) {
  170. fprintf(stderr, "Could not allocate an encoding context\n");
  171. error = AVERROR(ENOMEM);
  172. goto cleanup;
  173. }
  174. /* Set the basic encoder parameters.
  175. * The input file's sample rate is used to avoid a sample rate conversion. */
  176. avctx->channels = OUTPUT_CHANNELS;
  177. avctx->channel_layout = av_get_default_channel_layout(OUTPUT_CHANNELS);
  178. avctx->sample_rate = input_codec_context->sample_rate;
  179. avctx->sample_fmt = output_codec->sample_fmts[0];
  180. avctx->bit_rate = OUTPUT_BIT_RATE;
  181. /* Allow the use of the experimental AAC encoder. */
  182. avctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
  183. /* Set the sample rate for the container. */
  184. stream->time_base.den = input_codec_context->sample_rate;
  185. stream->time_base.num = 1;
  186. /* Some container formats (like MP4) require global headers to be present.
  187. * Mark the encoder so that it behaves accordingly. */
  188. if ((*output_format_context)->oformat->flags & AVFMT_GLOBALHEADER)
  189. avctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  190. /* Open the encoder for the audio stream to use it later. */
  191. if ((error = avcodec_open2(avctx, output_codec, NULL)) < 0) {
  192. fprintf(stderr, "Could not open output codec (error '%s')\n",
  193. av_err2str(error));
  194. goto cleanup;
  195. }
  196. error = avcodec_parameters_from_context(stream->codecpar, avctx);
  197. if (error < 0) {
  198. fprintf(stderr, "Could not initialize stream parameters\n");
  199. goto cleanup;
  200. }
  201. /* Save the encoder context for easier access later. */
  202. *output_codec_context = avctx;
  203. return 0;
  204. cleanup:
  205. avcodec_free_context(&avctx);
  206. avio_closep(&(*output_format_context)->pb);
  207. avformat_free_context(*output_format_context);
  208. *output_format_context = NULL;
  209. return error < 0 ? error : AVERROR_EXIT;
  210. }
  211. /**
  212. * Initialize one data packet for reading or writing.
  213. * @param 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 = swr_alloc_set_opts(NULL,
  257. av_get_default_channel_layout(output_codec_context->channels),
  258. output_codec_context->sample_fmt,
  259. output_codec_context->sample_rate,
  260. av_get_default_channel_layout(input_codec_context->channels),
  261. input_codec_context->sample_fmt,
  262. input_codec_context->sample_rate,
  263. 0, NULL);
  264. if (!*resample_context) {
  265. fprintf(stderr, "Could not allocate resample context\n");
  266. return AVERROR(ENOMEM);
  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->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. init_packet(&input_packet);
  335. /* Read one audio frame from the input file into a temporary packet. */
  336. if ((error = av_read_frame(input_format_context, &input_packet)) < 0) {
  337. /* If we are at the end of the file, flush the decoder below. */
  338. if (error == AVERROR_EOF)
  339. *finished = 1;
  340. else {
  341. fprintf(stderr, "Could not read frame (error '%s')\n",
  342. av_err2str(error));
  343. return error;
  344. }
  345. }
  346. /* Send the audio frame stored in the temporary packet to the decoder.
  347. * The input audio stream decoder is used to do this. */
  348. if ((error = avcodec_send_packet(input_codec_context, &input_packet)) < 0) {
  349. fprintf(stderr, "Could not send packet for decoding (error '%s')\n",
  350. av_err2str(error));
  351. return error;
  352. }
  353. /* Receive one frame from the decoder. */
  354. error = avcodec_receive_frame(input_codec_context, frame);
  355. /* If the decoder asks for more data to be able to decode a frame,
  356. * return indicating that no data is present. */
  357. if (error == AVERROR(EAGAIN)) {
  358. error = 0;
  359. goto cleanup;
  360. /* If the end of the input file is reached, stop decoding. */
  361. }
  362. else if (error == AVERROR_EOF) {
  363. *finished = 1;
  364. error = 0;
  365. goto cleanup;
  366. }
  367. else if (error < 0) {
  368. fprintf(stderr, "Could not decode frame (error '%s')\n",
  369. av_err2str(error));
  370. goto cleanup;
  371. /* Default case: Return decoded data. */
  372. }
  373. else {
  374. *data_present = 1;
  375. goto cleanup;
  376. }
  377. cleanup:
  378. av_packet_unref(&input_packet);
  379. return error;
  380. }
  381. /**
  382. * Initialize a temporary storage for the specified number of audio samples.
  383. * The conversion requires temporary storage due to the different format.
  384. * The number of audio samples to be allocated is specified in frame_size.
  385. * @param[out] converted_input_samples Array of converted samples. The
  386. * dimensions are reference, channel
  387. * (for multi-channel audio), sample.
  388. * @param output_codec_context Codec context of the output file
  389. * @param frame_size Number of samples to be converted in
  390. * each round
  391. * @return Error code (0 if successful)
  392. */
  393. static int init_converted_samples(uint8_t ***converted_input_samples,
  394. AVCodecContext *output_codec_context,
  395. int frame_size)
  396. {
  397. int error;
  398. /* Allocate as many pointers as there are audio channels.
  399. * Each pointer will later point to the audio samples of the corresponding
  400. * channels (although it may be NULL for interleaved formats).
  401. */
  402. if (!(*converted_input_samples = (uint8_t**)calloc(output_codec_context->channels,
  403. sizeof(**converted_input_samples)))) {
  404. fprintf(stderr, "Could not allocate converted input sample pointers\n");
  405. return AVERROR(ENOMEM);
  406. }
  407. /* Allocate memory for the samples of all channels in one consecutive
  408. * block for convenience. */
  409. if ((error = av_samples_alloc(*converted_input_samples, NULL,
  410. output_codec_context->channels,
  411. frame_size,
  412. output_codec_context->sample_fmt, 0)) < 0) {
  413. fprintf(stderr,
  414. "Could not allocate converted input samples (error '%s')\n",
  415. av_err2str(error));
  416. av_freep(&(*converted_input_samples)[0]);
  417. free(*converted_input_samples);
  418. return error;
  419. }
  420. return 0;
  421. }
  422. /**
  423. * Convert the input audio samples into the output sample format.
  424. * The conversion happens on a per-frame basis, the size of which is
  425. * specified by frame_size.
  426. * @param input_data Samples to be decoded. The dimensions are
  427. * channel (for multi-channel audio), sample.
  428. * @param[out] converted_data Converted samples. The dimensions are channel
  429. * (for multi-channel audio), sample.
  430. * @param frame_size Number of samples to be converted
  431. * @param resample_context Resample context for the conversion
  432. * @return Error code (0 if successful)
  433. */
  434. static int convert_samples(const uint8_t **input_data,
  435. uint8_t **converted_data, const int frame_size,
  436. SwrContext *resample_context)
  437. {
  438. int error;
  439. /* Convert the samples using the resampler. */
  440. if ((error = swr_convert(resample_context,
  441. converted_data, frame_size,
  442. input_data, frame_size)) < 0) {
  443. fprintf(stderr, "Could not convert input samples (error '%s')\n",
  444. av_err2str(error));
  445. return error;
  446. }
  447. return 0;
  448. }
  449. /**
  450. * Add converted input audio samples to the FIFO buffer for later processing.
  451. * @param fifo Buffer to add the samples to
  452. * @param converted_input_samples Samples to be added. The dimensions are channel
  453. * (for multi-channel audio), sample.
  454. * @param frame_size Number of samples to be converted
  455. * @return Error code (0 if successful)
  456. */
  457. static int add_samples_to_fifo(AVAudioFifo *fifo,
  458. uint8_t **converted_input_samples,
  459. const int frame_size)
  460. {
  461. int error;
  462. /* Make the FIFO as large as it needs to be to hold both,
  463. * the old and the new samples. */
  464. if ((error = av_audio_fifo_realloc(fifo, av_audio_fifo_size(fifo) + frame_size)) < 0) {
  465. fprintf(stderr, "Could not reallocate FIFO\n");
  466. return error;
  467. }
  468. /* Store the new samples in the FIFO buffer. */
  469. if (av_audio_fifo_write(fifo, (void **)converted_input_samples,
  470. frame_size) < frame_size) {
  471. fprintf(stderr, "Could not write data to FIFO\n");
  472. return AVERROR_EXIT;
  473. }
  474. return 0;
  475. }
  476. /**
  477. * Read one audio frame from the input file, decode, convert and store
  478. * it in the FIFO buffer.
  479. * @param fifo Buffer used for temporary storage
  480. * @param input_format_context Format context of the input file
  481. * @param input_codec_context Codec context of the input file
  482. * @param output_codec_context Codec context of the output file
  483. * @param resampler_context Resample context for the conversion
  484. * @param[out] finished Indicates whether the end of file has
  485. * been reached and all data has been
  486. * decoded. If this flag is false,
  487. * there is more data to be decoded,
  488. * i.e., this function has to be called
  489. * again.
  490. * @return Error code (0 if successful)
  491. */
  492. static int read_decode_convert_and_store(AVAudioFifo *fifo,
  493. AVFormatContext *input_format_context,
  494. AVCodecContext *input_codec_context,
  495. AVCodecContext *output_codec_context,
  496. SwrContext *resampler_context,
  497. int *finished)
  498. {
  499. /* Temporary storage of the input samples of the frame read from the file. */
  500. AVFrame *input_frame = NULL;
  501. /* Temporary storage for the converted input samples. */
  502. uint8_t **converted_input_samples = NULL;
  503. int data_present = 0;
  504. int ret = AVERROR_EXIT;
  505. /* Initialize temporary storage for one input frame. */
  506. if (init_input_frame(&input_frame))
  507. goto cleanup;
  508. /* Decode one frame worth of audio samples. */
  509. if (decode_audio_frame(input_frame, input_format_context,
  510. input_codec_context, &data_present, finished))
  511. goto cleanup;
  512. /* If we are at the end of the file and there are no more samples
  513. * in the decoder which are delayed, we are actually finished.
  514. * This must not be treated as an error. */
  515. if (*finished) {
  516. ret = 0;
  517. goto cleanup;
  518. }
  519. /* If there is decoded data, convert and store it. */
  520. if (data_present) {
  521. /* Initialize the temporary storage for the converted input samples. */
  522. if (init_converted_samples(&converted_input_samples, output_codec_context,
  523. input_frame->nb_samples))
  524. goto cleanup;
  525. /* Convert the input samples to the desired output sample format.
  526. * This requires a temporary storage provided by converted_input_samples. */
  527. if (convert_samples((const uint8_t**)input_frame->extended_data, converted_input_samples,
  528. input_frame->nb_samples, resampler_context))
  529. goto cleanup;
  530. /* Add the converted input samples to the FIFO buffer for later processing. */
  531. if (add_samples_to_fifo(fifo, converted_input_samples,
  532. input_frame->nb_samples))
  533. goto cleanup;
  534. ret = 0;
  535. }
  536. ret = 0;
  537. cleanup:
  538. if (converted_input_samples) {
  539. av_freep(&converted_input_samples[0]);
  540. free(converted_input_samples);
  541. }
  542. av_frame_free(&input_frame);
  543. return ret;
  544. }
  545. /**
  546. * Initialize one input frame for writing to the output file.
  547. * The frame will be exactly frame_size samples large.
  548. * @param[out] frame Frame to be initialized
  549. * @param output_codec_context Codec context of the output file
  550. * @param frame_size Size of the frame
  551. * @return Error code (0 if successful)
  552. */
  553. static int init_output_frame(AVFrame **frame,
  554. AVCodecContext *output_codec_context,
  555. int frame_size)
  556. {
  557. int error;
  558. /* Create a new frame to store the audio samples. */
  559. if (!(*frame = av_frame_alloc())) {
  560. fprintf(stderr, "Could not allocate output frame\n");
  561. return AVERROR_EXIT;
  562. }
  563. /* Set the frame's parameters, especially its size and format.
  564. * av_frame_get_buffer needs this to allocate memory for the
  565. * audio samples of the frame.
  566. * Default channel layouts based on the number of channels
  567. * are assumed for simplicity. */
  568. (*frame)->nb_samples = frame_size;
  569. (*frame)->channel_layout = output_codec_context->channel_layout;
  570. (*frame)->format = output_codec_context->sample_fmt;
  571. (*frame)->sample_rate = output_codec_context->sample_rate;
  572. /* Allocate the samples of the created frame. This call will make
  573. * sure that the audio frame can hold as many samples as specified. */
  574. if ((error = av_frame_get_buffer(*frame, 0)) < 0) {
  575. fprintf(stderr, "Could not allocate output frame samples (error '%s')\n",
  576. av_err2str(error));
  577. av_frame_free(frame);
  578. return error;
  579. }
  580. return 0;
  581. }
  582. /* Global timestamp for the audio frames. */
  583. static int64_t pts = 0;
  584. /**
  585. * Encode one frame worth of audio to the output file.
  586. * @param frame Samples to be encoded
  587. * @param output_format_context Format context of the output file
  588. * @param output_codec_context Codec context of the output file
  589. * @param[out] data_present Indicates whether data has been
  590. * encoded
  591. * @return Error code (0 if successful)
  592. */
  593. static int encode_audio_frame(AVFrame *frame,
  594. AVFormatContext *output_format_context,
  595. AVCodecContext *output_codec_context,
  596. int *data_present)
  597. {
  598. /* Packet used for temporary storage. */
  599. AVPacket output_packet;
  600. int error;
  601. 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. }
  615. else if (error < 0) {
  616. fprintf(stderr, "Could not send packet for encoding (error '%s')\n",
  617. av_err2str(error));
  618. return error;
  619. }
  620. /* Receive one encoded frame from the encoder. */
  621. error = avcodec_receive_packet(output_codec_context, &output_packet);
  622. /* If the encoder asks for more data to be able to provide an
  623. * encoded frame, return indicating that no data is present. */
  624. if (error == AVERROR(EAGAIN)) {
  625. error = 0;
  626. goto cleanup;
  627. /* If the last frame has been encoded, stop encoding. */
  628. }
  629. else if (error == AVERROR_EOF) {
  630. error = 0;
  631. goto cleanup;
  632. }
  633. else if (error < 0) {
  634. fprintf(stderr, "Could not encode frame (error '%s')\n",
  635. av_err2str(error));
  636. goto cleanup;
  637. /* Default case: Return encoded data. */
  638. }
  639. else {
  640. *data_present = 1;
  641. }
  642. /* Write one audio frame from the temporary packet to the output file. */
  643. if (*data_present &&
  644. (error = av_write_frame(output_format_context, &output_packet)) < 0) {
  645. fprintf(stderr, "Could not write frame (error '%s')\n",
  646. av_err2str(error));
  647. goto cleanup;
  648. }
  649. cleanup:
  650. av_packet_unref(&output_packet);
  651. return error;
  652. }
  653. /**
  654. * Load one audio frame from the FIFO buffer, encode and write it to the
  655. * output file.
  656. * @param fifo Buffer used for temporary storage
  657. * @param output_format_context Format context of the output file
  658. * @param output_codec_context Codec context of the output file
  659. * @return Error code (0 if successful)
  660. */
  661. static int load_encode_and_write(AVAudioFifo *fifo,
  662. AVFormatContext *output_format_context,
  663. AVCodecContext *output_codec_context)
  664. {
  665. /* Temporary storage of the output samples of the frame written to the file. */
  666. AVFrame *output_frame;
  667. /* Use the maximum number of possible samples per frame.
  668. * If there is less than the maximum possible frame size in the FIFO
  669. * buffer use this number. Otherwise, use the maximum possible frame size. */
  670. const int frame_size = FFMIN(av_audio_fifo_size(fifo),
  671. output_codec_context->frame_size);
  672. int data_written;
  673. /* Initialize temporary storage for one output frame. */
  674. if (init_output_frame(&output_frame, output_codec_context, frame_size))
  675. return AVERROR_EXIT;
  676. /* Read as many samples from the FIFO buffer as required to fill the frame.
  677. * The samples are stored in the frame temporarily. */
  678. if (av_audio_fifo_read(fifo, (void **)output_frame->data, frame_size) < frame_size) {
  679. fprintf(stderr, "Could not read data from FIFO\n");
  680. av_frame_free(&output_frame);
  681. return AVERROR_EXIT;
  682. }
  683. /* Encode one frame worth of audio samples. */
  684. if (encode_audio_frame(output_frame, output_format_context,
  685. output_codec_context, &data_written)) {
  686. av_frame_free(&output_frame);
  687. return AVERROR_EXIT;
  688. }
  689. av_frame_free(&output_frame);
  690. return 0;
  691. }
  692. /**
  693. * Write the trailer of the output file container.
  694. * @param output_format_context Format context of the output file
  695. * @return Error code (0 if successful)
  696. */
  697. static int write_output_file_trailer(AVFormatContext *output_format_context)
  698. {
  699. int error;
  700. if ((error = av_write_trailer(output_format_context)) < 0) {
  701. fprintf(stderr, "Could not write output file trailer (error '%s')\n",
  702. av_err2str(error));
  703. return error;
  704. }
  705. return 0;
  706. }
  707. int test_transcode()
  708. {
  709. AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
  710. AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
  711. SwrContext *resample_context = NULL;
  712. AVAudioFifo *fifo = NULL;
  713. int ret = AVERROR_EXIT;
  714. //if (argc != 3) {
  715. // fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
  716. // exit(1);
  717. //}
  718. const char *inputfile = "WAS_2019-09-05_14_19_42_109.wav";
  719. const char *outputfile = "transcode.aac";
  720. /* Open the input file for reading. */
  721. if (open_input_file(inputfile, &input_format_context,
  722. &input_codec_context))
  723. goto cleanup;
  724. /* Open the output file for writing. */
  725. if (open_output_file(outputfile, input_codec_context,
  726. &output_format_context, &output_codec_context))
  727. goto cleanup;
  728. /* Initialize the resampler to be able to convert audio sample formats. */
  729. if (init_resampler(input_codec_context, output_codec_context,
  730. &resample_context))
  731. goto cleanup;
  732. /* Initialize the FIFO buffer to store audio samples to be encoded. */
  733. if (init_fifo(&fifo, output_codec_context))
  734. goto cleanup;
  735. /* Write the header of the output file container. */
  736. if (write_output_file_header(output_format_context))
  737. goto cleanup;
  738. /* Loop as long as we have input samples to read or output samples
  739. * to write; abort as soon as we have neither. */
  740. while (1) {
  741. /* Use the encoder's desired frame size for processing. */
  742. const int output_frame_size = output_codec_context->frame_size;
  743. int finished = 0;
  744. /* Make sure that there is one frame worth of samples in the FIFO
  745. * buffer so that the encoder can do its work.
  746. * Since the decoder's and the encoder's frame size may differ, we
  747. * need to FIFO buffer to store as many frames worth of input samples
  748. * that they make up at least one frame worth of output samples. */
  749. while (av_audio_fifo_size(fifo) < output_frame_size) {
  750. /* Decode one frame worth of audio samples, convert it to the
  751. * output sample format and put it into the FIFO buffer. */
  752. if (read_decode_convert_and_store(fifo, input_format_context,
  753. input_codec_context,
  754. output_codec_context,
  755. resample_context, &finished))
  756. goto cleanup;
  757. /* If we are at the end of the input file, we continue
  758. * encoding the remaining audio samples to the output file. */
  759. if (finished)
  760. break;
  761. }
  762. /* If we have enough samples for the encoder, we encode them.
  763. * At the end of the file, we pass the remaining samples to
  764. * the encoder. */
  765. while (av_audio_fifo_size(fifo) >= output_frame_size ||
  766. (finished && av_audio_fifo_size(fifo) > 0))
  767. /* Take one frame worth of audio samples from the FIFO buffer,
  768. * encode it and write it to the output file. */
  769. if (load_encode_and_write(fifo, output_format_context,
  770. output_codec_context))
  771. goto cleanup;
  772. /* If we are at the end of the input file and have encoded
  773. * all remaining samples, we can exit this loop and finish. */
  774. if (finished) {
  775. int data_written;
  776. /* Flush the encoder as it may have delayed frames. */
  777. do {
  778. data_written = 0;
  779. if (encode_audio_frame(NULL, output_format_context,
  780. output_codec_context, &data_written))
  781. goto cleanup;
  782. } while (data_written);
  783. break;
  784. }
  785. }
  786. /* Write the trailer of the output file container. */
  787. if (write_output_file_trailer(output_format_context))
  788. goto cleanup;
  789. ret = 0;
  790. cleanup:
  791. if (fifo)
  792. av_audio_fifo_free(fifo);
  793. swr_free(&resample_context);
  794. if (output_codec_context)
  795. avcodec_free_context(&output_codec_context);
  796. if (output_format_context) {
  797. avio_closep(&output_format_context->pb);
  798. avformat_free_context(output_format_context);
  799. }
  800. if (input_codec_context)
  801. avcodec_free_context(&input_codec_context);
  802. if (input_format_context)
  803. avformat_close_input(&input_format_context);
  804. return ret;
  805. }
  806. int main1(int argc, char **argv)
  807. {
  808. AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
  809. AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
  810. SwrContext *resample_context = NULL;
  811. AVAudioFifo *fifo = NULL;
  812. int ret = AVERROR_EXIT;
  813. //if (argc != 3) {
  814. // fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
  815. // exit(1);
  816. //}
  817. const char *inputfile = "WAS_2019-09-05_14_19_42_109.wav";
  818. const char *outputfile = "transcode.aac";
  819. /* Open the input file for reading. */
  820. if (open_input_file(inputfile, &input_format_context,
  821. &input_codec_context))
  822. goto cleanup;
  823. /* Open the output file for writing. */
  824. if (open_output_file(outputfile, input_codec_context,
  825. &output_format_context, &output_codec_context))
  826. goto cleanup;
  827. /* Initialize the resampler to be able to convert audio sample formats. */
  828. if (init_resampler(input_codec_context, output_codec_context,
  829. &resample_context))
  830. goto cleanup;
  831. /* Initialize the FIFO buffer to store audio samples to be encoded. */
  832. if (init_fifo(&fifo, output_codec_context))
  833. goto cleanup;
  834. /* Write the header of the output file container. */
  835. if (write_output_file_header(output_format_context))
  836. goto cleanup;
  837. /* Loop as long as we have input samples to read or output samples
  838. * to write; abort as soon as we have neither. */
  839. while (1) {
  840. /* Use the encoder's desired frame size for processing. */
  841. const int output_frame_size = output_codec_context->frame_size;
  842. int finished = 0;
  843. /* Make sure that there is one frame worth of samples in the FIFO
  844. * buffer so that the encoder can do its work.
  845. * Since the decoder's and the encoder's frame size may differ, we
  846. * need to FIFO buffer to store as many frames worth of input samples
  847. * that they make up at least one frame worth of output samples. */
  848. while (av_audio_fifo_size(fifo) < output_frame_size) {
  849. /* Decode one frame worth of audio samples, convert it to the
  850. * output sample format and put it into the FIFO buffer. */
  851. if (read_decode_convert_and_store(fifo, input_format_context,
  852. input_codec_context,
  853. output_codec_context,
  854. resample_context, &finished))
  855. goto cleanup;
  856. /* If we are at the end of the input file, we continue
  857. * encoding the remaining audio samples to the output file. */
  858. if (finished)
  859. break;
  860. }
  861. /* If we have enough samples for the encoder, we encode them.
  862. * At the end of the file, we pass the remaining samples to
  863. * the encoder. */
  864. while (av_audio_fifo_size(fifo) >= output_frame_size ||
  865. (finished && av_audio_fifo_size(fifo) > 0))
  866. /* Take one frame worth of audio samples from the FIFO buffer,
  867. * encode it and write it to the output file. */
  868. if (load_encode_and_write(fifo, output_format_context,
  869. output_codec_context))
  870. goto cleanup;
  871. /* If we are at the end of the input file and have encoded
  872. * all remaining samples, we can exit this loop and finish. */
  873. if (finished) {
  874. int data_written;
  875. /* Flush the encoder as it may have delayed frames. */
  876. do {
  877. data_written = 0;
  878. if (encode_audio_frame(NULL, output_format_context,
  879. output_codec_context, &data_written))
  880. goto cleanup;
  881. } while (data_written);
  882. break;
  883. }
  884. }
  885. /* Write the trailer of the output file container. */
  886. if (write_output_file_trailer(output_format_context))
  887. goto cleanup;
  888. ret = 0;
  889. cleanup:
  890. if (fifo)
  891. av_audio_fifo_free(fifo);
  892. swr_free(&resample_context);
  893. if (output_codec_context)
  894. avcodec_free_context(&output_codec_context);
  895. if (output_format_context) {
  896. avio_closep(&output_format_context->pb);
  897. avformat_free_context(output_format_context);
  898. }
  899. if (input_codec_context)
  900. avcodec_free_context(&input_codec_context);
  901. if (input_format_context)
  902. avformat_close_input(&input_format_context);
  903. return ret;
  904. }