transcode_aac.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000
  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. extern "C" {
  31. #include <libavformat/avformat.h>
  32. #include <libavformat/avio.h>
  33. #include <libavutil/audio_fifo.h>
  34. #include <libswresample/swresample.h>
  35. }
  36. #include "headers_ffmpeg.h"
  37. /* The output bit rate in bit/s */
  38. #define OUTPUT_BIT_RATE 96000
  39. /* The number of output channels */
  40. #define OUTPUT_CHANNELS 2
  41. /**
  42. * Open an input file and the required decoder.
  43. * @param filename File to be opened
  44. * @param[out] input_format_context Format context of opened file
  45. * @param[out] input_codec_context Codec context of opened file
  46. * @return Error code (0 if successful)
  47. */
  48. static int open_input_file(const char *filename,
  49. AVFormatContext **input_format_context,
  50. AVCodecContext **input_codec_context)
  51. {
  52. AVCodecContext *avctx;
  53. FFmpegCodec *input_codec;
  54. int error;
  55. /* Open the input file to read from it. */
  56. if ((error = avformat_open_input(input_format_context, filename, NULL, NULL)) < 0) {
  57. fprintf(stderr,
  58. "Could not open input file '%s' (error '%s')\n",
  59. filename,
  60. av_err2str(error));
  61. *input_format_context = NULL;
  62. return error;
  63. }
  64. /* Get information on the input file (number of streams etc.). */
  65. if ((error = avformat_find_stream_info(*input_format_context, NULL)) < 0) {
  66. fprintf(stderr, "Could not open find stream info (error '%s')\n", av_err2str(error));
  67. avformat_close_input(input_format_context);
  68. return error;
  69. }
  70. /* Make sure that there is only one stream in the input file. */
  71. if ((*input_format_context)->nb_streams != 1) {
  72. fprintf(stderr,
  73. "Expected one audio input stream, but found %d\n",
  74. (*input_format_context)->nb_streams);
  75. avformat_close_input(input_format_context);
  76. return AVERROR_EXIT;
  77. }
  78. /* Find a decoder for the audio stream. */
  79. if (!(input_codec = avcodec_find_decoder(
  80. (*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", av_err2str(error));
  102. avcodec_free_context(&avctx);
  103. avformat_close_input(input_format_context);
  104. return error;
  105. }
  106. /* Save the decoder context for easier access later. */
  107. *input_codec_context = avctx;
  108. return 0;
  109. }
  110. /**
  111. * Open an output file and the required encoder.
  112. * Also set some basic encoder parameters.
  113. * Some of these parameters are based on the input file's parameters.
  114. * @param filename File to be opened
  115. * @param input_codec_context Codec context of input file
  116. * @param[out] output_format_context Format context of output file
  117. * @param[out] output_codec_context Codec context of output file
  118. * @return Error code (0 if successful)
  119. */
  120. static int open_output_file(const char *filename,
  121. AVCodecContext *input_codec_context,
  122. AVFormatContext **output_format_context,
  123. AVCodecContext **output_codec_context)
  124. {
  125. AVCodecContext *avctx = NULL;
  126. AVIOContext *output_io_context = NULL;
  127. AVStream *stream = NULL;
  128. FFmpegCodec *output_codec = NULL;
  129. int error;
  130. /* Open the output file to write to it. */
  131. if ((error = avio_open(&output_io_context, filename, AVIO_FLAG_WRITE)) < 0) {
  132. fprintf(stderr,
  133. "Could not open output file '%s' (error '%s')\n",
  134. filename,
  135. 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, NULL))) {
  147. fprintf(stderr, "Could not find output file format\n");
  148. goto cleanup;
  149. }
  150. if (!((*output_format_context)->url = av_strdup(filename))) {
  151. fprintf(stderr, "Could not allocate url.\n");
  152. error = AVERROR(ENOMEM);
  153. goto cleanup;
  154. }
  155. /* Find the encoder to be used by its name. */
  156. if (!(output_codec = avcodec_find_encoder(AV_CODEC_ID_AAC))) {
  157. fprintf(stderr, "Could not find an AAC encoder.\n");
  158. goto cleanup;
  159. }
  160. /* Create a new audio stream in the output file container. */
  161. if (!(stream = avformat_new_stream(*output_format_context, NULL))) {
  162. fprintf(stderr, "Could not create new stream\n");
  163. error = AVERROR(ENOMEM);
  164. goto cleanup;
  165. }
  166. avctx = avcodec_alloc_context3(output_codec);
  167. if (!avctx) {
  168. fprintf(stderr, "Could not allocate an encoding context\n");
  169. error = AVERROR(ENOMEM);
  170. goto cleanup;
  171. }
  172. /* Set the basic encoder parameters.
  173. * The input file's sample rate is used to avoid a sample rate conversion. */
  174. ffmpeg_set_codec_channels(avctx, OUTPUT_CHANNELS);
  175. ffmpeg_set_codec_channel_layout(avctx, ffmpeg_get_default_channel_layout(OUTPUT_CHANNELS));
  176. avctx->sample_rate = input_codec_context->sample_rate;
  177. avctx->sample_fmt = output_codec->sample_fmts[0];
  178. avctx->bit_rate = OUTPUT_BIT_RATE;
  179. /* Allow the use of the experimental AAC encoder. */
  180. avctx->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
  181. /* Set the sample rate for the container. */
  182. stream->time_base.den = input_codec_context->sample_rate;
  183. stream->time_base.num = 1;
  184. /* Some container formats (like MP4) require global headers to be present.
  185. * Mark the encoder so that it behaves accordingly. */
  186. if ((*output_format_context)->oformat->flags & AVFMT_GLOBALHEADER)
  187. avctx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
  188. /* Open the encoder for the audio stream to use it later. */
  189. if ((error = avcodec_open2(avctx, output_codec, NULL)) < 0) {
  190. fprintf(stderr, "Could not open output codec (error '%s')\n", av_err2str(error));
  191. goto cleanup;
  192. }
  193. error = avcodec_parameters_from_context(stream->codecpar, avctx);
  194. if (error < 0) {
  195. fprintf(stderr, "Could not initialize stream parameters\n");
  196. goto cleanup;
  197. }
  198. /* Save the encoder context for easier access later. */
  199. *output_codec_context = avctx;
  200. return 0;
  201. cleanup:
  202. avcodec_free_context(&avctx);
  203. avio_closep(&(*output_format_context)->pb);
  204. avformat_free_context(*output_format_context);
  205. *output_format_context = NULL;
  206. return error < 0 ? error : AVERROR_EXIT;
  207. }
  208. /**
  209. * Initialize one data packet for reading or writing.
  210. * @param packet Packet to be initialized
  211. */
  212. static void init_packet(AVPacket *packet)
  213. {
  214. av_init_packet(packet);
  215. /* Set the packet data and size so that it is recognized as being empty. */
  216. packet->data = NULL;
  217. packet->size = 0;
  218. }
  219. /**
  220. * Initialize one audio frame for reading from the input file.
  221. * @param[out] frame Frame to be initialized
  222. * @return Error code (0 if successful)
  223. */
  224. static int init_input_frame(AVFrame **frame)
  225. {
  226. if (!(*frame = av_frame_alloc())) {
  227. fprintf(stderr, "Could not allocate input frame\n");
  228. return AVERROR(ENOMEM);
  229. }
  230. return 0;
  231. }
  232. /**
  233. * Initialize the audio resampler based on the input and output codec settings.
  234. * If the input and output sample formats differ, a conversion is required
  235. * libswresample takes care of this, but requires initialization.
  236. * @param input_codec_context Codec context of the input file
  237. * @param output_codec_context Codec context of the output file
  238. * @param[out] resample_context Resample context for the required conversion
  239. * @return Error code (0 if successful)
  240. */
  241. static int init_resampler(AVCodecContext *input_codec_context,
  242. AVCodecContext *output_codec_context,
  243. SwrContext **resample_context)
  244. {
  245. int error;
  246. /*
  247. * Create a resampler context for the conversion.
  248. * Set the conversion parameters.
  249. * Default channel layouts based on the number of channels
  250. * are assumed for simplicity (they are sometimes not detected
  251. * properly by the demuxer and/or decoder).
  252. */
  253. *resample_context
  254. = ffmpeg_swr_alloc_set_opts(NULL,
  255. ffmpeg_get_default_channel_layout(ffmpeg_get_codec_context_channels(output_codec_context)),
  256. output_codec_context->sample_fmt,
  257. output_codec_context->sample_rate,
  258. ffmpeg_get_default_channel_layout(ffmpeg_get_codec_context_channels(input_codec_context)),
  259. input_codec_context->sample_fmt,
  260. input_codec_context->sample_rate,
  261. 0,
  262. 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. ffmpeg_get_codec_context_channels(output_codec_context),
  292. 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", 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,
  329. 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", 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", av_err2str(error));
  349. return error;
  350. }
  351. /* Receive one frame from the decoder. */
  352. error = avcodec_receive_frame(input_codec_context, frame);
  353. /* If the decoder asks for more data to be able to decode a frame,
  354. * return indicating that no data is present. */
  355. if (error == AVERROR(EAGAIN)) {
  356. error = 0;
  357. goto cleanup;
  358. /* If the end of the input file is reached, stop decoding. */
  359. } else if (error == AVERROR_EOF) {
  360. *finished = 1;
  361. error = 0;
  362. goto cleanup;
  363. } else if (error < 0) {
  364. fprintf(stderr, "Could not decode frame (error '%s')\n", av_err2str(error));
  365. goto cleanup;
  366. /* Default case: Return decoded data. */
  367. } else {
  368. *data_present = 1;
  369. goto cleanup;
  370. }
  371. cleanup:
  372. av_packet_unref(&input_packet);
  373. return error;
  374. }
  375. /**
  376. * Initialize a temporary storage for the specified number of audio samples.
  377. * The conversion requires temporary storage due to the different format.
  378. * The number of audio samples to be allocated is specified in frame_size.
  379. * @param[out] converted_input_samples Array of converted samples. The
  380. * dimensions are reference, channel
  381. * (for multi-channel audio), sample.
  382. * @param output_codec_context Codec context of the output file
  383. * @param frame_size Number of samples to be converted in
  384. * each round
  385. * @return Error code (0 if successful)
  386. */
  387. static int init_converted_samples(uint8_t ***converted_input_samples,
  388. AVCodecContext *output_codec_context,
  389. int frame_size)
  390. {
  391. int error;
  392. /* Allocate as many pointers as there are audio channels.
  393. * Each pointer will later point to the audio samples of the corresponding
  394. * channels (although it may be NULL for interleaved formats).
  395. */
  396. if (!(*converted_input_samples = (uint8_t **) calloc(ffmpeg_get_codec_context_channels(output_codec_context),
  397. sizeof(**converted_input_samples)))) {
  398. fprintf(stderr, "Could not allocate converted input sample pointers\n");
  399. return AVERROR(ENOMEM);
  400. }
  401. /* Allocate memory for the samples of all channels in one consecutive
  402. * block for convenience. */
  403. if ((error = ffmpeg_av_samples_alloc(*converted_input_samples,
  404. NULL,
  405. ffmpeg_get_codec_context_channels(output_codec_context),
  406. frame_size,
  407. output_codec_context->sample_fmt,
  408. 0))
  409. < 0) {
  410. fprintf(stderr,
  411. "Could not allocate converted input samples (error '%s')\n",
  412. av_err2str(error));
  413. av_freep(&(*converted_input_samples)[0]);
  414. free(*converted_input_samples);
  415. return error;
  416. }
  417. return 0;
  418. }
  419. /**
  420. * Convert the input audio samples into the output sample format.
  421. * The conversion happens on a per-frame basis, the size of which is
  422. * specified by frame_size.
  423. * @param input_data Samples to be decoded. The dimensions are
  424. * channel (for multi-channel audio), sample.
  425. * @param[out] converted_data Converted samples. The dimensions are channel
  426. * (for multi-channel audio), sample.
  427. * @param frame_size Number of samples to be converted
  428. * @param resample_context Resample context for the conversion
  429. * @return Error code (0 if successful)
  430. */
  431. static int convert_samples(const uint8_t **input_data,
  432. uint8_t **converted_data,
  433. const int frame_size,
  434. SwrContext *resample_context)
  435. {
  436. int error;
  437. /* Convert the samples using the resampler. */
  438. if ((error = swr_convert(resample_context, converted_data, frame_size, input_data, frame_size))
  439. < 0) {
  440. fprintf(stderr, "Could not convert input samples (error '%s')\n", 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, frame_size) < frame_size) {
  466. fprintf(stderr, "Could not write data to FIFO\n");
  467. return AVERROR_EXIT;
  468. }
  469. return 0;
  470. }
  471. /**
  472. * Read one audio frame from the input file, decode, convert and store
  473. * it in the FIFO buffer.
  474. * @param fifo Buffer used for temporary storage
  475. * @param input_format_context Format context of the input file
  476. * @param input_codec_context Codec context of the input file
  477. * @param output_codec_context Codec context of the output file
  478. * @param resampler_context Resample context for the conversion
  479. * @param[out] finished Indicates whether the end of file has
  480. * been reached and all data has been
  481. * decoded. If this flag is false,
  482. * there is more data to be decoded,
  483. * i.e., this function has to be called
  484. * again.
  485. * @return Error code (0 if successful)
  486. */
  487. static int read_decode_convert_and_store(AVAudioFifo *fifo,
  488. AVFormatContext *input_format_context,
  489. AVCodecContext *input_codec_context,
  490. AVCodecContext *output_codec_context,
  491. SwrContext *resampler_context,
  492. int *finished)
  493. {
  494. /* Temporary storage of the input samples of the frame read from the file. */
  495. AVFrame *input_frame = NULL;
  496. /* Temporary storage for the converted input samples. */
  497. uint8_t **converted_input_samples = NULL;
  498. int data_present = 0;
  499. int ret = AVERROR_EXIT;
  500. /* Initialize temporary storage for one input frame. */
  501. if (init_input_frame(&input_frame))
  502. goto cleanup;
  503. /* Decode one frame worth of audio samples. */
  504. if (decode_audio_frame(input_frame,
  505. input_format_context,
  506. input_codec_context,
  507. &data_present,
  508. finished))
  509. goto cleanup;
  510. /* If we are at the end of the file and there are no more samples
  511. * in the decoder which are delayed, we are actually finished.
  512. * This must not be treated as an error. */
  513. if (*finished) {
  514. ret = 0;
  515. goto cleanup;
  516. }
  517. /* If there is decoded data, convert and store it. */
  518. if (data_present) {
  519. /* Initialize the temporary storage for the converted input samples. */
  520. if (init_converted_samples(&converted_input_samples,
  521. output_codec_context,
  522. input_frame->nb_samples))
  523. goto cleanup;
  524. /* Convert the input samples to the desired output sample format.
  525. * This requires a temporary storage provided by converted_input_samples. */
  526. if (convert_samples((const uint8_t **) input_frame->extended_data,
  527. converted_input_samples,
  528. input_frame->nb_samples,
  529. resampler_context))
  530. goto cleanup;
  531. /* Add the converted input samples to the FIFO buffer for later processing. */
  532. if (add_samples_to_fifo(fifo, converted_input_samples, 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, AVCodecContext *output_codec_context, int frame_size)
  554. {
  555. int error;
  556. /* Create a new frame to store the audio samples. */
  557. if (!(*frame = av_frame_alloc())) {
  558. fprintf(stderr, "Could not allocate output frame\n");
  559. return AVERROR_EXIT;
  560. }
  561. /* Set the frame's parameters, especially its size and format.
  562. * av_frame_get_buffer needs this to allocate memory for the
  563. * audio samples of the frame.
  564. * Default channel layouts based on the number of channels
  565. * are assumed for simplicity. */
  566. (*frame)->nb_samples = frame_size;
  567. ffmpeg_set_frame_channel_layout(*frame, output_codec_context);
  568. (*frame)->format = output_codec_context->sample_fmt;
  569. (*frame)->sample_rate = output_codec_context->sample_rate;
  570. /* Allocate the samples of the created frame. This call will make
  571. * sure that the audio frame can hold as many samples as specified. */
  572. if ((error = av_frame_get_buffer(*frame, 0)) < 0) {
  573. fprintf(stderr, "Could not allocate output frame samples (error '%s')\n", av_err2str(error));
  574. av_frame_free(frame);
  575. return error;
  576. }
  577. return 0;
  578. }
  579. /* Global timestamp for the audio frames. */
  580. static int64_t pts = 0;
  581. /**
  582. * Encode one frame worth of audio to the output file.
  583. * @param frame Samples to be encoded
  584. * @param output_format_context Format context of the output file
  585. * @param output_codec_context Codec context of the output file
  586. * @param[out] data_present Indicates whether data has been
  587. * encoded
  588. * @return Error code (0 if successful)
  589. */
  590. static int encode_audio_frame(AVFrame *frame,
  591. AVFormatContext *output_format_context,
  592. AVCodecContext *output_codec_context,
  593. int *data_present)
  594. {
  595. /* Packet used for temporary storage. */
  596. AVPacket output_packet;
  597. int error;
  598. init_packet(&output_packet);
  599. /* Set a timestamp based on the sample rate for the container. */
  600. if (frame) {
  601. frame->pts = pts;
  602. pts += frame->nb_samples;
  603. }
  604. /* Send the audio frame stored in the temporary packet to the encoder.
  605. * The output audio stream encoder is used to do this. */
  606. error = avcodec_send_frame(output_codec_context, frame);
  607. /* The encoder signals that it has nothing more to encode. */
  608. if (error == AVERROR_EOF) {
  609. error = 0;
  610. goto cleanup;
  611. } else if (error < 0) {
  612. fprintf(stderr, "Could not send packet for encoding (error '%s')\n", 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", av_err2str(error));
  628. goto cleanup;
  629. /* Default case: Return encoded data. */
  630. } else {
  631. *data_present = 1;
  632. }
  633. /* Write one audio frame from the temporary packet to the output file. */
  634. if (*data_present && (error = av_write_frame(output_format_context, &output_packet)) < 0) {
  635. fprintf(stderr, "Could not write frame (error '%s')\n", av_err2str(error));
  636. goto cleanup;
  637. }
  638. cleanup:
  639. av_packet_unref(&output_packet);
  640. return error;
  641. }
  642. /**
  643. * Load one audio frame from the FIFO buffer, encode and write it to the
  644. * output file.
  645. * @param fifo Buffer used for temporary storage
  646. * @param output_format_context Format context of the output file
  647. * @param output_codec_context Codec context of the output file
  648. * @return Error code (0 if successful)
  649. */
  650. static int load_encode_and_write(AVAudioFifo *fifo,
  651. AVFormatContext *output_format_context,
  652. AVCodecContext *output_codec_context)
  653. {
  654. /* Temporary storage of the output samples of the frame written to the file. */
  655. AVFrame *output_frame;
  656. /* Use the maximum number of possible samples per frame.
  657. * If there is less than the maximum possible frame size in the FIFO
  658. * buffer use this number. Otherwise, use the maximum possible frame size. */
  659. const int frame_size = FFMIN(av_audio_fifo_size(fifo), output_codec_context->frame_size);
  660. int data_written;
  661. /* Initialize temporary storage for one output frame. */
  662. if (init_output_frame(&output_frame, output_codec_context, frame_size))
  663. return AVERROR_EXIT;
  664. /* Read as many samples from the FIFO buffer as required to fill the frame.
  665. * The samples are stored in the frame temporarily. */
  666. if (av_audio_fifo_read(fifo, (void **) output_frame->data, frame_size) < frame_size) {
  667. fprintf(stderr, "Could not read data from FIFO\n");
  668. av_frame_free(&output_frame);
  669. return AVERROR_EXIT;
  670. }
  671. /* Encode one frame worth of audio samples. */
  672. if (encode_audio_frame(output_frame,
  673. output_format_context,
  674. output_codec_context,
  675. &data_written)) {
  676. av_frame_free(&output_frame);
  677. return AVERROR_EXIT;
  678. }
  679. av_frame_free(&output_frame);
  680. return 0;
  681. }
  682. /**
  683. * Write the trailer of the output file container.
  684. * @param output_format_context Format context of the output file
  685. * @return Error code (0 if successful)
  686. */
  687. static int write_output_file_trailer(AVFormatContext *output_format_context)
  688. {
  689. int error;
  690. if ((error = av_write_trailer(output_format_context)) < 0) {
  691. fprintf(stderr, "Could not write output file trailer (error '%s')\n", av_err2str(error));
  692. return error;
  693. }
  694. return 0;
  695. }
  696. int test_transcode()
  697. {
  698. AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
  699. AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
  700. SwrContext *resample_context = NULL;
  701. AVAudioFifo *fifo = NULL;
  702. int ret = AVERROR_EXIT;
  703. //if (argc != 3) {
  704. // fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
  705. // exit(1);
  706. //}
  707. const char *inputfile = "WAS_2019-09-05_14_19_42_109.wav";
  708. const char *outputfile = "transcode.aac";
  709. /* Open the input file for reading. */
  710. if (open_input_file(inputfile, &input_format_context, &input_codec_context))
  711. goto cleanup;
  712. /* Open the output file for writing. */
  713. if (open_output_file(outputfile,
  714. input_codec_context,
  715. &output_format_context,
  716. &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, &resample_context))
  720. goto cleanup;
  721. /* Initialize the FIFO buffer to store audio samples to be encoded. */
  722. if (init_fifo(&fifo, output_codec_context))
  723. goto cleanup;
  724. /* Write the header of the output file container. */
  725. if (write_output_file_header(output_format_context))
  726. goto cleanup;
  727. /* Loop as long as we have input samples to read or output samples
  728. * to write; abort as soon as we have neither. */
  729. while (1) {
  730. /* Use the encoder's desired frame size for processing. */
  731. const int output_frame_size = output_codec_context->frame_size;
  732. int finished = 0;
  733. /* Make sure that there is one frame worth of samples in the FIFO
  734. * buffer so that the encoder can do its work.
  735. * Since the decoder's and the encoder's frame size may differ, we
  736. * need to FIFO buffer to store as many frames worth of input samples
  737. * that they make up at least one frame worth of output samples. */
  738. while (av_audio_fifo_size(fifo) < output_frame_size) {
  739. /* Decode one frame worth of audio samples, convert it to the
  740. * output sample format and put it into the FIFO buffer. */
  741. if (read_decode_convert_and_store(fifo,
  742. input_format_context,
  743. input_codec_context,
  744. output_codec_context,
  745. resample_context,
  746. &finished))
  747. goto cleanup;
  748. /* If we are at the end of the input file, we continue
  749. * encoding the remaining audio samples to the output file. */
  750. if (finished)
  751. break;
  752. }
  753. /* If we have enough samples for the encoder, we encode them.
  754. * At the end of the file, we pass the remaining samples to
  755. * the encoder. */
  756. while (av_audio_fifo_size(fifo) >= output_frame_size
  757. || (finished && av_audio_fifo_size(fifo) > 0))
  758. /* Take one frame worth of audio samples from the FIFO buffer,
  759. * encode it and write it to the output file. */
  760. if (load_encode_and_write(fifo, output_format_context, 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,
  770. output_format_context,
  771. output_codec_context,
  772. &data_written))
  773. goto cleanup;
  774. } while (data_written);
  775. break;
  776. }
  777. }
  778. /* Write the trailer of the output file container. */
  779. if (write_output_file_trailer(output_format_context))
  780. goto cleanup;
  781. ret = 0;
  782. cleanup:
  783. if (fifo)
  784. av_audio_fifo_free(fifo);
  785. swr_free(&resample_context);
  786. if (output_codec_context)
  787. avcodec_free_context(&output_codec_context);
  788. if (output_format_context) {
  789. avio_closep(&output_format_context->pb);
  790. avformat_free_context(output_format_context);
  791. }
  792. if (input_codec_context)
  793. avcodec_free_context(&input_codec_context);
  794. if (input_format_context)
  795. avformat_close_input(&input_format_context);
  796. return ret;
  797. }
  798. int main1(int argc, char **argv)
  799. {
  800. AVFormatContext *input_format_context = NULL, *output_format_context = NULL;
  801. AVCodecContext *input_codec_context = NULL, *output_codec_context = NULL;
  802. SwrContext *resample_context = NULL;
  803. AVAudioFifo *fifo = NULL;
  804. int ret = AVERROR_EXIT;
  805. //if (argc != 3) {
  806. // fprintf(stderr, "Usage: %s <input file> <output file>\n", argv[0]);
  807. // exit(1);
  808. //}
  809. const char *inputfile = "WAS_2019-09-05_14_19_42_109.wav";
  810. const char *outputfile = "transcode.aac";
  811. /* Open the input file for reading. */
  812. if (open_input_file(inputfile, &input_format_context, &input_codec_context))
  813. goto cleanup;
  814. /* Open the output file for writing. */
  815. if (open_output_file(outputfile,
  816. input_codec_context,
  817. &output_format_context,
  818. &output_codec_context))
  819. goto cleanup;
  820. /* Initialize the resampler to be able to convert audio sample formats. */
  821. if (init_resampler(input_codec_context, output_codec_context, &resample_context))
  822. goto cleanup;
  823. /* Initialize the FIFO buffer to store audio samples to be encoded. */
  824. if (init_fifo(&fifo, output_codec_context))
  825. goto cleanup;
  826. /* Write the header of the output file container. */
  827. if (write_output_file_header(output_format_context))
  828. goto cleanup;
  829. /* Loop as long as we have input samples to read or output samples
  830. * to write; abort as soon as we have neither. */
  831. while (1) {
  832. /* Use the encoder's desired frame size for processing. */
  833. const int output_frame_size = output_codec_context->frame_size;
  834. int finished = 0;
  835. /* Make sure that there is one frame worth of samples in the FIFO
  836. * buffer so that the encoder can do its work.
  837. * Since the decoder's and the encoder's frame size may differ, we
  838. * need to FIFO buffer to store as many frames worth of input samples
  839. * that they make up at least one frame worth of output samples. */
  840. while (av_audio_fifo_size(fifo) < output_frame_size) {
  841. /* Decode one frame worth of audio samples, convert it to the
  842. * output sample format and put it into the FIFO buffer. */
  843. if (read_decode_convert_and_store(fifo,
  844. input_format_context,
  845. input_codec_context,
  846. output_codec_context,
  847. resample_context,
  848. &finished))
  849. goto cleanup;
  850. /* If we are at the end of the input file, we continue
  851. * encoding the remaining audio samples to the output file. */
  852. if (finished)
  853. break;
  854. }
  855. /* If we have enough samples for the encoder, we encode them.
  856. * At the end of the file, we pass the remaining samples to
  857. * the encoder. */
  858. while (av_audio_fifo_size(fifo) >= output_frame_size
  859. || (finished && av_audio_fifo_size(fifo) > 0))
  860. /* Take one frame worth of audio samples from the FIFO buffer,
  861. * encode it and write it to the output file. */
  862. if (load_encode_and_write(fifo, output_format_context, output_codec_context))
  863. goto cleanup;
  864. /* If we are at the end of the input file and have encoded
  865. * all remaining samples, we can exit this loop and finish. */
  866. if (finished) {
  867. int data_written;
  868. /* Flush the encoder as it may have delayed frames. */
  869. do {
  870. data_written = 0;
  871. if (encode_audio_frame(NULL,
  872. output_format_context,
  873. output_codec_context,
  874. &data_written))
  875. goto cleanup;
  876. } while (data_written);
  877. break;
  878. }
  879. }
  880. /* Write the trailer of the output file container. */
  881. if (write_output_file_trailer(output_format_context))
  882. goto cleanup;
  883. ret = 0;
  884. cleanup:
  885. if (fifo)
  886. av_audio_fifo_free(fifo);
  887. swr_free(&resample_context);
  888. if (output_codec_context)
  889. avcodec_free_context(&output_codec_context);
  890. if (output_format_context) {
  891. avio_closep(&output_format_context->pb);
  892. avformat_free_context(output_format_context);
  893. }
  894. if (input_codec_context)
  895. avcodec_free_context(&input_codec_context);
  896. if (input_format_context)
  897. avformat_close_input(&input_format_context);
  898. return ret;
  899. }