transcode_aac.cpp 38 KB

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