🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4377 lines
167 KiB

  1. // WAV audio loader and writer. Public domain. See "unlicense" statement at the end of this file.
  2. // dr_wav - v0.9.0 - 2018-12-16
  3. //
  4. // David Reid - mackron@gmail.com
  5. /*
  6. DEPRECATED APIS
  7. ===============
  8. Version 0.9.0 deprecated the per-sample reading and seeking APIs and replaced them with versions that work on the resolution
  9. of a PCM frame instead. For example, given a stereo WAV file, previously you would pass 2 to drwav_read_f32() to read one
  10. PCM frame, whereas now you would pass in 1 to drwav_read_pcm_frames_f32(). The old APIs would return the number of samples
  11. read, whereas now it will return the number of PCM frames. Below is a list of APIs that have been deprecated and their
  12. replacements.
  13. drwav_read() -> drwav_read_pcm_frames()
  14. drwav_read_s16() -> drwav_read_pcm_frames_s16()
  15. drwav_read_f32() -> drwav_read_pcm_frames_f32()
  16. drwav_read_s32() -> drwav_read_pcm_frames_s32()
  17. drwav_seek_to_sample() -> drwav_seek_to_pcm_frame()
  18. drwav_write() -> drwav_write_pcm_frames()
  19. drwav_open_and_read_s16() -> drwav_open_and_read_pcm_frames_s16()
  20. drwav_open_and_read_f32() -> drwav_open_and_read_pcm_frames_f32()
  21. drwav_open_and_read_s32() -> drwav_open_and_read_pcm_frames_s32()
  22. drwav_open_file_and_read_s16() -> drwav_open_file_and_read_pcm_frames_s16()
  23. drwav_open_file_and_read_f32() -> drwav_open_file_and_read_pcm_frames_f32()
  24. drwav_open_file_and_read_s32() -> drwav_open_file_and_read_pcm_frames_s32()
  25. drwav_open_memory_and_read_s16() -> drwav_open_memory_and_read_pcm_frames_s16()
  26. drwav_open_memory_and_read_f32() -> drwav_open_memory_and_read_pcm_frames_f32()
  27. drwav_open_memory_and_read_s32() -> drwav_open_memory_and_read_pcm_frames_s32()
  28. drwav::totalSampleCount -> drwav::totalPCMFrameCount
  29. Rationale:
  30. 1) Most programs will want to read in multiples of the channel count which demands a per-frame reading API. Per-sample
  31. reading just adds complexity and maintenance costs for no practical benefit.
  32. 2) This is consistent with my other decoders - dr_flac and dr_mp3.
  33. These APIs will be removed completely in version 0.10.0. You can continue to use drwav_read_raw() if you need per-sample
  34. reading.
  35. */
  36. // USAGE
  37. //
  38. // This is a single-file library. To use it, do something like the following in one .c file.
  39. // #define DR_WAV_IMPLEMENTATION
  40. // #include "dr_wav.h"
  41. //
  42. // You can then #include this file in other parts of the program as you would with any other header file. Do something
  43. // like the following to read audio data:
  44. //
  45. // drwav wav;
  46. // if (!drwav_init_file(&wav, "my_song.wav")) {
  47. // // Error opening WAV file.
  48. // }
  49. //
  50. // drwav_int32* pDecodedInterleavedSamples = malloc(wav.totalPCMFrameCount * wav.channels * sizeof(drwav_int32));
  51. // size_t numberOfSamplesActuallyDecoded = drwav_read_pcm_frames_s32(&wav, wav.totalPCMFrameCount, pDecodedInterleavedSamples);
  52. //
  53. // ...
  54. //
  55. // drwav_uninit(&wav);
  56. //
  57. // You can also use drwav_open() to allocate and initialize the loader for you:
  58. //
  59. // drwav* pWav = drwav_open_file("my_song.wav");
  60. // if (pWav == NULL) {
  61. // // Error opening WAV file.
  62. // }
  63. //
  64. // ...
  65. //
  66. // drwav_close(pWav);
  67. //
  68. // If you just want to quickly open and read the audio data in a single operation you can do something like this:
  69. //
  70. // unsigned int channels;
  71. // unsigned int sampleRate;
  72. // drwav_uint64 totalPCMFrameCount;
  73. // float* pSampleData = drwav_open_file_and_read_pcm_frames_f32("my_song.wav", &channels, &sampleRate, &totalPCMFrameCount);
  74. // if (pSampleData == NULL) {
  75. // // Error opening and reading WAV file.
  76. // }
  77. //
  78. // ...
  79. //
  80. // drwav_free(pSampleData);
  81. //
  82. // The examples above use versions of the API that convert the audio data to a consistent format (32-bit signed PCM, in
  83. // this case), but you can still output the audio data in its internal format (see notes below for supported formats):
  84. //
  85. // size_t samplesRead = drwav_read_pcm_frames(&wav, wav.totalPCMFrameCount, pDecodedInterleavedSamples);
  86. //
  87. // You can also read the raw bytes of audio data, which could be useful if dr_wav does not have native support for
  88. // a particular data format:
  89. //
  90. // size_t bytesRead = drwav_read_raw(&wav, bytesToRead, pRawDataBuffer);
  91. //
  92. //
  93. // dr_wav can also be used to output WAV files. This does not currently support compressed formats. To use this, look at
  94. // drwav_open_write(), drwav_open_file_write(), etc. Use drwav_write_pcm_frames() to write samples, or drwav_write_raw()
  95. // to write raw data in the "data" chunk.
  96. //
  97. // drwav_data_format format;
  98. // format.container = drwav_container_riff; // <-- drwav_container_riff = normal WAV files, drwav_container_w64 = Sony Wave64.
  99. // format.format = DR_WAVE_FORMAT_PCM; // <-- Any of the DR_WAVE_FORMAT_* codes.
  100. // format.channels = 2;
  101. // format.sampleRate = 44100;
  102. // format.bitsPerSample = 16;
  103. // drwav* pWav = drwav_open_file_write("data/recording.wav", &format);
  104. //
  105. // ...
  106. //
  107. // drwav_uint64 samplesWritten = drwav_write_pcm_frames(pWav, frameCount, pSamples);
  108. //
  109. //
  110. // dr_wav has seamless support the Sony Wave64 format. The decoder will automatically detect it and it should Just Work
  111. // without any manual intervention.
  112. //
  113. //
  114. // OPTIONS
  115. // #define these options before including this file.
  116. //
  117. // #define DR_WAV_NO_CONVERSION_API
  118. // Disables conversion APIs such as drwav_read_pcm_frames_f32() and drwav_s16_to_f32().
  119. //
  120. // #define DR_WAV_NO_STDIO
  121. // Disables drwav_open_file(), drwav_open_file_write(), etc.
  122. //
  123. //
  124. //
  125. // QUICK NOTES
  126. // - Samples are always interleaved.
  127. // - The default read function does not do any data conversion. Use drwav_read_pcm_frames_f32(), drwav_read_pcm_frames_s32()
  128. // and drwav_read_pcm_frames_s16() to read and convert audio data to 32-bit floating point, signed 32-bit integer and
  129. // signed 16-bit integer samples respectively. Tested and supported internal formats include the following:
  130. // - Unsigned 8-bit PCM
  131. // - Signed 12-bit PCM
  132. // - Signed 16-bit PCM
  133. // - Signed 24-bit PCM
  134. // - Signed 32-bit PCM
  135. // - IEEE 32-bit floating point
  136. // - IEEE 64-bit floating point
  137. // - A-law and u-law
  138. // - Microsoft ADPCM
  139. // - IMA ADPCM (DVI, format code 0x11)
  140. // - dr_wav will try to read the WAV file as best it can, even if it's not strictly conformant to the WAV format.
  141. #ifndef dr_wav_h
  142. #define dr_wav_h
  143. #include <stddef.h>
  144. #if defined(_MSC_VER) && _MSC_VER < 1600
  145. typedef signed char drwav_int8;
  146. typedef unsigned char drwav_uint8;
  147. typedef signed short drwav_int16;
  148. typedef unsigned short drwav_uint16;
  149. typedef signed int drwav_int32;
  150. typedef unsigned int drwav_uint32;
  151. typedef signed __int64 drwav_int64;
  152. typedef unsigned __int64 drwav_uint64;
  153. #else
  154. #include <stdint.h>
  155. typedef int8_t drwav_int8;
  156. typedef uint8_t drwav_uint8;
  157. typedef int16_t drwav_int16;
  158. typedef uint16_t drwav_uint16;
  159. typedef int32_t drwav_int32;
  160. typedef uint32_t drwav_uint32;
  161. typedef int64_t drwav_int64;
  162. typedef uint64_t drwav_uint64;
  163. #endif
  164. typedef drwav_uint8 drwav_bool8;
  165. typedef drwav_uint32 drwav_bool32;
  166. #define DRWAV_TRUE 1
  167. #define DRWAV_FALSE 0
  168. #ifdef __cplusplus
  169. extern "C" {
  170. #endif
  171. // Common data formats.
  172. #define DR_WAVE_FORMAT_PCM 0x1
  173. #define DR_WAVE_FORMAT_ADPCM 0x2
  174. #define DR_WAVE_FORMAT_IEEE_FLOAT 0x3
  175. #define DR_WAVE_FORMAT_ALAW 0x6
  176. #define DR_WAVE_FORMAT_MULAW 0x7
  177. #define DR_WAVE_FORMAT_DVI_ADPCM 0x11
  178. #define DR_WAVE_FORMAT_EXTENSIBLE 0xFFFE
  179. // Constants.
  180. #ifndef DRWAV_MAX_SMPL_LOOPS
  181. #define DRWAV_MAX_SMPL_LOOPS 1
  182. #endif
  183. // Flags to pass into drwav_init_ex(), etc.
  184. #define DRWAV_SEQUENTIAL 0x00000001
  185. typedef enum
  186. {
  187. drwav_seek_origin_start,
  188. drwav_seek_origin_current
  189. } drwav_seek_origin;
  190. typedef enum
  191. {
  192. drwav_container_riff,
  193. drwav_container_w64
  194. } drwav_container;
  195. typedef struct
  196. {
  197. union
  198. {
  199. drwav_uint8 fourcc[4];
  200. drwav_uint8 guid[16];
  201. } id;
  202. // The size in bytes of the chunk.
  203. drwav_uint64 sizeInBytes;
  204. // RIFF = 2 byte alignment.
  205. // W64 = 8 byte alignment.
  206. unsigned int paddingSize;
  207. } drwav_chunk_header;
  208. // Callback for when data is read. Return value is the number of bytes actually read.
  209. //
  210. // pUserData [in] The user data that was passed to drwav_init(), drwav_open() and family.
  211. // pBufferOut [out] The output buffer.
  212. // bytesToRead [in] The number of bytes to read.
  213. //
  214. // Returns the number of bytes actually read.
  215. //
  216. // A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until
  217. // either the entire bytesToRead is filled or you have reached the end of the stream.
  218. typedef size_t (* drwav_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
  219. // Callback for when data is written. Returns value is the number of bytes actually written.
  220. //
  221. // pUserData [in] The user data that was passed to drwav_init_write(), drwav_open_write() and family.
  222. // pData [out] A pointer to the data to write.
  223. // bytesToWrite [in] The number of bytes to write.
  224. //
  225. // Returns the number of bytes actually written.
  226. //
  227. // If the return value differs from bytesToWrite, it indicates an error.
  228. typedef size_t (* drwav_write_proc)(void* pUserData, const void* pData, size_t bytesToWrite);
  229. // Callback for when data needs to be seeked.
  230. //
  231. // pUserData [in] The user data that was passed to drwav_init(), drwav_open() and family.
  232. // offset [in] The number of bytes to move, relative to the origin. Will never be negative.
  233. // origin [in] The origin of the seek - the current position or the start of the stream.
  234. //
  235. // Returns whether or not the seek was successful.
  236. //
  237. // Whether or not it is relative to the beginning or current position is determined by the "origin" parameter which
  238. // will be either drwav_seek_origin_start or drwav_seek_origin_current.
  239. typedef drwav_bool32 (* drwav_seek_proc)(void* pUserData, int offset, drwav_seek_origin origin);
  240. // Callback for when drwav_init_ex/drwav_open_ex finds a chunk.
  241. //
  242. // pChunkUserData [in] The user data that was passed to the pChunkUserData parameter of drwav_init_ex(), drwav_open_ex() and family.
  243. // onRead [in] A pointer to the function to call when reading.
  244. // onSeek [in] A pointer to the function to call when seeking.
  245. // pReadSeekUserData [in] The user data that was passed to the pReadSeekUserData parameter of drwav_init_ex(), drwav_open_ex() and family.
  246. // pChunkHeader [in] A pointer to an object containing basic header information about the chunk. Use this to identify the chunk.
  247. //
  248. // Returns the number of bytes read + seeked.
  249. //
  250. // To read data from the chunk, call onRead(), passing in pReadSeekUserData as the first parameter. Do the same
  251. // for seeking with onSeek(). The return value must be the total number of bytes you have read _plus_ seeked.
  252. //
  253. // You must not attempt to read beyond the boundary of the chunk.
  254. typedef drwav_uint64 (* drwav_chunk_proc)(void* pChunkUserData, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pReadSeekUserData, const drwav_chunk_header* pChunkHeader);
  255. // Structure for internal use. Only used for loaders opened with drwav_open_memory().
  256. typedef struct
  257. {
  258. const drwav_uint8* data;
  259. size_t dataSize;
  260. size_t currentReadPos;
  261. } drwav__memory_stream;
  262. // Structure for internal use. Only used for writers opened with drwav_open_memory_write().
  263. typedef struct
  264. {
  265. void** ppData;
  266. size_t* pDataSize;
  267. size_t dataSize;
  268. size_t dataCapacity;
  269. size_t currentWritePos;
  270. } drwav__memory_stream_write;
  271. typedef struct
  272. {
  273. drwav_container container; // RIFF, W64.
  274. drwav_uint32 format; // DR_WAVE_FORMAT_*
  275. drwav_uint32 channels;
  276. drwav_uint32 sampleRate;
  277. drwav_uint32 bitsPerSample;
  278. } drwav_data_format;
  279. typedef struct
  280. {
  281. // The format tag exactly as specified in the wave file's "fmt" chunk. This can be used by applications
  282. // that require support for data formats not natively supported by dr_wav.
  283. drwav_uint16 formatTag;
  284. // The number of channels making up the audio data. When this is set to 1 it is mono, 2 is stereo, etc.
  285. drwav_uint16 channels;
  286. // The sample rate. Usually set to something like 44100.
  287. drwav_uint32 sampleRate;
  288. // Average bytes per second. You probably don't need this, but it's left here for informational purposes.
  289. drwav_uint32 avgBytesPerSec;
  290. // Block align. This is equal to the number of channels * bytes per sample.
  291. drwav_uint16 blockAlign;
  292. // Bits per sample.
  293. drwav_uint16 bitsPerSample;
  294. // The size of the extended data. Only used internally for validation, but left here for informational purposes.
  295. drwav_uint16 extendedSize;
  296. // The number of valid bits per sample. When <formatTag> is equal to WAVE_FORMAT_EXTENSIBLE, <bitsPerSample>
  297. // is always rounded up to the nearest multiple of 8. This variable contains information about exactly how
  298. // many bits a valid per sample. Mainly used for informational purposes.
  299. drwav_uint16 validBitsPerSample;
  300. // The channel mask. Not used at the moment.
  301. drwav_uint32 channelMask;
  302. // The sub-format, exactly as specified by the wave file.
  303. drwav_uint8 subFormat[16];
  304. } drwav_fmt;
  305. typedef struct
  306. {
  307. drwav_uint32 cuePointId;
  308. drwav_uint32 type;
  309. drwav_uint32 start;
  310. drwav_uint32 end;
  311. drwav_uint32 fraction;
  312. drwav_uint32 playCount;
  313. } drwav_smpl_loop;
  314. typedef struct
  315. {
  316. drwav_uint32 manufacturer;
  317. drwav_uint32 product;
  318. drwav_uint32 samplePeriod;
  319. drwav_uint32 midiUnityNotes;
  320. drwav_uint32 midiPitchFraction;
  321. drwav_uint32 smpteFormat;
  322. drwav_uint32 smpteOffset;
  323. drwav_uint32 numSampleLoops;
  324. drwav_uint32 samplerData;
  325. drwav_smpl_loop loops[DRWAV_MAX_SMPL_LOOPS];
  326. } drwav_smpl;
  327. typedef struct
  328. {
  329. // A pointer to the function to call when more data is needed.
  330. drwav_read_proc onRead;
  331. // A pointer to the function to call when data needs to be written. Only used when the drwav object is opened in write mode.
  332. drwav_write_proc onWrite;
  333. // A pointer to the function to call when the wav file needs to be seeked.
  334. drwav_seek_proc onSeek;
  335. // The user data to pass to callbacks.
  336. void* pUserData;
  337. // Whether or not the WAV file is formatted as a standard RIFF file or W64.
  338. drwav_container container;
  339. // Structure containing format information exactly as specified by the wav file.
  340. drwav_fmt fmt;
  341. // The sample rate. Will be set to something like 44100.
  342. drwav_uint32 sampleRate;
  343. // The number of channels. This will be set to 1 for monaural streams, 2 for stereo, etc.
  344. drwav_uint16 channels;
  345. // The bits per sample. Will be set to something like 16, 24, etc.
  346. drwav_uint16 bitsPerSample;
  347. // Equal to fmt.formatTag, or the value specified by fmt.subFormat if fmt.formatTag is equal to 65534 (WAVE_FORMAT_EXTENSIBLE).
  348. drwav_uint16 translatedFormatTag;
  349. // The total number of PCM frames making up the audio data.
  350. drwav_uint64 totalPCMFrameCount;
  351. // The size in bytes of the data chunk.
  352. drwav_uint64 dataChunkDataSize;
  353. // The position in the stream of the first byte of the data chunk. This is used for seeking.
  354. drwav_uint64 dataChunkDataPos;
  355. // The number of bytes remaining in the data chunk.
  356. drwav_uint64 bytesRemaining;
  357. // Only used in sequential write mode. Keeps track of the desired size of the "data" chunk at the point of initialization time. Always
  358. // set to 0 for non-sequential writes and when the drwav object is opened in read mode. Used for validation.
  359. drwav_uint64 dataChunkDataSizeTargetWrite;
  360. // Keeps track of whether or not the wav writer was initialized in sequential mode.
  361. drwav_bool32 isSequentialWrite;
  362. // smpl chunk.
  363. drwav_smpl smpl;
  364. // A hack to avoid a DRWAV_MALLOC() when opening a decoder with drwav_open_memory().
  365. drwav__memory_stream memoryStream;
  366. drwav__memory_stream_write memoryStreamWrite;
  367. // Generic data for compressed formats. This data is shared across all block-compressed formats.
  368. struct
  369. {
  370. drwav_uint64 iCurrentSample; // The index of the next sample that will be read by drwav_read_*(). This is used with "totalSampleCount" to ensure we don't read excess samples at the end of the last block.
  371. } compressed;
  372. // Microsoft ADPCM specific data.
  373. struct
  374. {
  375. drwav_uint32 bytesRemainingInBlock;
  376. drwav_uint16 predictor[2];
  377. drwav_int32 delta[2];
  378. drwav_int32 cachedSamples[4]; // Samples are stored in this cache during decoding.
  379. drwav_uint32 cachedSampleCount;
  380. drwav_int32 prevSamples[2][2]; // The previous 2 samples for each channel (2 channels at most).
  381. } msadpcm;
  382. // IMA ADPCM specific data.
  383. struct
  384. {
  385. drwav_uint32 bytesRemainingInBlock;
  386. drwav_int32 predictor[2];
  387. drwav_int32 stepIndex[2];
  388. drwav_int32 cachedSamples[16]; // Samples are stored in this cache during decoding.
  389. drwav_uint32 cachedSampleCount;
  390. } ima;
  391. drwav_uint64 totalSampleCount; // <-- DEPRECATED. Will be removed in a future version.
  392. } drwav;
  393. // Initializes a pre-allocated drwav object.
  394. //
  395. // pWav [out] A pointer to the drwav object being initialized.
  396. // onRead [in] The function to call when data needs to be read from the client.
  397. // onSeek [in] The function to call when the read position of the client data needs to move.
  398. // onChunk [in, optional] The function to call when a chunk is enumerated at initialized time.
  399. // pUserData, pReadSeekUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek.
  400. // pChunkUserData [in, optional] A pointer to application defined data that will be passed to onChunk.
  401. // flags [in, optional] A set of flags for controlling how things are loaded.
  402. //
  403. // Returns true if successful; false otherwise.
  404. //
  405. // Close the loader with drwav_uninit().
  406. //
  407. // This is the lowest level function for initializing a WAV file. You can also use drwav_init_file() and drwav_init_memory()
  408. // to open the stream from a file or from a block of memory respectively.
  409. //
  410. // If you want dr_wav to manage the memory allocation for you, consider using drwav_open() instead. This will allocate
  411. // a drwav object on the heap and return a pointer to it.
  412. //
  413. // Possible values for flags:
  414. // DRWAV_SEQUENTIAL: Never perform a backwards seek while loading. This disables the chunk callback and will cause this function
  415. // to return as soon as the data chunk is found. Any chunks after the data chunk will be ignored.
  416. //
  417. // drwav_init() is equivalent to "drwav_init_ex(pWav, onRead, onSeek, NULL, pUserData, NULL, 0);".
  418. //
  419. // The onChunk callback is not called for the WAVE or FMT chunks. The contents of the FMT chunk can be read from pWav->fmt
  420. // after the function returns.
  421. //
  422. // See also: drwav_init_file(), drwav_init_memory(), drwav_uninit()
  423. drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData);
  424. drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags);
  425. // Initializes a pre-allocated drwav object for writing.
  426. //
  427. // onWrite [in] The function to call when data needs to be written.
  428. // onSeek [in] The function to call when the write position needs to move.
  429. // pUserData [in, optional] A pointer to application defined data that will be passed to onWrite and onSeek.
  430. //
  431. // Returns true if successful; false otherwise.
  432. //
  433. // Close the writer with drwav_uninit().
  434. //
  435. // This is the lowest level function for initializing a WAV file. You can also use drwav_init_file() and drwav_init_memory()
  436. // to open the stream from a file or from a block of memory respectively.
  437. //
  438. // If the total sample count is known, you can use drwav_init_write_sequential(). This avoids the need for dr_wav to perform
  439. // a post-processing step for storing the total sample count and the size of the data chunk which requires a backwards seek.
  440. //
  441. // If you want dr_wav to manage the memory allocation for you, consider using drwav_open() instead. This will allocate
  442. // a drwav object on the heap and return a pointer to it.
  443. //
  444. // See also: drwav_init_file_write(), drwav_init_memory_write(), drwav_uninit()
  445. drwav_bool32 drwav_init_write(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData);
  446. drwav_bool32 drwav_init_write_sequential(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData);
  447. // Uninitializes the given drwav object.
  448. //
  449. // Use this only for objects initialized with drwav_init().
  450. void drwav_uninit(drwav* pWav);
  451. // Opens a wav file using the given callbacks.
  452. //
  453. // onRead [in] The function to call when data needs to be read from the client.
  454. // onSeek [in] The function to call when the read position of the client data needs to move.
  455. // pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek.
  456. //
  457. // Returns null on error.
  458. //
  459. // Close the loader with drwav_close().
  460. //
  461. // You can also use drwav_open_file() and drwav_open_memory() to open the stream from a file or from a block of
  462. // memory respectively.
  463. //
  464. // This is different from drwav_init() in that it will allocate the drwav object for you via DRWAV_MALLOC() before
  465. // initializing it.
  466. //
  467. // See also: drwav_init(), drwav_open_file(), drwav_open_memory(), drwav_close()
  468. drwav* drwav_open(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData);
  469. drwav* drwav_open_ex(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags);
  470. // Opens a wav file for writing using the given callbacks.
  471. //
  472. // onWrite [in] The function to call when data needs to be written.
  473. // onSeek [in] The function to call when the write position needs to move.
  474. // pUserData [in, optional] A pointer to application defined data that will be passed to onWrite and onSeek.
  475. //
  476. // Returns null on error.
  477. //
  478. // Close the loader with drwav_close().
  479. //
  480. // You can also use drwav_open_file_write() and drwav_open_memory_write() to open the stream from a file or from a block
  481. // of memory respectively.
  482. //
  483. // This is different from drwav_init_write() in that it will allocate the drwav object for you via DRWAV_MALLOC() before
  484. // initializing it.
  485. //
  486. // See also: drwav_open_file_write(), drwav_open_memory_write(), drwav_close()
  487. drwav* drwav_open_write(const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData);
  488. drwav* drwav_open_write_sequential(const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData);
  489. // Uninitializes and deletes the the given drwav object.
  490. //
  491. // Use this only for objects created with drwav_open().
  492. void drwav_close(drwav* pWav);
  493. // Reads raw audio data.
  494. //
  495. // This is the lowest level function for reading audio data. It simply reads the given number of
  496. // bytes of the raw internal sample data.
  497. //
  498. // Consider using drwav_read_pcm_frames_s16(), drwav_read_pcm_frames_s32() or drwav_read_pcm_frames_f32() for
  499. // reading sample data in a consistent format.
  500. //
  501. // Returns the number of bytes actually read.
  502. size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut);
  503. // Reads a chunk of audio data in the native internal format.
  504. //
  505. // This is typically the most efficient way to retrieve audio data, but it does not do any format
  506. // conversions which means you'll need to convert the data manually if required.
  507. //
  508. // If the return value is less than <framesToRead> it means the end of the file has been reached or
  509. // you have requested more samples than can possibly fit in the output buffer.
  510. //
  511. // This function will only work when sample data is of a fixed size and uncompressed. If you are
  512. // using a compressed format consider using drwav_read_raw() or drwav_read_pcm_frames_s16/s32/f32/etc().
  513. drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut);
  514. // Seeks to the given PCM frame.
  515. //
  516. // Returns true if successful; false otherwise.
  517. drwav_bool32 drwav_seek_to_pcm_frame(drwav* pWav, drwav_uint64 targetFrameIndex);
  518. // Writes raw audio data.
  519. //
  520. // Returns the number of bytes actually written. If this differs from bytesToWrite, it indicates an error.
  521. size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData);
  522. // Writes PCM frames.
  523. //
  524. // Returns the number of PCM frames written.
  525. drwav_uint64 drwav_write_pcm_frames(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
  526. //// Conversion Utilities ////
  527. #ifndef DR_WAV_NO_CONVERSION_API
  528. // Reads a chunk of audio data and converts it to signed 16-bit PCM samples.
  529. //
  530. // Returns the number of PCM frames actually read.
  531. //
  532. // If the return value is less than <framesToRead> it means the end of the file has been reached.
  533. drwav_uint64 drwav_read_pcm_frames_s16(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut);
  534. // Low-level function for converting unsigned 8-bit PCM samples to signed 16-bit PCM samples.
  535. void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
  536. // Low-level function for converting signed 24-bit PCM samples to signed 16-bit PCM samples.
  537. void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
  538. // Low-level function for converting signed 32-bit PCM samples to signed 16-bit PCM samples.
  539. void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCount);
  540. // Low-level function for converting IEEE 32-bit floating point samples to signed 16-bit PCM samples.
  541. void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount);
  542. // Low-level function for converting IEEE 64-bit floating point samples to signed 16-bit PCM samples.
  543. void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount);
  544. // Low-level function for converting A-law samples to signed 16-bit PCM samples.
  545. void drwav_alaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
  546. // Low-level function for converting u-law samples to signed 16-bit PCM samples.
  547. void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
  548. // Reads a chunk of audio data and converts it to IEEE 32-bit floating point samples.
  549. //
  550. // Returns the number of PCM frames actually read.
  551. //
  552. // If the return value is less than <framesToRead> it means the end of the file has been reached.
  553. drwav_uint64 drwav_read_pcm_frames_f32(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut);
  554. // Low-level function for converting unsigned 8-bit PCM samples to IEEE 32-bit floating point samples.
  555. void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
  556. // Low-level function for converting signed 16-bit PCM samples to IEEE 32-bit floating point samples.
  557. void drwav_s16_to_f32(float* pOut, const drwav_int16* pIn, size_t sampleCount);
  558. // Low-level function for converting signed 24-bit PCM samples to IEEE 32-bit floating point samples.
  559. void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
  560. // Low-level function for converting signed 32-bit PCM samples to IEEE 32-bit floating point samples.
  561. void drwav_s32_to_f32(float* pOut, const drwav_int32* pIn, size_t sampleCount);
  562. // Low-level function for converting IEEE 64-bit floating point samples to IEEE 32-bit floating point samples.
  563. void drwav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount);
  564. // Low-level function for converting A-law samples to IEEE 32-bit floating point samples.
  565. void drwav_alaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
  566. // Low-level function for converting u-law samples to IEEE 32-bit floating point samples.
  567. void drwav_mulaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
  568. // Reads a chunk of audio data and converts it to signed 32-bit PCM samples.
  569. //
  570. // Returns the number of PCM frames actually read.
  571. //
  572. // If the return value is less than <framesToRead> it means the end of the file has been reached.
  573. drwav_uint64 drwav_read_pcm_frames_s32(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut);
  574. // Low-level function for converting unsigned 8-bit PCM samples to signed 32-bit PCM samples.
  575. void drwav_u8_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
  576. // Low-level function for converting signed 16-bit PCM samples to signed 32-bit PCM samples.
  577. void drwav_s16_to_s32(drwav_int32* pOut, const drwav_int16* pIn, size_t sampleCount);
  578. // Low-level function for converting signed 24-bit PCM samples to signed 32-bit PCM samples.
  579. void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
  580. // Low-level function for converting IEEE 32-bit floating point samples to signed 32-bit PCM samples.
  581. void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t sampleCount);
  582. // Low-level function for converting IEEE 64-bit floating point samples to signed 32-bit PCM samples.
  583. void drwav_f64_to_s32(drwav_int32* pOut, const double* pIn, size_t sampleCount);
  584. // Low-level function for converting A-law samples to signed 32-bit PCM samples.
  585. void drwav_alaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
  586. // Low-level function for converting u-law samples to signed 32-bit PCM samples.
  587. void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
  588. #endif //DR_WAV_NO_CONVERSION_API
  589. //// High-Level Convenience Helpers ////
  590. #ifndef DR_WAV_NO_STDIO
  591. // Helper for initializing a wave file using stdio.
  592. //
  593. // This holds the internal FILE object until drwav_uninit() is called. Keep this in mind if you're caching drwav
  594. // objects because the operating system may restrict the number of file handles an application can have open at
  595. // any given time.
  596. drwav_bool32 drwav_init_file(drwav* pWav, const char* filename);
  597. drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags);
  598. // Helper for initializing a wave file for writing using stdio.
  599. //
  600. // This holds the internal FILE object until drwav_uninit() is called. Keep this in mind if you're caching drwav
  601. // objects because the operating system may restrict the number of file handles an application can have open at
  602. // any given time.
  603. drwav_bool32 drwav_init_file_write(drwav* pWav, const char* filename, const drwav_data_format* pFormat);
  604. drwav_bool32 drwav_init_file_write_sequential(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount);
  605. // Helper for opening a wave file using stdio.
  606. //
  607. // This holds the internal FILE object until drwav_close() is called. Keep this in mind if you're caching drwav
  608. // objects because the operating system may restrict the number of file handles an application can have open at
  609. // any given time.
  610. drwav* drwav_open_file(const char* filename);
  611. drwav* drwav_open_file_ex(const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags);
  612. // Helper for opening a wave file for writing using stdio.
  613. //
  614. // This holds the internal FILE object until drwav_close() is called. Keep this in mind if you're caching drwav
  615. // objects because the operating system may restrict the number of file handles an application can have open at
  616. // any given time.
  617. drwav* drwav_open_file_write(const char* filename, const drwav_data_format* pFormat);
  618. drwav* drwav_open_file_write_sequential(const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount);
  619. #endif //DR_WAV_NO_STDIO
  620. // Helper for initializing a loader from a pre-allocated memory buffer.
  621. //
  622. // This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for
  623. // the lifetime of the drwav object.
  624. //
  625. // The buffer should contain the contents of the entire wave file, not just the sample data.
  626. drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize);
  627. drwav_bool32 drwav_init_memory_ex(drwav* pWav, const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags);
  628. // Helper for initializing a writer which outputs data to a memory buffer.
  629. //
  630. // dr_wav will manage the memory allocations, however it is up to the caller to free the data with drwav_free().
  631. //
  632. // The buffer will remain allocated even after drwav_uninit() is called. Indeed, the buffer should not be
  633. // considered valid until after drwav_uninit() has been called anyway.
  634. drwav_bool32 drwav_init_memory_write(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat);
  635. drwav_bool32 drwav_init_memory_write_sequential(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount);
  636. // Helper for opening a loader from a pre-allocated memory buffer.
  637. //
  638. // This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for
  639. // the lifetime of the drwav object.
  640. //
  641. // The buffer should contain the contents of the entire wave file, not just the sample data.
  642. drwav* drwav_open_memory(const void* data, size_t dataSize);
  643. drwav* drwav_open_memory_ex(const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags);
  644. // Helper for opening a writer which outputs data to a memory buffer.
  645. //
  646. // dr_wav will manage the memory allocations, however it is up to the caller to free the data with drwav_free().
  647. //
  648. // The buffer will remain allocated even after drwav_close() is called. Indeed, the buffer should not be
  649. // considered valid until after drwav_close() has been called anyway.
  650. drwav* drwav_open_memory_write(void** ppData, size_t* pDataSize, const drwav_data_format* pFormat);
  651. drwav* drwav_open_memory_write_sequential(void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount);
  652. #ifndef DR_WAV_NO_CONVERSION_API
  653. // Opens and reads a wav file in a single operation.
  654. drwav_int16* drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount);
  655. float* drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount);
  656. drwav_int32* drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount);
  657. #ifndef DR_WAV_NO_STDIO
  658. // Opens and decodes a wav file in a single operation.
  659. drwav_int16* drwav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount);
  660. float* drwav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount);
  661. drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount);
  662. #endif
  663. // Opens and decodes a wav file from a block of memory in a single operation.
  664. drwav_int16* drwav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount);
  665. float* drwav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount);
  666. drwav_int32* drwav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount);
  667. #endif
  668. // Frees data that was allocated internally by dr_wav.
  669. void drwav_free(void* pDataReturnedByOpenAndRead);
  670. // DEPRECATED APIS
  671. // ===============
  672. drwav_uint64 drwav_read(drwav* pWav, drwav_uint64 samplesToRead, void* pBufferOut);
  673. drwav_uint64 drwav_read_s16(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut);
  674. drwav_uint64 drwav_read_f32(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut);
  675. drwav_uint64 drwav_read_s32(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut);
  676. drwav_bool32 drwav_seek_to_sample(drwav* pWav, drwav_uint64 sample);
  677. drwav_uint64 drwav_write(drwav* pWav, drwav_uint64 samplesToWrite, const void* pData);
  678. #ifndef DR_WAV_NO_CONVERSION_API
  679. drwav_int16* drwav_open_and_read_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount);
  680. float* drwav_open_and_read_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount);
  681. drwav_int32* drwav_open_and_read_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount);
  682. #ifndef DR_WAV_NO_STDIO
  683. drwav_int16* drwav_open_memory_and_read_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount);
  684. float* drwav_open_file_and_read_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount);
  685. drwav_int32* drwav_open_file_and_read_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount);
  686. #endif
  687. drwav_int16* drwav_open_memory_and_read_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount);
  688. float* drwav_open_memory_and_read_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount);
  689. drwav_int32* drwav_open_memory_and_read_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount);
  690. #endif
  691. #ifdef __cplusplus
  692. }
  693. #endif
  694. #endif // dr_wav_h
  695. /////////////////////////////////////////////////////
  696. //
  697. // IMPLEMENTATION
  698. //
  699. /////////////////////////////////////////////////////
  700. #ifdef DR_WAV_IMPLEMENTATION
  701. #include <stdlib.h>
  702. #include <string.h> // For memcpy(), memset()
  703. #include <limits.h> // For INT_MAX
  704. #ifndef DR_WAV_NO_STDIO
  705. #include <stdio.h>
  706. #endif
  707. // Standard library stuff.
  708. #ifndef DRWAV_ASSERT
  709. #include <assert.h>
  710. #define DRWAV_ASSERT(expression) assert(expression)
  711. #endif
  712. #ifndef DRWAV_MALLOC
  713. #define DRWAV_MALLOC(sz) malloc((sz))
  714. #endif
  715. #ifndef DRWAV_REALLOC
  716. #define DRWAV_REALLOC(p, sz) realloc((p), (sz))
  717. #endif
  718. #ifndef DRWAV_FREE
  719. #define DRWAV_FREE(p) free((p))
  720. #endif
  721. #ifndef DRWAV_COPY_MEMORY
  722. #define DRWAV_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  723. #endif
  724. #ifndef DRWAV_ZERO_MEMORY
  725. #define DRWAV_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
  726. #endif
  727. #define drwav_countof(x) (sizeof(x) / sizeof(x[0]))
  728. #define drwav_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
  729. #define drwav_min(a, b) (((a) < (b)) ? (a) : (b))
  730. #define drwav_max(a, b) (((a) > (b)) ? (a) : (b))
  731. #define drwav_clamp(x, lo, hi) (drwav_max((lo), drwav_min((hi), (x))))
  732. #define drwav_assert DRWAV_ASSERT
  733. #define drwav_copy_memory DRWAV_COPY_MEMORY
  734. #define drwav_zero_memory DRWAV_ZERO_MEMORY
  735. typedef drwav_int32 drwav_result;
  736. #define DRWAV_SUCCESS 0
  737. #define DRWAV_ERROR -1
  738. #define DRWAV_INVALID_ARGS -2
  739. #define DRWAV_INVALID_OPERATION -3
  740. #define DRWAV_INVALID_FILE -100
  741. #define DRWAV_EOF -101
  742. #define DRWAV_MAX_SIMD_VECTOR_SIZE 64 // 64 for AVX-512 in the future.
  743. #ifdef _MSC_VER
  744. #define DRWAV_INLINE __forceinline
  745. #else
  746. #ifdef __GNUC__
  747. #define DRWAV_INLINE inline __attribute__((always_inline))
  748. #else
  749. #define DRWAV_INLINE inline
  750. #endif
  751. #endif
  752. #if defined(SIZE_MAX)
  753. #define DRWAV_SIZE_MAX SIZE_MAX
  754. #else
  755. #if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
  756. #define DRWAV_SIZE_MAX ((drwav_uint64)0xFFFFFFFFFFFFFFFF)
  757. #else
  758. #define DRWAV_SIZE_MAX 0xFFFFFFFF
  759. #endif
  760. #endif
  761. static const drwav_uint8 drwavGUID_W64_RIFF[16] = {0x72,0x69,0x66,0x66, 0x2E,0x91, 0xCF,0x11, 0xA5,0xD6, 0x28,0xDB,0x04,0xC1,0x00,0x00}; // 66666972-912E-11CF-A5D6-28DB04C10000
  762. static const drwav_uint8 drwavGUID_W64_WAVE[16] = {0x77,0x61,0x76,0x65, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; // 65766177-ACF3-11D3-8CD1-00C04F8EDB8A
  763. static const drwav_uint8 drwavGUID_W64_JUNK[16] = {0x6A,0x75,0x6E,0x6B, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; // 6B6E756A-ACF3-11D3-8CD1-00C04F8EDB8A
  764. static const drwav_uint8 drwavGUID_W64_FMT [16] = {0x66,0x6D,0x74,0x20, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; // 20746D66-ACF3-11D3-8CD1-00C04F8EDB8A
  765. static const drwav_uint8 drwavGUID_W64_FACT[16] = {0x66,0x61,0x63,0x74, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; // 74636166-ACF3-11D3-8CD1-00C04F8EDB8A
  766. static const drwav_uint8 drwavGUID_W64_DATA[16] = {0x64,0x61,0x74,0x61, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; // 61746164-ACF3-11D3-8CD1-00C04F8EDB8A
  767. static const drwav_uint8 drwavGUID_W64_SMPL[16] = {0x73,0x6D,0x70,0x6C, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A}; // 6C706D73-ACF3-11D3-8CD1-00C04F8EDB8A
  768. static DRWAV_INLINE drwav_bool32 drwav__guid_equal(const drwav_uint8 a[16], const drwav_uint8 b[16])
  769. {
  770. const drwav_uint32* a32 = (const drwav_uint32*)a;
  771. const drwav_uint32* b32 = (const drwav_uint32*)b;
  772. return
  773. a32[0] == b32[0] &&
  774. a32[1] == b32[1] &&
  775. a32[2] == b32[2] &&
  776. a32[3] == b32[3];
  777. }
  778. static DRWAV_INLINE drwav_bool32 drwav__fourcc_equal(const unsigned char* a, const char* b)
  779. {
  780. return
  781. a[0] == b[0] &&
  782. a[1] == b[1] &&
  783. a[2] == b[2] &&
  784. a[3] == b[3];
  785. }
  786. static DRWAV_INLINE int drwav__is_little_endian()
  787. {
  788. int n = 1;
  789. return (*(char*)&n) == 1;
  790. }
  791. static DRWAV_INLINE unsigned short drwav__bytes_to_u16(const unsigned char* data)
  792. {
  793. return (data[0] << 0) | (data[1] << 8);
  794. }
  795. static DRWAV_INLINE short drwav__bytes_to_s16(const unsigned char* data)
  796. {
  797. return (short)drwav__bytes_to_u16(data);
  798. }
  799. static DRWAV_INLINE unsigned int drwav__bytes_to_u32(const unsigned char* data)
  800. {
  801. return (data[0] << 0) | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
  802. }
  803. static DRWAV_INLINE drwav_uint64 drwav__bytes_to_u64(const unsigned char* data)
  804. {
  805. return
  806. ((drwav_uint64)data[0] << 0) | ((drwav_uint64)data[1] << 8) | ((drwav_uint64)data[2] << 16) | ((drwav_uint64)data[3] << 24) |
  807. ((drwav_uint64)data[4] << 32) | ((drwav_uint64)data[5] << 40) | ((drwav_uint64)data[6] << 48) | ((drwav_uint64)data[7] << 56);
  808. }
  809. static DRWAV_INLINE void drwav__bytes_to_guid(const unsigned char* data, drwav_uint8* guid)
  810. {
  811. for (int i = 0; i < 16; ++i) {
  812. guid[i] = data[i];
  813. }
  814. }
  815. static DRWAV_INLINE drwav_bool32 drwav__is_compressed_format_tag(drwav_uint16 formatTag)
  816. {
  817. return
  818. formatTag == DR_WAVE_FORMAT_ADPCM ||
  819. formatTag == DR_WAVE_FORMAT_DVI_ADPCM;
  820. }
  821. drwav_uint64 drwav_read_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut);
  822. drwav_uint64 drwav_read_s16__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut);
  823. drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData);
  824. drwav* drwav_open_write__internal(const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData);
  825. static drwav_result drwav__read_chunk_header(drwav_read_proc onRead, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav_chunk_header* pHeaderOut)
  826. {
  827. if (container == drwav_container_riff) {
  828. if (onRead(pUserData, pHeaderOut->id.fourcc, 4) != 4) {
  829. return DRWAV_EOF;
  830. }
  831. unsigned char sizeInBytes[4];
  832. if (onRead(pUserData, sizeInBytes, 4) != 4) {
  833. return DRWAV_INVALID_FILE;
  834. }
  835. pHeaderOut->sizeInBytes = drwav__bytes_to_u32(sizeInBytes);
  836. pHeaderOut->paddingSize = (unsigned int)(pHeaderOut->sizeInBytes % 2);
  837. *pRunningBytesReadOut += 8;
  838. } else {
  839. if (onRead(pUserData, pHeaderOut->id.guid, 16) != 16) {
  840. return DRWAV_EOF;
  841. }
  842. unsigned char sizeInBytes[8];
  843. if (onRead(pUserData, sizeInBytes, 8) != 8) {
  844. return DRWAV_INVALID_FILE;
  845. }
  846. pHeaderOut->sizeInBytes = drwav__bytes_to_u64(sizeInBytes) - 24; // <-- Subtract 24 because w64 includes the size of the header.
  847. pHeaderOut->paddingSize = (unsigned int)(pHeaderOut->sizeInBytes % 8);
  848. *pRunningBytesReadOut += 24;
  849. }
  850. return DRWAV_SUCCESS;
  851. }
  852. static drwav_bool32 drwav__seek_forward(drwav_seek_proc onSeek, drwav_uint64 offset, void* pUserData)
  853. {
  854. drwav_uint64 bytesRemainingToSeek = offset;
  855. while (bytesRemainingToSeek > 0) {
  856. if (bytesRemainingToSeek > 0x7FFFFFFF) {
  857. if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_current)) {
  858. return DRWAV_FALSE;
  859. }
  860. bytesRemainingToSeek -= 0x7FFFFFFF;
  861. } else {
  862. if (!onSeek(pUserData, (int)bytesRemainingToSeek, drwav_seek_origin_current)) {
  863. return DRWAV_FALSE;
  864. }
  865. bytesRemainingToSeek = 0;
  866. }
  867. }
  868. return DRWAV_TRUE;
  869. }
  870. static drwav_bool32 drwav__seek_from_start(drwav_seek_proc onSeek, drwav_uint64 offset, void* pUserData)
  871. {
  872. if (offset <= 0x7FFFFFFF) {
  873. return onSeek(pUserData, (int)offset, drwav_seek_origin_start);
  874. }
  875. // Larger than 32-bit seek.
  876. if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_start)) {
  877. return DRWAV_FALSE;
  878. }
  879. offset -= 0x7FFFFFFF;
  880. for (;;) {
  881. if (offset <= 0x7FFFFFFF) {
  882. return onSeek(pUserData, (int)offset, drwav_seek_origin_current);
  883. }
  884. if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_current)) {
  885. return DRWAV_FALSE;
  886. }
  887. offset -= 0x7FFFFFFF;
  888. }
  889. // Should never get here.
  890. //return DRWAV_TRUE;
  891. }
  892. static drwav_bool32 drwav__read_fmt(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav_fmt* fmtOut)
  893. {
  894. drwav_chunk_header header;
  895. if (drwav__read_chunk_header(onRead, pUserData, container, pRunningBytesReadOut, &header) != DRWAV_SUCCESS) {
  896. return DRWAV_FALSE;
  897. }
  898. // Skip non-fmt chunks.
  899. while ((container == drwav_container_riff && !drwav__fourcc_equal(header.id.fourcc, "fmt ")) || (container == drwav_container_w64 && !drwav__guid_equal(header.id.guid, drwavGUID_W64_FMT))) {
  900. if (!drwav__seek_forward(onSeek, header.sizeInBytes + header.paddingSize, pUserData)) {
  901. return DRWAV_FALSE;
  902. }
  903. *pRunningBytesReadOut += header.sizeInBytes + header.paddingSize;
  904. // Try the next header.
  905. if (drwav__read_chunk_header(onRead, pUserData, container, pRunningBytesReadOut, &header) != DRWAV_SUCCESS) {
  906. return DRWAV_FALSE;
  907. }
  908. }
  909. // Validation.
  910. if (container == drwav_container_riff) {
  911. if (!drwav__fourcc_equal(header.id.fourcc, "fmt ")) {
  912. return DRWAV_FALSE;
  913. }
  914. } else {
  915. if (!drwav__guid_equal(header.id.guid, drwavGUID_W64_FMT)) {
  916. return DRWAV_FALSE;
  917. }
  918. }
  919. unsigned char fmt[16];
  920. if (onRead(pUserData, fmt, sizeof(fmt)) != sizeof(fmt)) {
  921. return DRWAV_FALSE;
  922. }
  923. *pRunningBytesReadOut += sizeof(fmt);
  924. fmtOut->formatTag = drwav__bytes_to_u16(fmt + 0);
  925. fmtOut->channels = drwav__bytes_to_u16(fmt + 2);
  926. fmtOut->sampleRate = drwav__bytes_to_u32(fmt + 4);
  927. fmtOut->avgBytesPerSec = drwav__bytes_to_u32(fmt + 8);
  928. fmtOut->blockAlign = drwav__bytes_to_u16(fmt + 12);
  929. fmtOut->bitsPerSample = drwav__bytes_to_u16(fmt + 14);
  930. fmtOut->extendedSize = 0;
  931. fmtOut->validBitsPerSample = 0;
  932. fmtOut->channelMask = 0;
  933. memset(fmtOut->subFormat, 0, sizeof(fmtOut->subFormat));
  934. if (header.sizeInBytes > 16) {
  935. unsigned char fmt_cbSize[2];
  936. if (onRead(pUserData, fmt_cbSize, sizeof(fmt_cbSize)) != sizeof(fmt_cbSize)) {
  937. return DRWAV_FALSE; // Expecting more data.
  938. }
  939. *pRunningBytesReadOut += sizeof(fmt_cbSize);
  940. int bytesReadSoFar = 18;
  941. fmtOut->extendedSize = drwav__bytes_to_u16(fmt_cbSize);
  942. if (fmtOut->extendedSize > 0) {
  943. // Simple validation.
  944. if (fmtOut->formatTag == DR_WAVE_FORMAT_EXTENSIBLE) {
  945. if (fmtOut->extendedSize != 22) {
  946. return DRWAV_FALSE;
  947. }
  948. }
  949. if (fmtOut->formatTag == DR_WAVE_FORMAT_EXTENSIBLE) {
  950. unsigned char fmtext[22];
  951. if (onRead(pUserData, fmtext, fmtOut->extendedSize) != fmtOut->extendedSize) {
  952. return DRWAV_FALSE; // Expecting more data.
  953. }
  954. fmtOut->validBitsPerSample = drwav__bytes_to_u16(fmtext + 0);
  955. fmtOut->channelMask = drwav__bytes_to_u32(fmtext + 2);
  956. drwav__bytes_to_guid(fmtext + 6, fmtOut->subFormat);
  957. } else {
  958. if (!onSeek(pUserData, fmtOut->extendedSize, drwav_seek_origin_current)) {
  959. return DRWAV_FALSE;
  960. }
  961. }
  962. *pRunningBytesReadOut += fmtOut->extendedSize;
  963. bytesReadSoFar += fmtOut->extendedSize;
  964. }
  965. // Seek past any leftover bytes. For w64 the leftover will be defined based on the chunk size.
  966. if (!onSeek(pUserData, (int)(header.sizeInBytes - bytesReadSoFar), drwav_seek_origin_current)) {
  967. return DRWAV_FALSE;
  968. }
  969. *pRunningBytesReadOut += (header.sizeInBytes - bytesReadSoFar);
  970. }
  971. if (header.paddingSize > 0) {
  972. if (!onSeek(pUserData, header.paddingSize, drwav_seek_origin_current)) {
  973. return DRWAV_FALSE;
  974. }
  975. *pRunningBytesReadOut += header.paddingSize;
  976. }
  977. return DRWAV_TRUE;
  978. }
  979. #ifndef DR_WAV_NO_STDIO
  980. FILE* drwav_fopen(const char* filePath, const char* openMode)
  981. {
  982. FILE* pFile;
  983. #if defined(_MSC_VER) && _MSC_VER >= 1400
  984. if (fopen_s(&pFile, filePath, openMode) != 0) {
  985. return DRWAV_FALSE;
  986. }
  987. #else
  988. pFile = fopen(filePath, openMode);
  989. if (pFile == NULL) {
  990. return DRWAV_FALSE;
  991. }
  992. #endif
  993. return pFile;
  994. }
  995. static size_t drwav__on_read_stdio(void* pUserData, void* pBufferOut, size_t bytesToRead)
  996. {
  997. return fread(pBufferOut, 1, bytesToRead, (FILE*)pUserData);
  998. }
  999. static size_t drwav__on_write_stdio(void* pUserData, const void* pData, size_t bytesToWrite)
  1000. {
  1001. return fwrite(pData, 1, bytesToWrite, (FILE*)pUserData);
  1002. }
  1003. static drwav_bool32 drwav__on_seek_stdio(void* pUserData, int offset, drwav_seek_origin origin)
  1004. {
  1005. return fseek((FILE*)pUserData, offset, (origin == drwav_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
  1006. }
  1007. drwav_bool32 drwav_init_file(drwav* pWav, const char* filename)
  1008. {
  1009. return drwav_init_file_ex(pWav, filename, NULL, NULL, 0);
  1010. }
  1011. drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags)
  1012. {
  1013. FILE* pFile = drwav_fopen(filename, "rb");
  1014. if (pFile == NULL) {
  1015. return DRWAV_FALSE;
  1016. }
  1017. return drwav_init_ex(pWav, drwav__on_read_stdio, drwav__on_seek_stdio, onChunk, (void*)pFile, pChunkUserData, flags);
  1018. }
  1019. drwav_bool32 drwav_init_file_write__internal(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential)
  1020. {
  1021. FILE* pFile = drwav_fopen(filename, "wb");
  1022. if (pFile == NULL) {
  1023. return DRWAV_FALSE;
  1024. }
  1025. return drwav_init_write__internal(pWav, pFormat, totalSampleCount, isSequential, drwav__on_write_stdio, drwav__on_seek_stdio, (void*)pFile);
  1026. }
  1027. drwav_bool32 drwav_init_file_write(drwav* pWav, const char* filename, const drwav_data_format* pFormat)
  1028. {
  1029. return drwav_init_file_write__internal(pWav, filename, pFormat, 0, DRWAV_FALSE);
  1030. }
  1031. drwav_bool32 drwav_init_file_write_sequential(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount)
  1032. {
  1033. return drwav_init_file_write__internal(pWav, filename, pFormat, totalSampleCount, DRWAV_TRUE);
  1034. }
  1035. drwav* drwav_open_file(const char* filename)
  1036. {
  1037. return drwav_open_file_ex(filename, NULL, NULL, 0);
  1038. }
  1039. drwav* drwav_open_file_ex(const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags)
  1040. {
  1041. FILE* pFile = drwav_fopen(filename, "rb");
  1042. if (pFile == NULL) {
  1043. return DRWAV_FALSE;
  1044. }
  1045. drwav* pWav = drwav_open_ex(drwav__on_read_stdio, drwav__on_seek_stdio, onChunk, (void*)pFile, pChunkUserData, flags);
  1046. if (pWav == NULL) {
  1047. fclose(pFile);
  1048. return NULL;
  1049. }
  1050. return pWav;
  1051. }
  1052. drwav* drwav_open_file_write__internal(const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential)
  1053. {
  1054. FILE* pFile = drwav_fopen(filename, "wb");
  1055. if (pFile == NULL) {
  1056. return DRWAV_FALSE;
  1057. }
  1058. drwav* pWav = drwav_open_write__internal(pFormat, totalSampleCount, isSequential, drwav__on_write_stdio, drwav__on_seek_stdio, (void*)pFile);
  1059. if (pWav == NULL) {
  1060. fclose(pFile);
  1061. return NULL;
  1062. }
  1063. return pWav;
  1064. }
  1065. drwav* drwav_open_file_write(const char* filename, const drwav_data_format* pFormat)
  1066. {
  1067. return drwav_open_file_write__internal(filename, pFormat, 0, DRWAV_FALSE);
  1068. }
  1069. drwav* drwav_open_file_write_sequential(const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount)
  1070. {
  1071. return drwav_open_file_write__internal(filename, pFormat, totalSampleCount, DRWAV_TRUE);
  1072. }
  1073. #endif //DR_WAV_NO_STDIO
  1074. static size_t drwav__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead)
  1075. {
  1076. drwav__memory_stream* memory = (drwav__memory_stream*)pUserData;
  1077. drwav_assert(memory != NULL);
  1078. drwav_assert(memory->dataSize >= memory->currentReadPos);
  1079. size_t bytesRemaining = memory->dataSize - memory->currentReadPos;
  1080. if (bytesToRead > bytesRemaining) {
  1081. bytesToRead = bytesRemaining;
  1082. }
  1083. if (bytesToRead > 0) {
  1084. DRWAV_COPY_MEMORY(pBufferOut, memory->data + memory->currentReadPos, bytesToRead);
  1085. memory->currentReadPos += bytesToRead;
  1086. }
  1087. return bytesToRead;
  1088. }
  1089. static drwav_bool32 drwav__on_seek_memory(void* pUserData, int offset, drwav_seek_origin origin)
  1090. {
  1091. drwav__memory_stream* memory = (drwav__memory_stream*)pUserData;
  1092. drwav_assert(memory != NULL);
  1093. if (origin == drwav_seek_origin_current) {
  1094. if (offset > 0) {
  1095. if (memory->currentReadPos + offset > memory->dataSize) {
  1096. return DRWAV_FALSE; // Trying to seek too far forward.
  1097. }
  1098. } else {
  1099. if (memory->currentReadPos < (size_t)-offset) {
  1100. return DRWAV_FALSE; // Trying to seek too far backwards.
  1101. }
  1102. }
  1103. // This will never underflow thanks to the clamps above.
  1104. memory->currentReadPos += offset;
  1105. } else {
  1106. if ((drwav_uint32)offset <= memory->dataSize) {
  1107. memory->currentReadPos = offset;
  1108. } else {
  1109. return DRWAV_FALSE; // Trying to seek too far forward.
  1110. }
  1111. }
  1112. return DRWAV_TRUE;
  1113. }
  1114. static size_t drwav__on_write_memory(void* pUserData, const void* pDataIn, size_t bytesToWrite)
  1115. {
  1116. drwav__memory_stream_write* memory = (drwav__memory_stream_write*)pUserData;
  1117. drwav_assert(memory != NULL);
  1118. drwav_assert(memory->dataCapacity >= memory->currentWritePos);
  1119. size_t bytesRemaining = memory->dataCapacity - memory->currentWritePos;
  1120. if (bytesRemaining < bytesToWrite) {
  1121. // Need to reallocate.
  1122. size_t newDataCapacity = (memory->dataCapacity == 0) ? 256 : memory->dataCapacity * 2;
  1123. // If doubling wasn't enough, just make it the minimum required size to write the data.
  1124. if ((newDataCapacity - memory->currentWritePos) < bytesToWrite) {
  1125. newDataCapacity = memory->currentWritePos + bytesToWrite;
  1126. }
  1127. void* pNewData = DRWAV_REALLOC(*memory->ppData, newDataCapacity);
  1128. if (pNewData == NULL) {
  1129. return 0;
  1130. }
  1131. *memory->ppData = pNewData;
  1132. memory->dataCapacity = newDataCapacity;
  1133. }
  1134. drwav_uint8* pDataOut = (drwav_uint8*)(*memory->ppData);
  1135. DRWAV_COPY_MEMORY(pDataOut + memory->currentWritePos, pDataIn, bytesToWrite);
  1136. memory->currentWritePos += bytesToWrite;
  1137. if (memory->dataSize < memory->currentWritePos) {
  1138. memory->dataSize = memory->currentWritePos;
  1139. }
  1140. *memory->pDataSize = memory->dataSize;
  1141. return bytesToWrite;
  1142. }
  1143. static drwav_bool32 drwav__on_seek_memory_write(void* pUserData, int offset, drwav_seek_origin origin)
  1144. {
  1145. drwav__memory_stream_write* memory = (drwav__memory_stream_write*)pUserData;
  1146. drwav_assert(memory != NULL);
  1147. if (origin == drwav_seek_origin_current) {
  1148. if (offset > 0) {
  1149. if (memory->currentWritePos + offset > memory->dataSize) {
  1150. offset = (int)(memory->dataSize - memory->currentWritePos); // Trying to seek too far forward.
  1151. }
  1152. } else {
  1153. if (memory->currentWritePos < (size_t)-offset) {
  1154. offset = -(int)memory->currentWritePos; // Trying to seek too far backwards.
  1155. }
  1156. }
  1157. // This will never underflow thanks to the clamps above.
  1158. memory->currentWritePos += offset;
  1159. } else {
  1160. if ((drwav_uint32)offset <= memory->dataSize) {
  1161. memory->currentWritePos = offset;
  1162. } else {
  1163. memory->currentWritePos = memory->dataSize; // Trying to seek too far forward.
  1164. }
  1165. }
  1166. return DRWAV_TRUE;
  1167. }
  1168. drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize)
  1169. {
  1170. return drwav_init_memory_ex(pWav, data, dataSize, NULL, NULL, 0);
  1171. }
  1172. drwav_bool32 drwav_init_memory_ex(drwav* pWav, const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags)
  1173. {
  1174. if (data == NULL || dataSize == 0) {
  1175. return DRWAV_FALSE;
  1176. }
  1177. drwav__memory_stream memoryStream;
  1178. drwav_zero_memory(&memoryStream, sizeof(memoryStream));
  1179. memoryStream.data = (const unsigned char*)data;
  1180. memoryStream.dataSize = dataSize;
  1181. memoryStream.currentReadPos = 0;
  1182. if (!drwav_init_ex(pWav, drwav__on_read_memory, drwav__on_seek_memory, onChunk, (void*)&memoryStream, pChunkUserData, flags)) {
  1183. return DRWAV_FALSE;
  1184. }
  1185. pWav->memoryStream = memoryStream;
  1186. pWav->pUserData = &pWav->memoryStream;
  1187. return DRWAV_TRUE;
  1188. }
  1189. drwav_bool32 drwav_init_memory_write__internal(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential)
  1190. {
  1191. if (ppData == NULL) {
  1192. return DRWAV_FALSE;
  1193. }
  1194. *ppData = NULL; // Important because we're using realloc()!
  1195. *pDataSize = 0;
  1196. drwav__memory_stream_write memoryStreamWrite;
  1197. drwav_zero_memory(&memoryStreamWrite, sizeof(memoryStreamWrite));
  1198. memoryStreamWrite.ppData = ppData;
  1199. memoryStreamWrite.pDataSize = pDataSize;
  1200. memoryStreamWrite.dataSize = 0;
  1201. memoryStreamWrite.dataCapacity = 0;
  1202. memoryStreamWrite.currentWritePos = 0;
  1203. if (!drwav_init_write__internal(pWav, pFormat, totalSampleCount, isSequential, drwav__on_write_memory, drwav__on_seek_memory_write, (void*)&memoryStreamWrite)) {
  1204. return DRWAV_FALSE;
  1205. }
  1206. pWav->memoryStreamWrite = memoryStreamWrite;
  1207. pWav->pUserData = &pWav->memoryStreamWrite;
  1208. return DRWAV_TRUE;
  1209. }
  1210. drwav_bool32 drwav_init_memory_write(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat)
  1211. {
  1212. return drwav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, 0, DRWAV_FALSE);
  1213. }
  1214. drwav_bool32 drwav_init_memory_write_sequential(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount)
  1215. {
  1216. return drwav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, totalSampleCount, DRWAV_TRUE);
  1217. }
  1218. drwav* drwav_open_memory(const void* data, size_t dataSize)
  1219. {
  1220. return drwav_open_memory_ex(data, dataSize, NULL, NULL, 0);
  1221. }
  1222. drwav* drwav_open_memory_ex(const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags)
  1223. {
  1224. if (data == NULL || dataSize == 0) {
  1225. return NULL;
  1226. }
  1227. drwav__memory_stream memoryStream;
  1228. drwav_zero_memory(&memoryStream, sizeof(memoryStream));
  1229. memoryStream.data = (const unsigned char*)data;
  1230. memoryStream.dataSize = dataSize;
  1231. memoryStream.currentReadPos = 0;
  1232. drwav* pWav = drwav_open_ex(drwav__on_read_memory, drwav__on_seek_memory, onChunk, (void*)&memoryStream, pChunkUserData, flags);
  1233. if (pWav == NULL) {
  1234. return NULL;
  1235. }
  1236. pWav->memoryStream = memoryStream;
  1237. pWav->pUserData = &pWav->memoryStream;
  1238. return pWav;
  1239. }
  1240. drwav* drwav_open_memory_write__internal(void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential)
  1241. {
  1242. if (ppData == NULL) {
  1243. return NULL;
  1244. }
  1245. *ppData = NULL; // Important because we're using realloc()!
  1246. *pDataSize = 0;
  1247. drwav__memory_stream_write memoryStreamWrite;
  1248. drwav_zero_memory(&memoryStreamWrite, sizeof(memoryStreamWrite));
  1249. memoryStreamWrite.ppData = ppData;
  1250. memoryStreamWrite.pDataSize = pDataSize;
  1251. memoryStreamWrite.dataSize = 0;
  1252. memoryStreamWrite.dataCapacity = 0;
  1253. memoryStreamWrite.currentWritePos = 0;
  1254. drwav* pWav = drwav_open_write__internal(pFormat, totalSampleCount, isSequential, drwav__on_write_memory, drwav__on_seek_memory_write, (void*)&memoryStreamWrite);
  1255. if (pWav == NULL) {
  1256. return NULL;
  1257. }
  1258. pWav->memoryStreamWrite = memoryStreamWrite;
  1259. pWav->pUserData = &pWav->memoryStreamWrite;
  1260. return pWav;
  1261. }
  1262. drwav* drwav_open_memory_write(void** ppData, size_t* pDataSize, const drwav_data_format* pFormat)
  1263. {
  1264. return drwav_open_memory_write__internal(ppData, pDataSize, pFormat, 0, DRWAV_FALSE);
  1265. }
  1266. drwav* drwav_open_memory_write_sequential(void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount)
  1267. {
  1268. return drwav_open_memory_write__internal(ppData, pDataSize, pFormat, totalSampleCount, DRWAV_TRUE);
  1269. }
  1270. size_t drwav__on_read(drwav_read_proc onRead, void* pUserData, void* pBufferOut, size_t bytesToRead, drwav_uint64* pCursor)
  1271. {
  1272. drwav_assert(onRead != NULL);
  1273. drwav_assert(pCursor != NULL);
  1274. size_t bytesRead = onRead(pUserData, pBufferOut, bytesToRead);
  1275. *pCursor += bytesRead;
  1276. return bytesRead;
  1277. }
  1278. drwav_bool32 drwav__on_seek(drwav_seek_proc onSeek, void* pUserData, int offset, drwav_seek_origin origin, drwav_uint64* pCursor)
  1279. {
  1280. drwav_assert(onSeek != NULL);
  1281. drwav_assert(pCursor != NULL);
  1282. if (!onSeek(pUserData, offset, origin)) {
  1283. return DRWAV_FALSE;
  1284. }
  1285. if (origin == drwav_seek_origin_start) {
  1286. *pCursor = offset;
  1287. } else {
  1288. *pCursor += offset;
  1289. }
  1290. return DRWAV_TRUE;
  1291. }
  1292. static drwav_uint32 drwav_get_bytes_per_sample(drwav* pWav)
  1293. {
  1294. // The number of bytes per sample is based on the bits per sample or the block align. We prioritize floor(bitsPerSample/8), but if
  1295. // this is zero or the bits per sample is not a multiple of 8 we need to fall back to the block align.
  1296. drwav_uint32 bytesPerSample = pWav->bitsPerSample >> 3;
  1297. if (bytesPerSample == 0 || (pWav->bitsPerSample & 0x7) != 0) {
  1298. bytesPerSample = pWav->fmt.blockAlign/pWav->fmt.channels;
  1299. }
  1300. return bytesPerSample;
  1301. }
  1302. static drwav_uint32 drwav_get_bytes_per_pcm_frame(drwav* pWav)
  1303. {
  1304. // The number of bytes per frame is based on the bits per sample or the block align. We prioritize floor(bitsPerSample*channels/8), but if
  1305. // this is zero or the bits per frame is not a multiple of 8 we need to fall back to the block align.
  1306. drwav_uint32 bitsPerFrame = pWav->bitsPerSample * pWav->fmt.channels;
  1307. drwav_uint32 bytesPerFrame = bitsPerFrame >> 3;
  1308. if (bytesPerFrame == 0 || (bitsPerFrame & 0x7) != 0) {
  1309. bytesPerFrame = pWav->fmt.blockAlign;
  1310. }
  1311. return bytesPerFrame;
  1312. }
  1313. drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData)
  1314. {
  1315. return drwav_init_ex(pWav, onRead, onSeek, NULL, pUserData, NULL, 0);
  1316. }
  1317. drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags)
  1318. {
  1319. if (onRead == NULL || onSeek == NULL) {
  1320. return DRWAV_FALSE;
  1321. }
  1322. drwav_uint64 cursor = 0; // <-- Keeps track of the byte position so we can seek to specific locations.
  1323. drwav_bool32 sequential = (flags & DRWAV_SEQUENTIAL) != 0;
  1324. drwav_zero_memory(pWav, sizeof(*pWav));
  1325. pWav->onRead = onRead;
  1326. pWav->onSeek = onSeek;
  1327. pWav->pUserData = pReadSeekUserData;
  1328. // The first 4 bytes should be the RIFF identifier.
  1329. unsigned char riff[4];
  1330. if (drwav__on_read(onRead, pReadSeekUserData, riff, sizeof(riff), &cursor) != sizeof(riff)) {
  1331. return DRWAV_FALSE;
  1332. }
  1333. // The first 4 bytes can be used to identify the container. For RIFF files it will start with "RIFF" and for
  1334. // w64 it will start with "riff".
  1335. if (drwav__fourcc_equal(riff, "RIFF")) {
  1336. pWav->container = drwav_container_riff;
  1337. } else if (drwav__fourcc_equal(riff, "riff")) {
  1338. pWav->container = drwav_container_w64;
  1339. // Check the rest of the GUID for validity.
  1340. drwav_uint8 riff2[12];
  1341. if (drwav__on_read(onRead, pReadSeekUserData, riff2, sizeof(riff2), &cursor) != sizeof(riff2)) {
  1342. return DRWAV_FALSE;
  1343. }
  1344. for (int i = 0; i < 12; ++i) {
  1345. if (riff2[i] != drwavGUID_W64_RIFF[i+4]) {
  1346. return DRWAV_FALSE;
  1347. }
  1348. }
  1349. } else {
  1350. return DRWAV_FALSE; // Unknown or unsupported container.
  1351. }
  1352. if (pWav->container == drwav_container_riff) {
  1353. // RIFF/WAVE
  1354. unsigned char chunkSizeBytes[4];
  1355. if (drwav__on_read(onRead, pReadSeekUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) {
  1356. return DRWAV_FALSE;
  1357. }
  1358. unsigned int chunkSize = drwav__bytes_to_u32(chunkSizeBytes);
  1359. if (chunkSize < 36) {
  1360. return DRWAV_FALSE; // Chunk size should always be at least 36 bytes.
  1361. }
  1362. unsigned char wave[4];
  1363. if (drwav__on_read(onRead, pReadSeekUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) {
  1364. return DRWAV_FALSE;
  1365. }
  1366. if (!drwav__fourcc_equal(wave, "WAVE")) {
  1367. return DRWAV_FALSE; // Expecting "WAVE".
  1368. }
  1369. } else {
  1370. // W64
  1371. unsigned char chunkSize[8];
  1372. if (drwav__on_read(onRead, pReadSeekUserData, chunkSize, sizeof(chunkSize), &cursor) != sizeof(chunkSize)) {
  1373. return DRWAV_FALSE;
  1374. }
  1375. if (drwav__bytes_to_u64(chunkSize) < 80) {
  1376. return DRWAV_FALSE;
  1377. }
  1378. drwav_uint8 wave[16];
  1379. if (drwav__on_read(onRead, pReadSeekUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) {
  1380. return DRWAV_FALSE;
  1381. }
  1382. if (!drwav__guid_equal(wave, drwavGUID_W64_WAVE)) {
  1383. return DRWAV_FALSE;
  1384. }
  1385. }
  1386. // The next bytes should be the "fmt " chunk.
  1387. drwav_fmt fmt;
  1388. if (!drwav__read_fmt(onRead, onSeek, pReadSeekUserData, pWav->container, &cursor, &fmt)) {
  1389. return DRWAV_FALSE; // Failed to read the "fmt " chunk.
  1390. }
  1391. // Basic validation.
  1392. if (fmt.sampleRate == 0 || fmt.channels == 0 || fmt.bitsPerSample == 0 || fmt.blockAlign == 0) {
  1393. return DRWAV_FALSE; // Invalid channel count. Probably an invalid WAV file.
  1394. }
  1395. // Translate the internal format.
  1396. unsigned short translatedFormatTag = fmt.formatTag;
  1397. if (translatedFormatTag == DR_WAVE_FORMAT_EXTENSIBLE) {
  1398. translatedFormatTag = drwav__bytes_to_u16(fmt.subFormat + 0);
  1399. }
  1400. drwav_uint64 sampleCountFromFactChunk = 0;
  1401. // We need to enumerate over each chunk for two reasons:
  1402. // 1) The "data" chunk may not be the next one
  1403. // 2) We may want to report each chunk back to the client
  1404. //
  1405. // In order to correctly report each chunk back to the client we will need to keep looping until the end of the file.
  1406. drwav_bool32 foundDataChunk = DRWAV_FALSE;
  1407. drwav_uint64 dataChunkSize = 0;
  1408. // The next chunk we care about is the "data" chunk. This is not necessarily the next chunk so we'll need to loop.
  1409. drwav_uint64 chunkSize = 0;
  1410. for (;;)
  1411. {
  1412. drwav_chunk_header header;
  1413. drwav_result result = drwav__read_chunk_header(onRead, pReadSeekUserData, pWav->container, &cursor, &header);
  1414. if (result != DRWAV_SUCCESS) {
  1415. if (!foundDataChunk) {
  1416. return DRWAV_FALSE;
  1417. } else {
  1418. break; // Probably at the end of the file. Get out of the loop.
  1419. }
  1420. }
  1421. // Tell the client about this chunk.
  1422. if (!sequential && onChunk != NULL) {
  1423. drwav_uint64 callbackBytesRead = onChunk(pChunkUserData, onRead, onSeek, pReadSeekUserData, &header);
  1424. // dr_wav may need to read the contents of the chunk, so we now need to seek back to the position before
  1425. // we called the callback.
  1426. if (callbackBytesRead > 0) {
  1427. if (!drwav__seek_from_start(onSeek, cursor, pReadSeekUserData)) {
  1428. return DRWAV_FALSE;
  1429. }
  1430. }
  1431. }
  1432. if (!foundDataChunk) {
  1433. pWav->dataChunkDataPos = cursor;
  1434. }
  1435. chunkSize = header.sizeInBytes;
  1436. if (pWav->container == drwav_container_riff) {
  1437. if (drwav__fourcc_equal(header.id.fourcc, "data")) {
  1438. foundDataChunk = DRWAV_TRUE;
  1439. dataChunkSize = chunkSize;
  1440. }
  1441. } else {
  1442. if (drwav__guid_equal(header.id.guid, drwavGUID_W64_DATA)) {
  1443. foundDataChunk = DRWAV_TRUE;
  1444. dataChunkSize = chunkSize;
  1445. }
  1446. }
  1447. // If at this point we have found the data chunk and we're running in sequential mode, we need to break out of this loop. The reason for
  1448. // this is that we would otherwise require a backwards seek which sequential mode forbids.
  1449. if (foundDataChunk && sequential) {
  1450. break;
  1451. }
  1452. // Optional. Get the total sample count from the FACT chunk. This is useful for compressed formats.
  1453. if (pWav->container == drwav_container_riff) {
  1454. if (drwav__fourcc_equal(header.id.fourcc, "fact")) {
  1455. drwav_uint32 sampleCount;
  1456. if (drwav__on_read(onRead, pReadSeekUserData, &sampleCount, 4, &cursor) != 4) {
  1457. return DRWAV_FALSE;
  1458. }
  1459. chunkSize -= 4;
  1460. if (!foundDataChunk) {
  1461. pWav->dataChunkDataPos = cursor;
  1462. }
  1463. // The sample count in the "fact" chunk is either unreliable, or I'm not understanding it properly. For now I am only enabling this
  1464. // for Microsoft ADPCM formats.
  1465. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  1466. sampleCountFromFactChunk = sampleCount;
  1467. } else {
  1468. sampleCountFromFactChunk = 0;
  1469. }
  1470. }
  1471. } else {
  1472. if (drwav__guid_equal(header.id.guid, drwavGUID_W64_FACT)) {
  1473. if (drwav__on_read(onRead, pReadSeekUserData, &sampleCountFromFactChunk, 8, &cursor) != 8) {
  1474. return DRWAV_FALSE;
  1475. }
  1476. chunkSize -= 8;
  1477. if (!foundDataChunk) {
  1478. pWav->dataChunkDataPos = cursor;
  1479. }
  1480. }
  1481. }
  1482. // "smpl" chunk.
  1483. if (pWav->container == drwav_container_riff) {
  1484. if (drwav__fourcc_equal(header.id.fourcc, "smpl")) {
  1485. unsigned char smplHeaderData[36]; // 36 = size of the smpl header section, not including the loop data.
  1486. if (chunkSize >= sizeof(smplHeaderData)) {
  1487. drwav_uint64 bytesJustRead = drwav__on_read(onRead, pReadSeekUserData, smplHeaderData, sizeof(smplHeaderData), &cursor);
  1488. chunkSize -= bytesJustRead;
  1489. if (bytesJustRead == sizeof(smplHeaderData)) {
  1490. pWav->smpl.manufacturer = drwav__bytes_to_u32(smplHeaderData+0);
  1491. pWav->smpl.product = drwav__bytes_to_u32(smplHeaderData+4);
  1492. pWav->smpl.samplePeriod = drwav__bytes_to_u32(smplHeaderData+8);
  1493. pWav->smpl.midiUnityNotes = drwav__bytes_to_u32(smplHeaderData+12);
  1494. pWav->smpl.midiPitchFraction = drwav__bytes_to_u32(smplHeaderData+16);
  1495. pWav->smpl.smpteFormat = drwav__bytes_to_u32(smplHeaderData+20);
  1496. pWav->smpl.smpteOffset = drwav__bytes_to_u32(smplHeaderData+24);
  1497. pWav->smpl.numSampleLoops = drwav__bytes_to_u32(smplHeaderData+28);
  1498. pWav->smpl.samplerData = drwav__bytes_to_u32(smplHeaderData+32);
  1499. for (drwav_uint32 iLoop = 0; iLoop < pWav->smpl.numSampleLoops && iLoop < drwav_countof(pWav->smpl.loops); ++iLoop) {
  1500. unsigned char smplLoopData[24]; // 24 = size of a loop section in the smpl chunk.
  1501. bytesJustRead = drwav__on_read(onRead, pReadSeekUserData, smplLoopData, sizeof(smplLoopData), &cursor);
  1502. chunkSize -= bytesJustRead;
  1503. if (bytesJustRead == sizeof(smplLoopData)) {
  1504. pWav->smpl.loops[iLoop].cuePointId = drwav__bytes_to_u32(smplLoopData+0);
  1505. pWav->smpl.loops[iLoop].type = drwav__bytes_to_u32(smplLoopData+4);
  1506. pWav->smpl.loops[iLoop].start = drwav__bytes_to_u32(smplLoopData+8);
  1507. pWav->smpl.loops[iLoop].end = drwav__bytes_to_u32(smplLoopData+12);
  1508. pWav->smpl.loops[iLoop].fraction = drwav__bytes_to_u32(smplLoopData+16);
  1509. pWav->smpl.loops[iLoop].playCount = drwav__bytes_to_u32(smplLoopData+20);
  1510. } else {
  1511. break; // Break from the smpl loop for loop.
  1512. }
  1513. }
  1514. }
  1515. } else {
  1516. // Looks like invalid data. Ignore the chunk.
  1517. }
  1518. }
  1519. } else {
  1520. if (drwav__guid_equal(header.id.guid, drwavGUID_W64_SMPL)) {
  1521. // This path will be hit when a W64 WAV file contains a smpl chunk. I don't have a sample file to test this path, so a contribution
  1522. // is welcome to add support for this.
  1523. }
  1524. }
  1525. // Make sure we seek past the padding.
  1526. chunkSize += header.paddingSize;
  1527. if (!drwav__seek_forward(onSeek, chunkSize, pReadSeekUserData)) {
  1528. break;
  1529. }
  1530. cursor += chunkSize;
  1531. if (!foundDataChunk) {
  1532. pWav->dataChunkDataPos = cursor;
  1533. }
  1534. }
  1535. // If we haven't found a data chunk, return an error.
  1536. if (!foundDataChunk) {
  1537. return DRWAV_FALSE;
  1538. }
  1539. // We may have moved passed the data chunk. If so we need to move back. If running in sequential mode we can assume we are already sitting on the data chunk.
  1540. if (!sequential) {
  1541. if (!drwav__seek_from_start(onSeek, pWav->dataChunkDataPos, pReadSeekUserData)) {
  1542. return DRWAV_FALSE;
  1543. }
  1544. cursor = pWav->dataChunkDataPos;
  1545. }
  1546. // At this point we should be sitting on the first byte of the raw audio data.
  1547. pWav->fmt = fmt;
  1548. pWav->sampleRate = fmt.sampleRate;
  1549. pWav->channels = fmt.channels;
  1550. pWav->bitsPerSample = fmt.bitsPerSample;
  1551. pWav->bytesRemaining = dataChunkSize;
  1552. pWav->translatedFormatTag = translatedFormatTag;
  1553. pWav->dataChunkDataSize = dataChunkSize;
  1554. if (sampleCountFromFactChunk != 0) {
  1555. pWav->totalPCMFrameCount = sampleCountFromFactChunk;
  1556. } else {
  1557. pWav->totalPCMFrameCount = dataChunkSize / drwav_get_bytes_per_pcm_frame(pWav);
  1558. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  1559. drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  1560. pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (6*pWav->channels))) * 2)) / fmt.channels; // x2 because two samples per byte.
  1561. }
  1562. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  1563. drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  1564. pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (4*pWav->channels))) * 2) + (blockCount * pWav->channels)) / fmt.channels;
  1565. }
  1566. }
  1567. // Some formats only support a certain number of channels.
  1568. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  1569. if (pWav->channels > 2) {
  1570. return DRWAV_FALSE;
  1571. }
  1572. }
  1573. #ifdef DR_WAV_LIBSNDFILE_COMPAT
  1574. // I use libsndfile as a benchmark for testing, however in the version I'm using (from the Windows installer on the libsndfile website),
  1575. // it appears the total sample count libsndfile uses for MS-ADPCM is incorrect. It would seem they are computing the total sample count
  1576. // from the number of blocks, however this results in the inclusion of extra silent samples at the end of the last block. The correct
  1577. // way to know the total sample count is to inspect the "fact" chunk, which should always be present for compressed formats, and should
  1578. // always include the sample count. This little block of code below is only used to emulate the libsndfile logic so I can properly run my
  1579. // correctness tests against libsndfile, and is disabled by default.
  1580. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  1581. drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  1582. pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (6*pWav->channels))) * 2)) / fmt.channels; // x2 because two samples per byte.
  1583. }
  1584. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  1585. drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  1586. pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (4*pWav->channels))) * 2) + (blockCount * pWav->channels)) / fmt.channels;
  1587. }
  1588. #endif
  1589. pWav->totalSampleCount = pWav->totalPCMFrameCount * pWav->channels;
  1590. return DRWAV_TRUE;
  1591. }
  1592. drwav_uint32 drwav_riff_chunk_size_riff(drwav_uint64 dataChunkSize)
  1593. {
  1594. if (dataChunkSize <= (0xFFFFFFFF - 36)) {
  1595. return 36 + (drwav_uint32)dataChunkSize;
  1596. } else {
  1597. return 0xFFFFFFFF;
  1598. }
  1599. }
  1600. drwav_uint32 drwav_data_chunk_size_riff(drwav_uint64 dataChunkSize)
  1601. {
  1602. if (dataChunkSize <= 0xFFFFFFFF) {
  1603. return (drwav_uint32)dataChunkSize;
  1604. } else {
  1605. return 0xFFFFFFFF;
  1606. }
  1607. }
  1608. drwav_uint64 drwav_riff_chunk_size_w64(drwav_uint64 dataChunkSize)
  1609. {
  1610. return 80 + 24 + dataChunkSize; // +24 because W64 includes the size of the GUID and size fields.
  1611. }
  1612. drwav_uint64 drwav_data_chunk_size_w64(drwav_uint64 dataChunkSize)
  1613. {
  1614. return 24 + dataChunkSize; // +24 because W64 includes the size of the GUID and size fields.
  1615. }
  1616. drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData)
  1617. {
  1618. if (pWav == NULL) {
  1619. return DRWAV_FALSE;
  1620. }
  1621. if (onWrite == NULL) {
  1622. return DRWAV_FALSE;
  1623. }
  1624. if (!isSequential && onSeek == NULL) {
  1625. return DRWAV_FALSE; // <-- onSeek is required when in non-sequential mode.
  1626. }
  1627. // Not currently supporting compressed formats. Will need to add support for the "fact" chunk before we enable this.
  1628. if (pFormat->format == DR_WAVE_FORMAT_EXTENSIBLE) {
  1629. return DRWAV_FALSE;
  1630. }
  1631. if (pFormat->format == DR_WAVE_FORMAT_ADPCM || pFormat->format == DR_WAVE_FORMAT_DVI_ADPCM) {
  1632. return DRWAV_FALSE;
  1633. }
  1634. drwav_zero_memory(pWav, sizeof(*pWav));
  1635. pWav->onWrite = onWrite;
  1636. pWav->onSeek = onSeek;
  1637. pWav->pUserData = pUserData;
  1638. pWav->fmt.formatTag = (drwav_uint16)pFormat->format;
  1639. pWav->fmt.channels = (drwav_uint16)pFormat->channels;
  1640. pWav->fmt.sampleRate = pFormat->sampleRate;
  1641. pWav->fmt.avgBytesPerSec = (drwav_uint32)((pFormat->bitsPerSample * pFormat->sampleRate * pFormat->channels) / 8);
  1642. pWav->fmt.blockAlign = (drwav_uint16)((pFormat->channels * pFormat->bitsPerSample) / 8);
  1643. pWav->fmt.bitsPerSample = (drwav_uint16)pFormat->bitsPerSample;
  1644. pWav->fmt.extendedSize = 0;
  1645. pWav->isSequentialWrite = isSequential;
  1646. size_t runningPos = 0;
  1647. // The initial values for the "RIFF" and "data" chunks depends on whether or not we are initializing in sequential mode or not. In
  1648. // sequential mode we set this to its final values straight away since they can be calculated from the total sample count. In non-
  1649. // sequential mode we initialize it all to zero and fill it out in drwav_uninit() using a backwards seek.
  1650. drwav_uint64 initialDataChunkSize = 0;
  1651. if (isSequential) {
  1652. initialDataChunkSize = (totalSampleCount * pWav->fmt.bitsPerSample) / 8;
  1653. // The RIFF container has a limit on the number of samples. drwav is not allowing this. There's no practical limits for Wave64
  1654. // so for the sake of simplicity I'm not doing any validation for that.
  1655. if (pFormat->container == drwav_container_riff) {
  1656. if (initialDataChunkSize > (0xFFFFFFFF - 36)) {
  1657. return DRWAV_FALSE; // Not enough room to store every sample.
  1658. }
  1659. }
  1660. }
  1661. pWav->dataChunkDataSizeTargetWrite = initialDataChunkSize;
  1662. // "RIFF" chunk.
  1663. if (pFormat->container == drwav_container_riff) {
  1664. drwav_uint32 chunkSizeRIFF = 36 + (drwav_uint32)initialDataChunkSize; // +36 = "RIFF"+[RIFF Chunk Size]+"WAVE" + [sizeof "fmt " chunk]
  1665. runningPos += pWav->onWrite(pUserData, "RIFF", 4);
  1666. runningPos += pWav->onWrite(pUserData, &chunkSizeRIFF, 4);
  1667. runningPos += pWav->onWrite(pUserData, "WAVE", 4);
  1668. } else {
  1669. drwav_uint64 chunkSizeRIFF = 80 + 24 + initialDataChunkSize; // +24 because W64 includes the size of the GUID and size fields.
  1670. runningPos += pWav->onWrite(pUserData, drwavGUID_W64_RIFF, 16);
  1671. runningPos += pWav->onWrite(pUserData, &chunkSizeRIFF, 8);
  1672. runningPos += pWav->onWrite(pUserData, drwavGUID_W64_WAVE, 16);
  1673. }
  1674. // "fmt " chunk.
  1675. drwav_uint64 chunkSizeFMT;
  1676. if (pFormat->container == drwav_container_riff) {
  1677. chunkSizeFMT = 16;
  1678. runningPos += pWav->onWrite(pUserData, "fmt ", 4);
  1679. runningPos += pWav->onWrite(pUserData, &chunkSizeFMT, 4);
  1680. } else {
  1681. chunkSizeFMT = 40;
  1682. runningPos += pWav->onWrite(pUserData, drwavGUID_W64_FMT, 16);
  1683. runningPos += pWav->onWrite(pUserData, &chunkSizeFMT, 8);
  1684. }
  1685. runningPos += pWav->onWrite(pUserData, &pWav->fmt.formatTag, 2);
  1686. runningPos += pWav->onWrite(pUserData, &pWav->fmt.channels, 2);
  1687. runningPos += pWav->onWrite(pUserData, &pWav->fmt.sampleRate, 4);
  1688. runningPos += pWav->onWrite(pUserData, &pWav->fmt.avgBytesPerSec, 4);
  1689. runningPos += pWav->onWrite(pUserData, &pWav->fmt.blockAlign, 2);
  1690. runningPos += pWav->onWrite(pUserData, &pWav->fmt.bitsPerSample, 2);
  1691. pWav->dataChunkDataPos = runningPos;
  1692. // "data" chunk.
  1693. if (pFormat->container == drwav_container_riff) {
  1694. drwav_uint32 chunkSizeDATA = (drwav_uint32)initialDataChunkSize;
  1695. runningPos += pWav->onWrite(pUserData, "data", 4);
  1696. runningPos += pWav->onWrite(pUserData, &chunkSizeDATA, 4);
  1697. } else {
  1698. drwav_uint64 chunkSizeDATA = 24 + initialDataChunkSize; // +24 because W64 includes the size of the GUID and size fields.
  1699. runningPos += pWav->onWrite(pUserData, drwavGUID_W64_DATA, 16);
  1700. runningPos += pWav->onWrite(pUserData, &chunkSizeDATA, 8);
  1701. }
  1702. // Simple validation.
  1703. if (pFormat->container == drwav_container_riff) {
  1704. if (runningPos != 20 + chunkSizeFMT + 8) {
  1705. return DRWAV_FALSE;
  1706. }
  1707. } else {
  1708. if (runningPos != 40 + chunkSizeFMT + 24) {
  1709. return DRWAV_FALSE;
  1710. }
  1711. }
  1712. // Set some properties for the client's convenience.
  1713. pWav->container = pFormat->container;
  1714. pWav->channels = (drwav_uint16)pFormat->channels;
  1715. pWav->sampleRate = pFormat->sampleRate;
  1716. pWav->bitsPerSample = (drwav_uint16)pFormat->bitsPerSample;
  1717. pWav->translatedFormatTag = (drwav_uint16)pFormat->format;
  1718. return DRWAV_TRUE;
  1719. }
  1720. drwav_bool32 drwav_init_write(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData)
  1721. {
  1722. return drwav_init_write__internal(pWav, pFormat, 0, DRWAV_FALSE, onWrite, onSeek, pUserData); // DRWAV_FALSE = Not Sequential
  1723. }
  1724. drwav_bool32 drwav_init_write_sequential(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData)
  1725. {
  1726. return drwav_init_write__internal(pWav, pFormat, totalSampleCount, DRWAV_TRUE, onWrite, NULL, pUserData); // DRWAV_TRUE = Sequential
  1727. }
  1728. void drwav_uninit(drwav* pWav)
  1729. {
  1730. if (pWav == NULL) {
  1731. return;
  1732. }
  1733. // If the drwav object was opened in write mode we'll need to finalize a few things:
  1734. // - Make sure the "data" chunk is aligned to 16-bits for RIFF containers, or 64 bits for W64 containers.
  1735. // - Set the size of the "data" chunk.
  1736. if (pWav->onWrite != NULL) {
  1737. // Validation for sequential mode.
  1738. if (pWav->isSequentialWrite) {
  1739. drwav_assert(pWav->dataChunkDataSize == pWav->dataChunkDataSizeTargetWrite);
  1740. }
  1741. // Padding. Do not adjust pWav->dataChunkDataSize - this should not include the padding.
  1742. drwav_uint32 paddingSize = 0;
  1743. if (pWav->container == drwav_container_riff) {
  1744. paddingSize = (drwav_uint32)(pWav->dataChunkDataSize % 2);
  1745. } else {
  1746. paddingSize = (drwav_uint32)(pWav->dataChunkDataSize % 8);
  1747. }
  1748. if (paddingSize > 0) {
  1749. drwav_uint64 paddingData = 0;
  1750. pWav->onWrite(pWav->pUserData, &paddingData, paddingSize);
  1751. }
  1752. // Chunk sizes. When using sequential mode, these will have been filled in at initialization time. We only need
  1753. // to do this when using non-sequential mode.
  1754. if (pWav->onSeek && !pWav->isSequentialWrite) {
  1755. if (pWav->container == drwav_container_riff) {
  1756. // The "RIFF" chunk size.
  1757. if (pWav->onSeek(pWav->pUserData, 4, drwav_seek_origin_start)) {
  1758. drwav_uint32 riffChunkSize = drwav_riff_chunk_size_riff(pWav->dataChunkDataSize);
  1759. pWav->onWrite(pWav->pUserData, &riffChunkSize, 4);
  1760. }
  1761. // the "data" chunk size.
  1762. if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos + 4, drwav_seek_origin_start)) {
  1763. drwav_uint32 dataChunkSize = drwav_data_chunk_size_riff(pWav->dataChunkDataSize);
  1764. pWav->onWrite(pWav->pUserData, &dataChunkSize, 4);
  1765. }
  1766. } else {
  1767. // The "RIFF" chunk size.
  1768. if (pWav->onSeek(pWav->pUserData, 16, drwav_seek_origin_start)) {
  1769. drwav_uint64 riffChunkSize = drwav_riff_chunk_size_w64(pWav->dataChunkDataSize);
  1770. pWav->onWrite(pWav->pUserData, &riffChunkSize, 8);
  1771. }
  1772. // The "data" chunk size.
  1773. if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos + 16, drwav_seek_origin_start)) {
  1774. drwav_uint64 dataChunkSize = drwav_data_chunk_size_w64(pWav->dataChunkDataSize);
  1775. pWav->onWrite(pWav->pUserData, &dataChunkSize, 8);
  1776. }
  1777. }
  1778. }
  1779. }
  1780. #ifndef DR_WAV_NO_STDIO
  1781. // If we opened the file with drwav_open_file() we will want to close the file handle. We can know whether or not drwav_open_file()
  1782. // was used by looking at the onRead and onSeek callbacks.
  1783. if (pWav->onRead == drwav__on_read_stdio || pWav->onWrite == drwav__on_write_stdio) {
  1784. fclose((FILE*)pWav->pUserData);
  1785. }
  1786. #endif
  1787. }
  1788. drwav* drwav_open(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData)
  1789. {
  1790. return drwav_open_ex(onRead, onSeek, NULL, pUserData, NULL, 0);
  1791. }
  1792. drwav* drwav_open_ex(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags)
  1793. {
  1794. drwav* pWav = (drwav*)DRWAV_MALLOC(sizeof(*pWav));
  1795. if (pWav == NULL) {
  1796. return NULL;
  1797. }
  1798. if (!drwav_init_ex(pWav, onRead, onSeek, onChunk, pReadSeekUserData, pChunkUserData, flags)) {
  1799. DRWAV_FREE(pWav);
  1800. return NULL;
  1801. }
  1802. return pWav;
  1803. }
  1804. drwav* drwav_open_write__internal(const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData)
  1805. {
  1806. drwav* pWav = (drwav*)DRWAV_MALLOC(sizeof(*pWav));
  1807. if (pWav == NULL) {
  1808. return NULL;
  1809. }
  1810. if (!drwav_init_write__internal(pWav, pFormat, totalSampleCount, isSequential, onWrite, onSeek, pUserData)) {
  1811. DRWAV_FREE(pWav);
  1812. return NULL;
  1813. }
  1814. return pWav;
  1815. }
  1816. drwav* drwav_open_write(const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData)
  1817. {
  1818. return drwav_open_write__internal(pFormat, 0, DRWAV_FALSE, onWrite, onSeek, pUserData);
  1819. }
  1820. drwav* drwav_open_write_sequential(const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData)
  1821. {
  1822. return drwav_open_write__internal(pFormat, totalSampleCount, DRWAV_TRUE, onWrite, NULL, pUserData);
  1823. }
  1824. void drwav_close(drwav* pWav)
  1825. {
  1826. drwav_uninit(pWav);
  1827. DRWAV_FREE(pWav);
  1828. }
  1829. size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut)
  1830. {
  1831. if (pWav == NULL || bytesToRead == 0 || pBufferOut == NULL) {
  1832. return 0;
  1833. }
  1834. if (bytesToRead > pWav->bytesRemaining) {
  1835. bytesToRead = (size_t)pWav->bytesRemaining;
  1836. }
  1837. size_t bytesRead = pWav->onRead(pWav->pUserData, pBufferOut, bytesToRead);
  1838. pWav->bytesRemaining -= bytesRead;
  1839. return bytesRead;
  1840. }
  1841. drwav_uint64 drwav_read(drwav* pWav, drwav_uint64 samplesToRead, void* pBufferOut)
  1842. {
  1843. if (pWav == NULL || samplesToRead == 0 || pBufferOut == NULL) {
  1844. return 0;
  1845. }
  1846. // Cannot use this function for compressed formats.
  1847. if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  1848. return 0;
  1849. }
  1850. drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav);
  1851. if (bytesPerSample == 0) {
  1852. return 0;
  1853. }
  1854. // Don't try to read more samples than can potentially fit in the output buffer.
  1855. if (samplesToRead * bytesPerSample > DRWAV_SIZE_MAX) {
  1856. samplesToRead = DRWAV_SIZE_MAX / bytesPerSample;
  1857. }
  1858. size_t bytesRead = drwav_read_raw(pWav, (size_t)(samplesToRead * bytesPerSample), pBufferOut);
  1859. return bytesRead / bytesPerSample;
  1860. }
  1861. drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
  1862. {
  1863. if (pWav == NULL || framesToRead == 0 || pBufferOut == NULL) {
  1864. return 0;
  1865. }
  1866. // Cannot use this function for compressed formats.
  1867. if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  1868. return 0;
  1869. }
  1870. drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  1871. if (bytesPerFrame == 0) {
  1872. return 0;
  1873. }
  1874. // Don't try to read more samples than can potentially fit in the output buffer.
  1875. if (framesToRead * bytesPerFrame > DRWAV_SIZE_MAX) {
  1876. framesToRead = DRWAV_SIZE_MAX / bytesPerFrame;
  1877. }
  1878. size_t bytesRead = drwav_read_raw(pWav, (size_t)(framesToRead * bytesPerFrame), pBufferOut);
  1879. return bytesRead / bytesPerFrame;
  1880. }
  1881. drwav_bool32 drwav_seek_to_first_pcm_frame(drwav* pWav)
  1882. {
  1883. if (pWav->onWrite != NULL) {
  1884. return DRWAV_FALSE; // No seeking in write mode.
  1885. }
  1886. if (!pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos, drwav_seek_origin_start)) {
  1887. return DRWAV_FALSE;
  1888. }
  1889. if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  1890. pWav->compressed.iCurrentSample = 0;
  1891. }
  1892. pWav->bytesRemaining = pWav->dataChunkDataSize;
  1893. return DRWAV_TRUE;
  1894. }
  1895. drwav_bool32 drwav_seek_to_sample(drwav* pWav, drwav_uint64 sample)
  1896. {
  1897. // Seeking should be compatible with wave files > 2GB.
  1898. if (pWav->onWrite != NULL) {
  1899. return DRWAV_FALSE; // No seeking in write mode.
  1900. }
  1901. if (pWav == NULL || pWav->onSeek == NULL) {
  1902. return DRWAV_FALSE;
  1903. }
  1904. // If there are no samples, just return DRWAV_TRUE without doing anything.
  1905. if (pWav->totalSampleCount == 0) {
  1906. return DRWAV_TRUE;
  1907. }
  1908. // Make sure the sample is clamped.
  1909. if (sample >= pWav->totalSampleCount) {
  1910. sample = pWav->totalSampleCount - 1;
  1911. }
  1912. // For compressed formats we just use a slow generic seek. If we are seeking forward we just seek forward. If we are going backwards we need
  1913. // to seek back to the start.
  1914. if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  1915. // TODO: This can be optimized.
  1916. // If we're seeking forward it's simple - just keep reading samples until we hit the sample we're requesting. If we're seeking backwards,
  1917. // we first need to seek back to the start and then just do the same thing as a forward seek.
  1918. if (sample < pWav->compressed.iCurrentSample) {
  1919. if (!drwav_seek_to_first_pcm_frame(pWav)) {
  1920. return DRWAV_FALSE;
  1921. }
  1922. }
  1923. if (sample > pWav->compressed.iCurrentSample) {
  1924. drwav_uint64 offset = sample - pWav->compressed.iCurrentSample;
  1925. drwav_int16 devnull[2048];
  1926. while (offset > 0) {
  1927. drwav_uint64 samplesToRead = offset;
  1928. if (samplesToRead > 2048) {
  1929. samplesToRead = 2048;
  1930. }
  1931. drwav_uint64 samplesRead = 0;
  1932. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  1933. samplesRead = drwav_read_s16__msadpcm(pWav, samplesToRead, devnull);
  1934. } else if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  1935. samplesRead = drwav_read_s16__ima(pWav, samplesToRead, devnull);
  1936. } else {
  1937. assert(DRWAV_FALSE); // If this assertion is triggered it means I've implemented a new compressed format but forgot to add a branch for it here.
  1938. }
  1939. if (samplesRead != samplesToRead) {
  1940. return DRWAV_FALSE;
  1941. }
  1942. offset -= samplesRead;
  1943. }
  1944. }
  1945. } else {
  1946. drwav_uint64 totalSizeInBytes = pWav->totalPCMFrameCount * drwav_get_bytes_per_pcm_frame(pWav);
  1947. drwav_assert(totalSizeInBytes >= pWav->bytesRemaining);
  1948. drwav_uint64 currentBytePos = totalSizeInBytes - pWav->bytesRemaining;
  1949. drwav_uint64 targetBytePos = sample * drwav_get_bytes_per_sample(pWav);
  1950. drwav_uint64 offset;
  1951. if (currentBytePos < targetBytePos) {
  1952. // Offset forwards.
  1953. offset = (targetBytePos - currentBytePos);
  1954. } else {
  1955. // Offset backwards.
  1956. if (!drwav_seek_to_first_pcm_frame(pWav)) {
  1957. return DRWAV_FALSE;
  1958. }
  1959. offset = targetBytePos;
  1960. }
  1961. while (offset > 0) {
  1962. int offset32 = ((offset > INT_MAX) ? INT_MAX : (int)offset);
  1963. if (!pWav->onSeek(pWav->pUserData, offset32, drwav_seek_origin_current)) {
  1964. return DRWAV_FALSE;
  1965. }
  1966. pWav->bytesRemaining -= offset32;
  1967. offset -= offset32;
  1968. }
  1969. }
  1970. return DRWAV_TRUE;
  1971. }
  1972. drwav_bool32 drwav_seek_to_pcm_frame(drwav* pWav, drwav_uint64 targetFrameIndex)
  1973. {
  1974. return drwav_seek_to_sample(pWav, targetFrameIndex * pWav->channels);
  1975. }
  1976. size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData)
  1977. {
  1978. if (pWav == NULL || bytesToWrite == 0 || pData == NULL) {
  1979. return 0;
  1980. }
  1981. size_t bytesWritten = pWav->onWrite(pWav->pUserData, pData, bytesToWrite);
  1982. pWav->dataChunkDataSize += bytesWritten;
  1983. return bytesWritten;
  1984. }
  1985. drwav_uint64 drwav_write(drwav* pWav, drwav_uint64 samplesToWrite, const void* pData)
  1986. {
  1987. if (pWav == NULL || samplesToWrite == 0 || pData == NULL) {
  1988. return 0;
  1989. }
  1990. drwav_uint64 bytesToWrite = ((samplesToWrite * pWav->bitsPerSample) / 8);
  1991. if (bytesToWrite > DRWAV_SIZE_MAX) {
  1992. return 0;
  1993. }
  1994. drwav_uint64 bytesWritten = 0;
  1995. const drwav_uint8* pRunningData = (const drwav_uint8*)pData;
  1996. while (bytesToWrite > 0) {
  1997. drwav_uint64 bytesToWriteThisIteration = bytesToWrite;
  1998. if (bytesToWriteThisIteration > DRWAV_SIZE_MAX) {
  1999. bytesToWriteThisIteration = DRWAV_SIZE_MAX;
  2000. }
  2001. size_t bytesJustWritten = drwav_write_raw(pWav, (size_t)bytesToWriteThisIteration, pRunningData);
  2002. if (bytesJustWritten == 0) {
  2003. break;
  2004. }
  2005. bytesToWrite -= bytesJustWritten;
  2006. bytesWritten += bytesJustWritten;
  2007. pRunningData += bytesJustWritten;
  2008. }
  2009. return (bytesWritten * 8) / pWav->bitsPerSample;
  2010. }
  2011. drwav_uint64 drwav_write_pcm_frames(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
  2012. {
  2013. return drwav_write(pWav, framesToWrite * pWav->channels, pData) / pWav->channels;
  2014. }
  2015. drwav_uint64 drwav_read_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut)
  2016. {
  2017. drwav_assert(pWav != NULL);
  2018. drwav_assert(samplesToRead > 0);
  2019. drwav_assert(pBufferOut != NULL);
  2020. // TODO: Lots of room for optimization here.
  2021. drwav_uint64 totalSamplesRead = 0;
  2022. while (samplesToRead > 0 && pWav->compressed.iCurrentSample < pWav->totalSampleCount) {
  2023. // If there are no cached samples we need to load a new block.
  2024. if (pWav->msadpcm.cachedSampleCount == 0 && pWav->msadpcm.bytesRemainingInBlock == 0) {
  2025. if (pWav->channels == 1) {
  2026. // Mono.
  2027. drwav_uint8 header[7];
  2028. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  2029. return totalSamplesRead;
  2030. }
  2031. pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  2032. pWav->msadpcm.predictor[0] = header[0];
  2033. pWav->msadpcm.delta[0] = drwav__bytes_to_s16(header + 1);
  2034. pWav->msadpcm.prevSamples[0][1] = (drwav_int32)drwav__bytes_to_s16(header + 3);
  2035. pWav->msadpcm.prevSamples[0][0] = (drwav_int32)drwav__bytes_to_s16(header + 5);
  2036. pWav->msadpcm.cachedSamples[2] = pWav->msadpcm.prevSamples[0][0];
  2037. pWav->msadpcm.cachedSamples[3] = pWav->msadpcm.prevSamples[0][1];
  2038. pWav->msadpcm.cachedSampleCount = 2;
  2039. } else {
  2040. // Stereo.
  2041. drwav_uint8 header[14];
  2042. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  2043. return totalSamplesRead;
  2044. }
  2045. pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  2046. pWav->msadpcm.predictor[0] = header[0];
  2047. pWav->msadpcm.predictor[1] = header[1];
  2048. pWav->msadpcm.delta[0] = drwav__bytes_to_s16(header + 2);
  2049. pWav->msadpcm.delta[1] = drwav__bytes_to_s16(header + 4);
  2050. pWav->msadpcm.prevSamples[0][1] = (drwav_int32)drwav__bytes_to_s16(header + 6);
  2051. pWav->msadpcm.prevSamples[1][1] = (drwav_int32)drwav__bytes_to_s16(header + 8);
  2052. pWav->msadpcm.prevSamples[0][0] = (drwav_int32)drwav__bytes_to_s16(header + 10);
  2053. pWav->msadpcm.prevSamples[1][0] = (drwav_int32)drwav__bytes_to_s16(header + 12);
  2054. pWav->msadpcm.cachedSamples[0] = pWav->msadpcm.prevSamples[0][0];
  2055. pWav->msadpcm.cachedSamples[1] = pWav->msadpcm.prevSamples[1][0];
  2056. pWav->msadpcm.cachedSamples[2] = pWav->msadpcm.prevSamples[0][1];
  2057. pWav->msadpcm.cachedSamples[3] = pWav->msadpcm.prevSamples[1][1];
  2058. pWav->msadpcm.cachedSampleCount = 4;
  2059. }
  2060. }
  2061. // Output anything that's cached.
  2062. while (samplesToRead > 0 && pWav->msadpcm.cachedSampleCount > 0 && pWav->compressed.iCurrentSample < pWav->totalSampleCount) {
  2063. pBufferOut[0] = (drwav_int16)pWav->msadpcm.cachedSamples[drwav_countof(pWav->msadpcm.cachedSamples) - pWav->msadpcm.cachedSampleCount];
  2064. pWav->msadpcm.cachedSampleCount -= 1;
  2065. pBufferOut += 1;
  2066. samplesToRead -= 1;
  2067. totalSamplesRead += 1;
  2068. pWav->compressed.iCurrentSample += 1;
  2069. }
  2070. if (samplesToRead == 0) {
  2071. return totalSamplesRead;
  2072. }
  2073. // If there's nothing left in the cache, just go ahead and load more. If there's nothing left to load in the current block we just continue to the next
  2074. // loop iteration which will trigger the loading of a new block.
  2075. if (pWav->msadpcm.cachedSampleCount == 0) {
  2076. if (pWav->msadpcm.bytesRemainingInBlock == 0) {
  2077. continue;
  2078. } else {
  2079. drwav_uint8 nibbles;
  2080. if (pWav->onRead(pWav->pUserData, &nibbles, 1) != 1) {
  2081. return totalSamplesRead;
  2082. }
  2083. pWav->msadpcm.bytesRemainingInBlock -= 1;
  2084. // TODO: Optimize away these if statements.
  2085. drwav_int32 nibble0 = ((nibbles & 0xF0) >> 4); if ((nibbles & 0x80)) { nibble0 |= 0xFFFFFFF0UL; }
  2086. drwav_int32 nibble1 = ((nibbles & 0x0F) >> 0); if ((nibbles & 0x08)) { nibble1 |= 0xFFFFFFF0UL; }
  2087. static drwav_int32 adaptationTable[] = {
  2088. 230, 230, 230, 230, 307, 409, 512, 614,
  2089. 768, 614, 512, 409, 307, 230, 230, 230
  2090. };
  2091. static drwav_int32 coeff1Table[] = { 256, 512, 0, 192, 240, 460, 392 };
  2092. static drwav_int32 coeff2Table[] = { 0, -256, 0, 64, 0, -208, -232 };
  2093. if (pWav->channels == 1) {
  2094. // Mono.
  2095. drwav_int32 newSample0;
  2096. newSample0 = ((pWav->msadpcm.prevSamples[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevSamples[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
  2097. newSample0 += nibble0 * pWav->msadpcm.delta[0];
  2098. newSample0 = drwav_clamp(newSample0, -32768, 32767);
  2099. pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8;
  2100. if (pWav->msadpcm.delta[0] < 16) {
  2101. pWav->msadpcm.delta[0] = 16;
  2102. }
  2103. pWav->msadpcm.prevSamples[0][0] = pWav->msadpcm.prevSamples[0][1];
  2104. pWav->msadpcm.prevSamples[0][1] = newSample0;
  2105. drwav_int32 newSample1;
  2106. newSample1 = ((pWav->msadpcm.prevSamples[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevSamples[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
  2107. newSample1 += nibble1 * pWav->msadpcm.delta[0];
  2108. newSample1 = drwav_clamp(newSample1, -32768, 32767);
  2109. pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[0]) >> 8;
  2110. if (pWav->msadpcm.delta[0] < 16) {
  2111. pWav->msadpcm.delta[0] = 16;
  2112. }
  2113. pWav->msadpcm.prevSamples[0][0] = pWav->msadpcm.prevSamples[0][1];
  2114. pWav->msadpcm.prevSamples[0][1] = newSample1;
  2115. pWav->msadpcm.cachedSamples[2] = newSample0;
  2116. pWav->msadpcm.cachedSamples[3] = newSample1;
  2117. pWav->msadpcm.cachedSampleCount = 2;
  2118. } else {
  2119. // Stereo.
  2120. // Left.
  2121. drwav_int32 newSample0;
  2122. newSample0 = ((pWav->msadpcm.prevSamples[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevSamples[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
  2123. newSample0 += nibble0 * pWav->msadpcm.delta[0];
  2124. newSample0 = drwav_clamp(newSample0, -32768, 32767);
  2125. pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8;
  2126. if (pWav->msadpcm.delta[0] < 16) {
  2127. pWav->msadpcm.delta[0] = 16;
  2128. }
  2129. pWav->msadpcm.prevSamples[0][0] = pWav->msadpcm.prevSamples[0][1];
  2130. pWav->msadpcm.prevSamples[0][1] = newSample0;
  2131. // Right.
  2132. drwav_int32 newSample1;
  2133. newSample1 = ((pWav->msadpcm.prevSamples[1][1] * coeff1Table[pWav->msadpcm.predictor[1]]) + (pWav->msadpcm.prevSamples[1][0] * coeff2Table[pWav->msadpcm.predictor[1]])) >> 8;
  2134. newSample1 += nibble1 * pWav->msadpcm.delta[1];
  2135. newSample1 = drwav_clamp(newSample1, -32768, 32767);
  2136. pWav->msadpcm.delta[1] = (adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[1]) >> 8;
  2137. if (pWav->msadpcm.delta[1] < 16) {
  2138. pWav->msadpcm.delta[1] = 16;
  2139. }
  2140. pWav->msadpcm.prevSamples[1][0] = pWav->msadpcm.prevSamples[1][1];
  2141. pWav->msadpcm.prevSamples[1][1] = newSample1;
  2142. pWav->msadpcm.cachedSamples[2] = newSample0;
  2143. pWav->msadpcm.cachedSamples[3] = newSample1;
  2144. pWav->msadpcm.cachedSampleCount = 2;
  2145. }
  2146. }
  2147. }
  2148. }
  2149. return totalSamplesRead;
  2150. }
  2151. drwav_uint64 drwav_read_s16__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut)
  2152. {
  2153. drwav_assert(pWav != NULL);
  2154. drwav_assert(samplesToRead > 0);
  2155. drwav_assert(pBufferOut != NULL);
  2156. // TODO: Lots of room for optimization here.
  2157. drwav_uint64 totalSamplesRead = 0;
  2158. while (samplesToRead > 0 && pWav->compressed.iCurrentSample < pWav->totalSampleCount) {
  2159. // If there are no cached samples we need to load a new block.
  2160. if (pWav->ima.cachedSampleCount == 0 && pWav->ima.bytesRemainingInBlock == 0) {
  2161. if (pWav->channels == 1) {
  2162. // Mono.
  2163. drwav_uint8 header[4];
  2164. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  2165. return totalSamplesRead;
  2166. }
  2167. pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  2168. pWav->ima.predictor[0] = drwav__bytes_to_s16(header + 0);
  2169. pWav->ima.stepIndex[0] = header[2];
  2170. pWav->ima.cachedSamples[drwav_countof(pWav->ima.cachedSamples) - 1] = pWav->ima.predictor[0];
  2171. pWav->ima.cachedSampleCount = 1;
  2172. } else {
  2173. // Stereo.
  2174. drwav_uint8 header[8];
  2175. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  2176. return totalSamplesRead;
  2177. }
  2178. pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  2179. pWav->ima.predictor[0] = drwav__bytes_to_s16(header + 0);
  2180. pWav->ima.stepIndex[0] = header[2];
  2181. pWav->ima.predictor[1] = drwav__bytes_to_s16(header + 4);
  2182. pWav->ima.stepIndex[1] = header[6];
  2183. pWav->ima.cachedSamples[drwav_countof(pWav->ima.cachedSamples) - 2] = pWav->ima.predictor[0];
  2184. pWav->ima.cachedSamples[drwav_countof(pWav->ima.cachedSamples) - 1] = pWav->ima.predictor[1];
  2185. pWav->ima.cachedSampleCount = 2;
  2186. }
  2187. }
  2188. // Output anything that's cached.
  2189. while (samplesToRead > 0 && pWav->ima.cachedSampleCount > 0 && pWav->compressed.iCurrentSample < pWav->totalSampleCount) {
  2190. pBufferOut[0] = (drwav_int16)pWav->ima.cachedSamples[drwav_countof(pWav->ima.cachedSamples) - pWav->ima.cachedSampleCount];
  2191. pWav->ima.cachedSampleCount -= 1;
  2192. pBufferOut += 1;
  2193. samplesToRead -= 1;
  2194. totalSamplesRead += 1;
  2195. pWav->compressed.iCurrentSample += 1;
  2196. }
  2197. if (samplesToRead == 0) {
  2198. return totalSamplesRead;
  2199. }
  2200. // If there's nothing left in the cache, just go ahead and load more. If there's nothing left to load in the current block we just continue to the next
  2201. // loop iteration which will trigger the loading of a new block.
  2202. if (pWav->ima.cachedSampleCount == 0) {
  2203. if (pWav->ima.bytesRemainingInBlock == 0) {
  2204. continue;
  2205. } else {
  2206. static drwav_int32 indexTable[16] = {
  2207. -1, -1, -1, -1, 2, 4, 6, 8,
  2208. -1, -1, -1, -1, 2, 4, 6, 8
  2209. };
  2210. static drwav_int32 stepTable[89] = {
  2211. 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
  2212. 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
  2213. 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
  2214. 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
  2215. 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
  2216. 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
  2217. 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
  2218. 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
  2219. 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
  2220. };
  2221. // From what I can tell with stereo streams, it looks like every 4 bytes (8 samples) is for one channel. So it goes 4 bytes for the
  2222. // left channel, 4 bytes for the right channel.
  2223. pWav->ima.cachedSampleCount = 8 * pWav->channels;
  2224. for (drwav_uint32 iChannel = 0; iChannel < pWav->channels; ++iChannel) {
  2225. drwav_uint8 nibbles[4];
  2226. if (pWav->onRead(pWav->pUserData, &nibbles, 4) != 4) {
  2227. return totalSamplesRead;
  2228. }
  2229. pWav->ima.bytesRemainingInBlock -= 4;
  2230. for (drwav_uint32 iByte = 0; iByte < 4; ++iByte) {
  2231. drwav_uint8 nibble0 = ((nibbles[iByte] & 0x0F) >> 0);
  2232. drwav_uint8 nibble1 = ((nibbles[iByte] & 0xF0) >> 4);
  2233. drwav_int32 step = stepTable[pWav->ima.stepIndex[iChannel]];
  2234. drwav_int32 predictor = pWav->ima.predictor[iChannel];
  2235. drwav_int32 diff = step >> 3;
  2236. if (nibble0 & 1) diff += step >> 2;
  2237. if (nibble0 & 2) diff += step >> 1;
  2238. if (nibble0 & 4) diff += step;
  2239. if (nibble0 & 8) diff = -diff;
  2240. predictor = drwav_clamp(predictor + diff, -32768, 32767);
  2241. pWav->ima.predictor[iChannel] = predictor;
  2242. pWav->ima.stepIndex[iChannel] = drwav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble0], 0, (drwav_int32)drwav_countof(stepTable)-1);
  2243. pWav->ima.cachedSamples[(drwav_countof(pWav->ima.cachedSamples) - pWav->ima.cachedSampleCount) + (iByte*2+0)*pWav->channels + iChannel] = predictor;
  2244. step = stepTable[pWav->ima.stepIndex[iChannel]];
  2245. predictor = pWav->ima.predictor[iChannel];
  2246. diff = step >> 3;
  2247. if (nibble1 & 1) diff += step >> 2;
  2248. if (nibble1 & 2) diff += step >> 1;
  2249. if (nibble1 & 4) diff += step;
  2250. if (nibble1 & 8) diff = -diff;
  2251. predictor = drwav_clamp(predictor + diff, -32768, 32767);
  2252. pWav->ima.predictor[iChannel] = predictor;
  2253. pWav->ima.stepIndex[iChannel] = drwav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble1], 0, (drwav_int32)drwav_countof(stepTable)-1);
  2254. pWav->ima.cachedSamples[(drwav_countof(pWav->ima.cachedSamples) - pWav->ima.cachedSampleCount) + (iByte*2+1)*pWav->channels + iChannel] = predictor;
  2255. }
  2256. }
  2257. }
  2258. }
  2259. }
  2260. return totalSamplesRead;
  2261. }
  2262. #ifndef DR_WAV_NO_CONVERSION_API
  2263. static unsigned short g_drwavAlawTable[256] = {
  2264. 0xEA80, 0xEB80, 0xE880, 0xE980, 0xEE80, 0xEF80, 0xEC80, 0xED80, 0xE280, 0xE380, 0xE080, 0xE180, 0xE680, 0xE780, 0xE480, 0xE580,
  2265. 0xF540, 0xF5C0, 0xF440, 0xF4C0, 0xF740, 0xF7C0, 0xF640, 0xF6C0, 0xF140, 0xF1C0, 0xF040, 0xF0C0, 0xF340, 0xF3C0, 0xF240, 0xF2C0,
  2266. 0xAA00, 0xAE00, 0xA200, 0xA600, 0xBA00, 0xBE00, 0xB200, 0xB600, 0x8A00, 0x8E00, 0x8200, 0x8600, 0x9A00, 0x9E00, 0x9200, 0x9600,
  2267. 0xD500, 0xD700, 0xD100, 0xD300, 0xDD00, 0xDF00, 0xD900, 0xDB00, 0xC500, 0xC700, 0xC100, 0xC300, 0xCD00, 0xCF00, 0xC900, 0xCB00,
  2268. 0xFEA8, 0xFEB8, 0xFE88, 0xFE98, 0xFEE8, 0xFEF8, 0xFEC8, 0xFED8, 0xFE28, 0xFE38, 0xFE08, 0xFE18, 0xFE68, 0xFE78, 0xFE48, 0xFE58,
  2269. 0xFFA8, 0xFFB8, 0xFF88, 0xFF98, 0xFFE8, 0xFFF8, 0xFFC8, 0xFFD8, 0xFF28, 0xFF38, 0xFF08, 0xFF18, 0xFF68, 0xFF78, 0xFF48, 0xFF58,
  2270. 0xFAA0, 0xFAE0, 0xFA20, 0xFA60, 0xFBA0, 0xFBE0, 0xFB20, 0xFB60, 0xF8A0, 0xF8E0, 0xF820, 0xF860, 0xF9A0, 0xF9E0, 0xF920, 0xF960,
  2271. 0xFD50, 0xFD70, 0xFD10, 0xFD30, 0xFDD0, 0xFDF0, 0xFD90, 0xFDB0, 0xFC50, 0xFC70, 0xFC10, 0xFC30, 0xFCD0, 0xFCF0, 0xFC90, 0xFCB0,
  2272. 0x1580, 0x1480, 0x1780, 0x1680, 0x1180, 0x1080, 0x1380, 0x1280, 0x1D80, 0x1C80, 0x1F80, 0x1E80, 0x1980, 0x1880, 0x1B80, 0x1A80,
  2273. 0x0AC0, 0x0A40, 0x0BC0, 0x0B40, 0x08C0, 0x0840, 0x09C0, 0x0940, 0x0EC0, 0x0E40, 0x0FC0, 0x0F40, 0x0CC0, 0x0C40, 0x0DC0, 0x0D40,
  2274. 0x5600, 0x5200, 0x5E00, 0x5A00, 0x4600, 0x4200, 0x4E00, 0x4A00, 0x7600, 0x7200, 0x7E00, 0x7A00, 0x6600, 0x6200, 0x6E00, 0x6A00,
  2275. 0x2B00, 0x2900, 0x2F00, 0x2D00, 0x2300, 0x2100, 0x2700, 0x2500, 0x3B00, 0x3900, 0x3F00, 0x3D00, 0x3300, 0x3100, 0x3700, 0x3500,
  2276. 0x0158, 0x0148, 0x0178, 0x0168, 0x0118, 0x0108, 0x0138, 0x0128, 0x01D8, 0x01C8, 0x01F8, 0x01E8, 0x0198, 0x0188, 0x01B8, 0x01A8,
  2277. 0x0058, 0x0048, 0x0078, 0x0068, 0x0018, 0x0008, 0x0038, 0x0028, 0x00D8, 0x00C8, 0x00F8, 0x00E8, 0x0098, 0x0088, 0x00B8, 0x00A8,
  2278. 0x0560, 0x0520, 0x05E0, 0x05A0, 0x0460, 0x0420, 0x04E0, 0x04A0, 0x0760, 0x0720, 0x07E0, 0x07A0, 0x0660, 0x0620, 0x06E0, 0x06A0,
  2279. 0x02B0, 0x0290, 0x02F0, 0x02D0, 0x0230, 0x0210, 0x0270, 0x0250, 0x03B0, 0x0390, 0x03F0, 0x03D0, 0x0330, 0x0310, 0x0370, 0x0350
  2280. };
  2281. static unsigned short g_drwavMulawTable[256] = {
  2282. 0x8284, 0x8684, 0x8A84, 0x8E84, 0x9284, 0x9684, 0x9A84, 0x9E84, 0xA284, 0xA684, 0xAA84, 0xAE84, 0xB284, 0xB684, 0xBA84, 0xBE84,
  2283. 0xC184, 0xC384, 0xC584, 0xC784, 0xC984, 0xCB84, 0xCD84, 0xCF84, 0xD184, 0xD384, 0xD584, 0xD784, 0xD984, 0xDB84, 0xDD84, 0xDF84,
  2284. 0xE104, 0xE204, 0xE304, 0xE404, 0xE504, 0xE604, 0xE704, 0xE804, 0xE904, 0xEA04, 0xEB04, 0xEC04, 0xED04, 0xEE04, 0xEF04, 0xF004,
  2285. 0xF0C4, 0xF144, 0xF1C4, 0xF244, 0xF2C4, 0xF344, 0xF3C4, 0xF444, 0xF4C4, 0xF544, 0xF5C4, 0xF644, 0xF6C4, 0xF744, 0xF7C4, 0xF844,
  2286. 0xF8A4, 0xF8E4, 0xF924, 0xF964, 0xF9A4, 0xF9E4, 0xFA24, 0xFA64, 0xFAA4, 0xFAE4, 0xFB24, 0xFB64, 0xFBA4, 0xFBE4, 0xFC24, 0xFC64,
  2287. 0xFC94, 0xFCB4, 0xFCD4, 0xFCF4, 0xFD14, 0xFD34, 0xFD54, 0xFD74, 0xFD94, 0xFDB4, 0xFDD4, 0xFDF4, 0xFE14, 0xFE34, 0xFE54, 0xFE74,
  2288. 0xFE8C, 0xFE9C, 0xFEAC, 0xFEBC, 0xFECC, 0xFEDC, 0xFEEC, 0xFEFC, 0xFF0C, 0xFF1C, 0xFF2C, 0xFF3C, 0xFF4C, 0xFF5C, 0xFF6C, 0xFF7C,
  2289. 0xFF88, 0xFF90, 0xFF98, 0xFFA0, 0xFFA8, 0xFFB0, 0xFFB8, 0xFFC0, 0xFFC8, 0xFFD0, 0xFFD8, 0xFFE0, 0xFFE8, 0xFFF0, 0xFFF8, 0x0000,
  2290. 0x7D7C, 0x797C, 0x757C, 0x717C, 0x6D7C, 0x697C, 0x657C, 0x617C, 0x5D7C, 0x597C, 0x557C, 0x517C, 0x4D7C, 0x497C, 0x457C, 0x417C,
  2291. 0x3E7C, 0x3C7C, 0x3A7C, 0x387C, 0x367C, 0x347C, 0x327C, 0x307C, 0x2E7C, 0x2C7C, 0x2A7C, 0x287C, 0x267C, 0x247C, 0x227C, 0x207C,
  2292. 0x1EFC, 0x1DFC, 0x1CFC, 0x1BFC, 0x1AFC, 0x19FC, 0x18FC, 0x17FC, 0x16FC, 0x15FC, 0x14FC, 0x13FC, 0x12FC, 0x11FC, 0x10FC, 0x0FFC,
  2293. 0x0F3C, 0x0EBC, 0x0E3C, 0x0DBC, 0x0D3C, 0x0CBC, 0x0C3C, 0x0BBC, 0x0B3C, 0x0ABC, 0x0A3C, 0x09BC, 0x093C, 0x08BC, 0x083C, 0x07BC,
  2294. 0x075C, 0x071C, 0x06DC, 0x069C, 0x065C, 0x061C, 0x05DC, 0x059C, 0x055C, 0x051C, 0x04DC, 0x049C, 0x045C, 0x041C, 0x03DC, 0x039C,
  2295. 0x036C, 0x034C, 0x032C, 0x030C, 0x02EC, 0x02CC, 0x02AC, 0x028C, 0x026C, 0x024C, 0x022C, 0x020C, 0x01EC, 0x01CC, 0x01AC, 0x018C,
  2296. 0x0174, 0x0164, 0x0154, 0x0144, 0x0134, 0x0124, 0x0114, 0x0104, 0x00F4, 0x00E4, 0x00D4, 0x00C4, 0x00B4, 0x00A4, 0x0094, 0x0084,
  2297. 0x0078, 0x0070, 0x0068, 0x0060, 0x0058, 0x0050, 0x0048, 0x0040, 0x0038, 0x0030, 0x0028, 0x0020, 0x0018, 0x0010, 0x0008, 0x0000
  2298. };
  2299. static DRWAV_INLINE drwav_int16 drwav__alaw_to_s16(drwav_uint8 sampleIn)
  2300. {
  2301. return (short)g_drwavAlawTable[sampleIn];
  2302. }
  2303. static DRWAV_INLINE drwav_int16 drwav__mulaw_to_s16(drwav_uint8 sampleIn)
  2304. {
  2305. return (short)g_drwavMulawTable[sampleIn];
  2306. }
  2307. static void drwav__pcm_to_s16(drwav_int16* pOut, const unsigned char* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  2308. {
  2309. // Special case for 8-bit sample data because it's treated as unsigned.
  2310. if (bytesPerSample == 1) {
  2311. drwav_u8_to_s16(pOut, pIn, totalSampleCount);
  2312. return;
  2313. }
  2314. // Slightly more optimal implementation for common formats.
  2315. if (bytesPerSample == 2) {
  2316. for (unsigned int i = 0; i < totalSampleCount; ++i) {
  2317. *pOut++ = ((const drwav_int16*)pIn)[i];
  2318. }
  2319. return;
  2320. }
  2321. if (bytesPerSample == 3) {
  2322. drwav_s24_to_s16(pOut, pIn, totalSampleCount);
  2323. return;
  2324. }
  2325. if (bytesPerSample == 4) {
  2326. drwav_s32_to_s16(pOut, (const drwav_int32*)pIn, totalSampleCount);
  2327. return;
  2328. }
  2329. // Anything more than 64 bits per sample is not supported.
  2330. if (bytesPerSample > 8) {
  2331. drwav_zero_memory(pOut, totalSampleCount * sizeof(*pOut));
  2332. return;
  2333. }
  2334. // Generic, slow converter.
  2335. for (unsigned int i = 0; i < totalSampleCount; ++i) {
  2336. drwav_uint64 sample = 0;
  2337. unsigned int shift = (8 - bytesPerSample) * 8;
  2338. unsigned int j;
  2339. for (j = 0; j < bytesPerSample && j < 8; j += 1) {
  2340. sample |= (drwav_uint64)(pIn[j]) << shift;
  2341. shift += 8;
  2342. }
  2343. pIn += j;
  2344. *pOut++ = (drwav_int16)((drwav_int64)sample >> 48);
  2345. }
  2346. }
  2347. static void drwav__ieee_to_s16(drwav_int16* pOut, const unsigned char* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  2348. {
  2349. if (bytesPerSample == 4) {
  2350. drwav_f32_to_s16(pOut, (const float*)pIn, totalSampleCount);
  2351. return;
  2352. } else if (bytesPerSample == 8) {
  2353. drwav_f64_to_s16(pOut, (const double*)pIn, totalSampleCount);
  2354. return;
  2355. } else {
  2356. // Only supporting 32- and 64-bit float. Output silence in all other cases. Contributions welcome for 16-bit float.
  2357. drwav_zero_memory(pOut, totalSampleCount * sizeof(*pOut));
  2358. return;
  2359. }
  2360. }
  2361. drwav_uint64 drwav_read_s16__pcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut)
  2362. {
  2363. drwav_uint32 bytesPerSample;
  2364. // Fast path.
  2365. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 16) {
  2366. return drwav_read(pWav, samplesToRead, pBufferOut);
  2367. }
  2368. bytesPerSample = drwav_get_bytes_per_sample(pWav);
  2369. if (bytesPerSample == 0) {
  2370. return 0;
  2371. }
  2372. drwav_uint64 totalSamplesRead = 0;
  2373. unsigned char sampleData[4096];
  2374. while (samplesToRead > 0) {
  2375. drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData);
  2376. if (samplesRead == 0) {
  2377. break;
  2378. }
  2379. drwav__pcm_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  2380. pBufferOut += samplesRead;
  2381. samplesToRead -= samplesRead;
  2382. totalSamplesRead += samplesRead;
  2383. }
  2384. return totalSamplesRead;
  2385. }
  2386. drwav_uint64 drwav_read_s16__ieee(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut)
  2387. {
  2388. drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav);
  2389. if (bytesPerSample == 0) {
  2390. return 0;
  2391. }
  2392. drwav_uint64 totalSamplesRead = 0;
  2393. unsigned char sampleData[4096];
  2394. while (samplesToRead > 0) {
  2395. drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData);
  2396. if (samplesRead == 0) {
  2397. break;
  2398. }
  2399. drwav__ieee_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  2400. pBufferOut += samplesRead;
  2401. samplesToRead -= samplesRead;
  2402. totalSamplesRead += samplesRead;
  2403. }
  2404. return totalSamplesRead;
  2405. }
  2406. drwav_uint64 drwav_read_s16__alaw(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut)
  2407. {
  2408. drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav);
  2409. if (bytesPerSample == 0) {
  2410. return 0;
  2411. }
  2412. drwav_uint64 totalSamplesRead = 0;
  2413. unsigned char sampleData[4096];
  2414. while (samplesToRead > 0) {
  2415. drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData);
  2416. if (samplesRead == 0) {
  2417. break;
  2418. }
  2419. drwav_alaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead);
  2420. pBufferOut += samplesRead;
  2421. samplesToRead -= samplesRead;
  2422. totalSamplesRead += samplesRead;
  2423. }
  2424. return totalSamplesRead;
  2425. }
  2426. drwav_uint64 drwav_read_s16__mulaw(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut)
  2427. {
  2428. drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav);
  2429. if (bytesPerSample == 0) {
  2430. return 0;
  2431. }
  2432. drwav_uint64 totalSamplesRead = 0;
  2433. unsigned char sampleData[4096];
  2434. while (samplesToRead > 0) {
  2435. drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData);
  2436. if (samplesRead == 0) {
  2437. break;
  2438. }
  2439. drwav_mulaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead);
  2440. pBufferOut += samplesRead;
  2441. samplesToRead -= samplesRead;
  2442. totalSamplesRead += samplesRead;
  2443. }
  2444. return totalSamplesRead;
  2445. }
  2446. drwav_uint64 drwav_read_s16(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut)
  2447. {
  2448. if (pWav == NULL || samplesToRead == 0 || pBufferOut == NULL) {
  2449. return 0;
  2450. }
  2451. // Don't try to read more samples than can potentially fit in the output buffer.
  2452. if (samplesToRead * sizeof(drwav_int16) > DRWAV_SIZE_MAX) {
  2453. samplesToRead = DRWAV_SIZE_MAX / sizeof(drwav_int16);
  2454. }
  2455. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) {
  2456. return drwav_read_s16__pcm(pWav, samplesToRead, pBufferOut);
  2457. }
  2458. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  2459. return drwav_read_s16__msadpcm(pWav, samplesToRead, pBufferOut);
  2460. }
  2461. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
  2462. return drwav_read_s16__ieee(pWav, samplesToRead, pBufferOut);
  2463. }
  2464. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW) {
  2465. return drwav_read_s16__alaw(pWav, samplesToRead, pBufferOut);
  2466. }
  2467. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
  2468. return drwav_read_s16__mulaw(pWav, samplesToRead, pBufferOut);
  2469. }
  2470. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  2471. return drwav_read_s16__ima(pWav, samplesToRead, pBufferOut);
  2472. }
  2473. return 0;
  2474. }
  2475. drwav_uint64 drwav_read_pcm_frames_s16(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  2476. {
  2477. return drwav_read_s16(pWav, framesToRead * pWav->channels, pBufferOut) / pWav->channels;
  2478. }
  2479. void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
  2480. {
  2481. int r;
  2482. for (size_t i = 0; i < sampleCount; ++i) {
  2483. int x = pIn[i];
  2484. r = x - 128;
  2485. r = r << 8;
  2486. pOut[i] = (short)r;
  2487. }
  2488. }
  2489. void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
  2490. {
  2491. int r;
  2492. for (size_t i = 0; i < sampleCount; ++i) {
  2493. int x = ((int)(((unsigned int)(((const unsigned char*)pIn)[i*3+0]) << 8) | ((unsigned int)(((const unsigned char*)pIn)[i*3+1]) << 16) | ((unsigned int)(((const unsigned char*)pIn)[i*3+2])) << 24)) >> 8;
  2494. r = x >> 8;
  2495. pOut[i] = (short)r;
  2496. }
  2497. }
  2498. void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCount)
  2499. {
  2500. int r;
  2501. for (size_t i = 0; i < sampleCount; ++i) {
  2502. int x = pIn[i];
  2503. r = x >> 16;
  2504. pOut[i] = (short)r;
  2505. }
  2506. }
  2507. void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount)
  2508. {
  2509. int r;
  2510. for (size_t i = 0; i < sampleCount; ++i) {
  2511. float x = pIn[i];
  2512. float c;
  2513. c = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
  2514. c = c + 1;
  2515. r = (int)(c * 32767.5f);
  2516. r = r - 32768;
  2517. pOut[i] = (short)r;
  2518. }
  2519. }
  2520. void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount)
  2521. {
  2522. int r;
  2523. for (size_t i = 0; i < sampleCount; ++i) {
  2524. double x = pIn[i];
  2525. double c;
  2526. c = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
  2527. c = c + 1;
  2528. r = (int)(c * 32767.5);
  2529. r = r - 32768;
  2530. pOut[i] = (short)r;
  2531. }
  2532. }
  2533. void drwav_alaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
  2534. {
  2535. for (size_t i = 0; i < sampleCount; ++i) {
  2536. pOut[i] = drwav__alaw_to_s16(pIn[i]);
  2537. }
  2538. }
  2539. void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
  2540. {
  2541. for (size_t i = 0; i < sampleCount; ++i) {
  2542. pOut[i] = drwav__mulaw_to_s16(pIn[i]);
  2543. }
  2544. }
  2545. static void drwav__pcm_to_f32(float* pOut, const unsigned char* pIn, size_t sampleCount, unsigned int bytesPerSample)
  2546. {
  2547. // Special case for 8-bit sample data because it's treated as unsigned.
  2548. if (bytesPerSample == 1) {
  2549. drwav_u8_to_f32(pOut, pIn, sampleCount);
  2550. return;
  2551. }
  2552. // Slightly more optimal implementation for common formats.
  2553. if (bytesPerSample == 2) {
  2554. drwav_s16_to_f32(pOut, (const drwav_int16*)pIn, sampleCount);
  2555. return;
  2556. }
  2557. if (bytesPerSample == 3) {
  2558. drwav_s24_to_f32(pOut, pIn, sampleCount);
  2559. return;
  2560. }
  2561. if (bytesPerSample == 4) {
  2562. drwav_s32_to_f32(pOut, (const drwav_int32*)pIn, sampleCount);
  2563. return;
  2564. }
  2565. // Anything more than 64 bits per sample is not supported.
  2566. if (bytesPerSample > 8) {
  2567. drwav_zero_memory(pOut, sampleCount * sizeof(*pOut));
  2568. return;
  2569. }
  2570. // Generic, slow converter.
  2571. for (unsigned int i = 0; i < sampleCount; ++i) {
  2572. drwav_uint64 sample = 0;
  2573. unsigned int shift = (8 - bytesPerSample) * 8;
  2574. unsigned int j;
  2575. for (j = 0; j < bytesPerSample && j < 8; j += 1) {
  2576. sample |= (drwav_uint64)(pIn[j]) << shift;
  2577. shift += 8;
  2578. }
  2579. pIn += j;
  2580. *pOut++ = (float)((drwav_int64)sample / 9223372036854775807.0);
  2581. }
  2582. }
  2583. static void drwav__ieee_to_f32(float* pOut, const unsigned char* pIn, size_t sampleCount, unsigned int bytesPerSample)
  2584. {
  2585. if (bytesPerSample == 4) {
  2586. for (unsigned int i = 0; i < sampleCount; ++i) {
  2587. *pOut++ = ((const float*)pIn)[i];
  2588. }
  2589. return;
  2590. } else if (bytesPerSample == 8) {
  2591. drwav_f64_to_f32(pOut, (const double*)pIn, sampleCount);
  2592. return;
  2593. } else {
  2594. // Only supporting 32- and 64-bit float. Output silence in all other cases. Contributions welcome for 16-bit float.
  2595. drwav_zero_memory(pOut, sampleCount * sizeof(*pOut));
  2596. return;
  2597. }
  2598. }
  2599. drwav_uint64 drwav_read_f32__pcm(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut)
  2600. {
  2601. drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav);
  2602. if (bytesPerSample == 0) {
  2603. return 0;
  2604. }
  2605. drwav_uint64 totalSamplesRead = 0;
  2606. unsigned char sampleData[4096];
  2607. while (samplesToRead > 0) {
  2608. drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData);
  2609. if (samplesRead == 0) {
  2610. break;
  2611. }
  2612. drwav__pcm_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  2613. pBufferOut += samplesRead;
  2614. samplesToRead -= samplesRead;
  2615. totalSamplesRead += samplesRead;
  2616. }
  2617. return totalSamplesRead;
  2618. }
  2619. drwav_uint64 drwav_read_f32__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut)
  2620. {
  2621. // We're just going to borrow the implementation from the drwav_read_s16() since ADPCM is a little bit more complicated than other formats and I don't
  2622. // want to duplicate that code.
  2623. drwav_uint64 totalSamplesRead = 0;
  2624. drwav_int16 samples16[2048];
  2625. while (samplesToRead > 0) {
  2626. drwav_uint64 samplesRead = drwav_read_s16(pWav, drwav_min(samplesToRead, 2048), samples16);
  2627. if (samplesRead == 0) {
  2628. break;
  2629. }
  2630. drwav_s16_to_f32(pBufferOut, samples16, (size_t)samplesRead); // <-- Safe cast because we're clamping to 2048.
  2631. pBufferOut += samplesRead;
  2632. samplesToRead -= samplesRead;
  2633. totalSamplesRead += samplesRead;
  2634. }
  2635. return totalSamplesRead;
  2636. }
  2637. drwav_uint64 drwav_read_f32__ima(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut)
  2638. {
  2639. // We're just going to borrow the implementation from the drwav_read_s16() since IMA-ADPCM is a little bit more complicated than other formats and I don't
  2640. // want to duplicate that code.
  2641. drwav_uint64 totalSamplesRead = 0;
  2642. drwav_int16 samples16[2048];
  2643. while (samplesToRead > 0) {
  2644. drwav_uint64 samplesRead = drwav_read_s16(pWav, drwav_min(samplesToRead, 2048), samples16);
  2645. if (samplesRead == 0) {
  2646. break;
  2647. }
  2648. drwav_s16_to_f32(pBufferOut, samples16, (size_t)samplesRead); // <-- Safe cast because we're clamping to 2048.
  2649. pBufferOut += samplesRead;
  2650. samplesToRead -= samplesRead;
  2651. totalSamplesRead += samplesRead;
  2652. }
  2653. return totalSamplesRead;
  2654. }
  2655. drwav_uint64 drwav_read_f32__ieee(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut)
  2656. {
  2657. drwav_uint32 bytesPerSample;
  2658. // Fast path.
  2659. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT && pWav->bitsPerSample == 32) {
  2660. return drwav_read(pWav, samplesToRead, pBufferOut);
  2661. }
  2662. bytesPerSample = drwav_get_bytes_per_sample(pWav);
  2663. if (bytesPerSample == 0) {
  2664. return 0;
  2665. }
  2666. drwav_uint64 totalSamplesRead = 0;
  2667. unsigned char sampleData[4096];
  2668. while (samplesToRead > 0) {
  2669. drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData);
  2670. if (samplesRead == 0) {
  2671. break;
  2672. }
  2673. drwav__ieee_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  2674. pBufferOut += samplesRead;
  2675. samplesToRead -= samplesRead;
  2676. totalSamplesRead += samplesRead;
  2677. }
  2678. return totalSamplesRead;
  2679. }
  2680. drwav_uint64 drwav_read_f32__alaw(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut)
  2681. {
  2682. drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav);
  2683. if (bytesPerSample == 0) {
  2684. return 0;
  2685. }
  2686. drwav_uint64 totalSamplesRead = 0;
  2687. unsigned char sampleData[4096];
  2688. while (samplesToRead > 0) {
  2689. drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData);
  2690. if (samplesRead == 0) {
  2691. break;
  2692. }
  2693. drwav_alaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead);
  2694. pBufferOut += samplesRead;
  2695. samplesToRead -= samplesRead;
  2696. totalSamplesRead += samplesRead;
  2697. }
  2698. return totalSamplesRead;
  2699. }
  2700. drwav_uint64 drwav_read_f32__mulaw(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut)
  2701. {
  2702. drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav);
  2703. if (bytesPerSample == 0) {
  2704. return 0;
  2705. }
  2706. drwav_uint64 totalSamplesRead = 0;
  2707. unsigned char sampleData[4096];
  2708. while (samplesToRead > 0) {
  2709. drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData);
  2710. if (samplesRead == 0) {
  2711. break;
  2712. }
  2713. drwav_mulaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead);
  2714. pBufferOut += samplesRead;
  2715. samplesToRead -= samplesRead;
  2716. totalSamplesRead += samplesRead;
  2717. }
  2718. return totalSamplesRead;
  2719. }
  2720. drwav_uint64 drwav_read_f32(drwav* pWav, drwav_uint64 samplesToRead, float* pBufferOut)
  2721. {
  2722. if (pWav == NULL || samplesToRead == 0 || pBufferOut == NULL) {
  2723. return 0;
  2724. }
  2725. // Don't try to read more samples than can potentially fit in the output buffer.
  2726. if (samplesToRead * sizeof(float) > DRWAV_SIZE_MAX) {
  2727. samplesToRead = DRWAV_SIZE_MAX / sizeof(float);
  2728. }
  2729. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) {
  2730. return drwav_read_f32__pcm(pWav, samplesToRead, pBufferOut);
  2731. }
  2732. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  2733. return drwav_read_f32__msadpcm(pWav, samplesToRead, pBufferOut);
  2734. }
  2735. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
  2736. return drwav_read_f32__ieee(pWav, samplesToRead, pBufferOut);
  2737. }
  2738. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW) {
  2739. return drwav_read_f32__alaw(pWav, samplesToRead, pBufferOut);
  2740. }
  2741. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
  2742. return drwav_read_f32__mulaw(pWav, samplesToRead, pBufferOut);
  2743. }
  2744. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  2745. return drwav_read_f32__ima(pWav, samplesToRead, pBufferOut);
  2746. }
  2747. return 0;
  2748. }
  2749. drwav_uint64 drwav_read_pcm_frames_f32(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  2750. {
  2751. return drwav_read_f32(pWav, framesToRead * pWav->channels, pBufferOut) / pWav->channels;
  2752. }
  2753. void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
  2754. {
  2755. if (pOut == NULL || pIn == NULL) {
  2756. return;
  2757. }
  2758. #ifdef DR_WAV_LIBSNDFILE_COMPAT
  2759. // It appears libsndfile uses slightly different logic for the u8 -> f32 conversion to dr_wav, which in my opinion is incorrect. It appears
  2760. // libsndfile performs the conversion something like "f32 = (u8 / 256) * 2 - 1", however I think it should be "f32 = (u8 / 255) * 2 - 1" (note
  2761. // the divisor of 256 vs 255). I use libsndfile as a benchmark for testing, so I'm therefore leaving this block here just for my automated
  2762. // correctness testing. This is disabled by default.
  2763. for (size_t i = 0; i < sampleCount; ++i) {
  2764. *pOut++ = (pIn[i] / 256.0f) * 2 - 1;
  2765. }
  2766. #else
  2767. for (size_t i = 0; i < sampleCount; ++i) {
  2768. *pOut++ = (pIn[i] / 255.0f) * 2 - 1;
  2769. }
  2770. #endif
  2771. }
  2772. void drwav_s16_to_f32(float* pOut, const drwav_int16* pIn, size_t sampleCount)
  2773. {
  2774. if (pOut == NULL || pIn == NULL) {
  2775. return;
  2776. }
  2777. for (size_t i = 0; i < sampleCount; ++i) {
  2778. *pOut++ = pIn[i] / 32768.0f;
  2779. }
  2780. }
  2781. void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
  2782. {
  2783. if (pOut == NULL || pIn == NULL) {
  2784. return;
  2785. }
  2786. for (size_t i = 0; i < sampleCount; ++i) {
  2787. unsigned int s0 = pIn[i*3 + 0];
  2788. unsigned int s1 = pIn[i*3 + 1];
  2789. unsigned int s2 = pIn[i*3 + 2];
  2790. int sample32 = (int)((s0 << 8) | (s1 << 16) | (s2 << 24));
  2791. *pOut++ = (float)(sample32 / 2147483648.0);
  2792. }
  2793. }
  2794. void drwav_s32_to_f32(float* pOut, const drwav_int32* pIn, size_t sampleCount)
  2795. {
  2796. if (pOut == NULL || pIn == NULL) {
  2797. return;
  2798. }
  2799. for (size_t i = 0; i < sampleCount; ++i) {
  2800. *pOut++ = (float)(pIn[i] / 2147483648.0);
  2801. }
  2802. }
  2803. void drwav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount)
  2804. {
  2805. if (pOut == NULL || pIn == NULL) {
  2806. return;
  2807. }
  2808. for (size_t i = 0; i < sampleCount; ++i) {
  2809. *pOut++ = (float)pIn[i];
  2810. }
  2811. }
  2812. void drwav_alaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
  2813. {
  2814. if (pOut == NULL || pIn == NULL) {
  2815. return;
  2816. }
  2817. for (size_t i = 0; i < sampleCount; ++i) {
  2818. *pOut++ = drwav__alaw_to_s16(pIn[i]) / 32768.0f;
  2819. }
  2820. }
  2821. void drwav_mulaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
  2822. {
  2823. if (pOut == NULL || pIn == NULL) {
  2824. return;
  2825. }
  2826. for (size_t i = 0; i < sampleCount; ++i) {
  2827. *pOut++ = drwav__mulaw_to_s16(pIn[i]) / 32768.0f;
  2828. }
  2829. }
  2830. static void drwav__pcm_to_s32(drwav_int32* pOut, const unsigned char* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  2831. {
  2832. // Special case for 8-bit sample data because it's treated as unsigned.
  2833. if (bytesPerSample == 1) {
  2834. drwav_u8_to_s32(pOut, pIn, totalSampleCount);
  2835. return;
  2836. }
  2837. // Slightly more optimal implementation for common formats.
  2838. if (bytesPerSample == 2) {
  2839. drwav_s16_to_s32(pOut, (const drwav_int16*)pIn, totalSampleCount);
  2840. return;
  2841. }
  2842. if (bytesPerSample == 3) {
  2843. drwav_s24_to_s32(pOut, pIn, totalSampleCount);
  2844. return;
  2845. }
  2846. if (bytesPerSample == 4) {
  2847. for (unsigned int i = 0; i < totalSampleCount; ++i) {
  2848. *pOut++ = ((const drwav_int32*)pIn)[i];
  2849. }
  2850. return;
  2851. }
  2852. // Anything more than 64 bits per sample is not supported.
  2853. if (bytesPerSample > 8) {
  2854. drwav_zero_memory(pOut, totalSampleCount * sizeof(*pOut));
  2855. return;
  2856. }
  2857. // Generic, slow converter.
  2858. for (unsigned int i = 0; i < totalSampleCount; ++i) {
  2859. drwav_uint64 sample = 0;
  2860. unsigned int shift = (8 - bytesPerSample) * 8;
  2861. unsigned int j;
  2862. for (j = 0; j < bytesPerSample && j < 8; j += 1) {
  2863. sample |= (drwav_uint64)(pIn[j]) << shift;
  2864. shift += 8;
  2865. }
  2866. pIn += j;
  2867. *pOut++ = (drwav_int32)((drwav_int64)sample >> 32);
  2868. }
  2869. }
  2870. static void drwav__ieee_to_s32(drwav_int32* pOut, const unsigned char* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  2871. {
  2872. if (bytesPerSample == 4) {
  2873. drwav_f32_to_s32(pOut, (const float*)pIn, totalSampleCount);
  2874. return;
  2875. } else if (bytesPerSample == 8) {
  2876. drwav_f64_to_s32(pOut, (const double*)pIn, totalSampleCount);
  2877. return;
  2878. } else {
  2879. // Only supporting 32- and 64-bit float. Output silence in all other cases. Contributions welcome for 16-bit float.
  2880. drwav_zero_memory(pOut, totalSampleCount * sizeof(*pOut));
  2881. return;
  2882. }
  2883. }
  2884. drwav_uint64 drwav_read_s32__pcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut)
  2885. {
  2886. drwav_uint32 bytesPerSample;
  2887. // Fast path.
  2888. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 32) {
  2889. return drwav_read(pWav, samplesToRead, pBufferOut);
  2890. }
  2891. bytesPerSample = drwav_get_bytes_per_sample(pWav);
  2892. if (bytesPerSample == 0) {
  2893. return 0;
  2894. }
  2895. drwav_uint64 totalSamplesRead = 0;
  2896. unsigned char sampleData[4096];
  2897. while (samplesToRead > 0) {
  2898. drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData);
  2899. if (samplesRead == 0) {
  2900. break;
  2901. }
  2902. drwav__pcm_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  2903. pBufferOut += samplesRead;
  2904. samplesToRead -= samplesRead;
  2905. totalSamplesRead += samplesRead;
  2906. }
  2907. return totalSamplesRead;
  2908. }
  2909. drwav_uint64 drwav_read_s32__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut)
  2910. {
  2911. // We're just going to borrow the implementation from the drwav_read_s16() since ADPCM is a little bit more complicated than other formats and I don't
  2912. // want to duplicate that code.
  2913. drwav_uint64 totalSamplesRead = 0;
  2914. drwav_int16 samples16[2048];
  2915. while (samplesToRead > 0) {
  2916. drwav_uint64 samplesRead = drwav_read_s16(pWav, drwav_min(samplesToRead, 2048), samples16);
  2917. if (samplesRead == 0) {
  2918. break;
  2919. }
  2920. drwav_s16_to_s32(pBufferOut, samples16, (size_t)samplesRead); // <-- Safe cast because we're clamping to 2048.
  2921. pBufferOut += samplesRead;
  2922. samplesToRead -= samplesRead;
  2923. totalSamplesRead += samplesRead;
  2924. }
  2925. return totalSamplesRead;
  2926. }
  2927. drwav_uint64 drwav_read_s32__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut)
  2928. {
  2929. // We're just going to borrow the implementation from the drwav_read_s16() since IMA-ADPCM is a little bit more complicated than other formats and I don't
  2930. // want to duplicate that code.
  2931. drwav_uint64 totalSamplesRead = 0;
  2932. drwav_int16 samples16[2048];
  2933. while (samplesToRead > 0) {
  2934. drwav_uint64 samplesRead = drwav_read_s16(pWav, drwav_min(samplesToRead, 2048), samples16);
  2935. if (samplesRead == 0) {
  2936. break;
  2937. }
  2938. drwav_s16_to_s32(pBufferOut, samples16, (size_t)samplesRead); // <-- Safe cast because we're clamping to 2048.
  2939. pBufferOut += samplesRead;
  2940. samplesToRead -= samplesRead;
  2941. totalSamplesRead += samplesRead;
  2942. }
  2943. return totalSamplesRead;
  2944. }
  2945. drwav_uint64 drwav_read_s32__ieee(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut)
  2946. {
  2947. drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav);
  2948. if (bytesPerSample == 0) {
  2949. return 0;
  2950. }
  2951. drwav_uint64 totalSamplesRead = 0;
  2952. unsigned char sampleData[4096];
  2953. while (samplesToRead > 0) {
  2954. drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData);
  2955. if (samplesRead == 0) {
  2956. break;
  2957. }
  2958. drwav__ieee_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  2959. pBufferOut += samplesRead;
  2960. samplesToRead -= samplesRead;
  2961. totalSamplesRead += samplesRead;
  2962. }
  2963. return totalSamplesRead;
  2964. }
  2965. drwav_uint64 drwav_read_s32__alaw(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut)
  2966. {
  2967. drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav);
  2968. if (bytesPerSample == 0) {
  2969. return 0;
  2970. }
  2971. drwav_uint64 totalSamplesRead = 0;
  2972. unsigned char sampleData[4096];
  2973. while (samplesToRead > 0) {
  2974. drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData);
  2975. if (samplesRead == 0) {
  2976. break;
  2977. }
  2978. drwav_alaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead);
  2979. pBufferOut += samplesRead;
  2980. samplesToRead -= samplesRead;
  2981. totalSamplesRead += samplesRead;
  2982. }
  2983. return totalSamplesRead;
  2984. }
  2985. drwav_uint64 drwav_read_s32__mulaw(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut)
  2986. {
  2987. drwav_uint32 bytesPerSample = drwav_get_bytes_per_sample(pWav);
  2988. if (bytesPerSample == 0) {
  2989. return 0;
  2990. }
  2991. drwav_uint64 totalSamplesRead = 0;
  2992. unsigned char sampleData[4096];
  2993. while (samplesToRead > 0) {
  2994. drwav_uint64 samplesRead = drwav_read(pWav, drwav_min(samplesToRead, sizeof(sampleData)/bytesPerSample), sampleData);
  2995. if (samplesRead == 0) {
  2996. break;
  2997. }
  2998. drwav_mulaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead);
  2999. pBufferOut += samplesRead;
  3000. samplesToRead -= samplesRead;
  3001. totalSamplesRead += samplesRead;
  3002. }
  3003. return totalSamplesRead;
  3004. }
  3005. drwav_uint64 drwav_read_s32(drwav* pWav, drwav_uint64 samplesToRead, drwav_int32* pBufferOut)
  3006. {
  3007. if (pWav == NULL || samplesToRead == 0 || pBufferOut == NULL) {
  3008. return 0;
  3009. }
  3010. // Don't try to read more samples than can potentially fit in the output buffer.
  3011. if (samplesToRead * sizeof(drwav_int32) > DRWAV_SIZE_MAX) {
  3012. samplesToRead = DRWAV_SIZE_MAX / sizeof(drwav_int32);
  3013. }
  3014. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) {
  3015. return drwav_read_s32__pcm(pWav, samplesToRead, pBufferOut);
  3016. }
  3017. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  3018. return drwav_read_s32__msadpcm(pWav, samplesToRead, pBufferOut);
  3019. }
  3020. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
  3021. return drwav_read_s32__ieee(pWav, samplesToRead, pBufferOut);
  3022. }
  3023. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW) {
  3024. return drwav_read_s32__alaw(pWav, samplesToRead, pBufferOut);
  3025. }
  3026. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
  3027. return drwav_read_s32__mulaw(pWav, samplesToRead, pBufferOut);
  3028. }
  3029. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  3030. return drwav_read_s32__ima(pWav, samplesToRead, pBufferOut);
  3031. }
  3032. return 0;
  3033. }
  3034. drwav_uint64 drwav_read_pcm_frames_s32(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  3035. {
  3036. return drwav_read_s32(pWav, framesToRead * pWav->channels, pBufferOut) / pWav->channels;
  3037. }
  3038. void drwav_u8_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
  3039. {
  3040. if (pOut == NULL || pIn == NULL) {
  3041. return;
  3042. }
  3043. for (size_t i = 0; i < sampleCount; ++i) {
  3044. *pOut++ = ((int)pIn[i] - 128) << 24;
  3045. }
  3046. }
  3047. void drwav_s16_to_s32(drwav_int32* pOut, const drwav_int16* pIn, size_t sampleCount)
  3048. {
  3049. if (pOut == NULL || pIn == NULL) {
  3050. return;
  3051. }
  3052. for (size_t i = 0; i < sampleCount; ++i) {
  3053. *pOut++ = pIn[i] << 16;
  3054. }
  3055. }
  3056. void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
  3057. {
  3058. if (pOut == NULL || pIn == NULL) {
  3059. return;
  3060. }
  3061. for (size_t i = 0; i < sampleCount; ++i) {
  3062. unsigned int s0 = pIn[i*3 + 0];
  3063. unsigned int s1 = pIn[i*3 + 1];
  3064. unsigned int s2 = pIn[i*3 + 2];
  3065. drwav_int32 sample32 = (drwav_int32)((s0 << 8) | (s1 << 16) | (s2 << 24));
  3066. *pOut++ = sample32;
  3067. }
  3068. }
  3069. void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t sampleCount)
  3070. {
  3071. if (pOut == NULL || pIn == NULL) {
  3072. return;
  3073. }
  3074. for (size_t i = 0; i < sampleCount; ++i) {
  3075. *pOut++ = (drwav_int32)(2147483648.0 * pIn[i]);
  3076. }
  3077. }
  3078. void drwav_f64_to_s32(drwav_int32* pOut, const double* pIn, size_t sampleCount)
  3079. {
  3080. if (pOut == NULL || pIn == NULL) {
  3081. return;
  3082. }
  3083. for (size_t i = 0; i < sampleCount; ++i) {
  3084. *pOut++ = (drwav_int32)(2147483648.0 * pIn[i]);
  3085. }
  3086. }
  3087. void drwav_alaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
  3088. {
  3089. if (pOut == NULL || pIn == NULL) {
  3090. return;
  3091. }
  3092. for (size_t i = 0; i < sampleCount; ++i) {
  3093. *pOut++ = ((drwav_int32)drwav__alaw_to_s16(pIn[i])) << 16;
  3094. }
  3095. }
  3096. void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
  3097. {
  3098. if (pOut == NULL || pIn == NULL) {
  3099. return;
  3100. }
  3101. for (size_t i= 0; i < sampleCount; ++i) {
  3102. *pOut++ = ((drwav_int32)drwav__mulaw_to_s16(pIn[i])) << 16;
  3103. }
  3104. }
  3105. drwav_int16* drwav__read_and_close_s16(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount)
  3106. {
  3107. drwav_assert(pWav != NULL);
  3108. drwav_uint64 sampleDataSize = pWav->totalSampleCount * sizeof(drwav_int16);
  3109. if (sampleDataSize > DRWAV_SIZE_MAX) {
  3110. drwav_uninit(pWav);
  3111. return NULL; // File's too big.
  3112. }
  3113. drwav_int16* pSampleData = (drwav_int16*)DRWAV_MALLOC((size_t)sampleDataSize); // <-- Safe cast due to the check above.
  3114. if (pSampleData == NULL) {
  3115. drwav_uninit(pWav);
  3116. return NULL; // Failed to allocate memory.
  3117. }
  3118. drwav_uint64 samplesRead = drwav_read_s16(pWav, (size_t)pWav->totalSampleCount, pSampleData);
  3119. if (samplesRead != pWav->totalSampleCount) {
  3120. DRWAV_FREE(pSampleData);
  3121. drwav_uninit(pWav);
  3122. return NULL; // There was an error reading the samples.
  3123. }
  3124. drwav_uninit(pWav);
  3125. if (sampleRate) *sampleRate = pWav->sampleRate;
  3126. if (channels) *channels = pWav->channels;
  3127. if (totalSampleCount) *totalSampleCount = pWav->totalSampleCount;
  3128. return pSampleData;
  3129. }
  3130. float* drwav__read_and_close_f32(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount)
  3131. {
  3132. drwav_assert(pWav != NULL);
  3133. drwav_uint64 sampleDataSize = pWav->totalSampleCount * sizeof(float);
  3134. if (sampleDataSize > DRWAV_SIZE_MAX) {
  3135. drwav_uninit(pWav);
  3136. return NULL; // File's too big.
  3137. }
  3138. float* pSampleData = (float*)DRWAV_MALLOC((size_t)sampleDataSize); // <-- Safe cast due to the check above.
  3139. if (pSampleData == NULL) {
  3140. drwav_uninit(pWav);
  3141. return NULL; // Failed to allocate memory.
  3142. }
  3143. drwav_uint64 samplesRead = drwav_read_f32(pWav, (size_t)pWav->totalSampleCount, pSampleData);
  3144. if (samplesRead != pWav->totalSampleCount) {
  3145. DRWAV_FREE(pSampleData);
  3146. drwav_uninit(pWav);
  3147. return NULL; // There was an error reading the samples.
  3148. }
  3149. drwav_uninit(pWav);
  3150. if (sampleRate) *sampleRate = pWav->sampleRate;
  3151. if (channels) *channels = pWav->channels;
  3152. if (totalSampleCount) *totalSampleCount = pWav->totalSampleCount;
  3153. return pSampleData;
  3154. }
  3155. drwav_int32* drwav__read_and_close_s32(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount)
  3156. {
  3157. drwav_assert(pWav != NULL);
  3158. drwav_uint64 sampleDataSize = pWav->totalSampleCount * sizeof(drwav_int32);
  3159. if (sampleDataSize > DRWAV_SIZE_MAX) {
  3160. drwav_uninit(pWav);
  3161. return NULL; // File's too big.
  3162. }
  3163. drwav_int32* pSampleData = (drwav_int32*)DRWAV_MALLOC((size_t)sampleDataSize); // <-- Safe cast due to the check above.
  3164. if (pSampleData == NULL) {
  3165. drwav_uninit(pWav);
  3166. return NULL; // Failed to allocate memory.
  3167. }
  3168. drwav_uint64 samplesRead = drwav_read_s32(pWav, (size_t)pWav->totalSampleCount, pSampleData);
  3169. if (samplesRead != pWav->totalSampleCount) {
  3170. DRWAV_FREE(pSampleData);
  3171. drwav_uninit(pWav);
  3172. return NULL; // There was an error reading the samples.
  3173. }
  3174. drwav_uninit(pWav);
  3175. if (sampleRate) *sampleRate = pWav->sampleRate;
  3176. if (channels) *channels = pWav->channels;
  3177. if (totalSampleCount) *totalSampleCount = pWav->totalSampleCount;
  3178. return pSampleData;
  3179. }
  3180. drwav_int16* drwav_open_and_read_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount)
  3181. {
  3182. if (channels) *channels = 0;
  3183. if (sampleRate) *sampleRate = 0;
  3184. if (totalSampleCount) *totalSampleCount = 0;
  3185. drwav wav;
  3186. if (!drwav_init(&wav, onRead, onSeek, pUserData)) {
  3187. return NULL;
  3188. }
  3189. return drwav__read_and_close_s16(&wav, channels, sampleRate, totalSampleCount);
  3190. }
  3191. drwav_int16* drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut)
  3192. {
  3193. if (channelsOut) *channelsOut = 0;
  3194. if (sampleRateOut) *sampleRateOut = 0;
  3195. if (totalFrameCountOut) *totalFrameCountOut = 0;
  3196. unsigned int channels;
  3197. unsigned int sampleRate;
  3198. drwav_uint64 totalSampleCount;
  3199. drwav_int16* result = drwav_open_and_read_s16(onRead, onSeek, pUserData, &channels, &sampleRate, &totalSampleCount);
  3200. if (result == NULL) {
  3201. return NULL;
  3202. }
  3203. if (channelsOut) *channelsOut = channels;
  3204. if (sampleRateOut) *sampleRateOut = sampleRate;
  3205. if (totalFrameCountOut) *totalFrameCountOut = totalSampleCount / channels;
  3206. return result;
  3207. }
  3208. float* drwav_open_and_read_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount)
  3209. {
  3210. if (sampleRate) *sampleRate = 0;
  3211. if (channels) *channels = 0;
  3212. if (totalSampleCount) *totalSampleCount = 0;
  3213. drwav wav;
  3214. if (!drwav_init(&wav, onRead, onSeek, pUserData)) {
  3215. return NULL;
  3216. }
  3217. return drwav__read_and_close_f32(&wav, channels, sampleRate, totalSampleCount);
  3218. }
  3219. float* drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut)
  3220. {
  3221. if (channelsOut) *channelsOut = 0;
  3222. if (sampleRateOut) *sampleRateOut = 0;
  3223. if (totalFrameCountOut) *totalFrameCountOut = 0;
  3224. unsigned int channels;
  3225. unsigned int sampleRate;
  3226. drwav_uint64 totalSampleCount;
  3227. float* result = drwav_open_and_read_f32(onRead, onSeek, pUserData, &channels, &sampleRate, &totalSampleCount);
  3228. if (result == NULL) {
  3229. return NULL;
  3230. }
  3231. if (channelsOut) *channelsOut = channels;
  3232. if (sampleRateOut) *sampleRateOut = sampleRate;
  3233. if (totalFrameCountOut) *totalFrameCountOut = totalSampleCount / channels;
  3234. return result;
  3235. }
  3236. drwav_int32* drwav_open_and_read_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount)
  3237. {
  3238. if (sampleRate) *sampleRate = 0;
  3239. if (channels) *channels = 0;
  3240. if (totalSampleCount) *totalSampleCount = 0;
  3241. drwav wav;
  3242. if (!drwav_init(&wav, onRead, onSeek, pUserData)) {
  3243. return NULL;
  3244. }
  3245. return drwav__read_and_close_s32(&wav, channels, sampleRate, totalSampleCount);
  3246. }
  3247. drwav_int32* drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut)
  3248. {
  3249. if (channelsOut) *channelsOut = 0;
  3250. if (sampleRateOut) *sampleRateOut = 0;
  3251. if (totalFrameCountOut) *totalFrameCountOut = 0;
  3252. unsigned int channels;
  3253. unsigned int sampleRate;
  3254. drwav_uint64 totalSampleCount;
  3255. drwav_int32* result = drwav_open_and_read_s32(onRead, onSeek, pUserData, &channels, &sampleRate, &totalSampleCount);
  3256. if (result == NULL) {
  3257. return NULL;
  3258. }
  3259. if (channelsOut) *channelsOut = channels;
  3260. if (sampleRateOut) *sampleRateOut = sampleRate;
  3261. if (totalFrameCountOut) *totalFrameCountOut = totalSampleCount / channels;
  3262. return result;
  3263. }
  3264. #ifndef DR_WAV_NO_STDIO
  3265. drwav_int16* drwav_open_file_and_read_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount)
  3266. {
  3267. if (sampleRate) *sampleRate = 0;
  3268. if (channels) *channels = 0;
  3269. if (totalSampleCount) *totalSampleCount = 0;
  3270. drwav wav;
  3271. if (!drwav_init_file(&wav, filename)) {
  3272. return NULL;
  3273. }
  3274. return drwav__read_and_close_s16(&wav, channels, sampleRate, totalSampleCount);
  3275. }
  3276. drwav_int16* drwav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut)
  3277. {
  3278. if (channelsOut) *channelsOut = 0;
  3279. if (sampleRateOut) *sampleRateOut = 0;
  3280. if (totalFrameCountOut) *totalFrameCountOut = 0;
  3281. unsigned int channels;
  3282. unsigned int sampleRate;
  3283. drwav_uint64 totalSampleCount;
  3284. drwav_int16* result = drwav_open_file_and_read_s16(filename, &channels, &sampleRate, &totalSampleCount);
  3285. if (result == NULL) {
  3286. return NULL;
  3287. }
  3288. if (channelsOut) *channelsOut = channels;
  3289. if (sampleRateOut) *sampleRateOut = sampleRate;
  3290. if (totalFrameCountOut) *totalFrameCountOut = totalSampleCount / channels;
  3291. return result;
  3292. }
  3293. float* drwav_open_file_and_read_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount)
  3294. {
  3295. if (sampleRate) *sampleRate = 0;
  3296. if (channels) *channels = 0;
  3297. if (totalSampleCount) *totalSampleCount = 0;
  3298. drwav wav;
  3299. if (!drwav_init_file(&wav, filename)) {
  3300. return NULL;
  3301. }
  3302. return drwav__read_and_close_f32(&wav, channels, sampleRate, totalSampleCount);
  3303. }
  3304. float* drwav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut)
  3305. {
  3306. if (channelsOut) *channelsOut = 0;
  3307. if (sampleRateOut) *sampleRateOut = 0;
  3308. if (totalFrameCountOut) *totalFrameCountOut = 0;
  3309. unsigned int channels;
  3310. unsigned int sampleRate;
  3311. drwav_uint64 totalSampleCount;
  3312. float* result = drwav_open_file_and_read_f32(filename, &channels, &sampleRate, &totalSampleCount);
  3313. if (result == NULL) {
  3314. return NULL;
  3315. }
  3316. if (channelsOut) *channelsOut = channels;
  3317. if (sampleRateOut) *sampleRateOut = sampleRate;
  3318. if (totalFrameCountOut) *totalFrameCountOut = totalSampleCount / channels;
  3319. return result;
  3320. }
  3321. drwav_int32* drwav_open_file_and_read_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount)
  3322. {
  3323. if (sampleRate) *sampleRate = 0;
  3324. if (channels) *channels = 0;
  3325. if (totalSampleCount) *totalSampleCount = 0;
  3326. drwav wav;
  3327. if (!drwav_init_file(&wav, filename)) {
  3328. return NULL;
  3329. }
  3330. return drwav__read_and_close_s32(&wav, channels, sampleRate, totalSampleCount);
  3331. }
  3332. drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut)
  3333. {
  3334. if (channelsOut) *channelsOut = 0;
  3335. if (sampleRateOut) *sampleRateOut = 0;
  3336. if (totalFrameCountOut) *totalFrameCountOut = 0;
  3337. unsigned int channels;
  3338. unsigned int sampleRate;
  3339. drwav_uint64 totalSampleCount;
  3340. drwav_int32* result = drwav_open_file_and_read_s32(filename, &channels, &sampleRate, &totalSampleCount);
  3341. if (result == NULL) {
  3342. return NULL;
  3343. }
  3344. if (channelsOut) *channelsOut = channels;
  3345. if (sampleRateOut) *sampleRateOut = sampleRate;
  3346. if (totalFrameCountOut) *totalFrameCountOut = totalSampleCount / channels;
  3347. return result;
  3348. }
  3349. #endif
  3350. drwav_int16* drwav_open_memory_and_read_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount)
  3351. {
  3352. if (sampleRate) *sampleRate = 0;
  3353. if (channels) *channels = 0;
  3354. if (totalSampleCount) *totalSampleCount = 0;
  3355. drwav wav;
  3356. if (!drwav_init_memory(&wav, data, dataSize)) {
  3357. return NULL;
  3358. }
  3359. return drwav__read_and_close_s16(&wav, channels, sampleRate, totalSampleCount);
  3360. }
  3361. drwav_int16* drwav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut)
  3362. {
  3363. if (channelsOut) *channelsOut = 0;
  3364. if (sampleRateOut) *sampleRateOut = 0;
  3365. if (totalFrameCountOut) *totalFrameCountOut = 0;
  3366. unsigned int channels;
  3367. unsigned int sampleRate;
  3368. drwav_uint64 totalSampleCount;
  3369. drwav_int16* result = drwav_open_memory_and_read_s16(data, dataSize, &channels, &sampleRate, &totalSampleCount);
  3370. if (result == NULL) {
  3371. return NULL;
  3372. }
  3373. if (channelsOut) *channelsOut = channels;
  3374. if (sampleRateOut) *sampleRateOut = sampleRate;
  3375. if (totalFrameCountOut) *totalFrameCountOut = totalSampleCount / channels;
  3376. return result;
  3377. }
  3378. float* drwav_open_memory_and_read_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount)
  3379. {
  3380. if (sampleRate) *sampleRate = 0;
  3381. if (channels) *channels = 0;
  3382. if (totalSampleCount) *totalSampleCount = 0;
  3383. drwav wav;
  3384. if (!drwav_init_memory(&wav, data, dataSize)) {
  3385. return NULL;
  3386. }
  3387. return drwav__read_and_close_f32(&wav, channels, sampleRate, totalSampleCount);
  3388. }
  3389. float* drwav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut)
  3390. {
  3391. if (channelsOut) *channelsOut = 0;
  3392. if (sampleRateOut) *sampleRateOut = 0;
  3393. if (totalFrameCountOut) *totalFrameCountOut = 0;
  3394. unsigned int channels;
  3395. unsigned int sampleRate;
  3396. drwav_uint64 totalSampleCount;
  3397. float* result = drwav_open_memory_and_read_f32(data, dataSize, &channels, &sampleRate, &totalSampleCount);
  3398. if (result == NULL) {
  3399. return NULL;
  3400. }
  3401. if (channelsOut) *channelsOut = channels;
  3402. if (sampleRateOut) *sampleRateOut = sampleRate;
  3403. if (totalFrameCountOut) *totalFrameCountOut = totalSampleCount / channels;
  3404. return result;
  3405. }
  3406. drwav_int32* drwav_open_memory_and_read_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalSampleCount)
  3407. {
  3408. if (sampleRate) *sampleRate = 0;
  3409. if (channels) *channels = 0;
  3410. if (totalSampleCount) *totalSampleCount = 0;
  3411. drwav wav;
  3412. if (!drwav_init_memory(&wav, data, dataSize)) {
  3413. return NULL;
  3414. }
  3415. return drwav__read_and_close_s32(&wav, channels, sampleRate, totalSampleCount);
  3416. }
  3417. drwav_int32* drwav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut)
  3418. {
  3419. if (channelsOut) *channelsOut = 0;
  3420. if (sampleRateOut) *sampleRateOut = 0;
  3421. if (totalFrameCountOut) *totalFrameCountOut = 0;
  3422. unsigned int channels;
  3423. unsigned int sampleRate;
  3424. drwav_uint64 totalSampleCount;
  3425. drwav_int32* result = drwav_open_memory_and_read_s32(data, dataSize, &channels, &sampleRate, &totalSampleCount);
  3426. if (result == NULL) {
  3427. return NULL;
  3428. }
  3429. if (channelsOut) *channelsOut = channels;
  3430. if (sampleRateOut) *sampleRateOut = sampleRate;
  3431. if (totalFrameCountOut) *totalFrameCountOut = totalSampleCount / channels;
  3432. return result;
  3433. }
  3434. #endif //DR_WAV_NO_CONVERSION_API
  3435. void drwav_free(void* pDataReturnedByOpenAndRead)
  3436. {
  3437. DRWAV_FREE(pDataReturnedByOpenAndRead);
  3438. }
  3439. #endif //DR_WAV_IMPLEMENTATION
  3440. // REVISION HISTORY
  3441. //
  3442. // v0.9.0 - 2018-12-16
  3443. // - API CHANGE: Add new reading APIs for reading by PCM frames instead of samples. Old APIs have been deprecated and
  3444. // will be removed in v0.10.0. Deprecated APIs and their replacements:
  3445. // drwav_read() -> drwav_read_pcm_frames()
  3446. // drwav_read_s16() -> drwav_read_pcm_frames_s16()
  3447. // drwav_read_f32() -> drwav_read_pcm_frames_f32()
  3448. // drwav_read_s32() -> drwav_read_pcm_frames_s32()
  3449. // drwav_seek_to_sample() -> drwav_seek_to_pcm_frame()
  3450. // drwav_write() -> drwav_write_pcm_frames()
  3451. // drwav_open_and_read_s16() -> drwav_open_and_read_pcm_frames_s16()
  3452. // drwav_open_and_read_f32() -> drwav_open_and_read_pcm_frames_f32()
  3453. // drwav_open_and_read_s32() -> drwav_open_and_read_pcm_frames_s32()
  3454. // drwav_open_file_and_read_s16() -> drwav_open_file_and_read_pcm_frames_s16()
  3455. // drwav_open_file_and_read_f32() -> drwav_open_file_and_read_pcm_frames_f32()
  3456. // drwav_open_file_and_read_s32() -> drwav_open_file_and_read_pcm_frames_s32()
  3457. // drwav_open_memory_and_read_s16() -> drwav_open_memory_and_read_pcm_frames_s16()
  3458. // drwav_open_memory_and_read_f32() -> drwav_open_memory_and_read_pcm_frames_f32()
  3459. // drwav_open_memory_and_read_s32() -> drwav_open_memory_and_read_pcm_frames_s32()
  3460. // drwav::totalSampleCount -> drwav::totalPCMFrameCount
  3461. // - API CHANGE: Rename drwav_open_and_read_file_*() to drwav_open_file_and_read_*().
  3462. // - API CHANGE: Rename drwav_open_and_read_memory_*() to drwav_open_memory_and_read_*().
  3463. // - Add built-in support for smpl chunks.
  3464. // - Add support for firing a callback for each chunk in the file at initialization time.
  3465. // - This is enabled through the drwav_init_ex(), etc. family of APIs.
  3466. // - Handle invalid FMT chunks more robustly.
  3467. //
  3468. // v0.8.5 - 2018-09-11
  3469. // - Const correctness.
  3470. // - Fix a potential stack overflow.
  3471. //
  3472. // v0.8.4 - 2018-08-07
  3473. // - Improve 64-bit detection.
  3474. //
  3475. // v0.8.3 - 2018-08-05
  3476. // - Fix C++ build on older versions of GCC.
  3477. //
  3478. // v0.8.2 - 2018-08-02
  3479. // - Fix some big-endian bugs.
  3480. //
  3481. // v0.8.1 - 2018-06-29
  3482. // - Add support for sequential writing APIs.
  3483. // - Disable seeking in write mode.
  3484. // - Fix bugs with Wave64.
  3485. // - Fix typos.
  3486. //
  3487. // v0.8 - 2018-04-27
  3488. // - Bug fix.
  3489. // - Start using major.minor.revision versioning.
  3490. //
  3491. // v0.7f - 2018-02-05
  3492. // - Restrict ADPCM formats to a maximum of 2 channels.
  3493. //
  3494. // v0.7e - 2018-02-02
  3495. // - Fix a crash.
  3496. //
  3497. // v0.7d - 2018-02-01
  3498. // - Fix a crash.
  3499. //
  3500. // v0.7c - 2018-02-01
  3501. // - Set drwav.bytesPerSample to 0 for all compressed formats.
  3502. // - Fix a crash when reading 16-bit floating point WAV files. In this case dr_wav will output silence for
  3503. // all format conversion reading APIs (*_s16, *_s32, *_f32 APIs).
  3504. // - Fix some divide-by-zero errors.
  3505. //
  3506. // v0.7b - 2018-01-22
  3507. // - Fix errors with seeking of compressed formats.
  3508. // - Fix compilation error when DR_WAV_NO_CONVERSION_API
  3509. //
  3510. // v0.7a - 2017-11-17
  3511. // - Fix some GCC warnings.
  3512. //
  3513. // v0.7 - 2017-11-04
  3514. // - Add writing APIs.
  3515. //
  3516. // v0.6 - 2017-08-16
  3517. // - API CHANGE: Rename dr_* types to drwav_*.
  3518. // - Add support for custom implementations of malloc(), realloc(), etc.
  3519. // - Add support for Microsoft ADPCM.
  3520. // - Add support for IMA ADPCM (DVI, format code 0x11).
  3521. // - Optimizations to drwav_read_s16().
  3522. // - Bug fixes.
  3523. //
  3524. // v0.5g - 2017-07-16
  3525. // - Change underlying type for booleans to unsigned.
  3526. //
  3527. // v0.5f - 2017-04-04
  3528. // - Fix a minor bug with drwav_open_and_read_s16() and family.
  3529. //
  3530. // v0.5e - 2016-12-29
  3531. // - Added support for reading samples as signed 16-bit integers. Use the _s16() family of APIs for this.
  3532. // - Minor fixes to documentation.
  3533. //
  3534. // v0.5d - 2016-12-28
  3535. // - Use drwav_int*/drwav_uint* sized types to improve compiler support.
  3536. //
  3537. // v0.5c - 2016-11-11
  3538. // - Properly handle JUNK chunks that come before the FMT chunk.
  3539. //
  3540. // v0.5b - 2016-10-23
  3541. // - A minor change to drwav_bool8 and drwav_bool32 types.
  3542. //
  3543. // v0.5a - 2016-10-11
  3544. // - Fixed a bug with drwav_open_and_read() and family due to incorrect argument ordering.
  3545. // - Improve A-law and mu-law efficiency.
  3546. //
  3547. // v0.5 - 2016-09-29
  3548. // - API CHANGE. Swap the order of "channels" and "sampleRate" parameters in drwav_open_and_read*(). Rationale for this is to
  3549. // keep it consistent with dr_audio and dr_flac.
  3550. //
  3551. // v0.4b - 2016-09-18
  3552. // - Fixed a typo in documentation.
  3553. //
  3554. // v0.4a - 2016-09-18
  3555. // - Fixed a typo.
  3556. // - Change date format to ISO 8601 (YYYY-MM-DD)
  3557. //
  3558. // v0.4 - 2016-07-13
  3559. // - API CHANGE. Make onSeek consistent with dr_flac.
  3560. // - API CHANGE. Rename drwav_seek() to drwav_seek_to_sample() for clarity and consistency with dr_flac.
  3561. // - Added support for Sony Wave64.
  3562. //
  3563. // v0.3a - 2016-05-28
  3564. // - API CHANGE. Return drwav_bool32 instead of int in onSeek callback.
  3565. // - Fixed a memory leak.
  3566. //
  3567. // v0.3 - 2016-05-22
  3568. // - Lots of API changes for consistency.
  3569. //
  3570. // v0.2a - 2016-05-16
  3571. // - Fixed Linux/GCC build.
  3572. //
  3573. // v0.2 - 2016-05-11
  3574. // - Added support for reading data as signed 32-bit PCM for consistency with dr_flac.
  3575. //
  3576. // v0.1a - 2016-05-07
  3577. // - Fixed a bug in drwav_open_file() where the file handle would not be closed if the loader failed to initialize.
  3578. //
  3579. // v0.1 - 2016-05-04
  3580. // - Initial versioned release.
  3581. /*
  3582. This is free and unencumbered software released into the public domain.
  3583. Anyone is free to copy, modify, publish, use, compile, sell, or
  3584. distribute this software, either in source code form or as a compiled
  3585. binary, for any purpose, commercial or non-commercial, and by any
  3586. means.
  3587. In jurisdictions that recognize copyright laws, the author or authors
  3588. of this software dedicate any and all copyright interest in the
  3589. software to the public domain. We make this dedication for the benefit
  3590. of the public at large and to the detriment of our heirs and
  3591. successors. We intend this dedication to be an overt act of
  3592. relinquishment in perpetuity of all present and future rights to this
  3593. software under copyright law.
  3594. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  3595. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  3596. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  3597. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
  3598. OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
  3599. ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  3600. OTHER DEALINGS IN THE SOFTWARE.
  3601. For more information, please refer to <http://unlicense.org/>
  3602. */