YARP
Yet Another Robot Platform
 
Loading...
Searching...
No Matches
dr_wav.h
Go to the documentation of this file.
1/*
2WAV audio loader and writer. Choice of public domain or MIT-0. See license statements at the end of this file.
3dr_wav - v0.14.5 - 2026-03-03
4
5David Reid - mackron@gmail.com
6
7GitHub: https://github.com/mackron/dr_libs
8*/
9
10/*
11Introduction
12============
13This is a single file library. To use it, do something like the following in one .c file.
14
15 ```c
16 #define DR_WAV_IMPLEMENTATION
17 #include "dr_wav.h"
18 ```
19
20You can then #include this file in other parts of the program as you would with any other header file. Do something like the following to read audio data:
21
22 ```c
23 drwav wav;
24 if (!drwav_init_file(&wav, "my_song.wav", NULL)) {
25 // Error opening WAV file.
26 }
27
28 drwav_int32* pDecodedInterleavedPCMFrames = malloc(wav.totalPCMFrameCount * wav.channels * sizeof(drwav_int32));
29 size_t numberOfSamplesActuallyDecoded = drwav_read_pcm_frames_s32(&wav, wav.totalPCMFrameCount, pDecodedInterleavedPCMFrames);
30
31 ...
32
33 drwav_uninit(&wav);
34 ```
35
36If you just want to quickly open and read the audio data in a single operation you can do something like this:
37
38 ```c
39 unsigned int channels;
40 unsigned int sampleRate;
41 drwav_uint64 totalPCMFrameCount;
42 float* pSampleData = drwav_open_file_and_read_pcm_frames_f32("my_song.wav", &channels, &sampleRate, &totalPCMFrameCount, NULL);
43 if (pSampleData == NULL) {
44 // Error opening and reading WAV file.
45 }
46
47 ...
48
49 drwav_free(pSampleData, NULL);
50 ```
51
52The examples above use versions of the API that convert the audio data to a consistent format (32-bit signed PCM, in this case), but you can still output the
53audio data in its internal format (see notes below for supported formats):
54
55 ```c
56 size_t framesRead = drwav_read_pcm_frames(&wav, wav.totalPCMFrameCount, pDecodedInterleavedPCMFrames);
57 ```
58
59You can also read the raw bytes of audio data, which could be useful if dr_wav does not have native support for a particular data format:
60
61 ```c
62 size_t bytesRead = drwav_read_raw(&wav, bytesToRead, pRawDataBuffer);
63 ```
64
65dr_wav can also be used to output WAV files. This does not currently support compressed formats. To use this, look at `drwav_init_write()`,
66`drwav_init_file_write()`, etc. Use `drwav_write_pcm_frames()` to write samples, or `drwav_write_raw()` to write raw data in the "data" chunk.
67
68 ```c
69 drwav_data_format format;
70 format.container = drwav_container_riff; // <-- drwav_container_riff = normal WAV files, drwav_container_w64 = Sony Wave64.
71 format.format = DR_WAVE_FORMAT_PCM; // <-- Any of the DR_WAVE_FORMAT_* codes.
72 format.channels = 2;
73 format.sampleRate = 44100;
74 format.bitsPerSample = 16;
75 drwav_init_file_write(&wav, "data/recording.wav", &format, NULL);
76
77 ...
78
79 drwav_uint64 framesWritten = drwav_write_pcm_frames(pWav, frameCount, pSamples);
80 ```
81
82Note that writing to AIFF or RIFX is not supported.
83
84dr_wav has support for decoding from a number of different encapsulation formats. See below for details.
85
86
87Build Options
88=============
89#define these options before including this file.
90
91#define DR_WAV_NO_CONVERSION_API
92 Disables conversion APIs such as `drwav_read_pcm_frames_f32()` and `drwav_s16_to_f32()`.
93
94#define DR_WAV_NO_STDIO
95 Disables APIs that initialize a decoder from a file such as `drwav_init_file()`, `drwav_init_file_write()`, etc.
96
97#define DR_WAV_NO_WCHAR
98 Disables all functions ending with `_w`. Use this if your compiler does not provide wchar.h. Not required if DR_WAV_NO_STDIO is also defined.
99
100
101Supported Encapsulations
102========================
103- RIFF (Regular WAV)
104- RIFX (Big-Endian)
105- AIFF (Does not currently support ADPCM)
106- RF64
107- W64
108
109Note that AIFF and RIFX do not support write mode, nor do they support reading of metadata.
110
111
112Supported Encodings
113===================
114- Unsigned 8-bit PCM
115- Signed 12-bit PCM
116- Signed 16-bit PCM
117- Signed 24-bit PCM
118- Signed 32-bit PCM
119- IEEE 32-bit floating point
120- IEEE 64-bit floating point
121- A-law and u-law
122- Microsoft ADPCM
123- IMA ADPCM (DVI, format code 0x11)
124
1258-bit PCM encodings are always assumed to be unsigned. Signed 8-bit encoding can only be read with `drwav_read_raw()`.
126
127Note that ADPCM is not currently supported with AIFF. Contributions welcome.
128
129
130Notes
131=====
132- Samples are always interleaved.
133- The default read function does not do any data conversion. Use `drwav_read_pcm_frames_f32()`, `drwav_read_pcm_frames_s32()` and `drwav_read_pcm_frames_s16()`
134 to read and convert audio data to 32-bit floating point, signed 32-bit integer and signed 16-bit integer samples respectively.
135- dr_wav will try to read the WAV file as best it can, even if it's not strictly conformant to the WAV format.
136*/
137
138#ifndef dr_wav_h
139#define dr_wav_h
140
141#ifdef __cplusplus
142extern "C" {
143#endif
144
145#define DRWAV_STRINGIFY(x) #x
146#define DRWAV_XSTRINGIFY(x) DRWAV_STRINGIFY(x)
147
148#define DRWAV_VERSION_MAJOR 0
149#define DRWAV_VERSION_MINOR 14
150#define DRWAV_VERSION_REVISION 5
151#define DRWAV_VERSION_STRING DRWAV_XSTRINGIFY(DRWAV_VERSION_MAJOR) "." DRWAV_XSTRINGIFY(DRWAV_VERSION_MINOR) "." DRWAV_XSTRINGIFY(DRWAV_VERSION_REVISION)
152
153#include <stddef.h> /* For size_t. */
154
155/* Sized Types */
156typedef signed char drwav_int8;
157typedef unsigned char drwav_uint8;
158typedef signed short drwav_int16;
159typedef unsigned short drwav_uint16;
160typedef signed int drwav_int32;
161typedef unsigned int drwav_uint32;
162#if defined(_MSC_VER) && !defined(__clang__)
163 typedef signed __int64 drwav_int64;
164 typedef unsigned __int64 drwav_uint64;
165#else
166 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
167 #pragma GCC diagnostic push
168 #pragma GCC diagnostic ignored "-Wlong-long"
169 #if defined(__clang__)
170 #pragma GCC diagnostic ignored "-Wc++11-long-long"
171 #endif
172 #endif
173 typedef signed long long drwav_int64;
174 typedef unsigned long long drwav_uint64;
175 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
176 #pragma GCC diagnostic pop
177 #endif
178#endif
179#if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined (_M_IA64) || defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC) || defined(__powerpc64__)
181#else
183#endif
186#define DRWAV_TRUE 1
187#define DRWAV_FALSE 0
188/* End Sized Types */
189
190/* Decorations */
191#if !defined(DRWAV_API)
192 #if defined(DRWAV_DLL)
193 #if defined(_WIN32)
194 #define DRWAV_DLL_IMPORT __declspec(dllimport)
195 #define DRWAV_DLL_EXPORT __declspec(dllexport)
196 #define DRWAV_DLL_PRIVATE static
197 #else
198 #if defined(__GNUC__) && __GNUC__ >= 4
199 #define DRWAV_DLL_IMPORT __attribute__((visibility("default")))
200 #define DRWAV_DLL_EXPORT __attribute__((visibility("default")))
201 #define DRWAV_DLL_PRIVATE __attribute__((visibility("hidden")))
202 #else
203 #define DRWAV_DLL_IMPORT
204 #define DRWAV_DLL_EXPORT
205 #define DRWAV_DLL_PRIVATE static
206 #endif
207 #endif
208
209 #if defined(DR_WAV_IMPLEMENTATION) || defined(DRWAV_IMPLEMENTATION)
210 #define DRWAV_API DRWAV_DLL_EXPORT
211 #else
212 #define DRWAV_API DRWAV_DLL_IMPORT
213 #endif
214 #define DRWAV_PRIVATE DRWAV_DLL_PRIVATE
215 #else
216 #define DRWAV_API extern
217 #define DRWAV_PRIVATE static
218 #endif
219#endif
220/* End Decorations */
221
222/* Result Codes */
224#define DRWAV_SUCCESS 0
225#define DRWAV_ERROR -1 /* A generic error. */
226#define DRWAV_INVALID_ARGS -2
227#define DRWAV_INVALID_OPERATION -3
228#define DRWAV_OUT_OF_MEMORY -4
229#define DRWAV_OUT_OF_RANGE -5
230#define DRWAV_ACCESS_DENIED -6
231#define DRWAV_DOES_NOT_EXIST -7
232#define DRWAV_ALREADY_EXISTS -8
233#define DRWAV_TOO_MANY_OPEN_FILES -9
234#define DRWAV_INVALID_FILE -10
235#define DRWAV_TOO_BIG -11
236#define DRWAV_PATH_TOO_LONG -12
237#define DRWAV_NAME_TOO_LONG -13
238#define DRWAV_NOT_DIRECTORY -14
239#define DRWAV_IS_DIRECTORY -15
240#define DRWAV_DIRECTORY_NOT_EMPTY -16
241#define DRWAV_END_OF_FILE -17
242#define DRWAV_NO_SPACE -18
243#define DRWAV_BUSY -19
244#define DRWAV_IO_ERROR -20
245#define DRWAV_INTERRUPT -21
246#define DRWAV_UNAVAILABLE -22
247#define DRWAV_ALREADY_IN_USE -23
248#define DRWAV_BAD_ADDRESS -24
249#define DRWAV_BAD_SEEK -25
250#define DRWAV_BAD_PIPE -26
251#define DRWAV_DEADLOCK -27
252#define DRWAV_TOO_MANY_LINKS -28
253#define DRWAV_NOT_IMPLEMENTED -29
254#define DRWAV_NO_MESSAGE -30
255#define DRWAV_BAD_MESSAGE -31
256#define DRWAV_NO_DATA_AVAILABLE -32
257#define DRWAV_INVALID_DATA -33
258#define DRWAV_TIMEOUT -34
259#define DRWAV_NO_NETWORK -35
260#define DRWAV_NOT_UNIQUE -36
261#define DRWAV_NOT_SOCKET -37
262#define DRWAV_NO_ADDRESS -38
263#define DRWAV_BAD_PROTOCOL -39
264#define DRWAV_PROTOCOL_UNAVAILABLE -40
265#define DRWAV_PROTOCOL_NOT_SUPPORTED -41
266#define DRWAV_PROTOCOL_FAMILY_NOT_SUPPORTED -42
267#define DRWAV_ADDRESS_FAMILY_NOT_SUPPORTED -43
268#define DRWAV_SOCKET_NOT_SUPPORTED -44
269#define DRWAV_CONNECTION_RESET -45
270#define DRWAV_ALREADY_CONNECTED -46
271#define DRWAV_NOT_CONNECTED -47
272#define DRWAV_CONNECTION_REFUSED -48
273#define DRWAV_NO_HOST -49
274#define DRWAV_IN_PROGRESS -50
275#define DRWAV_CANCELLED -51
276#define DRWAV_MEMORY_ALREADY_MAPPED -52
277#define DRWAV_AT_END -53
278/* End Result Codes */
279
280/* Common data formats. */
281#define DR_WAVE_FORMAT_PCM 0x1
282#define DR_WAVE_FORMAT_ADPCM 0x2
283#define DR_WAVE_FORMAT_IEEE_FLOAT 0x3
284#define DR_WAVE_FORMAT_ALAW 0x6
285#define DR_WAVE_FORMAT_MULAW 0x7
286#define DR_WAVE_FORMAT_DVI_ADPCM 0x11
287#define DR_WAVE_FORMAT_EXTENSIBLE 0xFFFE
288
289/* Flags to pass into drwav_init_ex(), etc. */
290#define DRWAV_SEQUENTIAL 0x00000001
291#define DRWAV_WITH_METADATA 0x00000002
292
295
296/* Allocation Callbacks */
297typedef struct
298{
300 void* (* onMalloc)(size_t sz, void* pUserData);
301 void* (* onRealloc)(void* p, size_t sz, void* pUserData);
302 void (* onFree)(void* p, void* pUserData);
304/* End Allocation Callbacks */
305
312
321
322typedef struct
323{
324 union
325 {
326 drwav_uint8 fourcc[4];
327 drwav_uint8 guid[16];
328 } id;
329
330 /* The size in bytes of the chunk. */
332
333 /*
334 RIFF = 2 byte alignment.
335 W64 = 8 byte alignment.
336 */
337 unsigned int paddingSize;
339
340typedef struct
341{
342 /*
343 The format tag exactly as specified in the wave file's "fmt" chunk. This can be used by applications
344 that require support for data formats not natively supported by dr_wav.
345 */
347
348 /* The number of channels making up the audio data. When this is set to 1 it is mono, 2 is stereo, etc. */
350
351 /* The sample rate. Usually set to something like 44100. */
353
354 /* Average bytes per second. You probably don't need this, but it's left here for informational purposes. */
356
357 /* Block align. This is equal to the number of channels * bytes per sample. */
359
360 /* Bits per sample. */
362
363 /* The size of the extended data. Only used internally for validation, but left here for informational purposes. */
365
366 /*
367 The number of valid bits per sample. When <formatTag> is equal to WAVE_FORMAT_EXTENSIBLE, <bitsPerSample>
368 is always rounded up to the nearest multiple of 8. This variable contains information about exactly how
369 many bits are valid per sample. Mainly used for informational purposes.
370 */
372
373 /* The channel mask. Not used at the moment. */
375
376 /* The sub-format, exactly as specified by the wave file. */
377 drwav_uint8 subFormat[16];
378} drwav_fmt;
379
381
382
383/*
384Callback for when data is read. Return value is the number of bytes actually read.
385
386pUserData [in] The user data that was passed to drwav_init() and family.
387pBufferOut [out] The output buffer.
388bytesToRead [in] The number of bytes to read.
389
390Returns the number of bytes actually read.
391
392A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until
393either the entire bytesToRead is filled or you have reached the end of the stream.
394*/
395typedef size_t (* drwav_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
396
397/*
398Callback for when data is written. Returns value is the number of bytes actually written.
399
400pUserData [in] The user data that was passed to drwav_init_write() and family.
401pData [out] A pointer to the data to write.
402bytesToWrite [in] The number of bytes to write.
403
404Returns the number of bytes actually written.
405
406If the return value differs from bytesToWrite, it indicates an error.
407*/
408typedef size_t (* drwav_write_proc)(void* pUserData, const void* pData, size_t bytesToWrite);
409
410/*
411Callback for when data needs to be seeked.
412
413pUserData [in] The user data that was passed to drwav_init() and family.
414offset [in] The number of bytes to move, relative to the origin. Will never be negative.
415origin [in] The origin of the seek - the current position or the start of the stream.
416
417Returns whether or not the seek was successful.
418
419Whether or not it is relative to the beginning or current position is determined by the "origin" parameter which will be either DRWAV_SEEK_SET or
420DRWAV_SEEK_CUR.
421*/
422typedef drwav_bool32 (* drwav_seek_proc)(void* pUserData, int offset, drwav_seek_origin origin);
423
424/*
425Callback for when the current position in the stream needs to be retrieved.
426
427pUserData [in] The user data that was passed to drwav_init() and family.
428pCursor [out] A pointer to a variable to receive the current position in the stream.
429
430Returns whether or not the operation was successful.
431*/
432typedef drwav_bool32 (* drwav_tell_proc)(void* pUserData, drwav_int64* pCursor);
433
434/*
435Callback for when drwav_init_ex() finds a chunk.
436
437pChunkUserData [in] The user data that was passed to the pChunkUserData parameter of drwav_init_ex() and family.
438onRead [in] A pointer to the function to call when reading.
439onSeek [in] A pointer to the function to call when seeking.
440pReadSeekUserData [in] The user data that was passed to the pReadSeekUserData parameter of drwav_init_ex() and family.
441pChunkHeader [in] A pointer to an object containing basic header information about the chunk. Use this to identify the chunk.
442container [in] Whether or not the WAV file is a RIFF or Wave64 container. If you're unsure of the difference, assume RIFF.
443pFMT [in] A pointer to the object containing the contents of the "fmt" chunk.
444
445Returns the number of bytes read + seeked.
446
447To read data from the chunk, call onRead(), passing in pReadSeekUserData as the first parameter. Do the same for seeking with onSeek(). The return value must
448be the total number of bytes you have read _plus_ seeked.
449
450Use the `container` argument to discriminate the fields in `pChunkHeader->id`. If the container is `drwav_container_riff` or `drwav_container_rf64` you should
451use `id.fourcc`, otherwise you should use `id.guid`.
452
453The `pFMT` parameter can be used to determine the data format of the wave file. Use `drwav_fmt_get_format()` to get the sample format, which will be one of the
454`DR_WAVE_FORMAT_*` identifiers.
455
456The read pointer will be sitting on the first byte after the chunk's header. You must not attempt to read beyond the boundary of the chunk.
457*/
458typedef drwav_uint64 (* drwav_chunk_proc)(void* pChunkUserData, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pReadSeekUserData, const drwav_chunk_header* pChunkHeader, drwav_container container, const drwav_fmt* pFMT);
459
460
461/* Structure for internal use. Only used for loaders opened with drwav_init_memory(). */
462typedef struct
463{
465 size_t dataSize;
468
469/* Structure for internal use. Only used for writers opened with drwav_init_memory_write(). */
470typedef struct
471{
472 void** ppData;
473 size_t* pDataSize;
474 size_t dataSize;
478
487
488typedef enum
489{
491
492 /*
493 Unknown simply means a chunk that drwav does not handle specifically. You can still ask to
494 receive these chunks as metadata objects. It is then up to you to interpret the chunk's data.
495 You can also write unknown metadata to a wav file. Be careful writing unknown chunks if you
496 have also edited the audio data. The unknown chunks could represent offsets/sizes that no
497 longer correctly correspond to the audio data.
498 */
500
501 /* Only 1 of each of these metadata items are allowed in a wav file. */
507
508 /*
509 Wav files often have a LIST chunk. This is a chunk that contains a set of subchunks. For this
510 higher-level metadata API, we don't make a distinction between a regular chunk and a LIST
511 subchunk. Instead, they are all just 'metadata' items.
512
513 There can be multiple of these metadata items in a wav file.
514 */
518
533
534 /* Other type constants for convenience. */
549
553
554 drwav_metadata_type_all = -2, /*0xFFFFFFFF & ~drwav_metadata_type_unknown,*/
557
558/*
559Sampler Metadata
560
561The sampler chunk contains information about how a sound should be played in the context of a whole
562audio production, and when used in a sampler. See https://en.wikipedia.org/wiki/Sample-based_synthesis.
563*/
570
571typedef struct
572{
573 /* The ID of the associated cue point, see drwav_cue and drwav_cue_point. As with all cue point IDs, this can correspond to a label chunk to give this loop a name, see drwav_list_label_or_note. */
575
576 /* See drwav_smpl_loop_type. */
578
579 /* The offset of the first sample to be played in the loop. */
581
582 /* The offset into the audio data of the last sample to be played in the loop. */
584
585 /* A value to represent that playback should occur at a point between samples. This value ranges from 0 to UINT32_MAX. Where a value of 0 means no fraction, and a value of (UINT32_MAX / 2) would mean half a sample. */
587
588 /* Number of times to play the loop. 0 means loop infinitely. */
591
592typedef struct
593{
594 /* IDs for a particular MIDI manufacturer. 0 if not used. */
597
598 /* The period of 1 sample in nanoseconds. */
600
601 /* The MIDI root note of this file. 0 to 127. */
603
604 /* The fraction of a semitone up from the given MIDI note. This is a value from 0 to UINT32_MAX, where 0 means no change and (UINT32_MAX / 2) is half a semitone (AKA 50 cents). */
606
607 /* Data relating to SMPTE standards which are used for syncing audio and video. 0 if not used. */
610
611 /* drwav_smpl_loop loops. */
613
614 /* Optional sampler-specific data. */
616
619} drwav_smpl;
620
621/*
622Instrument Metadata
623
624The inst metadata contains data about how a sound should be played as part of an instrument. This
625commonly read by samplers. See https://en.wikipedia.org/wiki/Sample-based_synthesis.
626*/
627typedef struct
628{
629 drwav_int8 midiUnityNote; /* The root note of the audio as a MIDI note number. 0 to 127. */
630 drwav_int8 fineTuneCents; /* -50 to +50 */
631 drwav_int8 gainDecibels; /* -64 to +64 */
632 drwav_int8 lowNote; /* 0 to 127 */
633 drwav_int8 highNote; /* 0 to 127 */
634 drwav_int8 lowVelocity; /* 1 to 127 */
635 drwav_int8 highVelocity; /* 1 to 127 */
636} drwav_inst;
637
638/*
639Cue Metadata
640
641Cue points are markers at specific points in the audio. They often come with an associated piece of
642drwav_list_label_or_note metadata which contains the text for the marker.
643*/
644typedef struct
645{
646 /* Unique identification value. */
648
649 /* Set to 0. This is only relevant if there is a 'playlist' chunk - which is not supported by dr_wav. */
651
652 /* Should always be "data". This represents the fourcc value of the chunk that this cue point corresponds to. dr_wav only supports a single data chunk so this should always be "data". */
653 drwav_uint8 dataChunkId[4];
654
655 /* Set to 0. This is only relevant if there is a wave list chunk. dr_wav, like lots of readers/writers, do not support this. */
657
658 /* Set to 0 for uncompressed formats. Else the last byte in compressed wave data where decompression can begin to find the value of the corresponding sample value. */
660
661 /* For uncompressed formats this is the offset of the cue point into the audio data. For compressed formats this is relative to the block specified with blockStart. */
664
670
671/*
672Acid Metadata
673
674This chunk contains some information about the time signature and the tempo of the audio.
675*/
676typedef enum
677{
678 drwav_acid_flag_one_shot = 1, /* If this is not set, then it is a loop instead of a one-shot. */
682 drwav_acid_flag_acidizer = 16 /* Not sure what this means. */
684
685typedef struct
686{
687 /* A bit-field, see drwav_acid_flag. */
689
690 /* Valid if flags contains drwav_acid_flag_root_note_set. It represents the MIDI root note the file - a value from 0 to 127. */
692
693 /* Reserved values that should probably be ignored. reserved1 seems to often be 128 and reserved2 is 0. */
696
697 /* Number of beats. */
699
700 /* The time signature of the audio. */
703
704 /* Beats per minute of the track. Setting a value of 0 suggests that there is no tempo. */
705 float tempo;
706} drwav_acid;
707
708/*
709Cue Label or Note metadata
710
711These are 2 different types of metadata, but they have the exact same format. Labels tend to be the
712more common and represent a short name for a cue point. Notes might be used to represent a longer
713comment.
714*/
715typedef struct
716{
717 /* The ID of a cue point that this label or note corresponds to. */
719
720 /* Size of the string not including any null terminator. */
722
723 /* The string. The *init_with_metadata functions null terminate this for convenience. */
724 char* pString;
726
727/*
728BEXT metadata, also known as Broadcast Wave Format (BWF)
729
730This metadata adds some extra description to an audio file. You must check the version field to
731determine if the UMID or the loudness fields are valid.
732*/
733typedef struct
734{
735 /*
736 These top 3 fields, and the umid field are actually defined in the standard as a statically
737 sized buffers. In order to reduce the size of this struct (and therefore the union in the
738 metadata struct), we instead store these as pointers.
739 */
740 char* pDescription; /* Can be NULL or a null-terminated string, must be <= 256 characters. */
741 char* pOriginatorName; /* Can be NULL or a null-terminated string, must be <= 32 characters. */
742 char* pOriginatorReference; /* Can be NULL or a null-terminated string, must be <= 32 characters. */
743 char pOriginationDate[10]; /* ASCII "yyyy:mm:dd". */
744 char pOriginationTime[8]; /* ASCII "hh:mm:ss". */
745 drwav_uint64 timeReference; /* First sample count since midnight. */
746 drwav_uint16 version; /* Version of the BWF, check this to see if the fields below are valid. */
747
748 /*
749 Unrestricted ASCII characters containing a collection of strings terminated by CR/LF. Each
750 string shall contain a description of a coding process applied to the audio data.
751 */
754
755 /* Fields below this point are only valid if the version is 1 or above. */
756 drwav_uint8* pUMID; /* Exactly 64 bytes of SMPTE UMID */
757
758 /* Fields below this point are only valid if the version is 2 or above. */
759 drwav_uint16 loudnessValue; /* Integrated Loudness Value of the file in LUFS (multiplied by 100). */
760 drwav_uint16 loudnessRange; /* Loudness Range of the file in LU (multiplied by 100). */
761 drwav_uint16 maxTruePeakLevel; /* Maximum True Peak Level of the file expressed as dBTP (multiplied by 100). */
762 drwav_uint16 maxMomentaryLoudness; /* Highest value of the Momentary Loudness Level of the file in LUFS (multiplied by 100). */
763 drwav_uint16 maxShortTermLoudness; /* Highest value of the Short-Term Loudness Level of the file in LUFS (multiplied by 100). */
764} drwav_bext;
765
766/*
767Info Text Metadata
768
769There a many different types of information text that can be saved in this format. This is where
770things like the album name, the artists, the year it was produced, etc are saved. See
771drwav_metadata_type for the full list of types that dr_wav supports.
772*/
773typedef struct
774{
775 /* Size of the string not including any null terminator. */
777
778 /* The string. The *init_with_metadata functions null terminate this for convenience. */
779 char* pString;
781
782/*
783Labelled Cue Region Metadata
784
785The labelled cue region metadata is used to associate some region of audio with text. The region
786starts at a cue point, and extends for the given number of samples.
787*/
788typedef struct
789{
790 /* The ID of a cue point that this object corresponds to. */
792
793 /* The number of samples from the cue point forwards that should be considered this region */
795
796 /* Four characters used to say what the purpose of this region is. */
797 drwav_uint8 purposeId[4];
798
799 /* Unsure of the exact meanings of these. It appears to be acceptable to set them all to 0. */
804
805 /* Size of the string not including any null terminator. */
807
808 /* The string. The *init_with_metadata functions null terminate this for convenience. */
809 char* pString;
811
812/*
813Unknown Metadata
814
815This chunk just represents a type of chunk that dr_wav does not understand.
816
817Unknown metadata has a location attached to it. This is because wav files can have a LIST chunk
818that contains subchunks. These LIST chunks can be one of two types. An adtl list, or an INFO
819list. This enum is used to specify the location of a chunk that dr_wav currently doesn't support.
820*/
828
836
837/*
838Metadata is saved as a union of all the supported types.
839*/
840typedef struct
841{
842 /* Determines which item in the union is valid. */
844
845 union
846 {
852 drwav_list_label_or_note labelOrNote; /* List label or list note. */
854 drwav_list_info_text infoText; /* Any of the list info types. */
856 } data;
858
859typedef struct
860{
861 /* A pointer to the function to call when more data is needed. */
863
864 /* A pointer to the function to call when data needs to be written. Only used when the drwav object is opened in write mode. */
866
867 /* A pointer to the function to call when the wav file needs to be seeked. */
869
870 /* A pointer to the function to call when the position of the stream needs to be retrieved. */
872
873 /* The user data to pass to callbacks. */
875
876 /* Allocation callbacks. */
878
879
880 /* Whether or not the WAV file is formatted as a standard RIFF file or W64. */
882
883
884 /* Structure containing format information exactly as specified by the wav file. */
886
887 /* The sample rate. Will be set to something like 44100. */
889
890 /* The number of channels. This will be set to 1 for monaural streams, 2 for stereo, etc. */
892
893 /* The bits per sample. Will be set to something like 16, 24, etc. */
895
896 /* Equal to fmt.formatTag, or the value specified by fmt.subFormat if fmt.formatTag is equal to 65534 (WAVE_FORMAT_EXTENSIBLE). */
898
899 /* The total number of PCM frames making up the audio data. */
901
902
903 /* The size in bytes of the data chunk. */
905
906 /* The position in the stream of the first data byte of the data chunk. This is used for seeking. */
908
909 /* The number of bytes remaining in the data chunk. */
911
912 /* The current read position in PCM frames. */
914
915
916 /*
917 Only used in sequential write mode. Keeps track of the desired size of the "data" chunk at the point of initialization time. Always
918 set to 0 for non-sequential writes and when the drwav object is opened in read mode. Used for validation.
919 */
921
922 /* Keeps track of whether or not the wav writer was initialized in sequential mode. */
924
925
926 /* A array of metadata. This is valid after the *init_with_metadata call returns. It will be valid until drwav_uninit() is called. You can take ownership of this data with drwav_take_ownership_of_metadata(). */
929
930
931 /* A hack to avoid a DRWAV_MALLOC() when opening a decoder with drwav_init_memory(). */
934
935
936 /* Microsoft ADPCM specific data. */
937 struct
938 {
940 drwav_uint16 predictor[2];
941 drwav_int32 delta[2];
942 drwav_int32 cachedFrames[4]; /* Samples are stored in this cache during decoding. */
944 drwav_int32 prevFrames[2][2]; /* The previous 2 samples for each channel (2 channels at most). */
945 } msadpcm;
946
947 /* IMA ADPCM specific data. */
948 struct
949 {
950 drwav_uint32 bytesRemainingInBlock;
951 drwav_int32 predictor[2];
952 drwav_int32 stepIndex[2];
953 drwav_int32 cachedFrames[16]; /* Samples are stored in this cache during decoding. */
954 drwav_uint32 cachedFrameCount;
955 } ima;
956
957 /* AIFF specific data. */
958 struct
959 {
960 drwav_bool8 isLE; /* Will be set to true if the audio data is little-endian encoded. */
961 drwav_bool8 isUnsigned; /* Only used for 8-bit samples. When set to true, will be treated as unsigned. */
962 } aiff;
963} drwav;
964
965
966/*
967Initializes a pre-allocated drwav object for reading.
968
969pWav [out] A pointer to the drwav object being initialized.
970onRead [in] The function to call when data needs to be read from the client.
971onSeek [in] The function to call when the read position of the client data needs to move.
972onChunk [in, optional] The function to call when a chunk is enumerated at initialized time.
973pUserData, pReadSeekUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek.
974pChunkUserData [in, optional] A pointer to application defined data that will be passed to onChunk.
975flags [in, optional] A set of flags for controlling how things are loaded.
976
977Returns true if successful; false otherwise.
978
979Close the loader with drwav_uninit().
980
981This is the lowest level function for initializing a WAV file. You can also use drwav_init_file() and drwav_init_memory()
982to open the stream from a file or from a block of memory respectively.
983
984Possible values for flags:
985 DRWAV_SEQUENTIAL: Never perform a backwards seek while loading. This disables the chunk callback and will cause this function
986 to return as soon as the data chunk is found. Any chunks after the data chunk will be ignored.
987
988drwav_init() is equivalent to "drwav_init_ex(pWav, onRead, onSeek, NULL, pUserData, NULL, 0);".
989
990The onChunk callback is not called for the WAVE or FMT chunks. The contents of the FMT chunk can be read from pWav->fmt
991after the function returns.
992
993See also: drwav_init_file(), drwav_init_memory(), drwav_uninit()
994*/
995DRWAV_API drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
996DRWAV_API drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, drwav_chunk_proc onChunk, void* pReadSeekTellUserData, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
997DRWAV_API drwav_bool32 drwav_init_with_metadata(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void* pUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
998
999/*
1000Initializes a pre-allocated drwav object for writing.
1001
1002onWrite [in] The function to call when data needs to be written.
1003onSeek [in] The function to call when the write position needs to move.
1004pUserData [in, optional] A pointer to application defined data that will be passed to onWrite and onSeek.
1005metadata, numMetadata [in, optional] An array of metadata objects that should be written to the file. The array is not edited. You are responsible for this metadata memory and it must maintain valid until drwav_uninit() is called.
1006
1007Returns true if successful; false otherwise.
1008
1009Close the writer with drwav_uninit().
1010
1011This is the lowest level function for initializing a WAV file. You can also use drwav_init_file_write() and drwav_init_memory_write()
1012to open the stream from a file or from a block of memory respectively.
1013
1014If the total sample count is known, you can use drwav_init_write_sequential(). This avoids the need for dr_wav to perform
1015a post-processing step for storing the total sample count and the size of the data chunk which requires a backwards seek.
1016
1017See also: drwav_init_file_write(), drwav_init_memory_write(), drwav_uninit()
1018*/
1019DRWAV_API drwav_bool32 drwav_init_write(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
1020DRWAV_API drwav_bool32 drwav_init_write_sequential(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
1021DRWAV_API drwav_bool32 drwav_init_write_sequential_pcm_frames(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
1022DRWAV_API drwav_bool32 drwav_init_write_with_metadata(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks, drwav_metadata* pMetadata, drwav_uint32 metadataCount);
1023
1024/*
1025Utility function to determine the target size of the entire data to be written (including all headers and chunks).
1026
1027Returns the target size in bytes.
1028
1029The metadata argument can be NULL meaning no metadata exists.
1030
1031Useful if the application needs to know the size to allocate.
1032
1033Only writing to the RIFF chunk and one data chunk is currently supported.
1034
1035See also: drwav_init_write(), drwav_init_file_write(), drwav_init_memory_write()
1036*/
1038
1039/*
1040Take ownership of the metadata objects that were allocated via one of the init_with_metadata() function calls. The init_with_metdata functions perform a single heap allocation for this metadata.
1041
1042Useful if you want the data to persist beyond the lifetime of the drwav object.
1043
1044You must free the data returned from this function using drwav_free().
1045*/
1047
1048/*
1049Uninitializes the given drwav object.
1050
1051Use this only for objects initialized with drwav_init*() functions (drwav_init(), drwav_init_ex(), drwav_init_write(), drwav_init_write_sequential()).
1052*/
1054
1055
1056/*
1057Reads raw audio data.
1058
1059This is the lowest level function for reading audio data. It simply reads the given number of
1060bytes of the raw internal sample data.
1061
1062Consider using drwav_read_pcm_frames_s16(), drwav_read_pcm_frames_s32() or drwav_read_pcm_frames_f32() for
1063reading sample data in a consistent format.
1064
1065pBufferOut can be NULL in which case a seek will be performed.
1066
1067Returns the number of bytes actually read.
1068*/
1069DRWAV_API size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut);
1070
1071/*
1072Reads up to the specified number of PCM frames from the WAV file.
1073
1074The output data will be in the file's internal format, converted to native-endian byte order. Use
1075drwav_read_pcm_frames_s16/f32/s32() to read data in a specific format.
1076
1077If the return value is less than <framesToRead> it means the end of the file has been reached or
1078you have requested more PCM frames than can possibly fit in the output buffer.
1079
1080This function will only work when sample data is of a fixed size and uncompressed. If you are
1081using a compressed format consider using drwav_read_raw() or drwav_read_pcm_frames_s16/s32/f32().
1082
1083pBufferOut can be NULL in which case a seek will be performed.
1084*/
1085DRWAV_API drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut);
1088
1089/*
1090Seeks to the given PCM frame.
1091
1092Returns true if successful; false otherwise.
1093*/
1095
1096/*
1097Retrieves the current read position in pcm frames.
1098*/
1100
1101/*
1102Retrieves the length of the file.
1103*/
1105
1106
1107/*
1108Writes raw audio data.
1109
1110Returns the number of bytes actually written. If this differs from bytesToWrite, it indicates an error.
1111*/
1112DRWAV_API size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData);
1113
1114/*
1115Writes PCM frames.
1116
1117Returns the number of PCM frames written.
1118
1119Input samples need to be in native-endian byte order. On big-endian architectures the input data will be converted to
1120little-endian. Use drwav_write_raw() to write raw audio data without performing any conversion.
1121*/
1122DRWAV_API drwav_uint64 drwav_write_pcm_frames(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
1123DRWAV_API drwav_uint64 drwav_write_pcm_frames_le(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
1124DRWAV_API drwav_uint64 drwav_write_pcm_frames_be(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
1125
1126/* Conversion Utilities */
1127#ifndef DR_WAV_NO_CONVERSION_API
1128
1129/*
1130Reads a chunk of audio data and converts it to signed 16-bit PCM samples.
1131
1132pBufferOut can be NULL in which case a seek will be performed.
1133
1134Returns the number of PCM frames actually read.
1135
1136If the return value is less than <framesToRead> it means the end of the file has been reached.
1137*/
1141
1142/* Low-level function for converting unsigned 8-bit PCM samples to signed 16-bit PCM samples. */
1143DRWAV_API void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
1144
1145/* Low-level function for converting signed 24-bit PCM samples to signed 16-bit PCM samples. */
1146DRWAV_API void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
1147
1148/* Low-level function for converting signed 32-bit PCM samples to signed 16-bit PCM samples. */
1149DRWAV_API void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCount);
1150
1151/* Low-level function for converting IEEE 32-bit floating point samples to signed 16-bit PCM samples. */
1152DRWAV_API void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount);
1153
1154/* Low-level function for converting IEEE 64-bit floating point samples to signed 16-bit PCM samples. */
1155DRWAV_API void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount);
1156
1157/* Low-level function for converting A-law samples to signed 16-bit PCM samples. */
1158DRWAV_API void drwav_alaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
1159
1160/* Low-level function for converting u-law samples to signed 16-bit PCM samples. */
1161DRWAV_API void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
1162
1163
1164/*
1165Reads a chunk of audio data and converts it to IEEE 32-bit floating point samples.
1166
1167pBufferOut can be NULL in which case a seek will be performed.
1168
1169Returns the number of PCM frames actually read.
1170
1171If the return value is less than <framesToRead> it means the end of the file has been reached.
1172*/
1176
1177/* Low-level function for converting unsigned 8-bit PCM samples to IEEE 32-bit floating point samples. */
1178DRWAV_API void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
1179
1180/* Low-level function for converting signed 16-bit PCM samples to IEEE 32-bit floating point samples. */
1181DRWAV_API void drwav_s16_to_f32(float* pOut, const drwav_int16* pIn, size_t sampleCount);
1182
1183/* Low-level function for converting signed 24-bit PCM samples to IEEE 32-bit floating point samples. */
1184DRWAV_API void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
1185
1186/* Low-level function for converting signed 32-bit PCM samples to IEEE 32-bit floating point samples. */
1187DRWAV_API void drwav_s32_to_f32(float* pOut, const drwav_int32* pIn, size_t sampleCount);
1188
1189/* Low-level function for converting IEEE 64-bit floating point samples to IEEE 32-bit floating point samples. */
1190DRWAV_API void drwav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount);
1191
1192/* Low-level function for converting A-law samples to IEEE 32-bit floating point samples. */
1193DRWAV_API void drwav_alaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
1194
1195/* Low-level function for converting u-law samples to IEEE 32-bit floating point samples. */
1196DRWAV_API void drwav_mulaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
1197
1198
1199/*
1200Reads a chunk of audio data and converts it to signed 32-bit PCM samples.
1201
1202pBufferOut can be NULL in which case a seek will be performed.
1203
1204Returns the number of PCM frames actually read.
1205
1206If the return value is less than <framesToRead> it means the end of the file has been reached.
1207*/
1211
1212/* Low-level function for converting unsigned 8-bit PCM samples to signed 32-bit PCM samples. */
1213DRWAV_API void drwav_u8_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
1214
1215/* Low-level function for converting signed 16-bit PCM samples to signed 32-bit PCM samples. */
1216DRWAV_API void drwav_s16_to_s32(drwav_int32* pOut, const drwav_int16* pIn, size_t sampleCount);
1217
1218/* Low-level function for converting signed 24-bit PCM samples to signed 32-bit PCM samples. */
1219DRWAV_API void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
1220
1221/* Low-level function for converting IEEE 32-bit floating point samples to signed 32-bit PCM samples. */
1222DRWAV_API void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t sampleCount);
1223
1224/* Low-level function for converting IEEE 64-bit floating point samples to signed 32-bit PCM samples. */
1225DRWAV_API void drwav_f64_to_s32(drwav_int32* pOut, const double* pIn, size_t sampleCount);
1226
1227/* Low-level function for converting A-law samples to signed 32-bit PCM samples. */
1228DRWAV_API void drwav_alaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
1229
1230/* Low-level function for converting u-law samples to signed 32-bit PCM samples. */
1231DRWAV_API void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
1232
1233#endif /* DR_WAV_NO_CONVERSION_API */
1234
1235
1236/* High-Level Convenience Helpers */
1237
1238#ifndef DR_WAV_NO_STDIO
1239/*
1240Helper for initializing a wave file for reading using stdio.
1241
1242This holds the internal FILE object until drwav_uninit() is called. Keep this in mind if you're caching drwav
1243objects because the operating system may restrict the number of file handles an application can have open at
1244any given time.
1245*/
1246DRWAV_API drwav_bool32 drwav_init_file(drwav* pWav, const char* filename, const drwav_allocation_callbacks* pAllocationCallbacks);
1247DRWAV_API drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
1248DRWAV_API drwav_bool32 drwav_init_file_w(drwav* pWav, const wchar_t* filename, const drwav_allocation_callbacks* pAllocationCallbacks);
1249DRWAV_API drwav_bool32 drwav_init_file_ex_w(drwav* pWav, const wchar_t* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
1250DRWAV_API drwav_bool32 drwav_init_file_with_metadata(drwav* pWav, const char* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
1251DRWAV_API drwav_bool32 drwav_init_file_with_metadata_w(drwav* pWav, const wchar_t* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
1252
1253
1254/*
1255Helper for initializing a wave file for writing using stdio.
1256
1257This holds the internal FILE object until drwav_uninit() is called. Keep this in mind if you're caching drwav
1258objects because the operating system may restrict the number of file handles an application can have open at
1259any given time.
1260*/
1261DRWAV_API drwav_bool32 drwav_init_file_write(drwav* pWav, const char* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks);
1262DRWAV_API drwav_bool32 drwav_init_file_write_sequential(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks);
1263DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks);
1264DRWAV_API drwav_bool32 drwav_init_file_write_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks);
1265DRWAV_API drwav_bool32 drwav_init_file_write_sequential_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks);
1266DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks);
1267#endif /* DR_WAV_NO_STDIO */
1268
1269/*
1270Helper for initializing a loader from a pre-allocated memory buffer.
1271
1272This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for
1273the lifetime of the drwav object.
1274
1275The buffer should contain the contents of the entire wave file, not just the sample data.
1276*/
1277DRWAV_API drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize, const drwav_allocation_callbacks* pAllocationCallbacks);
1278DRWAV_API drwav_bool32 drwav_init_memory_ex(drwav* pWav, const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
1279DRWAV_API drwav_bool32 drwav_init_memory_with_metadata(drwav* pWav, const void* data, size_t dataSize, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
1280
1281/*
1282Helper for initializing a writer which outputs data to a memory buffer.
1283
1284dr_wav will manage the memory allocations, however it is up to the caller to free the data with drwav_free().
1285
1286The buffer will remain allocated even after drwav_uninit() is called. The buffer should not be considered valid
1287until after drwav_uninit() has been called.
1288*/
1289DRWAV_API drwav_bool32 drwav_init_memory_write(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks);
1290DRWAV_API drwav_bool32 drwav_init_memory_write_sequential(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks);
1291DRWAV_API drwav_bool32 drwav_init_memory_write_sequential_pcm_frames(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks);
1292
1293
1294#ifndef DR_WAV_NO_CONVERSION_API
1295/*
1296Opens and reads an entire wav file in a single operation.
1297
1298The return value is a heap-allocated buffer containing the audio data. Use drwav_free() to free the buffer.
1299*/
1300DRWAV_API drwav_int16* drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
1301DRWAV_API float* drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
1302DRWAV_API drwav_int32* drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
1303#ifndef DR_WAV_NO_STDIO
1304/*
1305Opens and decodes an entire wav file in a single operation.
1306
1307The return value is a heap-allocated buffer containing the audio data. Use drwav_free() to free the buffer.
1308*/
1309DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
1310DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
1311DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
1312DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
1313DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
1314DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
1315#endif
1316/*
1317Opens and decodes an entire wav file from a block of memory in a single operation.
1318
1319The return value is a heap-allocated buffer containing the audio data. Use drwav_free() to free the buffer.
1320*/
1321DRWAV_API 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, const drwav_allocation_callbacks* pAllocationCallbacks);
1322DRWAV_API float* drwav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
1323DRWAV_API 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, const drwav_allocation_callbacks* pAllocationCallbacks);
1324#endif
1325
1326/* Frees data that was allocated internally by dr_wav. */
1327DRWAV_API void drwav_free(void* p, const drwav_allocation_callbacks* pAllocationCallbacks);
1328
1329/* Converts bytes from a wav stream to a sized type of native endian. */
1337
1338/* Compares a GUID for the purpose of checking the type of a Wave64 chunk. */
1340
1341/* Compares a four-character-code for the purpose of checking the type of a RIFF chunk. */
1343
1344#ifdef __cplusplus
1345}
1346#endif
1347#endif /* dr_wav_h */
1348
1349
1350/************************************************************************************************************************************************************
1351 ************************************************************************************************************************************************************
1352
1353 IMPLEMENTATION
1354
1355 ************************************************************************************************************************************************************
1356 ************************************************************************************************************************************************************/
1357#if defined(DR_WAV_IMPLEMENTATION) || defined(DRWAV_IMPLEMENTATION)
1358#ifndef dr_wav_c
1359#define dr_wav_c
1360
1361#ifdef __MRC__
1362/* MrC currently doesn't compile dr_wav correctly with any optimizations enabled. */
1363#pragma options opt off
1364#endif
1365
1366#include <stdlib.h>
1367#include <string.h>
1368#include <limits.h> /* For INT_MAX */
1369
1370#ifndef DR_WAV_NO_STDIO
1371#include <stdio.h>
1372#ifndef DR_WAV_NO_WCHAR
1373#include <wchar.h>
1374#endif
1375#endif
1376
1377/* Standard library stuff. */
1378#ifndef DRWAV_ASSERT
1379#include <assert.h>
1380#define DRWAV_ASSERT(expression) assert(expression)
1381#endif
1382#ifndef DRWAV_MALLOC
1383#define DRWAV_MALLOC(sz) malloc((sz))
1384#endif
1385#ifndef DRWAV_REALLOC
1386#define DRWAV_REALLOC(p, sz) realloc((p), (sz))
1387#endif
1388#ifndef DRWAV_FREE
1389#define DRWAV_FREE(p) free((p))
1390#endif
1391#ifndef DRWAV_COPY_MEMORY
1392#define DRWAV_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
1393#endif
1394#ifndef DRWAV_ZERO_MEMORY
1395#define DRWAV_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
1396#endif
1397#ifndef DRWAV_ZERO_OBJECT
1398#define DRWAV_ZERO_OBJECT(p) DRWAV_ZERO_MEMORY((p), sizeof(*p))
1399#endif
1400
1401#define drwav_countof(x) (sizeof(x) / sizeof(x[0]))
1402#define drwav_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
1403#define drwav_min(a, b) (((a) < (b)) ? (a) : (b))
1404#define drwav_max(a, b) (((a) > (b)) ? (a) : (b))
1405#define drwav_clamp(x, lo, hi) (drwav_max((lo), drwav_min((hi), (x))))
1406#define drwav_offset_ptr(p, offset) (((drwav_uint8*)(p)) + (offset))
1407
1408#define DRWAV_MAX_SIMD_VECTOR_SIZE 32
1409
1410/* Architecture Detection */
1411#if defined(__x86_64__) || (defined(_M_X64) && !defined(_M_ARM64EC))
1412 #define DRWAV_X64
1413#elif defined(__i386) || defined(_M_IX86)
1414 #define DRWAV_X86
1415#elif defined(__arm__) || defined(_M_ARM)
1416 #define DRWAV_ARM
1417#endif
1418/* End Architecture Detection */
1419
1420/* Inline */
1421#ifdef _MSC_VER
1422 #define DRWAV_INLINE __forceinline
1423#elif defined(__GNUC__)
1424 /*
1425 I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when
1426 the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some
1427 case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the
1428 command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue
1429 I am using "__inline__" only when we're compiling in strict ANSI mode.
1430 */
1431 #if defined(__STRICT_ANSI__)
1432 #define DRWAV_GNUC_INLINE_HINT __inline__
1433 #else
1434 #define DRWAV_GNUC_INLINE_HINT inline
1435 #endif
1436
1437 #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
1438 #define DRWAV_INLINE DRWAV_GNUC_INLINE_HINT __attribute__((always_inline))
1439 #else
1440 #define DRWAV_INLINE DRWAV_GNUC_INLINE_HINT
1441 #endif
1442#elif defined(__WATCOMC__)
1443 #define DRWAV_INLINE __inline
1444#else
1445 #define DRWAV_INLINE
1446#endif
1447/* End Inline */
1448
1449/* SIZE_MAX */
1450#if defined(SIZE_MAX)
1451 #define DRWAV_SIZE_MAX SIZE_MAX
1452#else
1453 #if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
1454 #define DRWAV_SIZE_MAX ((drwav_uint64)0xFFFFFFFFFFFFFFFF)
1455 #else
1456 #define DRWAV_SIZE_MAX 0xFFFFFFFF
1457 #endif
1458#endif
1459/* End SIZE_MAX */
1460
1461/* Weird bit manipulation is for C89 compatibility (no direct support for 64-bit integers). */
1462#define DRWAV_INT64_MIN ((drwav_int64) ((drwav_uint64)0x80000000 << 32))
1463#define DRWAV_INT64_MAX ((drwav_int64)(((drwav_uint64)0x7FFFFFFF << 32) | 0xFFFFFFFF))
1464
1465#if defined(_MSC_VER) && _MSC_VER >= 1400
1466 #define DRWAV_HAS_BYTESWAP16_INTRINSIC
1467 #define DRWAV_HAS_BYTESWAP32_INTRINSIC
1468 #define DRWAV_HAS_BYTESWAP64_INTRINSIC
1469#elif defined(__clang__)
1470 #if defined(__has_builtin)
1471 #if __has_builtin(__builtin_bswap16)
1472 #define DRWAV_HAS_BYTESWAP16_INTRINSIC
1473 #endif
1474 #if __has_builtin(__builtin_bswap32)
1475 #define DRWAV_HAS_BYTESWAP32_INTRINSIC
1476 #endif
1477 #if __has_builtin(__builtin_bswap64)
1478 #define DRWAV_HAS_BYTESWAP64_INTRINSIC
1479 #endif
1480 #endif
1481#elif defined(__GNUC__)
1482 #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
1483 #define DRWAV_HAS_BYTESWAP32_INTRINSIC
1484 #define DRWAV_HAS_BYTESWAP64_INTRINSIC
1485 #endif
1486 #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
1487 #define DRWAV_HAS_BYTESWAP16_INTRINSIC
1488 #endif
1489#endif
1490
1491DRWAV_API void drwav_version(drwav_uint32* pMajor, drwav_uint32* pMinor, drwav_uint32* pRevision)
1492{
1493 if (pMajor) {
1494 *pMajor = DRWAV_VERSION_MAJOR;
1495 }
1496
1497 if (pMinor) {
1498 *pMinor = DRWAV_VERSION_MINOR;
1499 }
1500
1501 if (pRevision) {
1502 *pRevision = DRWAV_VERSION_REVISION;
1503 }
1504}
1505
1506DRWAV_API const char* drwav_version_string(void)
1507{
1508 return DRWAV_VERSION_STRING;
1509}
1510
1511/*
1512These limits are used for basic validation when initializing the decoder. If you exceed these limits, first of all: what on Earth are
1513you doing?! (Let me know, I'd be curious!) Second, you can adjust these by #define-ing them before the dr_wav implementation.
1514*/
1515#ifndef DRWAV_MAX_SAMPLE_RATE
1516#define DRWAV_MAX_SAMPLE_RATE 384000
1517#endif
1518#ifndef DRWAV_MAX_CHANNELS
1519#define DRWAV_MAX_CHANNELS 256
1520#endif
1521#ifndef DRWAV_MAX_BITS_PER_SAMPLE
1522#define DRWAV_MAX_BITS_PER_SAMPLE 64
1523#endif
1524
1525static 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 */
1526static 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 */
1527/*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 */
1528static 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 */
1529static 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 */
1530static 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 */
1531/*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 */
1532
1533
1534static DRWAV_INLINE int drwav__is_little_endian(void)
1535{
1536#if defined(DRWAV_X86) || defined(DRWAV_X64)
1537 return DRWAV_TRUE;
1538#elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
1539 return DRWAV_TRUE;
1540#else
1541 int n = 1;
1542 return (*(char*)&n) == 1;
1543#endif
1544}
1545
1546
1547static DRWAV_INLINE void drwav_bytes_to_guid(const drwav_uint8* data, drwav_uint8* guid)
1548{
1549 int i;
1550 for (i = 0; i < 16; ++i) {
1551 guid[i] = data[i];
1552 }
1553}
1554
1555
1556static DRWAV_INLINE drwav_uint16 drwav__bswap16(drwav_uint16 n)
1557{
1558#ifdef DRWAV_HAS_BYTESWAP16_INTRINSIC
1559 #if defined(_MSC_VER)
1560 return _byteswap_ushort(n);
1561 #elif defined(__GNUC__) || defined(__clang__)
1562 return __builtin_bswap16(n);
1563 #else
1564 #error "This compiler does not support the byte swap intrinsic."
1565 #endif
1566#else
1567 return ((n & 0xFF00) >> 8) |
1568 ((n & 0x00FF) << 8);
1569#endif
1570}
1571
1572static DRWAV_INLINE drwav_uint32 drwav__bswap32(drwav_uint32 n)
1573{
1574#ifdef DRWAV_HAS_BYTESWAP32_INTRINSIC
1575 #if defined(_MSC_VER)
1576 return _byteswap_ulong(n);
1577 #elif defined(__GNUC__) || defined(__clang__)
1578 #if defined(DRWAV_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(DRWAV_64BIT) /* <-- 64-bit inline assembly has not been tested, so disabling for now. */
1579 /* Inline assembly optimized implementation for ARM. In my testing, GCC does not generate optimized code with __builtin_bswap32(). */
1580 drwav_uint32 r;
1581 __asm__ __volatile__ (
1582 #if defined(DRWAV_64BIT)
1583 "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n) /* <-- This is untested. If someone in the community could test this, that would be appreciated! */
1584 #else
1585 "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
1586 #endif
1587 );
1588 return r;
1589 #else
1590 return __builtin_bswap32(n);
1591 #endif
1592 #else
1593 #error "This compiler does not support the byte swap intrinsic."
1594 #endif
1595#else
1596 return ((n & 0xFF000000) >> 24) |
1597 ((n & 0x00FF0000) >> 8) |
1598 ((n & 0x0000FF00) << 8) |
1599 ((n & 0x000000FF) << 24);
1600#endif
1601}
1602
1603static DRWAV_INLINE drwav_uint64 drwav__bswap64(drwav_uint64 n)
1604{
1605#ifdef DRWAV_HAS_BYTESWAP64_INTRINSIC
1606 #if defined(_MSC_VER)
1607 return _byteswap_uint64(n);
1608 #elif defined(__GNUC__) || defined(__clang__)
1609 return __builtin_bswap64(n);
1610 #else
1611 #error "This compiler does not support the byte swap intrinsic."
1612 #endif
1613#else
1614 /* Weird "<< 32" bitshift is required for C89 because it doesn't support 64-bit constants. Should be optimized out by a good compiler. */
1615 return ((n & ((drwav_uint64)0xFF000000 << 32)) >> 56) |
1616 ((n & ((drwav_uint64)0x00FF0000 << 32)) >> 40) |
1617 ((n & ((drwav_uint64)0x0000FF00 << 32)) >> 24) |
1618 ((n & ((drwav_uint64)0x000000FF << 32)) >> 8) |
1619 ((n & ((drwav_uint64)0xFF000000 )) << 8) |
1620 ((n & ((drwav_uint64)0x00FF0000 )) << 24) |
1621 ((n & ((drwav_uint64)0x0000FF00 )) << 40) |
1622 ((n & ((drwav_uint64)0x000000FF )) << 56);
1623#endif
1624}
1625
1626
1627static DRWAV_INLINE drwav_int16 drwav__bswap_s16(drwav_int16 n)
1628{
1629 return (drwav_int16)drwav__bswap16((drwav_uint16)n);
1630}
1631
1632static DRWAV_INLINE void drwav__bswap_samples_s16(drwav_int16* pSamples, drwav_uint64 sampleCount)
1633{
1634 drwav_uint64 iSample;
1635 for (iSample = 0; iSample < sampleCount; iSample += 1) {
1636 pSamples[iSample] = drwav__bswap_s16(pSamples[iSample]);
1637 }
1638}
1639
1640
1641static DRWAV_INLINE void drwav__bswap_s24(drwav_uint8* p)
1642{
1643 drwav_uint8 t;
1644 t = p[0];
1645 p[0] = p[2];
1646 p[2] = t;
1647}
1648
1649static DRWAV_INLINE void drwav__bswap_samples_s24(drwav_uint8* pSamples, drwav_uint64 sampleCount)
1650{
1651 drwav_uint64 iSample;
1652 for (iSample = 0; iSample < sampleCount; iSample += 1) {
1653 drwav_uint8* pSample = pSamples + (iSample*3);
1654 drwav__bswap_s24(pSample);
1655 }
1656}
1657
1658
1659static DRWAV_INLINE drwav_int32 drwav__bswap_s32(drwav_int32 n)
1660{
1661 return (drwav_int32)drwav__bswap32((drwav_uint32)n);
1662}
1663
1664static DRWAV_INLINE void drwav__bswap_samples_s32(drwav_int32* pSamples, drwav_uint64 sampleCount)
1665{
1666 drwav_uint64 iSample;
1667 for (iSample = 0; iSample < sampleCount; iSample += 1) {
1668 pSamples[iSample] = drwav__bswap_s32(pSamples[iSample]);
1669 }
1670}
1671
1672
1673static DRWAV_INLINE drwav_int64 drwav__bswap_s64(drwav_int64 n)
1674{
1675 return (drwav_int64)drwav__bswap64((drwav_uint64)n);
1676}
1677
1678static DRWAV_INLINE void drwav__bswap_samples_s64(drwav_int64* pSamples, drwav_uint64 sampleCount)
1679{
1680 drwav_uint64 iSample;
1681 for (iSample = 0; iSample < sampleCount; iSample += 1) {
1682 pSamples[iSample] = drwav__bswap_s64(pSamples[iSample]);
1683 }
1684}
1685
1686
1687static DRWAV_INLINE float drwav__bswap_f32(float n)
1688{
1689 union {
1690 drwav_uint32 i;
1691 float f;
1692 } x;
1693 x.f = n;
1694 x.i = drwav__bswap32(x.i);
1695
1696 return x.f;
1697}
1698
1699static DRWAV_INLINE void drwav__bswap_samples_f32(float* pSamples, drwav_uint64 sampleCount)
1700{
1701 drwav_uint64 iSample;
1702 for (iSample = 0; iSample < sampleCount; iSample += 1) {
1703 pSamples[iSample] = drwav__bswap_f32(pSamples[iSample]);
1704 }
1705}
1706
1707
1708static DRWAV_INLINE void drwav__bswap_samples(void* pSamples, drwav_uint64 sampleCount, drwav_uint32 bytesPerSample)
1709{
1710 switch (bytesPerSample)
1711 {
1712 case 1:
1713 {
1714 /* No-op. */
1715 } break;
1716 case 2:
1717 {
1718 drwav__bswap_samples_s16((drwav_int16*)pSamples, sampleCount);
1719 } break;
1720 case 3:
1721 {
1722 drwav__bswap_samples_s24((drwav_uint8*)pSamples, sampleCount);
1723 } break;
1724 case 4:
1725 {
1726 drwav__bswap_samples_s32((drwav_int32*)pSamples, sampleCount);
1727 } break;
1728 case 8:
1729 {
1730 drwav__bswap_samples_s64((drwav_int64*)pSamples, sampleCount);
1731 } break;
1732 default:
1733 {
1734 /* Unsupported format. */
1735 DRWAV_ASSERT(DRWAV_FALSE);
1736 } break;
1737 }
1738}
1739
1740
1741
1742DRWAV_PRIVATE DRWAV_INLINE drwav_bool32 drwav_is_container_be(drwav_container container)
1743{
1744 if (container == drwav_container_rifx || container == drwav_container_aiff) {
1745 return DRWAV_TRUE;
1746 } else {
1747 return DRWAV_FALSE;
1748 }
1749}
1750
1751
1752DRWAV_PRIVATE DRWAV_INLINE drwav_uint16 drwav_bytes_to_u16_le(const drwav_uint8* data)
1753{
1754 return ((drwav_uint16)data[0] << 0) | ((drwav_uint16)data[1] << 8);
1755}
1756
1757DRWAV_PRIVATE DRWAV_INLINE drwav_uint16 drwav_bytes_to_u16_be(const drwav_uint8* data)
1758{
1759 return ((drwav_uint16)data[1] << 0) | ((drwav_uint16)data[0] << 8);
1760}
1761
1762DRWAV_PRIVATE DRWAV_INLINE drwav_uint16 drwav_bytes_to_u16_ex(const drwav_uint8* data, drwav_container container)
1763{
1764 if (drwav_is_container_be(container)) {
1765 return drwav_bytes_to_u16_be(data);
1766 } else {
1767 return drwav_bytes_to_u16_le(data);
1768 }
1769}
1770
1771
1772DRWAV_PRIVATE DRWAV_INLINE drwav_uint32 drwav_bytes_to_u32_le(const drwav_uint8* data)
1773{
1774 return ((drwav_uint32)data[0] << 0) | ((drwav_uint32)data[1] << 8) | ((drwav_uint32)data[2] << 16) | ((drwav_uint32)data[3] << 24);
1775}
1776
1777DRWAV_PRIVATE DRWAV_INLINE drwav_uint32 drwav_bytes_to_u32_be(const drwav_uint8* data)
1778{
1779 return ((drwav_uint32)data[3] << 0) | ((drwav_uint32)data[2] << 8) | ((drwav_uint32)data[1] << 16) | ((drwav_uint32)data[0] << 24);
1780}
1781
1782DRWAV_PRIVATE DRWAV_INLINE drwav_uint32 drwav_bytes_to_u32_ex(const drwav_uint8* data, drwav_container container)
1783{
1784 if (drwav_is_container_be(container)) {
1785 return drwav_bytes_to_u32_be(data);
1786 } else {
1787 return drwav_bytes_to_u32_le(data);
1788 }
1789}
1790
1791
1792
1793DRWAV_PRIVATE drwav_int64 drwav_aiff_extented_to_s64(const drwav_uint8* data)
1794{
1795 drwav_uint32 exponent = ((drwav_uint32)data[0] << 8) | data[1];
1796 drwav_uint64 hi = ((drwav_uint64)data[2] << 24) | ((drwav_uint64)data[3] << 16) | ((drwav_uint64)data[4] << 8) | ((drwav_uint64)data[5] << 0);
1797 drwav_uint64 lo = ((drwav_uint64)data[6] << 24) | ((drwav_uint64)data[7] << 16) | ((drwav_uint64)data[8] << 8) | ((drwav_uint64)data[9] << 0);
1798 drwav_uint64 significand = (hi << 32) | lo;
1799 int sign = exponent >> 15;
1800
1801 /* Remove sign bit. */
1802 exponent &= 0x7FFF;
1803
1804 /* Special cases. */
1805 if (exponent == 0 && significand == 0) {
1806 return 0;
1807 } else if (exponent == 0x7FFF) {
1808 return sign ? DRWAV_INT64_MIN : DRWAV_INT64_MAX; /* Infinite. */
1809 }
1810
1811 exponent -= 16383;
1812
1813 if (exponent > 63) {
1814 return sign ? DRWAV_INT64_MIN : DRWAV_INT64_MAX; /* Too big for a 64-bit integer. */
1815 } else if (exponent < 1) {
1816 return 0; /* Number is less than 1, so rounds down to 0. */
1817 }
1818
1819 significand >>= (63 - exponent);
1820
1821 if (sign) {
1822 return -(drwav_int64)significand;
1823 } else {
1824 return (drwav_int64)significand;
1825 }
1826}
1827
1828
1829DRWAV_PRIVATE void* drwav__malloc_default(size_t sz, void* pUserData)
1830{
1831 (void)pUserData;
1832 return DRWAV_MALLOC(sz);
1833}
1834
1835DRWAV_PRIVATE void* drwav__realloc_default(void* p, size_t sz, void* pUserData)
1836{
1837 (void)pUserData;
1838 return DRWAV_REALLOC(p, sz);
1839}
1840
1841DRWAV_PRIVATE void drwav__free_default(void* p, void* pUserData)
1842{
1843 (void)pUserData;
1844 DRWAV_FREE(p);
1845}
1846
1847
1848DRWAV_PRIVATE void* drwav__malloc_from_callbacks(size_t sz, const drwav_allocation_callbacks* pAllocationCallbacks)
1849{
1850 if (pAllocationCallbacks == NULL) {
1851 return NULL;
1852 }
1853
1854 if (pAllocationCallbacks->onMalloc != NULL) {
1855 return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
1856 }
1857
1858 /* Try using realloc(). */
1859 if (pAllocationCallbacks->onRealloc != NULL) {
1860 return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
1861 }
1862
1863 return NULL;
1864}
1865
1866DRWAV_PRIVATE void* drwav__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drwav_allocation_callbacks* pAllocationCallbacks)
1867{
1868 if (pAllocationCallbacks == NULL) {
1869 return NULL;
1870 }
1871
1872 if (pAllocationCallbacks->onRealloc != NULL) {
1873 return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
1874 }
1875
1876 /* Try emulating realloc() in terms of malloc()/free(). */
1877 if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
1878 void* p2;
1879
1880 p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
1881 if (p2 == NULL) {
1882 return NULL;
1883 }
1884
1885 if (p != NULL) {
1886 DRWAV_COPY_MEMORY(p2, p, szOld);
1887 pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
1888 }
1889
1890 return p2;
1891 }
1892
1893 return NULL;
1894}
1895
1896DRWAV_PRIVATE void drwav__free_from_callbacks(void* p, const drwav_allocation_callbacks* pAllocationCallbacks)
1897{
1898 if (p == NULL || pAllocationCallbacks == NULL) {
1899 return;
1900 }
1901
1902 if (pAllocationCallbacks->onFree != NULL) {
1903 pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
1904 }
1905}
1906
1907
1908DRWAV_PRIVATE drwav_allocation_callbacks drwav_copy_allocation_callbacks_or_defaults(const drwav_allocation_callbacks* pAllocationCallbacks)
1909{
1910 if (pAllocationCallbacks != NULL) {
1911 /* Copy. */
1912 return *pAllocationCallbacks;
1913 } else {
1914 /* Defaults. */
1915 drwav_allocation_callbacks allocationCallbacks;
1916 allocationCallbacks.pUserData = NULL;
1917 allocationCallbacks.onMalloc = drwav__malloc_default;
1918 allocationCallbacks.onRealloc = drwav__realloc_default;
1919 allocationCallbacks.onFree = drwav__free_default;
1920 return allocationCallbacks;
1921 }
1922}
1923
1924
1925static DRWAV_INLINE drwav_bool32 drwav__is_compressed_format_tag(drwav_uint16 formatTag)
1926{
1927 return
1928 formatTag == DR_WAVE_FORMAT_ADPCM ||
1929 formatTag == DR_WAVE_FORMAT_DVI_ADPCM;
1930}
1931
1932DRWAV_PRIVATE unsigned int drwav__chunk_padding_size_riff(drwav_uint64 chunkSize)
1933{
1934 return (unsigned int)(chunkSize % 2);
1935}
1936
1937DRWAV_PRIVATE unsigned int drwav__chunk_padding_size_w64(drwav_uint64 chunkSize)
1938{
1939 return (unsigned int)(chunkSize % 8);
1940}
1941
1942DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut);
1943DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut);
1944DRWAV_PRIVATE drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount);
1945
1946DRWAV_PRIVATE drwav_result drwav__read_chunk_header(drwav_read_proc onRead, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav_chunk_header* pHeaderOut)
1947{
1948 if (container == drwav_container_riff || container == drwav_container_rifx || container == drwav_container_rf64 || container == drwav_container_aiff) {
1949 drwav_uint8 sizeInBytes[4];
1950
1951 if (onRead(pUserData, pHeaderOut->id.fourcc, 4) != 4) {
1952 return DRWAV_AT_END;
1953 }
1954
1955 if (onRead(pUserData, sizeInBytes, 4) != 4) {
1956 return DRWAV_INVALID_FILE;
1957 }
1958
1959 pHeaderOut->sizeInBytes = drwav_bytes_to_u32_ex(sizeInBytes, container);
1960 pHeaderOut->paddingSize = drwav__chunk_padding_size_riff(pHeaderOut->sizeInBytes);
1961
1962 *pRunningBytesReadOut += 8;
1963 } else if (container == drwav_container_w64) {
1964 drwav_uint8 sizeInBytes[8];
1965
1966 if (onRead(pUserData, pHeaderOut->id.guid, 16) != 16) {
1967 return DRWAV_AT_END;
1968 }
1969
1970 if (onRead(pUserData, sizeInBytes, 8) != 8) {
1971 return DRWAV_INVALID_FILE;
1972 }
1973
1974 pHeaderOut->sizeInBytes = drwav_bytes_to_u64(sizeInBytes) - 24; /* <-- Subtract 24 because w64 includes the size of the header. */
1975 pHeaderOut->paddingSize = drwav__chunk_padding_size_w64(pHeaderOut->sizeInBytes);
1976 *pRunningBytesReadOut += 24;
1977 } else {
1978 return DRWAV_INVALID_FILE;
1979 }
1980
1981 return DRWAV_SUCCESS;
1982}
1983
1984DRWAV_PRIVATE drwav_bool32 drwav__seek_forward(drwav_seek_proc onSeek, drwav_uint64 offset, void* pUserData)
1985{
1986 drwav_uint64 bytesRemainingToSeek = offset;
1987 while (bytesRemainingToSeek > 0) {
1988 if (bytesRemainingToSeek > 0x7FFFFFFF) {
1989 if (!onSeek(pUserData, 0x7FFFFFFF, DRWAV_SEEK_CUR)) {
1990 return DRWAV_FALSE;
1991 }
1992 bytesRemainingToSeek -= 0x7FFFFFFF;
1993 } else {
1994 if (!onSeek(pUserData, (int)bytesRemainingToSeek, DRWAV_SEEK_CUR)) {
1995 return DRWAV_FALSE;
1996 }
1997 bytesRemainingToSeek = 0;
1998 }
1999 }
2000
2001 return DRWAV_TRUE;
2002}
2003
2004DRWAV_PRIVATE drwav_bool32 drwav__seek_from_start(drwav_seek_proc onSeek, drwav_uint64 offset, void* pUserData)
2005{
2006 if (offset <= 0x7FFFFFFF) {
2007 return onSeek(pUserData, (int)offset, DRWAV_SEEK_SET);
2008 }
2009
2010 /* Larger than 32-bit seek. */
2011 if (!onSeek(pUserData, 0x7FFFFFFF, DRWAV_SEEK_SET)) {
2012 return DRWAV_FALSE;
2013 }
2014 offset -= 0x7FFFFFFF;
2015
2016 for (;;) {
2017 if (offset <= 0x7FFFFFFF) {
2018 return onSeek(pUserData, (int)offset, DRWAV_SEEK_CUR);
2019 }
2020
2021 if (!onSeek(pUserData, 0x7FFFFFFF, DRWAV_SEEK_CUR)) {
2022 return DRWAV_FALSE;
2023 }
2024 offset -= 0x7FFFFFFF;
2025 }
2026
2027 /* Should never get here. */
2028 /*return DRWAV_TRUE; */
2029}
2030
2031
2032
2033DRWAV_PRIVATE size_t drwav__on_read(drwav_read_proc onRead, void* pUserData, void* pBufferOut, size_t bytesToRead, drwav_uint64* pCursor)
2034{
2035 size_t bytesRead;
2036
2037 DRWAV_ASSERT(onRead != NULL);
2038 DRWAV_ASSERT(pCursor != NULL);
2039
2040 bytesRead = onRead(pUserData, pBufferOut, bytesToRead);
2041 *pCursor += bytesRead;
2042 return bytesRead;
2043}
2044
2045#if 0
2046DRWAV_PRIVATE drwav_bool32 drwav__on_seek(drwav_seek_proc onSeek, void* pUserData, int offset, drwav_seek_origin origin, drwav_uint64* pCursor)
2047{
2048 DRWAV_ASSERT(onSeek != NULL);
2049 DRWAV_ASSERT(pCursor != NULL);
2050
2051 if (!onSeek(pUserData, offset, origin)) {
2052 return DRWAV_FALSE;
2053 }
2054
2055 if (origin == DRWAV_SEEK_SET) {
2056 *pCursor = offset;
2057 } else {
2058 *pCursor += offset;
2059 }
2060
2061 return DRWAV_TRUE;
2062}
2063#endif
2064
2065
2066#define DRWAV_SMPL_BYTES 36
2067#define DRWAV_SMPL_LOOP_BYTES 24
2068#define DRWAV_INST_BYTES 7
2069#define DRWAV_ACID_BYTES 24
2070#define DRWAV_CUE_BYTES 4
2071#define DRWAV_BEXT_BYTES 602
2072#define DRWAV_BEXT_DESCRIPTION_BYTES 256
2073#define DRWAV_BEXT_ORIGINATOR_NAME_BYTES 32
2074#define DRWAV_BEXT_ORIGINATOR_REF_BYTES 32
2075#define DRWAV_BEXT_RESERVED_BYTES 180
2076#define DRWAV_BEXT_UMID_BYTES 64
2077#define DRWAV_CUE_POINT_BYTES 24
2078#define DRWAV_LIST_LABEL_OR_NOTE_BYTES 4
2079#define DRWAV_LIST_LABELLED_TEXT_BYTES 20
2080
2081#define DRWAV_METADATA_ALIGNMENT 8
2082
2083typedef enum
2084{
2085 drwav__metadata_parser_stage_count,
2086 drwav__metadata_parser_stage_read
2087} drwav__metadata_parser_stage;
2088
2089typedef struct
2090{
2091 drwav_read_proc onRead;
2092 drwav_seek_proc onSeek;
2093 void *pReadSeekUserData;
2094 drwav__metadata_parser_stage stage;
2095 drwav_metadata *pMetadata;
2096 drwav_uint32 metadataCount;
2097 drwav_uint8 *pData;
2098 drwav_uint8 *pDataCursor;
2099 drwav_uint64 metadataCursor;
2100 drwav_uint64 extraCapacity;
2101} drwav__metadata_parser;
2102
2103DRWAV_PRIVATE size_t drwav__metadata_memory_capacity(drwav__metadata_parser* pParser)
2104{
2105 drwav_uint64 cap = sizeof(drwav_metadata) * (drwav_uint64)pParser->metadataCount + pParser->extraCapacity;
2106 if (cap > DRWAV_SIZE_MAX) {
2107 return 0; /* Too big. */
2108 }
2109
2110 return (size_t)cap; /* Safe cast thanks to the check above. */
2111}
2112
2113DRWAV_PRIVATE drwav_uint8* drwav__metadata_get_memory(drwav__metadata_parser* pParser, size_t size, size_t align)
2114{
2115 drwav_uint8* pResult;
2116
2117 if (align) {
2118 drwav_uintptr modulo = (drwav_uintptr)pParser->pDataCursor % align;
2119 if (modulo != 0) {
2120 pParser->pDataCursor += align - modulo;
2121 }
2122 }
2123
2124 pResult = pParser->pDataCursor;
2125
2126 /*
2127 Getting to the point where this function is called means there should always be memory
2128 available. Out of memory checks should have been done at an earlier stage.
2129 */
2130 DRWAV_ASSERT((pResult + size) <= (pParser->pData + drwav__metadata_memory_capacity(pParser)));
2131
2132 pParser->pDataCursor += size;
2133 return pResult;
2134}
2135
2136DRWAV_PRIVATE void drwav__metadata_request_extra_memory_for_stage_2(drwav__metadata_parser* pParser, size_t bytes, size_t align)
2137{
2138 size_t extra = bytes + (align ? (align - 1) : 0);
2139 pParser->extraCapacity += extra;
2140}
2141
2142DRWAV_PRIVATE drwav_result drwav__metadata_alloc(drwav__metadata_parser* pParser, drwav_allocation_callbacks* pAllocationCallbacks)
2143{
2144 if (pParser->extraCapacity != 0 || pParser->metadataCount != 0) {
2145 pAllocationCallbacks->onFree(pParser->pData, pAllocationCallbacks->pUserData);
2146
2147 pParser->pData = (drwav_uint8*)pAllocationCallbacks->onMalloc(drwav__metadata_memory_capacity(pParser), pAllocationCallbacks->pUserData);
2148 pParser->pDataCursor = pParser->pData;
2149
2150 if (pParser->pData == NULL) {
2151 return DRWAV_OUT_OF_MEMORY;
2152 }
2153
2154 /*
2155 We don't need to worry about specifying an alignment here because malloc always returns something
2156 of suitable alignment. This also means pParser->pMetadata is all that we need to store in order
2157 for us to free when we are done.
2158 */
2159 pParser->pMetadata = (drwav_metadata*)drwav__metadata_get_memory(pParser, sizeof(drwav_metadata) * pParser->metadataCount, 1);
2160 pParser->metadataCursor = 0;
2161 }
2162
2163 return DRWAV_SUCCESS;
2164}
2165
2166DRWAV_PRIVATE size_t drwav__metadata_parser_read(drwav__metadata_parser* pParser, void* pBufferOut, size_t bytesToRead, drwav_uint64* pCursor)
2167{
2168 if (pCursor != NULL) {
2169 return drwav__on_read(pParser->onRead, pParser->pReadSeekUserData, pBufferOut, bytesToRead, pCursor);
2170 } else {
2171 return pParser->onRead(pParser->pReadSeekUserData, pBufferOut, bytesToRead);
2172 }
2173}
2174
2175DRWAV_PRIVATE drwav_uint64 drwav__read_smpl_to_metadata_obj(drwav__metadata_parser* pParser, const drwav_chunk_header* pChunkHeader, drwav_metadata* pMetadata)
2176{
2177 drwav_uint8 smplHeaderData[DRWAV_SMPL_BYTES];
2178 drwav_uint64 totalBytesRead = 0;
2179 size_t bytesJustRead;
2180
2181 if (pMetadata == NULL) {
2182 return 0;
2183 }
2184
2185 bytesJustRead = drwav__metadata_parser_read(pParser, smplHeaderData, sizeof(smplHeaderData), &totalBytesRead);
2186
2187 DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
2188 DRWAV_ASSERT(pChunkHeader != NULL);
2189
2190 if (pMetadata != NULL && bytesJustRead == sizeof(smplHeaderData)) {
2191 drwav_uint32 iSampleLoop;
2192 drwav_uint32 loopCount;
2193 drwav_uint32 calculatedLoopCount;
2194
2195 /*
2196 When we calcualted the amount of memory required for the "smpl" chunk we excluded the chunk entirely
2197 if the loop count in the header did not match with the calculated count based on the size of the
2198 chunk. When this happens, the second stage will still hit this path but the `pMetadata` will be
2199 non-null, but will either be pointing at the very end of the allocation or at the start of another
2200 chunk. We need to check the loop counts for consistency *before* dereferencing the pMetadata object
2201 so it's consistent with how we do it in the first stage.
2202 */
2203 loopCount = drwav_bytes_to_u32(smplHeaderData + 28);
2204 calculatedLoopCount = (pChunkHeader->sizeInBytes - DRWAV_SMPL_BYTES) / DRWAV_SMPL_LOOP_BYTES;
2205 if (loopCount != calculatedLoopCount) {
2206 return totalBytesRead;
2207 }
2208
2209 pMetadata->type = drwav_metadata_type_smpl;
2210 pMetadata->data.smpl.manufacturerId = drwav_bytes_to_u32(smplHeaderData + 0);
2211 pMetadata->data.smpl.productId = drwav_bytes_to_u32(smplHeaderData + 4);
2212 pMetadata->data.smpl.samplePeriodNanoseconds = drwav_bytes_to_u32(smplHeaderData + 8);
2213 pMetadata->data.smpl.midiUnityNote = drwav_bytes_to_u32(smplHeaderData + 12);
2214 pMetadata->data.smpl.midiPitchFraction = drwav_bytes_to_u32(smplHeaderData + 16);
2215 pMetadata->data.smpl.smpteFormat = drwav_bytes_to_u32(smplHeaderData + 20);
2216 pMetadata->data.smpl.smpteOffset = drwav_bytes_to_u32(smplHeaderData + 24);
2217 pMetadata->data.smpl.sampleLoopCount = drwav_bytes_to_u32(smplHeaderData + 28);
2218 pMetadata->data.smpl.samplerSpecificDataSizeInBytes = drwav_bytes_to_u32(smplHeaderData + 32);
2219
2220 /*
2221 The loop count needs to be validated against the size of the chunk for safety so we don't
2222 attempt to read over the boundary of the chunk.
2223 */
2224 if (pMetadata->data.smpl.sampleLoopCount == calculatedLoopCount) {
2225 pMetadata->data.smpl.pLoops = (drwav_smpl_loop*)drwav__metadata_get_memory(pParser, sizeof(drwav_smpl_loop) * pMetadata->data.smpl.sampleLoopCount, DRWAV_METADATA_ALIGNMENT);
2226
2227 for (iSampleLoop = 0; iSampleLoop < pMetadata->data.smpl.sampleLoopCount; ++iSampleLoop) {
2228 drwav_uint8 smplLoopData[DRWAV_SMPL_LOOP_BYTES];
2229 bytesJustRead = drwav__metadata_parser_read(pParser, smplLoopData, sizeof(smplLoopData), &totalBytesRead);
2230
2231 if (bytesJustRead == sizeof(smplLoopData)) {
2232 pMetadata->data.smpl.pLoops[iSampleLoop].cuePointId = drwav_bytes_to_u32(smplLoopData + 0);
2233 pMetadata->data.smpl.pLoops[iSampleLoop].type = drwav_bytes_to_u32(smplLoopData + 4);
2234 pMetadata->data.smpl.pLoops[iSampleLoop].firstSampleOffset = drwav_bytes_to_u32(smplLoopData + 8);
2235 pMetadata->data.smpl.pLoops[iSampleLoop].lastSampleOffset = drwav_bytes_to_u32(smplLoopData + 12);
2236 pMetadata->data.smpl.pLoops[iSampleLoop].sampleFraction = drwav_bytes_to_u32(smplLoopData + 16);
2237 pMetadata->data.smpl.pLoops[iSampleLoop].playCount = drwav_bytes_to_u32(smplLoopData + 20);
2238 } else {
2239 break;
2240 }
2241 }
2242
2243 if (pMetadata->data.smpl.samplerSpecificDataSizeInBytes > 0) {
2244 pMetadata->data.smpl.pSamplerSpecificData = drwav__metadata_get_memory(pParser, pMetadata->data.smpl.samplerSpecificDataSizeInBytes, 1);
2245 DRWAV_ASSERT(pMetadata->data.smpl.pSamplerSpecificData != NULL);
2246
2247 drwav__metadata_parser_read(pParser, pMetadata->data.smpl.pSamplerSpecificData, pMetadata->data.smpl.samplerSpecificDataSizeInBytes, &totalBytesRead);
2248 }
2249 } else {
2250 /*
2251 Getting here means the loop count in the header does not match up with the size of the
2252 chunk. Clear out the data to zero just to be safe.
2253
2254 This should never actually get hit because we check for it above, but keeping this here
2255 for added safety.
2256 */
2257 DRWAV_ZERO_OBJECT(&pMetadata->data.smpl);
2258 }
2259 }
2260
2261 return totalBytesRead;
2262}
2263
2264DRWAV_PRIVATE drwav_uint64 drwav__read_cue_to_metadata_obj(drwav__metadata_parser* pParser, const drwav_chunk_header* pChunkHeader, drwav_metadata* pMetadata)
2265{
2266 drwav_uint8 cueHeaderSectionData[DRWAV_CUE_BYTES];
2267 drwav_uint64 totalBytesRead = 0;
2268 size_t bytesJustRead;
2269
2270 if (pMetadata == NULL) {
2271 return 0;
2272 }
2273
2274 bytesJustRead = drwav__metadata_parser_read(pParser, cueHeaderSectionData, sizeof(cueHeaderSectionData), &totalBytesRead);
2275
2276 DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
2277
2278 if (bytesJustRead == sizeof(cueHeaderSectionData)) {
2279 pMetadata->type = drwav_metadata_type_cue;
2280 pMetadata->data.cue.cuePointCount = drwav_bytes_to_u32(cueHeaderSectionData);
2281
2282 /*
2283 We need to validate the cue point count against the size of the chunk so we don't read
2284 beyond the chunk.
2285 */
2286 if (pMetadata->data.cue.cuePointCount == (pChunkHeader->sizeInBytes - DRWAV_CUE_BYTES) / DRWAV_CUE_POINT_BYTES) {
2287 pMetadata->data.cue.pCuePoints = (drwav_cue_point*)drwav__metadata_get_memory(pParser, sizeof(drwav_cue_point) * pMetadata->data.cue.cuePointCount, DRWAV_METADATA_ALIGNMENT);
2288 DRWAV_ASSERT(pMetadata->data.cue.pCuePoints != NULL);
2289
2290 if (pMetadata->data.cue.cuePointCount > 0) {
2291 drwav_uint32 iCuePoint;
2292
2293 for (iCuePoint = 0; iCuePoint < pMetadata->data.cue.cuePointCount; ++iCuePoint) {
2294 drwav_uint8 cuePointData[DRWAV_CUE_POINT_BYTES];
2295 bytesJustRead = drwav__metadata_parser_read(pParser, cuePointData, sizeof(cuePointData), &totalBytesRead);
2296
2297 if (bytesJustRead == sizeof(cuePointData)) {
2298 pMetadata->data.cue.pCuePoints[iCuePoint].id = drwav_bytes_to_u32(cuePointData + 0);
2299 pMetadata->data.cue.pCuePoints[iCuePoint].playOrderPosition = drwav_bytes_to_u32(cuePointData + 4);
2300 pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[0] = cuePointData[8];
2301 pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[1] = cuePointData[9];
2302 pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[2] = cuePointData[10];
2303 pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[3] = cuePointData[11];
2304 pMetadata->data.cue.pCuePoints[iCuePoint].chunkStart = drwav_bytes_to_u32(cuePointData + 12);
2305 pMetadata->data.cue.pCuePoints[iCuePoint].blockStart = drwav_bytes_to_u32(cuePointData + 16);
2306 pMetadata->data.cue.pCuePoints[iCuePoint].sampleOffset = drwav_bytes_to_u32(cuePointData + 20);
2307 } else {
2308 break;
2309 }
2310 }
2311 }
2312 }
2313 }
2314
2315 return totalBytesRead;
2316}
2317
2318DRWAV_PRIVATE drwav_uint64 drwav__read_inst_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata)
2319{
2320 drwav_uint8 instData[DRWAV_INST_BYTES];
2321 drwav_uint64 bytesRead;
2322
2323 if (pMetadata == NULL) {
2324 return 0;
2325 }
2326
2327 bytesRead = drwav__metadata_parser_read(pParser, instData, sizeof(instData), NULL);
2328
2329 DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
2330
2331 if (bytesRead == sizeof(instData)) {
2332 pMetadata->type = drwav_metadata_type_inst;
2333 pMetadata->data.inst.midiUnityNote = (drwav_int8)instData[0];
2334 pMetadata->data.inst.fineTuneCents = (drwav_int8)instData[1];
2335 pMetadata->data.inst.gainDecibels = (drwav_int8)instData[2];
2336 pMetadata->data.inst.lowNote = (drwav_int8)instData[3];
2337 pMetadata->data.inst.highNote = (drwav_int8)instData[4];
2338 pMetadata->data.inst.lowVelocity = (drwav_int8)instData[5];
2339 pMetadata->data.inst.highVelocity = (drwav_int8)instData[6];
2340 }
2341
2342 return bytesRead;
2343}
2344
2345DRWAV_PRIVATE drwav_uint64 drwav__read_acid_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata)
2346{
2347 drwav_uint8 acidData[DRWAV_ACID_BYTES];
2348 drwav_uint64 bytesRead;
2349
2350 if (pMetadata == NULL) {
2351 return 0;
2352 }
2353
2354 bytesRead = drwav__metadata_parser_read(pParser, acidData, sizeof(acidData), NULL);
2355
2356 DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
2357
2358 if (bytesRead == sizeof(acidData)) {
2359 pMetadata->type = drwav_metadata_type_acid;
2360 pMetadata->data.acid.flags = drwav_bytes_to_u32(acidData + 0);
2361 pMetadata->data.acid.midiUnityNote = drwav_bytes_to_u16(acidData + 4);
2362 pMetadata->data.acid.reserved1 = drwav_bytes_to_u16(acidData + 6);
2363 pMetadata->data.acid.reserved2 = drwav_bytes_to_f32(acidData + 8);
2364 pMetadata->data.acid.numBeats = drwav_bytes_to_u32(acidData + 12);
2365 pMetadata->data.acid.meterDenominator = drwav_bytes_to_u16(acidData + 16);
2366 pMetadata->data.acid.meterNumerator = drwav_bytes_to_u16(acidData + 18);
2367 pMetadata->data.acid.tempo = drwav_bytes_to_f32(acidData + 20);
2368 }
2369
2370 return bytesRead;
2371}
2372
2373DRWAV_PRIVATE size_t drwav__strlen(const char* str)
2374{
2375 size_t result = 0;
2376
2377 while (*str++) {
2378 result += 1;
2379 }
2380
2381 return result;
2382}
2383
2384DRWAV_PRIVATE size_t drwav__strlen_clamped(const char* str, size_t maxToRead)
2385{
2386 size_t result = 0;
2387
2388 while (*str++ && result < maxToRead) {
2389 result += 1;
2390 }
2391
2392 return result;
2393}
2394
2395DRWAV_PRIVATE char* drwav__metadata_copy_string(drwav__metadata_parser* pParser, const char* str, size_t maxToRead)
2396{
2397 size_t len = drwav__strlen_clamped(str, maxToRead);
2398
2399 if (len) {
2400 char* result = (char*)drwav__metadata_get_memory(pParser, len + 1, 1);
2401 DRWAV_ASSERT(result != NULL);
2402
2403 DRWAV_COPY_MEMORY(result, str, len);
2404 result[len] = '\0';
2405
2406 return result;
2407 } else {
2408 return NULL;
2409 }
2410}
2411
2412typedef struct
2413{
2414 const void* pBuffer;
2415 size_t sizeInBytes;
2416 size_t cursor;
2417} drwav_buffer_reader;
2418
2419DRWAV_PRIVATE drwav_result drwav_buffer_reader_init(const void* pBuffer, size_t sizeInBytes, drwav_buffer_reader* pReader)
2420{
2421 DRWAV_ASSERT(pBuffer != NULL);
2422 DRWAV_ASSERT(pReader != NULL);
2423
2424 DRWAV_ZERO_OBJECT(pReader);
2425
2426 pReader->pBuffer = pBuffer;
2427 pReader->sizeInBytes = sizeInBytes;
2428 pReader->cursor = 0;
2429
2430 return DRWAV_SUCCESS;
2431}
2432
2433DRWAV_PRIVATE const void* drwav_buffer_reader_ptr(const drwav_buffer_reader* pReader)
2434{
2435 DRWAV_ASSERT(pReader != NULL);
2436
2437 return drwav_offset_ptr(pReader->pBuffer, pReader->cursor);
2438}
2439
2440DRWAV_PRIVATE drwav_result drwav_buffer_reader_seek(drwav_buffer_reader* pReader, size_t bytesToSeek)
2441{
2442 DRWAV_ASSERT(pReader != NULL);
2443
2444 if (pReader->cursor + bytesToSeek > pReader->sizeInBytes) {
2445 return DRWAV_BAD_SEEK; /* Seeking too far forward. */
2446 }
2447
2448 pReader->cursor += bytesToSeek;
2449
2450 return DRWAV_SUCCESS;
2451}
2452
2453DRWAV_PRIVATE drwav_result drwav_buffer_reader_read(drwav_buffer_reader* pReader, void* pDst, size_t bytesToRead, size_t* pBytesRead)
2454{
2455 drwav_result result = DRWAV_SUCCESS;
2456 size_t bytesRemaining;
2457
2458 DRWAV_ASSERT(pReader != NULL);
2459
2460 if (pBytesRead != NULL) {
2461 *pBytesRead = 0;
2462 }
2463
2464 bytesRemaining = (pReader->sizeInBytes - pReader->cursor);
2465 if (bytesToRead > bytesRemaining) {
2466 bytesToRead = bytesRemaining;
2467 }
2468
2469 if (pDst == NULL) {
2470 /* Seek. */
2471 result = drwav_buffer_reader_seek(pReader, bytesToRead);
2472 } else {
2473 /* Read. */
2474 DRWAV_COPY_MEMORY(pDst, drwav_buffer_reader_ptr(pReader), bytesToRead);
2475 pReader->cursor += bytesToRead;
2476 }
2477
2478 DRWAV_ASSERT(pReader->cursor <= pReader->sizeInBytes);
2479
2480 if (result == DRWAV_SUCCESS) {
2481 if (pBytesRead != NULL) {
2482 *pBytesRead = bytesToRead;
2483 }
2484 }
2485
2486 return DRWAV_SUCCESS;
2487}
2488
2489DRWAV_PRIVATE drwav_result drwav_buffer_reader_read_u16(drwav_buffer_reader* pReader, drwav_uint16* pDst)
2490{
2491 drwav_result result;
2492 size_t bytesRead;
2493 drwav_uint8 data[2];
2494
2495 DRWAV_ASSERT(pReader != NULL);
2496 DRWAV_ASSERT(pDst != NULL);
2497
2498 *pDst = 0; /* Safety. */
2499
2500 result = drwav_buffer_reader_read(pReader, data, sizeof(*pDst), &bytesRead);
2501 if (result != DRWAV_SUCCESS || bytesRead != sizeof(*pDst)) {
2502 return result;
2503 }
2504
2505 *pDst = drwav_bytes_to_u16(data);
2506
2507 return DRWAV_SUCCESS;
2508}
2509
2510DRWAV_PRIVATE drwav_result drwav_buffer_reader_read_u32(drwav_buffer_reader* pReader, drwav_uint32* pDst)
2511{
2512 drwav_result result;
2513 size_t bytesRead;
2514 drwav_uint8 data[4];
2515
2516 DRWAV_ASSERT(pReader != NULL);
2517 DRWAV_ASSERT(pDst != NULL);
2518
2519 *pDst = 0; /* Safety. */
2520
2521 result = drwav_buffer_reader_read(pReader, data, sizeof(*pDst), &bytesRead);
2522 if (result != DRWAV_SUCCESS || bytesRead != sizeof(*pDst)) {
2523 return result;
2524 }
2525
2526 *pDst = drwav_bytes_to_u32(data);
2527
2528 return DRWAV_SUCCESS;
2529}
2530
2531
2532
2533DRWAV_PRIVATE drwav_uint64 drwav__read_bext_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata, drwav_uint64 chunkSize)
2534{
2535 drwav_uint8 bextData[DRWAV_BEXT_BYTES];
2536 size_t bytesRead = drwav__metadata_parser_read(pParser, bextData, sizeof(bextData), NULL);
2537
2538 DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
2539
2540 if (bytesRead == sizeof(bextData)) {
2541 drwav_buffer_reader reader;
2542 drwav_uint32 timeReferenceLow;
2543 drwav_uint32 timeReferenceHigh;
2544 size_t extraBytes;
2545
2546 pMetadata->type = drwav_metadata_type_bext;
2547
2548 if (drwav_buffer_reader_init(bextData, bytesRead, &reader) == DRWAV_SUCCESS) {
2549 pMetadata->data.bext.pDescription = drwav__metadata_copy_string(pParser, (const char*)drwav_buffer_reader_ptr(&reader), DRWAV_BEXT_DESCRIPTION_BYTES);
2550 drwav_buffer_reader_seek(&reader, DRWAV_BEXT_DESCRIPTION_BYTES);
2551
2552 pMetadata->data.bext.pOriginatorName = drwav__metadata_copy_string(pParser, (const char*)drwav_buffer_reader_ptr(&reader), DRWAV_BEXT_ORIGINATOR_NAME_BYTES);
2553 drwav_buffer_reader_seek(&reader, DRWAV_BEXT_ORIGINATOR_NAME_BYTES);
2554
2555 pMetadata->data.bext.pOriginatorReference = drwav__metadata_copy_string(pParser, (const char*)drwav_buffer_reader_ptr(&reader), DRWAV_BEXT_ORIGINATOR_REF_BYTES);
2556 drwav_buffer_reader_seek(&reader, DRWAV_BEXT_ORIGINATOR_REF_BYTES);
2557
2558 drwav_buffer_reader_read(&reader, pMetadata->data.bext.pOriginationDate, sizeof(pMetadata->data.bext.pOriginationDate), NULL);
2559 drwav_buffer_reader_read(&reader, pMetadata->data.bext.pOriginationTime, sizeof(pMetadata->data.bext.pOriginationTime), NULL);
2560
2561 drwav_buffer_reader_read_u32(&reader, &timeReferenceLow);
2562 drwav_buffer_reader_read_u32(&reader, &timeReferenceHigh);
2563 pMetadata->data.bext.timeReference = ((drwav_uint64)timeReferenceHigh << 32) + timeReferenceLow;
2564
2565 drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.version);
2566
2567 pMetadata->data.bext.pUMID = drwav__metadata_get_memory(pParser, DRWAV_BEXT_UMID_BYTES, 1);
2568 drwav_buffer_reader_read(&reader, pMetadata->data.bext.pUMID, DRWAV_BEXT_UMID_BYTES, NULL);
2569
2570 drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.loudnessValue);
2571 drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.loudnessRange);
2572 drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxTruePeakLevel);
2573 drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxMomentaryLoudness);
2574 drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxShortTermLoudness);
2575
2576 DRWAV_ASSERT((drwav_offset_ptr(drwav_buffer_reader_ptr(&reader), DRWAV_BEXT_RESERVED_BYTES)) == (bextData + DRWAV_BEXT_BYTES));
2577
2578 extraBytes = (size_t)(chunkSize - DRWAV_BEXT_BYTES);
2579 if (extraBytes > 0) {
2580 pMetadata->data.bext.pCodingHistory = (char*)drwav__metadata_get_memory(pParser, extraBytes + 1, 1);
2581 DRWAV_ASSERT(pMetadata->data.bext.pCodingHistory != NULL);
2582
2583 bytesRead += drwav__metadata_parser_read(pParser, pMetadata->data.bext.pCodingHistory, extraBytes, NULL);
2584 pMetadata->data.bext.codingHistorySize = (drwav_uint32)drwav__strlen(pMetadata->data.bext.pCodingHistory);
2585 } else {
2586 pMetadata->data.bext.pCodingHistory = NULL;
2587 pMetadata->data.bext.codingHistorySize = 0;
2588 }
2589 }
2590 }
2591
2592 return bytesRead;
2593}
2594
2595DRWAV_PRIVATE drwav_uint64 drwav__read_list_label_or_note_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata, drwav_uint64 chunkSize, drwav_metadata_type type)
2596{
2597 drwav_uint8 cueIDBuffer[DRWAV_LIST_LABEL_OR_NOTE_BYTES];
2598 drwav_uint64 totalBytesRead = 0;
2599 size_t bytesJustRead = drwav__metadata_parser_read(pParser, cueIDBuffer, sizeof(cueIDBuffer), &totalBytesRead);
2600
2601 DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
2602
2603 if (bytesJustRead == sizeof(cueIDBuffer)) {
2604 drwav_uint32 sizeIncludingNullTerminator;
2605
2606 pMetadata->type = type;
2607 pMetadata->data.labelOrNote.cuePointId = drwav_bytes_to_u32(cueIDBuffer);
2608
2609 sizeIncludingNullTerminator = (drwav_uint32)chunkSize - DRWAV_LIST_LABEL_OR_NOTE_BYTES;
2610 if (sizeIncludingNullTerminator > 0) {
2611 pMetadata->data.labelOrNote.stringLength = sizeIncludingNullTerminator - 1;
2612 pMetadata->data.labelOrNote.pString = (char*)drwav__metadata_get_memory(pParser, sizeIncludingNullTerminator, 1);
2613 DRWAV_ASSERT(pMetadata->data.labelOrNote.pString != NULL);
2614
2615 drwav__metadata_parser_read(pParser, pMetadata->data.labelOrNote.pString, sizeIncludingNullTerminator, &totalBytesRead);
2616 } else {
2617 pMetadata->data.labelOrNote.stringLength = 0;
2618 pMetadata->data.labelOrNote.pString = NULL;
2619 }
2620 }
2621
2622 return totalBytesRead;
2623}
2624
2625DRWAV_PRIVATE drwav_uint64 drwav__read_list_labelled_cue_region_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata, drwav_uint64 chunkSize)
2626{
2627 drwav_uint8 buffer[DRWAV_LIST_LABELLED_TEXT_BYTES];
2628 drwav_uint64 totalBytesRead = 0;
2629 size_t bytesJustRead = drwav__metadata_parser_read(pParser, buffer, sizeof(buffer), &totalBytesRead);
2630
2631 DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
2632
2633 if (bytesJustRead == sizeof(buffer)) {
2634 drwav_uint32 sizeIncludingNullTerminator;
2635
2639 pMetadata->data.labelledCueRegion.purposeId[0] = buffer[8];
2640 pMetadata->data.labelledCueRegion.purposeId[1] = buffer[9];
2641 pMetadata->data.labelledCueRegion.purposeId[2] = buffer[10];
2642 pMetadata->data.labelledCueRegion.purposeId[3] = buffer[11];
2647
2648 sizeIncludingNullTerminator = (drwav_uint32)chunkSize - DRWAV_LIST_LABELLED_TEXT_BYTES;
2649 if (sizeIncludingNullTerminator > 0) {
2650 pMetadata->data.labelledCueRegion.stringLength = sizeIncludingNullTerminator - 1;
2651 pMetadata->data.labelledCueRegion.pString = (char*)drwav__metadata_get_memory(pParser, sizeIncludingNullTerminator, 1);
2652 DRWAV_ASSERT(pMetadata->data.labelledCueRegion.pString != NULL);
2653
2654 drwav__metadata_parser_read(pParser, pMetadata->data.labelledCueRegion.pString, sizeIncludingNullTerminator, &totalBytesRead);
2655 } else {
2656 pMetadata->data.labelledCueRegion.stringLength = 0;
2657 pMetadata->data.labelledCueRegion.pString = NULL;
2658 }
2659 }
2660
2661 return totalBytesRead;
2662}
2663
2664DRWAV_PRIVATE drwav_uint64 drwav__metadata_process_info_text_chunk(drwav__metadata_parser* pParser, drwav_uint64 chunkSize, drwav_metadata_type type)
2665{
2666 drwav_uint64 bytesRead = 0;
2667 drwav_uint32 stringSizeWithNullTerminator = (drwav_uint32)chunkSize;
2668
2669 if (pParser->stage == drwav__metadata_parser_stage_count) {
2670 pParser->metadataCount += 1;
2671 drwav__metadata_request_extra_memory_for_stage_2(pParser, stringSizeWithNullTerminator, 1);
2672 } else {
2673 drwav_metadata* pMetadata = &pParser->pMetadata[pParser->metadataCursor];
2674 pMetadata->type = type;
2675 if (stringSizeWithNullTerminator > 0) {
2676 pMetadata->data.infoText.stringLength = stringSizeWithNullTerminator - 1;
2677 pMetadata->data.infoText.pString = (char*)drwav__metadata_get_memory(pParser, stringSizeWithNullTerminator, 1);
2678 DRWAV_ASSERT(pMetadata->data.infoText.pString != NULL);
2679
2680 bytesRead = drwav__metadata_parser_read(pParser, pMetadata->data.infoText.pString, (size_t)stringSizeWithNullTerminator, NULL);
2681 if (bytesRead == chunkSize) {
2682 pParser->metadataCursor += 1;
2683 } else {
2684 /* Failed to parse. */
2685 }
2686 } else {
2687 pMetadata->data.infoText.stringLength = 0;
2688 pMetadata->data.infoText.pString = NULL;
2689 pParser->metadataCursor += 1;
2690 }
2691 }
2692
2693 return bytesRead;
2694}
2695
2696DRWAV_PRIVATE drwav_uint64 drwav__metadata_process_unknown_chunk(drwav__metadata_parser* pParser, const drwav_uint8* pChunkId, drwav_uint64 chunkSize, drwav_metadata_location location)
2697{
2698 drwav_uint64 bytesRead = 0;
2699
2700 if (location == drwav_metadata_location_invalid) {
2701 return 0;
2702 }
2703
2704 if (drwav_fourcc_equal(pChunkId, "data") || drwav_fourcc_equal(pChunkId, "fmt ") || drwav_fourcc_equal(pChunkId, "fact")) {
2705 return 0;
2706 }
2707
2708 if (pParser->stage == drwav__metadata_parser_stage_count) {
2709 pParser->metadataCount += 1;
2710 drwav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)chunkSize, 1);
2711 } else {
2712 drwav_metadata* pMetadata = &pParser->pMetadata[pParser->metadataCursor];
2713 pMetadata->type = drwav_metadata_type_unknown;
2714 pMetadata->data.unknown.chunkLocation = location;
2715 pMetadata->data.unknown.id[0] = pChunkId[0];
2716 pMetadata->data.unknown.id[1] = pChunkId[1];
2717 pMetadata->data.unknown.id[2] = pChunkId[2];
2718 pMetadata->data.unknown.id[3] = pChunkId[3];
2719 pMetadata->data.unknown.dataSizeInBytes = (drwav_uint32)chunkSize;
2720 pMetadata->data.unknown.pData = (drwav_uint8 *)drwav__metadata_get_memory(pParser, (size_t)chunkSize, 1);
2721 DRWAV_ASSERT(pMetadata->data.unknown.pData != NULL);
2722
2723 bytesRead = drwav__metadata_parser_read(pParser, pMetadata->data.unknown.pData, pMetadata->data.unknown.dataSizeInBytes, NULL);
2724 if (bytesRead == pMetadata->data.unknown.dataSizeInBytes) {
2725 pParser->metadataCursor += 1;
2726 } else {
2727 /* Failed to read. */
2728 }
2729 }
2730
2731 return bytesRead;
2732}
2733
2734DRWAV_PRIVATE drwav_bool32 drwav__chunk_matches(drwav_metadata_type allowedMetadataTypes, const drwav_uint8* pChunkID, drwav_metadata_type type, const char* pID)
2735{
2736 return (allowedMetadataTypes & type) && drwav_fourcc_equal(pChunkID, pID);
2737}
2738
2739DRWAV_PRIVATE drwav_uint64 drwav__metadata_process_chunk(drwav__metadata_parser* pParser, const drwav_chunk_header* pChunkHeader, drwav_metadata_type allowedMetadataTypes)
2740{
2741 const drwav_uint8 *pChunkID = pChunkHeader->id.fourcc;
2742 drwav_uint64 bytesRead = 0;
2743
2744 if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_smpl, "smpl")) {
2745 if (pChunkHeader->sizeInBytes >= DRWAV_SMPL_BYTES) {
2746 if (pParser->stage == drwav__metadata_parser_stage_count) {
2748 size_t bytesJustRead;
2749
2750 if (!pParser->onSeek(pParser->pReadSeekUserData, 28, DRWAV_SEEK_CUR)) {
2751 return bytesRead;
2752 }
2753 bytesRead += 28;
2754
2755 bytesJustRead = drwav__metadata_parser_read(pParser, buffer, sizeof(buffer), &bytesRead);
2756 if (bytesJustRead == sizeof(buffer)) {
2758 drwav_uint64 calculatedLoopCount;
2759
2760 /* The loop count must be validated against the size of the chunk. */
2761 calculatedLoopCount = (pChunkHeader->sizeInBytes - DRWAV_SMPL_BYTES) / DRWAV_SMPL_LOOP_BYTES;
2762 if (calculatedLoopCount == loopCount) {
2763 bytesJustRead = drwav__metadata_parser_read(pParser, buffer, sizeof(buffer), &bytesRead);
2764 if (bytesJustRead == sizeof(buffer)) {
2765 drwav_uint32 samplerSpecificDataSizeInBytes = drwav_bytes_to_u32(buffer);
2766
2767 pParser->metadataCount += 1;
2768 drwav__metadata_request_extra_memory_for_stage_2(pParser, sizeof(drwav_smpl_loop) * loopCount, DRWAV_METADATA_ALIGNMENT);
2769 drwav__metadata_request_extra_memory_for_stage_2(pParser, samplerSpecificDataSizeInBytes, 1);
2770 }
2771 } else {
2772 /* Loop count in header does not match the size of the chunk. */
2773 }
2774 }
2775 } else {
2776 bytesRead = drwav__read_smpl_to_metadata_obj(pParser, pChunkHeader, &pParser->pMetadata[pParser->metadataCursor]);
2777 if (bytesRead == pChunkHeader->sizeInBytes) {
2778 pParser->metadataCursor += 1;
2779 } else {
2780 /* Failed to parse. */
2781 }
2782 }
2783 } else {
2784 /* Incorrectly formed chunk. */
2785 }
2786 } else if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_inst, "inst")) {
2787 if (pChunkHeader->sizeInBytes == DRWAV_INST_BYTES) {
2788 if (pParser->stage == drwav__metadata_parser_stage_count) {
2789 pParser->metadataCount += 1;
2790 } else {
2791 bytesRead = drwav__read_inst_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor]);
2792 if (bytesRead == pChunkHeader->sizeInBytes) {
2793 pParser->metadataCursor += 1;
2794 } else {
2795 /* Failed to parse. */
2796 }
2797 }
2798 } else {
2799 /* Incorrectly formed chunk. */
2800 }
2801 } else if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_acid, "acid")) {
2802 if (pChunkHeader->sizeInBytes == DRWAV_ACID_BYTES) {
2803 if (pParser->stage == drwav__metadata_parser_stage_count) {
2804 pParser->metadataCount += 1;
2805 } else {
2806 bytesRead = drwav__read_acid_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor]);
2807 if (bytesRead == pChunkHeader->sizeInBytes) {
2808 pParser->metadataCursor += 1;
2809 } else {
2810 /* Failed to parse. */
2811 }
2812 }
2813 } else {
2814 /* Incorrectly formed chunk. */
2815 }
2816 } else if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_cue, "cue ")) {
2817 if (pChunkHeader->sizeInBytes >= DRWAV_CUE_BYTES) {
2818 if (pParser->stage == drwav__metadata_parser_stage_count) {
2819 size_t cueCount;
2820
2821 pParser->metadataCount += 1;
2822 cueCount = (size_t)(pChunkHeader->sizeInBytes - DRWAV_CUE_BYTES) / DRWAV_CUE_POINT_BYTES;
2823 drwav__metadata_request_extra_memory_for_stage_2(pParser, sizeof(drwav_cue_point) * cueCount, DRWAV_METADATA_ALIGNMENT);
2824 } else {
2825 bytesRead = drwav__read_cue_to_metadata_obj(pParser, pChunkHeader, &pParser->pMetadata[pParser->metadataCursor]);
2826 if (bytesRead == pChunkHeader->sizeInBytes) {
2827 pParser->metadataCursor += 1;
2828 } else {
2829 /* Failed to parse. */
2830 }
2831 }
2832 } else {
2833 /* Incorrectly formed chunk. */
2834 }
2835 } else if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_bext, "bext")) {
2836 if (pChunkHeader->sizeInBytes >= DRWAV_BEXT_BYTES) {
2837 if (pParser->stage == drwav__metadata_parser_stage_count) {
2838 /* The description field is the largest one in a bext chunk, so that is the max size of this temporary buffer. */
2839 char buffer[DRWAV_BEXT_DESCRIPTION_BYTES + 1];
2840 size_t allocSizeNeeded = DRWAV_BEXT_UMID_BYTES; /* We know we will need SMPTE umid size. */
2841 size_t bytesJustRead;
2842
2843 buffer[DRWAV_BEXT_DESCRIPTION_BYTES] = '\0';
2844 bytesJustRead = drwav__metadata_parser_read(pParser, buffer, DRWAV_BEXT_DESCRIPTION_BYTES, &bytesRead);
2845 if (bytesJustRead != DRWAV_BEXT_DESCRIPTION_BYTES) {
2846 return bytesRead;
2847 }
2848 allocSizeNeeded += drwav__strlen(buffer) + 1;
2849
2850 buffer[DRWAV_BEXT_ORIGINATOR_NAME_BYTES] = '\0';
2851 bytesJustRead = drwav__metadata_parser_read(pParser, buffer, DRWAV_BEXT_ORIGINATOR_NAME_BYTES, &bytesRead);
2852 if (bytesJustRead != DRWAV_BEXT_ORIGINATOR_NAME_BYTES) {
2853 return bytesRead;
2854 }
2855 allocSizeNeeded += drwav__strlen(buffer) + 1;
2856
2857 buffer[DRWAV_BEXT_ORIGINATOR_REF_BYTES] = '\0';
2858 bytesJustRead = drwav__metadata_parser_read(pParser, buffer, DRWAV_BEXT_ORIGINATOR_REF_BYTES, &bytesRead);
2859 if (bytesJustRead != DRWAV_BEXT_ORIGINATOR_REF_BYTES) {
2860 return bytesRead;
2861 }
2862 allocSizeNeeded += drwav__strlen(buffer) + 1;
2863 allocSizeNeeded += (size_t)pChunkHeader->sizeInBytes - DRWAV_BEXT_BYTES + 1; /* Coding history. */
2864
2865 drwav__metadata_request_extra_memory_for_stage_2(pParser, allocSizeNeeded, 1);
2866
2867 pParser->metadataCount += 1;
2868 } else {
2869 bytesRead = drwav__read_bext_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], pChunkHeader->sizeInBytes);
2870 if (bytesRead == pChunkHeader->sizeInBytes) {
2871 pParser->metadataCursor += 1;
2872 } else {
2873 /* Failed to parse. */
2874 }
2875 }
2876 } else {
2877 /* Incorrectly formed chunk. */
2878 }
2879 } else if (drwav_fourcc_equal(pChunkID, "LIST") || drwav_fourcc_equal(pChunkID, "list")) {
2881 while (bytesRead < pChunkHeader->sizeInBytes) {
2882 drwav_uint8 subchunkId[4];
2883 drwav_uint8 subchunkSizeBuffer[4];
2884 drwav_uint64 subchunkDataSize;
2885 drwav_uint64 subchunkBytesRead = 0;
2886 drwav_uint64 bytesJustRead = drwav__metadata_parser_read(pParser, subchunkId, sizeof(subchunkId), &bytesRead);
2887 if (bytesJustRead != sizeof(subchunkId)) {
2888 break;
2889 }
2890
2891 /*
2892 The first thing in a list chunk should be "adtl" or "INFO".
2893
2894 - adtl means this list is a Associated Data List Chunk and will contain labels, notes
2895 or labelled cue regions.
2896 - INFO means this list is an Info List Chunk containing info text chunks such as IPRD
2897 which would specifies the album of this wav file.
2898
2899 No data follows the adtl or INFO id so we just make note of what type this list is and
2900 continue.
2901 */
2902 if (drwav_fourcc_equal(subchunkId, "adtl")) {
2904 continue;
2905 } else if (drwav_fourcc_equal(subchunkId, "INFO")) {
2907 continue;
2908 }
2909
2910 bytesJustRead = drwav__metadata_parser_read(pParser, subchunkSizeBuffer, sizeof(subchunkSizeBuffer), &bytesRead);
2911 if (bytesJustRead != sizeof(subchunkSizeBuffer)) {
2912 break;
2913 }
2914 subchunkDataSize = drwav_bytes_to_u32(subchunkSizeBuffer);
2915
2916 if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_label, "labl") || drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_note, "note")) {
2917 if (subchunkDataSize >= DRWAV_LIST_LABEL_OR_NOTE_BYTES) {
2918 drwav_uint64 stringSizeWithNullTerm = subchunkDataSize - DRWAV_LIST_LABEL_OR_NOTE_BYTES;
2919 if (pParser->stage == drwav__metadata_parser_stage_count) {
2920 pParser->metadataCount += 1;
2921 drwav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)stringSizeWithNullTerm, 1);
2922 } else {
2923 subchunkBytesRead = drwav__read_list_label_or_note_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], subchunkDataSize, drwav_fourcc_equal(subchunkId, "labl") ? drwav_metadata_type_list_label : drwav_metadata_type_list_note);
2924 if (subchunkBytesRead == subchunkDataSize) {
2925 pParser->metadataCursor += 1;
2926 } else {
2927 /* Failed to parse. */
2928 }
2929 }
2930 } else {
2931 /* Incorrectly formed chunk. */
2932 }
2933 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_labelled_cue_region, "ltxt")) {
2934 if (subchunkDataSize >= DRWAV_LIST_LABELLED_TEXT_BYTES) {
2935 drwav_uint64 stringSizeWithNullTerminator = subchunkDataSize - DRWAV_LIST_LABELLED_TEXT_BYTES;
2936 if (pParser->stage == drwav__metadata_parser_stage_count) {
2937 pParser->metadataCount += 1;
2938 drwav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)stringSizeWithNullTerminator, 1);
2939 } else {
2940 subchunkBytesRead = drwav__read_list_labelled_cue_region_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], subchunkDataSize);
2941 if (subchunkBytesRead == subchunkDataSize) {
2942 pParser->metadataCursor += 1;
2943 } else {
2944 /* Failed to parse. */
2945 }
2946 }
2947 } else {
2948 /* Incorrectly formed chunk. */
2949 }
2950 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_software, "ISFT")) {
2951 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_software);
2952 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_copyright, "ICOP")) {
2953 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_copyright);
2954 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_title, "INAM")) {
2955 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_title);
2956 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_artist, "IART")) {
2957 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_artist);
2958 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_comment, "ICMT")) {
2959 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_comment);
2960 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_date, "ICRD")) {
2961 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_date);
2962 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_genre, "IGNR")) {
2963 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_genre);
2964 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_album, "IPRD")) {
2965 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_album);
2966 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_tracknumber, "ITRK")) {
2967 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_tracknumber);
2968 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_location, "IARL")) {
2969 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_location);
2970 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_organization, "ICMS")) {
2971 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_organization);
2972 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_keywords, "IKEY")) {
2973 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_keywords);
2974 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_medium, "IMED")) {
2975 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_medium);
2976 } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_description, "ISBJ")) {
2977 subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_description);
2978 } else if ((allowedMetadataTypes & drwav_metadata_type_unknown) != 0) {
2979 subchunkBytesRead = drwav__metadata_process_unknown_chunk(pParser, subchunkId, subchunkDataSize, listType);
2980 }
2981
2982 bytesRead += subchunkBytesRead;
2983 DRWAV_ASSERT(subchunkBytesRead <= subchunkDataSize);
2984
2985 if (subchunkBytesRead < subchunkDataSize) {
2986 drwav_uint64 bytesToSeek = subchunkDataSize - subchunkBytesRead;
2987
2988 if (!pParser->onSeek(pParser->pReadSeekUserData, (int)bytesToSeek, DRWAV_SEEK_CUR)) {
2989 break;
2990 }
2991 bytesRead += bytesToSeek;
2992 }
2993
2994 if ((subchunkDataSize % 2) == 1) {
2995 if (!pParser->onSeek(pParser->pReadSeekUserData, 1, DRWAV_SEEK_CUR)) {
2996 break;
2997 }
2998 bytesRead += 1;
2999 }
3000 }
3001 } else if ((allowedMetadataTypes & drwav_metadata_type_unknown) != 0) {
3002 bytesRead = drwav__metadata_process_unknown_chunk(pParser, pChunkID, pChunkHeader->sizeInBytes, drwav_metadata_location_top_level);
3003 }
3004
3005 return bytesRead;
3006}
3007
3008
3009DRWAV_PRIVATE drwav_uint32 drwav_get_bytes_per_pcm_frame(drwav* pWav)
3010{
3011 drwav_uint32 bytesPerFrame;
3012
3013 /*
3014 The bytes per frame is a bit ambiguous. It can be either be based on the bits per sample, or the block align. The way I'm doing it here
3015 is that if the bits per sample is a multiple of 8, use floor(bitsPerSample*channels/8), otherwise fall back to the block align.
3016 */
3017 if ((pWav->bitsPerSample & 0x7) == 0) {
3018 /* Bits per sample is a multiple of 8. */
3019 bytesPerFrame = (pWav->bitsPerSample * pWav->fmt.channels) >> 3;
3020 } else {
3021 bytesPerFrame = pWav->fmt.blockAlign;
3022 }
3023
3024 /* Validation for known formats. a-law and mu-law should be 1 byte per channel. If it's not, it's not decodable. */
3026 if (bytesPerFrame != pWav->fmt.channels) {
3027 return 0; /* Invalid file. */
3028 }
3029 }
3030
3031 return bytesPerFrame;
3032}
3033
3035{
3036 if (pFMT == NULL) {
3037 return 0;
3038 }
3039
3040 if (pFMT->formatTag != DR_WAVE_FORMAT_EXTENSIBLE) {
3041 return pFMT->formatTag;
3042 } else {
3043 return drwav_bytes_to_u16(pFMT->subFormat); /* Only the first two bytes are required. */
3044 }
3045}
3046
3047DRWAV_PRIVATE drwav_bool32 drwav_preinit(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void* pReadSeekTellUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
3048{
3049 if (pWav == NULL || onRead == NULL || onSeek == NULL) { /* <-- onTell is optional. */
3050 return DRWAV_FALSE;
3051 }
3052
3053 DRWAV_ZERO_MEMORY(pWav, sizeof(*pWav));
3054 pWav->onRead = onRead;
3055 pWav->onSeek = onSeek;
3056 pWav->onTell = onTell;
3057 pWav->pUserData = pReadSeekTellUserData;
3058 pWav->allocationCallbacks = drwav_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
3059
3060 if (pWav->allocationCallbacks.onFree == NULL || (pWav->allocationCallbacks.onMalloc == NULL && pWav->allocationCallbacks.onRealloc == NULL)) {
3061 return DRWAV_FALSE; /* Invalid allocation callbacks. */
3062 }
3063
3064 return DRWAV_TRUE;
3065}
3066
3067DRWAV_PRIVATE drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags)
3068{
3069 /* This function assumes drwav_preinit() has been called beforehand. */
3070 drwav_result result;
3071 drwav_uint64 cursor; /* <-- Keeps track of the byte position so we can seek to specific locations. */
3072 drwav_bool32 sequential;
3073 drwav_uint8 riff[4];
3074 drwav_fmt fmt;
3075 unsigned short translatedFormatTag;
3076 drwav_uint64 dataChunkSize = 0; /* <-- Important! Don't explicitly set this to 0 anywhere else. Calculation of the size of the data chunk is performed in different paths depending on the container. */
3077 drwav_uint64 sampleCountFromFactChunk = 0; /* Same as dataChunkSize - make sure this is the only place this is initialized to 0. */
3078 drwav_uint64 metadataStartPos;
3079 drwav__metadata_parser metadataParser;
3080 drwav_bool8 isProcessingMetadata = DRWAV_FALSE;
3081 drwav_bool8 foundChunk_fmt = DRWAV_FALSE;
3082 drwav_bool8 foundChunk_data = DRWAV_FALSE;
3083 drwav_bool8 isAIFCFormType = DRWAV_FALSE; /* Only used with AIFF. */
3084 drwav_uint64 aiffFrameCount = 0;
3085
3086 cursor = 0;
3087 sequential = (flags & DRWAV_SEQUENTIAL) != 0;
3088 DRWAV_ZERO_OBJECT(&fmt);
3089
3090 /* The first 4 bytes should be the RIFF identifier. */
3091 if (drwav__on_read(pWav->onRead, pWav->pUserData, riff, sizeof(riff), &cursor) != sizeof(riff)) {
3092 return DRWAV_FALSE;
3093 }
3094
3095 /*
3096 The first 4 bytes can be used to identify the container. For RIFF files it will start with "RIFF" and for
3097 w64 it will start with "riff".
3098 */
3099 if (drwav_fourcc_equal(riff, "RIFF")) {
3101 } else if (drwav_fourcc_equal(riff, "RIFX")) {
3103 } else if (drwav_fourcc_equal(riff, "riff")) {
3104 int i;
3105 drwav_uint8 riff2[12];
3106
3108
3109 /* Check the rest of the GUID for validity. */
3110 if (drwav__on_read(pWav->onRead, pWav->pUserData, riff2, sizeof(riff2), &cursor) != sizeof(riff2)) {
3111 return DRWAV_FALSE;
3112 }
3113
3114 for (i = 0; i < 12; ++i) {
3115 if (riff2[i] != drwavGUID_W64_RIFF[i+4]) {
3116 return DRWAV_FALSE;
3117 }
3118 }
3119 } else if (drwav_fourcc_equal(riff, "RF64")) {
3121 } else if (drwav_fourcc_equal(riff, "FORM")) {
3123 } else {
3124 return DRWAV_FALSE; /* Unknown or unsupported container. */
3125 }
3126
3127
3129 drwav_uint8 chunkSizeBytes[4];
3130 drwav_uint8 wave[4];
3131
3132 if (drwav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) {
3133 return DRWAV_FALSE;
3134 }
3135
3137 if (drwav_bytes_to_u32_ex(chunkSizeBytes, pWav->container) < 36) {
3138 /*
3139 I've had a report of a WAV file failing to load when the size of the WAVE chunk is not encoded
3140 and is instead just set to 0. I'm going to relax the validation here to allow these files to
3141 load. Considering the chunk size isn't actually used this should be safe. With this change my
3142 test suite still passes.
3143 */
3144 /*return DRWAV_FALSE;*/ /* Chunk size should always be at least 36 bytes. */
3145 }
3146 } else if (pWav->container == drwav_container_rf64) {
3147 if (drwav_bytes_to_u32_le(chunkSizeBytes) != 0xFFFFFFFF) {
3148 return DRWAV_FALSE; /* Chunk size should always be set to -1/0xFFFFFFFF for RF64. The actual size is retrieved later. */
3149 }
3150 } else {
3151 return DRWAV_FALSE; /* Should never hit this. */
3152 }
3153
3154 if (drwav__on_read(pWav->onRead, pWav->pUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) {
3155 return DRWAV_FALSE;
3156 }
3157
3158 if (!drwav_fourcc_equal(wave, "WAVE")) {
3159 return DRWAV_FALSE; /* Expecting "WAVE". */
3160 }
3161 } else if (pWav->container == drwav_container_w64) {
3162 drwav_uint8 chunkSizeBytes[8];
3163 drwav_uint8 wave[16];
3164
3165 if (drwav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) {
3166 return DRWAV_FALSE;
3167 }
3168
3169 if (drwav_bytes_to_u64(chunkSizeBytes) < 80) {
3170 return DRWAV_FALSE;
3171 }
3172
3173 if (drwav__on_read(pWav->onRead, pWav->pUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) {
3174 return DRWAV_FALSE;
3175 }
3176
3177 if (!drwav_guid_equal(wave, drwavGUID_W64_WAVE)) {
3178 return DRWAV_FALSE;
3179 }
3180 } else if (pWav->container == drwav_container_aiff) {
3181 drwav_uint8 chunkSizeBytes[4];
3182 drwav_uint8 aiff[4];
3183
3184 if (drwav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) {
3185 return DRWAV_FALSE;
3186 }
3187
3188 if (drwav_bytes_to_u32_be(chunkSizeBytes) < 18) {
3189 return DRWAV_FALSE;
3190 }
3191
3192 if (drwav__on_read(pWav->onRead, pWav->pUserData, aiff, sizeof(aiff), &cursor) != sizeof(aiff)) {
3193 return DRWAV_FALSE;
3194 }
3195
3196 if (drwav_fourcc_equal(aiff, "AIFF")) {
3197 isAIFCFormType = DRWAV_FALSE;
3198 } else if (drwav_fourcc_equal(aiff, "AIFC")) {
3199 isAIFCFormType = DRWAV_TRUE;
3200 } else {
3201 return DRWAV_FALSE; /* Expecting "AIFF" or "AIFC". */
3202 }
3203 } else {
3204 return DRWAV_FALSE;
3205 }
3206
3207
3208 /* For RF64, the "ds64" chunk must come next, before the "fmt " chunk. */
3209 if (pWav->container == drwav_container_rf64) {
3210 drwav_uint8 sizeBytes[8];
3211 drwav_uint64 bytesRemainingInChunk;
3212 drwav_chunk_header header;
3213 result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header);
3214 if (result != DRWAV_SUCCESS) {
3215 return DRWAV_FALSE;
3216 }
3217
3218 if (!drwav_fourcc_equal(header.id.fourcc, "ds64")) {
3219 return DRWAV_FALSE; /* Expecting "ds64". */
3220 }
3221
3222 bytesRemainingInChunk = header.sizeInBytes + header.paddingSize;
3223
3224 /* We don't care about the size of the RIFF chunk - skip it. */
3225 if (!drwav__seek_forward(pWav->onSeek, 8, pWav->pUserData)) {
3226 return DRWAV_FALSE;
3227 }
3228 bytesRemainingInChunk -= 8;
3229 cursor += 8;
3230
3231
3232 /* Next 8 bytes is the size of the "data" chunk. */
3233 if (drwav__on_read(pWav->onRead, pWav->pUserData, sizeBytes, sizeof(sizeBytes), &cursor) != sizeof(sizeBytes)) {
3234 return DRWAV_FALSE;
3235 }
3236 bytesRemainingInChunk -= 8;
3237 dataChunkSize = drwav_bytes_to_u64(sizeBytes);
3238
3239
3240 /* Next 8 bytes is the same count which we would usually derived from the FACT chunk if it was available. */
3241 if (drwav__on_read(pWav->onRead, pWav->pUserData, sizeBytes, sizeof(sizeBytes), &cursor) != sizeof(sizeBytes)) {
3242 return DRWAV_FALSE;
3243 }
3244 bytesRemainingInChunk -= 8;
3245 sampleCountFromFactChunk = drwav_bytes_to_u64(sizeBytes);
3246
3247
3248 /* Skip over everything else. */
3249 if (!drwav__seek_forward(pWav->onSeek, bytesRemainingInChunk, pWav->pUserData)) {
3250 return DRWAV_FALSE;
3251 }
3252 cursor += bytesRemainingInChunk;
3253 }
3254
3255
3256 metadataStartPos = cursor;
3257
3258 /*
3259 Whether or not we are processing metadata controls how we load. We can load more efficiently when
3260 metadata is not being processed, but we also cannot process metadata for Wave64 because I have not
3261 been able to test it. If someone is able to test this and provide a patch I'm happy to enable it.
3262
3263 Seqential mode cannot support metadata because it involves seeking backwards.
3264 */
3265 isProcessingMetadata = !sequential && ((flags & DRWAV_WITH_METADATA) != 0);
3266
3267 /* Don't allow processing of metadata with untested containers. */
3269 isProcessingMetadata = DRWAV_FALSE;
3270 }
3271
3272 DRWAV_ZERO_MEMORY(&metadataParser, sizeof(metadataParser));
3273 if (isProcessingMetadata) {
3274 metadataParser.onRead = pWav->onRead;
3275 metadataParser.onSeek = pWav->onSeek;
3276 metadataParser.pReadSeekUserData = pWav->pUserData;
3277 metadataParser.stage = drwav__metadata_parser_stage_count;
3278 }
3279
3280
3281 /*
3282 From here on out, chunks might be in any order. In order to robustly handle metadata we'll need
3283 to loop through every chunk and handle them as we find them. In sequential mode we need to get
3284 out of the loop as soon as we find the data chunk because we won't be able to seek back.
3285 */
3286 for (;;) { /* For each chunk... */
3287 drwav_chunk_header header;
3288 drwav_uint64 chunkSize;
3289
3290 result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header);
3291 if (result != DRWAV_SUCCESS) {
3292 break;
3293 }
3294
3295 chunkSize = header.sizeInBytes;
3296
3297
3298 /*
3299 Always tell the caller about this chunk. We cannot do this in sequential mode because the
3300 callback is allowed to read from the file, in which case we'll need to rewind.
3301 */
3302 if (!sequential && onChunk != NULL) {
3303 drwav_uint64 callbackBytesRead = onChunk(pChunkUserData, pWav->onRead, pWav->onSeek, pWav->pUserData, &header, pWav->container, &fmt);
3304
3305 /*
3306 dr_wav may need to read the contents of the chunk, so we now need to seek back to the position before
3307 we called the callback.
3308 */
3309 if (callbackBytesRead > 0) {
3310 if (drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData) == DRWAV_FALSE) {
3311 return DRWAV_FALSE;
3312 }
3313 }
3314 }
3315
3316
3317 /* Explicitly handle known chunks first. */
3318
3319 /* "fmt " */
3320 if (((pWav->container == drwav_container_riff || pWav->container == drwav_container_rifx || pWav->container == drwav_container_rf64) && drwav_fourcc_equal(header.id.fourcc, "fmt ")) ||
3321 ((pWav->container == drwav_container_w64) && drwav_guid_equal(header.id.guid, drwavGUID_W64_FMT))) {
3322 drwav_uint8 fmtData[16];
3323
3324 foundChunk_fmt = DRWAV_TRUE;
3325
3326 if (pWav->onRead(pWav->pUserData, fmtData, sizeof(fmtData)) != sizeof(fmtData)) {
3327 return DRWAV_FALSE;
3328 }
3329 cursor += sizeof(fmtData);
3330
3331 fmt.formatTag = drwav_bytes_to_u16_ex(fmtData + 0, pWav->container);
3332 fmt.channels = drwav_bytes_to_u16_ex(fmtData + 2, pWav->container);
3333 fmt.sampleRate = drwav_bytes_to_u32_ex(fmtData + 4, pWav->container);
3334 fmt.avgBytesPerSec = drwav_bytes_to_u32_ex(fmtData + 8, pWav->container);
3335 fmt.blockAlign = drwav_bytes_to_u16_ex(fmtData + 12, pWav->container);
3336 fmt.bitsPerSample = drwav_bytes_to_u16_ex(fmtData + 14, pWav->container);
3337
3338 fmt.extendedSize = 0;
3339 fmt.validBitsPerSample = 0;
3340 fmt.channelMask = 0;
3341 DRWAV_ZERO_MEMORY(fmt.subFormat, sizeof(fmt.subFormat));
3342
3343 if (header.sizeInBytes > 16) {
3344 drwav_uint8 fmt_cbSize[2];
3345 int bytesReadSoFar = 0;
3346
3347 if (pWav->onRead(pWav->pUserData, fmt_cbSize, sizeof(fmt_cbSize)) != sizeof(fmt_cbSize)) {
3348 return DRWAV_FALSE; /* Expecting more data. */
3349 }
3350 cursor += sizeof(fmt_cbSize);
3351
3352 bytesReadSoFar = 18;
3353
3354 fmt.extendedSize = drwav_bytes_to_u16_ex(fmt_cbSize, pWav->container);
3355 if (fmt.extendedSize > 0) {
3356 /* Simple validation. */
3358 if (fmt.extendedSize != 22) {
3359 return DRWAV_FALSE;
3360 }
3361 }
3362
3364 drwav_uint8 fmtext[22];
3365
3366 if (pWav->onRead(pWav->pUserData, fmtext, fmt.extendedSize) != fmt.extendedSize) {
3367 return DRWAV_FALSE; /* Expecting more data. */
3368 }
3369
3370 fmt.validBitsPerSample = drwav_bytes_to_u16_ex(fmtext + 0, pWav->container);
3371 fmt.channelMask = drwav_bytes_to_u32_ex(fmtext + 2, pWav->container);
3372 drwav_bytes_to_guid(fmtext + 6, fmt.subFormat);
3373 } else {
3374 if (pWav->onSeek(pWav->pUserData, fmt.extendedSize, DRWAV_SEEK_CUR) == DRWAV_FALSE) {
3375 return DRWAV_FALSE;
3376 }
3377 }
3378 cursor += fmt.extendedSize;
3379
3380 bytesReadSoFar += fmt.extendedSize;
3381 }
3382
3383 /* Seek past any leftover bytes. For w64 the leftover will be defined based on the chunk size. */
3384 if (pWav->onSeek(pWav->pUserData, (int)(header.sizeInBytes - bytesReadSoFar), DRWAV_SEEK_CUR) == DRWAV_FALSE) {
3385 return DRWAV_FALSE;
3386 }
3387 cursor += (header.sizeInBytes - bytesReadSoFar);
3388 }
3389
3390 if (header.paddingSize > 0) {
3391 if (drwav__seek_forward(pWav->onSeek, header.paddingSize, pWav->pUserData) == DRWAV_FALSE) {
3392 break;
3393 }
3394 cursor += header.paddingSize;
3395 }
3396
3397 /* Go to the next chunk. Don't include this chunk in metadata. */
3398 continue;
3399 }
3400
3401 /* "data" */
3402 if (((pWav->container == drwav_container_riff || pWav->container == drwav_container_rifx || pWav->container == drwav_container_rf64) && drwav_fourcc_equal(header.id.fourcc, "data")) ||
3403 ((pWav->container == drwav_container_w64) && drwav_guid_equal(header.id.guid, drwavGUID_W64_DATA))) {
3404 foundChunk_data = DRWAV_TRUE;
3405
3406 pWav->dataChunkDataPos = cursor;
3407
3408 if (pWav->container != drwav_container_rf64) { /* The data chunk size for RF64 will always be set to 0xFFFFFFFF here. It was set to it's true value earlier. */
3409 dataChunkSize = chunkSize;
3410 }
3411
3412 /* If we're running in sequential mode, or we're not reading metadata, we have enough now that we can get out of the loop. */
3413 if (sequential || !isProcessingMetadata) {
3414 break; /* No need to keep reading beyond the data chunk. */
3415 } else {
3416 chunkSize += header.paddingSize; /* <-- Make sure we seek past the padding. */
3417 if (drwav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == DRWAV_FALSE) {
3418 break;
3419 }
3420 cursor += chunkSize;
3421
3422 continue; /* There may be some more metadata to read. */
3423 }
3424 }
3425
3426 /* "fact". This is optional. Can use this to get the sample count which is useful for compressed formats. For RF64 we retrieved the sample count from the ds64 chunk earlier. */
3427 if (((pWav->container == drwav_container_riff || pWav->container == drwav_container_rifx || pWav->container == drwav_container_rf64) && drwav_fourcc_equal(header.id.fourcc, "fact")) ||
3428 ((pWav->container == drwav_container_w64) && drwav_guid_equal(header.id.guid, drwavGUID_W64_FACT))) {
3430 drwav_uint8 sampleCount[4];
3431 if (drwav__on_read(pWav->onRead, pWav->pUserData, &sampleCount, 4, &cursor) != 4) {
3432 return DRWAV_FALSE;
3433 }
3434
3435 chunkSize -= 4;
3436
3437 /*
3438 The sample count in the "fact" chunk is either unreliable, or I'm not understanding it properly. For now I am only enabling this
3439 for Microsoft ADPCM formats.
3440 */
3442 sampleCountFromFactChunk = drwav_bytes_to_u32_ex(sampleCount, pWav->container);
3443 } else {
3444 sampleCountFromFactChunk = 0;
3445 }
3446 } else if (pWav->container == drwav_container_w64) {
3447 if (drwav__on_read(pWav->onRead, pWav->pUserData, &sampleCountFromFactChunk, 8, &cursor) != 8) {
3448 return DRWAV_FALSE;
3449 }
3450
3451 chunkSize -= 8;
3452 } else if (pWav->container == drwav_container_rf64) {
3453 /* We retrieved the sample count from the ds64 chunk earlier so no need to do that here. */
3454 }
3455
3456 /* Seek to the next chunk in preparation for the next iteration. */
3457 chunkSize += header.paddingSize; /* <-- Make sure we seek past the padding. */
3458 if (drwav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == DRWAV_FALSE) {
3459 break;
3460 }
3461 cursor += chunkSize;
3462
3463 continue;
3464 }
3465
3466
3467 /* "COMM". AIFF/AIFC only. */
3468 if (pWav->container == drwav_container_aiff && drwav_fourcc_equal(header.id.fourcc, "COMM")) {
3469 drwav_uint8 commData[24];
3470 drwav_uint32 commDataBytesToRead;
3471 drwav_uint16 channels;
3472 drwav_uint32 frameCount;
3473 drwav_uint16 sampleSizeInBits;
3474 drwav_int64 sampleRate;
3475 drwav_uint16 compressionFormat;
3476
3477 foundChunk_fmt = DRWAV_TRUE;
3478
3479 if (isAIFCFormType) {
3480 commDataBytesToRead = 24;
3481 if (header.sizeInBytes < commDataBytesToRead) {
3482 return DRWAV_FALSE; /* Invalid COMM chunk. */
3483 }
3484 } else {
3485 commDataBytesToRead = 18;
3486 if (header.sizeInBytes != commDataBytesToRead) {
3487 return DRWAV_FALSE; /* INVALID COMM chunk. */
3488 }
3489 }
3490
3491 if (drwav__on_read(pWav->onRead, pWav->pUserData, commData, commDataBytesToRead, &cursor) != commDataBytesToRead) {
3492 return DRWAV_FALSE;
3493 }
3494
3495
3496 channels = drwav_bytes_to_u16_ex (commData + 0, pWav->container);
3497 frameCount = drwav_bytes_to_u32_ex (commData + 2, pWav->container);
3498 sampleSizeInBits = drwav_bytes_to_u16_ex (commData + 6, pWav->container);
3499 sampleRate = drwav_aiff_extented_to_s64(commData + 8);
3500
3501 if (sampleRate < 0 || sampleRate > 0xFFFFFFFF) {
3502 return DRWAV_FALSE; /* Invalid sample rate. */
3503 }
3504
3505 if (isAIFCFormType) {
3506 const drwav_uint8* type = commData + 18;
3507
3508 if (drwav_fourcc_equal(type, "NONE")) {
3509 compressionFormat = DR_WAVE_FORMAT_PCM; /* PCM, big-endian. */
3510 } else if (drwav_fourcc_equal(type, "raw ")) {
3511 compressionFormat = DR_WAVE_FORMAT_PCM;
3512
3513 /* In my testing, it looks like when the "raw " compression type is used, 8-bit samples should be considered unsigned. */
3514 if (sampleSizeInBits == 8) {
3515 pWav->aiff.isUnsigned = DRWAV_TRUE;
3516 }
3517 } else if (drwav_fourcc_equal(type, "sowt")) {
3518 compressionFormat = DR_WAVE_FORMAT_PCM; /* PCM, little-endian. */
3519 pWav->aiff.isLE = DRWAV_TRUE;
3520 } else if (drwav_fourcc_equal(type, "fl32") || drwav_fourcc_equal(type, "fl64") || drwav_fourcc_equal(type, "FL32") || drwav_fourcc_equal(type, "FL64")) {
3521 compressionFormat = DR_WAVE_FORMAT_IEEE_FLOAT;
3522 } else if (drwav_fourcc_equal(type, "alaw") || drwav_fourcc_equal(type, "ALAW")) {
3523 compressionFormat = DR_WAVE_FORMAT_ALAW;
3524 } else if (drwav_fourcc_equal(type, "ulaw") || drwav_fourcc_equal(type, "ULAW")) {
3525 compressionFormat = DR_WAVE_FORMAT_MULAW;
3526 } else if (drwav_fourcc_equal(type, "ima4")) {
3527 compressionFormat = DR_WAVE_FORMAT_DVI_ADPCM;
3528 sampleSizeInBits = 4;
3529
3530 /*
3531 I haven't been able to figure out how to get correct decoding for IMA ADPCM. Until this is figured out
3532 we'll need to abort when we encounter such an encoding. Advice welcome!
3533 */
3534 (void)compressionFormat;
3535 (void)sampleSizeInBits;
3536
3537 return DRWAV_FALSE;
3538 } else {
3539 return DRWAV_FALSE; /* Unknown or unsupported compression format. Need to abort. */
3540 }
3541 } else {
3542 compressionFormat = DR_WAVE_FORMAT_PCM; /* It's a standard AIFF form which is always compressed. */
3543 }
3544
3545 /* With AIFF we want to use the explicitly defined frame count rather than deriving it from the size of the chunk. */
3546 aiffFrameCount = frameCount;
3547
3548 /* We should now have enough information to fill out our fmt structure. */
3549 fmt.formatTag = compressionFormat;
3550 fmt.channels = channels;
3551 fmt.sampleRate = (drwav_uint32)sampleRate;
3552 fmt.bitsPerSample = sampleSizeInBits;
3553 fmt.blockAlign = (drwav_uint16)(fmt.channels * fmt.bitsPerSample / 8);
3554 fmt.avgBytesPerSec = fmt.blockAlign * fmt.sampleRate;
3555
3556 if (fmt.blockAlign == 0 && compressionFormat == DR_WAVE_FORMAT_DVI_ADPCM) {
3557 fmt.blockAlign = 34 * fmt.channels;
3558 }
3559
3560 /*
3561 Weird one. I've seen some alaw and ulaw encoded files that for some reason set the bits per sample to 16 when
3562 it should be 8. To get this working I need to explicitly check for this and change it.
3563 */
3564 if (compressionFormat == DR_WAVE_FORMAT_ALAW || compressionFormat == DR_WAVE_FORMAT_MULAW) {
3565 if (fmt.bitsPerSample > 8) {
3566 fmt.bitsPerSample = 8;
3567 fmt.blockAlign = fmt.channels;
3568 }
3569 }
3570
3571 /* In AIFF, samples are padded to 8 byte boundaries. We need to round up our bits per sample here. */
3572 fmt.bitsPerSample += (fmt.bitsPerSample & 7);
3573
3574
3575 /* If the form type is AIFC there will be some additional data in the chunk. We need to seek past it. */
3576 if (isAIFCFormType) {
3577 if (drwav__seek_forward(pWav->onSeek, (chunkSize - commDataBytesToRead), pWav->pUserData) == DRWAV_FALSE) {
3578 return DRWAV_FALSE;
3579 }
3580 cursor += (chunkSize - commDataBytesToRead);
3581 }
3582
3583 /* Don't fall through or else we'll end up treating this chunk as metadata which is incorrect. */
3584 continue;
3585 }
3586
3587
3588 /* "SSND". AIFF/AIFC only. This is the AIFF equivalent of the "data" chunk. */
3589 if (pWav->container == drwav_container_aiff && drwav_fourcc_equal(header.id.fourcc, "SSND")) {
3590 drwav_uint8 offsetAndBlockSizeData[8];
3591 drwav_uint32 offset;
3592
3593 foundChunk_data = DRWAV_TRUE;
3594
3595 if (drwav__on_read(pWav->onRead, pWav->pUserData, offsetAndBlockSizeData, sizeof(offsetAndBlockSizeData), &cursor) != sizeof(offsetAndBlockSizeData)) {
3596 return DRWAV_FALSE;
3597 }
3598
3599 /* The position of the audio data starts at an offset. */
3600 offset = drwav_bytes_to_u32_ex(offsetAndBlockSizeData + 0, pWav->container);
3601 pWav->dataChunkDataPos = cursor + offset;
3602
3603 /* The data chunk size needs to be reduced by the offset or else seeking will break. */
3604 dataChunkSize = chunkSize;
3605 if (dataChunkSize > offset) {
3606 dataChunkSize -= offset;
3607 } else {
3608 dataChunkSize = 0;
3609 }
3610
3611 if (sequential) {
3612 if (foundChunk_fmt) { /* <-- Name is misleading, but will be set to true if the COMM chunk has been parsed. */
3613 /*
3614 Getting here means we're opening in sequential mode and we've found the SSND (data) and COMM (fmt) chunks. We need
3615 to get out of the loop here or else we'll end up going past the data chunk and will have no way of getting back to
3616 it since we're not allowed to seek backwards.
3617
3618 One subtle detail here is that there is an offset with the SSND chunk. We need to make sure we seek past this offset
3619 so we're left sitting on the first byte of actual audio data.
3620 */
3621 if (drwav__seek_forward(pWav->onSeek, offset, pWav->pUserData) == DRWAV_FALSE) {
3622 return DRWAV_FALSE;
3623 }
3624 cursor += offset;
3625
3626 break;
3627 } else {
3628 /*
3629 Getting here means the COMM chunk was not found. In sequential mode, if we haven't yet found the COMM chunk
3630 we'll need to abort because we can't be doing a backwards seek back to the SSND chunk in order to read the
3631 data. For this reason, this configuration of AIFF files are not supported with sequential mode.
3632 */
3633 return DRWAV_FALSE;
3634 }
3635 } else {
3636 chunkSize += header.paddingSize; /* <-- Make sure we seek past the padding. */
3637 chunkSize -= sizeof(offsetAndBlockSizeData); /* <-- This was read earlier. */
3638
3639 if (drwav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == DRWAV_FALSE) {
3640 break;
3641 }
3642 cursor += chunkSize;
3643
3644 continue; /* There may be some more metadata to read. */
3645 }
3646 }
3647
3648
3649 /* Getting here means it's not a chunk that we care about internally, but might need to be handled as metadata by the caller. */
3650 if (isProcessingMetadata) {
3651 drwav__metadata_process_chunk(&metadataParser, &header, drwav_metadata_type_all_including_unknown);
3652
3653 /* Go back to the start of the chunk so we can normalize the position of the cursor. */
3654 if (drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData) == DRWAV_FALSE) {
3655 break; /* Failed to seek. Can't reliable read the remaining chunks. Get out. */
3656 }
3657 }
3658
3659
3660 /* Make sure we skip past the content of this chunk before we go to the next one. */
3661 chunkSize += header.paddingSize; /* <-- Make sure we seek past the padding. */
3662 if (drwav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData) == DRWAV_FALSE) {
3663 break;
3664 }
3665 cursor += chunkSize;
3666 }
3667
3668 /* There's some mandatory chunks that must exist. If they were not found in the iteration above we must abort. */
3669 if (!foundChunk_fmt || !foundChunk_data) {
3670 return DRWAV_FALSE;
3671 }
3672
3673 /* Basic validation. */
3674 if ((fmt.sampleRate == 0 || fmt.sampleRate > DRWAV_MAX_SAMPLE_RATE ) ||
3675 (fmt.channels == 0 || fmt.channels > DRWAV_MAX_CHANNELS ) ||
3676 (fmt.bitsPerSample == 0 || fmt.bitsPerSample > DRWAV_MAX_BITS_PER_SAMPLE) ||
3677 fmt.blockAlign == 0) {
3678 return DRWAV_FALSE; /* Probably an invalid WAV file. */
3679 }
3680
3681 /* Translate the internal format. */
3682 translatedFormatTag = fmt.formatTag;
3683 if (translatedFormatTag == DR_WAVE_FORMAT_EXTENSIBLE) {
3684 translatedFormatTag = drwav_bytes_to_u16_ex(fmt.subFormat + 0, pWav->container);
3685 }
3686
3687 /* 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. */
3688 if (!sequential) {
3689 if (!drwav__seek_from_start(pWav->onSeek, pWav->dataChunkDataPos, pWav->pUserData)) {
3690 return DRWAV_FALSE;
3691 }
3692 cursor = pWav->dataChunkDataPos;
3693 }
3694
3695
3696 /*
3697 At this point we should have done the initial parsing of each of our chunks, but we now need to
3698 do a second pass to extract the actual contents of the metadata (the first pass just calculated
3699 the length of the memory allocation).
3700
3701 We only do this if we've actually got metadata to parse.
3702 */
3703 if (isProcessingMetadata && metadataParser.metadataCount > 0) {
3704 if (drwav__seek_from_start(pWav->onSeek, metadataStartPos, pWav->pUserData) == DRWAV_FALSE) {
3705 return DRWAV_FALSE;
3706 }
3707
3708 result = drwav__metadata_alloc(&metadataParser, &pWav->allocationCallbacks);
3709 if (result != DRWAV_SUCCESS) {
3710 return DRWAV_FALSE;
3711 }
3712
3713 metadataParser.stage = drwav__metadata_parser_stage_read;
3714
3715 for (;;) {
3716 drwav_chunk_header header;
3717 drwav_uint64 metadataBytesRead;
3718
3719 result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header);
3720 if (result != DRWAV_SUCCESS) {
3721 break;
3722 }
3723
3724 metadataBytesRead = drwav__metadata_process_chunk(&metadataParser, &header, drwav_metadata_type_all_including_unknown);
3725
3726 /* Move to the end of the chunk so we can keep iterating. */
3727 if (drwav__seek_forward(pWav->onSeek, (header.sizeInBytes + header.paddingSize) - metadataBytesRead, pWav->pUserData) == DRWAV_FALSE) {
3728 drwav_free(metadataParser.pMetadata, &pWav->allocationCallbacks);
3729 return DRWAV_FALSE;
3730 }
3731 }
3732
3733 /* Getting here means we're finished parsing the metadata. */
3734 pWav->pMetadata = metadataParser.pMetadata;
3735 pWav->metadataCount = metadataParser.metadataCount;
3736 }
3737
3738 /*
3739 It's possible for the size reported in the data chunk to be greater than that of the file. We
3740 need to do a validation check here to make sure we don't exceed the file size. To skip this
3741 check, set the onTell callback to NULL.
3742 */
3743 if (pWav->onTell != NULL && pWav->onSeek != NULL) {
3744 if (pWav->onSeek(pWav->pUserData, 0, DRWAV_SEEK_END) == DRWAV_TRUE) {
3745 drwav_int64 fileSize;
3746 if (pWav->onTell(pWav->pUserData, &fileSize)) {
3747 if (dataChunkSize + pWav->dataChunkDataPos > (drwav_uint64)fileSize) {
3748 dataChunkSize = (drwav_uint64)fileSize - pWav->dataChunkDataPos;
3749 }
3750 }
3751 } else {
3752 /*
3753 Failed to seek to the end of the file. It might not be supported by the backend so in
3754 this case we cannot perform the validation check.
3755 */
3756 }
3757 }
3758
3759 /*
3760 I've seen a WAV file in the wild where a RIFF-ecapsulated file has the size of it's "RIFF" and
3761 "data" chunks set to 0xFFFFFFFF when the file is definitely not that big. In this case we're
3762 going to have to calculate the size by reading and discarding bytes, and then seeking back. We
3763 cannot do this in sequential mode. We just assume that the rest of the file is audio data.
3764 */
3765 if (dataChunkSize == 0xFFFFFFFF && (pWav->container == drwav_container_riff || pWav->container == drwav_container_rifx) && pWav->isSequentialWrite == DRWAV_FALSE) {
3766 dataChunkSize = 0;
3767
3768 for (;;) {
3769 drwav_uint8 temp[4096];
3770 size_t bytesRead = pWav->onRead(pWav->pUserData, temp, sizeof(temp));
3771 dataChunkSize += bytesRead;
3772
3773 if (bytesRead < sizeof(temp)) {
3774 break;
3775 }
3776 }
3777 }
3778
3779 /* At this point we want to be sitting on the first byte of the raw audio data. */
3780 if (drwav__seek_from_start(pWav->onSeek, pWav->dataChunkDataPos, pWav->pUserData) == DRWAV_FALSE) {
3782 return DRWAV_FALSE;
3783 }
3784
3785
3786 pWav->fmt = fmt;
3787 pWav->sampleRate = fmt.sampleRate;
3788 pWav->channels = fmt.channels;
3789 pWav->bitsPerSample = fmt.bitsPerSample;
3790 pWav->translatedFormatTag = translatedFormatTag;
3791
3792 /*
3793 I've had a report where files would start glitching after seeking. The reason for this is the data
3794 chunk is not a clean multiple of the PCM frame size in bytes. Where this becomes a problem is when
3795 seeking, because the number of bytes remaining in the data chunk is used to calculate the current
3796 byte position. If this byte position is not aligned to the number of bytes in a PCM frame, it will
3797 result in the seek not being cleanly positioned at the start of the PCM frame thereby resulting in
3798 all decoded frames after that being corrupted.
3799
3800 To address this, we need to round the data chunk size down to the nearest multiple of the frame size.
3801 */
3802 if (!drwav__is_compressed_format_tag(translatedFormatTag)) {
3803 drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
3804 if (bytesPerFrame > 0) {
3805 dataChunkSize -= (dataChunkSize % bytesPerFrame);
3806 }
3807 }
3808
3809 pWav->bytesRemaining = dataChunkSize;
3810 pWav->dataChunkDataSize = dataChunkSize;
3811
3812 if (sampleCountFromFactChunk != 0) {
3813 pWav->totalPCMFrameCount = sampleCountFromFactChunk;
3814 } else if (aiffFrameCount != 0) {
3815 pWav->totalPCMFrameCount = aiffFrameCount;
3816 } else {
3817 drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
3818 if (bytesPerFrame == 0) {
3820 return DRWAV_FALSE; /* Invalid file. */
3821 }
3822
3823 pWav->totalPCMFrameCount = dataChunkSize / bytesPerFrame;
3824
3826 drwav_uint64 totalBlockHeaderSizeInBytes;
3827 drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
3828
3829 /* Make sure any trailing partial block is accounted for. */
3830 if ((blockCount * fmt.blockAlign) < dataChunkSize) {
3831 blockCount += 1;
3832 }
3833
3834 /* We decode two samples per byte. There will be blockCount headers in the data chunk. This is enough to know how to calculate the total PCM frame count. */
3835 totalBlockHeaderSizeInBytes = blockCount * (6*fmt.channels);
3836 pWav->totalPCMFrameCount = ((dataChunkSize - totalBlockHeaderSizeInBytes) * 2) / fmt.channels;
3837 }
3839 drwav_uint64 totalBlockHeaderSizeInBytes;
3840 drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
3841
3842 /* Make sure any trailing partial block is accounted for. */
3843 if ((blockCount * fmt.blockAlign) < dataChunkSize) {
3844 blockCount += 1;
3845 }
3846
3847 /* We decode two samples per byte. There will be blockCount headers in the data chunk. This is enough to know how to calculate the total PCM frame count. */
3848 totalBlockHeaderSizeInBytes = blockCount * (4*fmt.channels);
3849 pWav->totalPCMFrameCount = ((dataChunkSize - totalBlockHeaderSizeInBytes) * 2) / fmt.channels;
3850
3851 /* The header includes a decoded sample for each channel which acts as the initial predictor sample. */
3852 pWav->totalPCMFrameCount += blockCount;
3853 }
3854 }
3855
3856 /* Some formats only support a certain number of channels. */
3858 if (pWav->channels > 2) {
3860 return DRWAV_FALSE;
3861 }
3862 }
3863
3864 /* The number of bytes per frame must be known. If not, it's an invalid file and not decodable. */
3865 if (drwav_get_bytes_per_pcm_frame(pWav) == 0) {
3867 return DRWAV_FALSE;
3868 }
3869
3870#ifdef DR_WAV_LIBSNDFILE_COMPAT
3871 /*
3872 I use libsndfile as a benchmark for testing, however in the version I'm using (from the Windows installer on the libsndfile website),
3873 it appears the total sample count libsndfile uses for MS-ADPCM is incorrect. It would seem they are computing the total sample count
3874 from the number of blocks, however this results in the inclusion of extra silent samples at the end of the last block. The correct
3875 way to know the total sample count is to inspect the "fact" chunk, which should always be present for compressed formats, and should
3876 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
3877 correctness tests against libsndfile, and is disabled by default.
3878 */
3880 drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
3881 pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (6*pWav->channels))) * 2)) / fmt.channels; /* x2 because two samples per byte. */
3882 }
3884 drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
3885 pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (4*pWav->channels))) * 2) + (blockCount * pWav->channels)) / fmt.channels;
3886 }
3887#endif
3888
3889 return DRWAV_TRUE;
3890}
3891
3892DRWAV_API drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
3893{
3894 return drwav_init_ex(pWav, onRead, onSeek, onTell, NULL, pUserData, NULL, 0, pAllocationCallbacks);
3895}
3896
3897DRWAV_API drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, drwav_chunk_proc onChunk, void* pReadSeekTellUserData, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
3898{
3899 if (!drwav_preinit(pWav, onRead, onSeek, onTell, pReadSeekTellUserData, pAllocationCallbacks)) {
3900 return DRWAV_FALSE;
3901 }
3902
3903 return drwav_init__internal(pWav, onChunk, pChunkUserData, flags);
3904}
3905
3906DRWAV_API drwav_bool32 drwav_init_with_metadata(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void* pUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
3907{
3908 if (!drwav_preinit(pWav, onRead, onSeek, onTell, pUserData, pAllocationCallbacks)) {
3909 return DRWAV_FALSE;
3910 }
3911
3912 return drwav_init__internal(pWav, NULL, NULL, flags | DRWAV_WITH_METADATA);
3913}
3914
3916{
3917 drwav_metadata *result = pWav->pMetadata;
3918
3919 pWav->pMetadata = NULL;
3920 pWav->metadataCount = 0;
3921
3922 return result;
3923}
3924
3925
3926DRWAV_PRIVATE size_t drwav__write(drwav* pWav, const void* pData, size_t dataSize)
3927{
3928 DRWAV_ASSERT(pWav != NULL);
3929 DRWAV_ASSERT(pWav->onWrite != NULL);
3930
3931 /* Generic write. Assumes no byte reordering required. */
3932 return pWav->onWrite(pWav->pUserData, pData, dataSize);
3933}
3934
3935DRWAV_PRIVATE size_t drwav__write_byte(drwav* pWav, drwav_uint8 byte)
3936{
3937 DRWAV_ASSERT(pWav != NULL);
3938 DRWAV_ASSERT(pWav->onWrite != NULL);
3939
3940 return pWav->onWrite(pWav->pUserData, &byte, 1);
3941}
3942
3943DRWAV_PRIVATE size_t drwav__write_u16ne_to_le(drwav* pWav, drwav_uint16 value)
3944{
3945 DRWAV_ASSERT(pWav != NULL);
3946 DRWAV_ASSERT(pWav->onWrite != NULL);
3947
3948 if (!drwav__is_little_endian()) {
3949 value = drwav__bswap16(value);
3950 }
3951
3952 return drwav__write(pWav, &value, 2);
3953}
3954
3955DRWAV_PRIVATE size_t drwav__write_u32ne_to_le(drwav* pWav, drwav_uint32 value)
3956{
3957 DRWAV_ASSERT(pWav != NULL);
3958 DRWAV_ASSERT(pWav->onWrite != NULL);
3959
3960 if (!drwav__is_little_endian()) {
3961 value = drwav__bswap32(value);
3962 }
3963
3964 return drwav__write(pWav, &value, 4);
3965}
3966
3967DRWAV_PRIVATE size_t drwav__write_u64ne_to_le(drwav* pWav, drwav_uint64 value)
3968{
3969 DRWAV_ASSERT(pWav != NULL);
3970 DRWAV_ASSERT(pWav->onWrite != NULL);
3971
3972 if (!drwav__is_little_endian()) {
3973 value = drwav__bswap64(value);
3974 }
3975
3976 return drwav__write(pWav, &value, 8);
3977}
3978
3979DRWAV_PRIVATE size_t drwav__write_f32ne_to_le(drwav* pWav, float value)
3980{
3981 union {
3982 drwav_uint32 u32;
3983 float f32;
3984 } u;
3985
3986 DRWAV_ASSERT(pWav != NULL);
3987 DRWAV_ASSERT(pWav->onWrite != NULL);
3988
3989 u.f32 = value;
3990
3991 if (!drwav__is_little_endian()) {
3992 u.u32 = drwav__bswap32(u.u32);
3993 }
3994
3995 return drwav__write(pWav, &u.u32, 4);
3996}
3997
3998DRWAV_PRIVATE size_t drwav__write_or_count(drwav* pWav, const void* pData, size_t dataSize)
3999{
4000 if (pWav == NULL) {
4001 return dataSize;
4002 }
4003
4004 return drwav__write(pWav, pData, dataSize);
4005}
4006
4007DRWAV_PRIVATE size_t drwav__write_or_count_byte(drwav* pWav, drwav_uint8 byte)
4008{
4009 if (pWav == NULL) {
4010 return 1;
4011 }
4012
4013 return drwav__write_byte(pWav, byte);
4014}
4015
4016DRWAV_PRIVATE size_t drwav__write_or_count_u16ne_to_le(drwav* pWav, drwav_uint16 value)
4017{
4018 if (pWav == NULL) {
4019 return 2;
4020 }
4021
4022 return drwav__write_u16ne_to_le(pWav, value);
4023}
4024
4025DRWAV_PRIVATE size_t drwav__write_or_count_u32ne_to_le(drwav* pWav, drwav_uint32 value)
4026{
4027 if (pWav == NULL) {
4028 return 4;
4029 }
4030
4031 return drwav__write_u32ne_to_le(pWav, value);
4032}
4033
4034#if 0 /* Unused for now. */
4035DRWAV_PRIVATE size_t drwav__write_or_count_u64ne_to_le(drwav* pWav, drwav_uint64 value)
4036{
4037 if (pWav == NULL) {
4038 return 8;
4039 }
4040
4041 return drwav__write_u64ne_to_le(pWav, value);
4042}
4043#endif
4044
4045DRWAV_PRIVATE size_t drwav__write_or_count_f32ne_to_le(drwav* pWav, float value)
4046{
4047 if (pWav == NULL) {
4048 return 4;
4049 }
4050
4051 return drwav__write_f32ne_to_le(pWav, value);
4052}
4053
4054DRWAV_PRIVATE size_t drwav__write_or_count_string_to_fixed_size_buf(drwav* pWav, char* str, size_t bufFixedSize)
4055{
4056 size_t len;
4057
4058 if (pWav == NULL) {
4059 return bufFixedSize;
4060 }
4061
4062 len = drwav__strlen_clamped(str, bufFixedSize);
4063 drwav__write_or_count(pWav, str, len);
4064
4065 if (len < bufFixedSize) {
4066 size_t i;
4067 for (i = 0; i < bufFixedSize - len; ++i) {
4068 drwav__write_byte(pWav, 0);
4069 }
4070 }
4071
4072 return bufFixedSize;
4073}
4074
4075
4076/* pWav can be NULL meaning just count the bytes that would be written. */
4077DRWAV_PRIVATE size_t drwav__write_or_count_metadata(drwav* pWav, drwav_metadata* pMetadatas, drwav_uint32 metadataCount)
4078{
4079 size_t bytesWritten = 0;
4080 drwav_bool32 hasListAdtl = DRWAV_FALSE;
4081 drwav_bool32 hasListInfo = DRWAV_FALSE;
4082 drwav_uint32 iMetadata;
4083
4084 if (pMetadatas == NULL || metadataCount == 0) {
4085 return 0;
4086 }
4087
4088 for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
4089 drwav_metadata* pMetadata = &pMetadatas[iMetadata];
4090 drwav_uint32 chunkSize = 0;
4091
4093 hasListInfo = DRWAV_TRUE;
4094 }
4095
4097 hasListAdtl = DRWAV_TRUE;
4098 }
4099
4100 switch (pMetadata->type) {
4102 {
4103 drwav_uint32 iLoop;
4104
4105 chunkSize = DRWAV_SMPL_BYTES + DRWAV_SMPL_LOOP_BYTES * pMetadata->data.smpl.sampleLoopCount + pMetadata->data.smpl.samplerSpecificDataSizeInBytes;
4106
4107 bytesWritten += drwav__write_or_count(pWav, "smpl", 4);
4108 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
4109
4110 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.manufacturerId);
4111 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.productId);
4112 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.samplePeriodNanoseconds);
4113 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.midiUnityNote);
4114 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.midiPitchFraction);
4115 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.smpteFormat);
4116 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.smpteOffset);
4117 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.sampleLoopCount);
4118 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.samplerSpecificDataSizeInBytes);
4119
4120 for (iLoop = 0; iLoop < pMetadata->data.smpl.sampleLoopCount; ++iLoop) {
4121 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].cuePointId);
4122 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].type);
4123 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].firstSampleOffset);
4124 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].lastSampleOffset);
4125 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].sampleFraction);
4126 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].playCount);
4127 }
4128
4129 if (pMetadata->data.smpl.samplerSpecificDataSizeInBytes > 0) {
4130 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.smpl.pSamplerSpecificData, pMetadata->data.smpl.samplerSpecificDataSizeInBytes);
4131 }
4132 } break;
4133
4135 {
4136 chunkSize = DRWAV_INST_BYTES;
4137
4138 bytesWritten += drwav__write_or_count(pWav, "inst", 4);
4139 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
4140 bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.midiUnityNote, 1);
4141 bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.fineTuneCents, 1);
4142 bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.gainDecibels, 1);
4143 bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.lowNote, 1);
4144 bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.highNote, 1);
4145 bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.lowVelocity, 1);
4146 bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.highVelocity, 1);
4147 } break;
4148
4150 {
4151 drwav_uint32 iCuePoint;
4152
4153 chunkSize = DRWAV_CUE_BYTES + DRWAV_CUE_POINT_BYTES * pMetadata->data.cue.cuePointCount;
4154
4155 bytesWritten += drwav__write_or_count(pWav, "cue ", 4);
4156 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
4157 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.cuePointCount);
4158 for (iCuePoint = 0; iCuePoint < pMetadata->data.cue.cuePointCount; ++iCuePoint) {
4159 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].id);
4160 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].playOrderPosition);
4161 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId, 4);
4162 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].chunkStart);
4163 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].blockStart);
4164 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].sampleOffset);
4165 }
4166 } break;
4167
4169 {
4170 chunkSize = DRWAV_ACID_BYTES;
4171
4172 bytesWritten += drwav__write_or_count(pWav, "acid", 4);
4173 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
4174 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.acid.flags);
4175 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.midiUnityNote);
4176 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.reserved1);
4177 bytesWritten += drwav__write_or_count_f32ne_to_le(pWav, pMetadata->data.acid.reserved2);
4178 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.acid.numBeats);
4179 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.meterDenominator);
4180 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.meterNumerator);
4181 bytesWritten += drwav__write_or_count_f32ne_to_le(pWav, pMetadata->data.acid.tempo);
4182 } break;
4183
4185 {
4186 char reservedBuf[DRWAV_BEXT_RESERVED_BYTES];
4187 drwav_uint32 timeReferenceLow;
4188 drwav_uint32 timeReferenceHigh;
4189
4190 chunkSize = DRWAV_BEXT_BYTES + pMetadata->data.bext.codingHistorySize;
4191
4192 bytesWritten += drwav__write_or_count(pWav, "bext", 4);
4193 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
4194
4195 bytesWritten += drwav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pDescription, DRWAV_BEXT_DESCRIPTION_BYTES);
4196 bytesWritten += drwav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pOriginatorName, DRWAV_BEXT_ORIGINATOR_NAME_BYTES);
4197 bytesWritten += drwav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pOriginatorReference, DRWAV_BEXT_ORIGINATOR_REF_BYTES);
4198 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.bext.pOriginationDate, sizeof(pMetadata->data.bext.pOriginationDate));
4199 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.bext.pOriginationTime, sizeof(pMetadata->data.bext.pOriginationTime));
4200
4201 timeReferenceLow = (drwav_uint32)(pMetadata->data.bext.timeReference & 0xFFFFFFFF);
4202 timeReferenceHigh = (drwav_uint32)(pMetadata->data.bext.timeReference >> 32);
4203 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, timeReferenceLow);
4204 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, timeReferenceHigh);
4205
4206 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.version);
4207 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.bext.pUMID, DRWAV_BEXT_UMID_BYTES);
4208 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.loudnessValue);
4209 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.loudnessRange);
4210 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxTruePeakLevel);
4211 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxMomentaryLoudness);
4212 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxShortTermLoudness);
4213
4214 DRWAV_ZERO_MEMORY(reservedBuf, sizeof(reservedBuf));
4215 bytesWritten += drwav__write_or_count(pWav, reservedBuf, sizeof(reservedBuf));
4216
4217 if (pMetadata->data.bext.codingHistorySize > 0) {
4218 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.bext.pCodingHistory, pMetadata->data.bext.codingHistorySize);
4219 }
4220 } break;
4221
4223 {
4225 chunkSize = pMetadata->data.unknown.dataSizeInBytes;
4226
4227 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.id, 4);
4228 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
4229 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.pData, pMetadata->data.unknown.dataSizeInBytes);
4230 }
4231 } break;
4232
4233 default: break;
4234 }
4235 if ((chunkSize % 2) != 0) {
4236 bytesWritten += drwav__write_or_count_byte(pWav, 0);
4237 }
4238 }
4239
4240 if (hasListInfo) {
4241 drwav_uint32 chunkSize = 4; /* Start with 4 bytes for "INFO". */
4242 for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
4243 drwav_metadata* pMetadata = &pMetadatas[iMetadata];
4244
4246 chunkSize += 8; /* For id and string size. */
4247 chunkSize += pMetadata->data.infoText.stringLength + 1; /* Include null terminator. */
4249 chunkSize += 8; /* For id string size. */
4250 chunkSize += pMetadata->data.unknown.dataSizeInBytes;
4251 }
4252
4253 if ((chunkSize % 2) != 0) {
4254 chunkSize += 1;
4255 }
4256 }
4257
4258 bytesWritten += drwav__write_or_count(pWav, "LIST", 4);
4259 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
4260 bytesWritten += drwav__write_or_count(pWav, "INFO", 4);
4261
4262 for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
4263 drwav_metadata* pMetadata = &pMetadatas[iMetadata];
4264 drwav_uint32 subchunkSize = 0;
4265
4267 const char* pID = NULL;
4268
4269 switch (pMetadata->type) {
4270 case drwav_metadata_type_list_info_software: pID = "ISFT"; break;
4271 case drwav_metadata_type_list_info_copyright: pID = "ICOP"; break;
4272 case drwav_metadata_type_list_info_title: pID = "INAM"; break;
4273 case drwav_metadata_type_list_info_artist: pID = "IART"; break;
4274 case drwav_metadata_type_list_info_comment: pID = "ICMT"; break;
4275 case drwav_metadata_type_list_info_date: pID = "ICRD"; break;
4276 case drwav_metadata_type_list_info_genre: pID = "IGNR"; break;
4277 case drwav_metadata_type_list_info_album: pID = "IPRD"; break;
4278 case drwav_metadata_type_list_info_tracknumber: pID = "ITRK"; break;
4279 case drwav_metadata_type_list_info_location: pID = "IARL"; break;
4280 case drwav_metadata_type_list_info_organization: pID = "ICMS"; break;
4281 case drwav_metadata_type_list_info_keywords: pID = "IKEY"; break;
4282 case drwav_metadata_type_list_info_medium: pID = "IMED"; break;
4283 case drwav_metadata_type_list_info_description: pID = "ISBJ"; break;
4284 default: break;
4285 }
4286
4287 DRWAV_ASSERT(pID != NULL);
4288
4289 if (pMetadata->data.infoText.stringLength) {
4290 subchunkSize = pMetadata->data.infoText.stringLength + 1;
4291 bytesWritten += drwav__write_or_count(pWav, pID, 4);
4292 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, subchunkSize);
4293 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.infoText.pString, pMetadata->data.infoText.stringLength);
4294 bytesWritten += drwav__write_or_count_byte(pWav, '\0');
4295 }
4297 if (pMetadata->data.unknown.dataSizeInBytes) {
4298 subchunkSize = pMetadata->data.unknown.dataSizeInBytes;
4299
4300 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.id, 4);
4301 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.unknown.dataSizeInBytes);
4302 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.pData, subchunkSize);
4303 }
4304 }
4305
4306 if ((subchunkSize % 2) != 0) {
4307 bytesWritten += drwav__write_or_count_byte(pWav, 0);
4308 }
4309 }
4310 }
4311
4312 if (hasListAdtl) {
4313 drwav_uint32 chunkSize = 4; /* start with 4 bytes for "adtl" */
4314
4315 for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
4316 drwav_metadata* pMetadata = &pMetadatas[iMetadata];
4317
4318 switch (pMetadata->type)
4319 {
4322 {
4323 chunkSize += 8; /* for id and chunk size */
4324 chunkSize += DRWAV_LIST_LABEL_OR_NOTE_BYTES;
4325
4326 if (pMetadata->data.labelOrNote.stringLength > 0) {
4327 chunkSize += pMetadata->data.labelOrNote.stringLength + 1;
4328 }
4329 } break;
4330
4332 {
4333 chunkSize += 8; /* for id and chunk size */
4334 chunkSize += DRWAV_LIST_LABELLED_TEXT_BYTES;
4335
4336 if (pMetadata->data.labelledCueRegion.stringLength > 0) {
4337 chunkSize += pMetadata->data.labelledCueRegion.stringLength + 1;
4338 }
4339 } break;
4340
4342 {
4344 chunkSize += 8; /* for id and chunk size */
4345 chunkSize += pMetadata->data.unknown.dataSizeInBytes;
4346 }
4347 } break;
4348
4349 default: break;
4350 }
4351
4352 if ((chunkSize % 2) != 0) {
4353 chunkSize += 1;
4354 }
4355 }
4356
4357 bytesWritten += drwav__write_or_count(pWav, "LIST", 4);
4358 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
4359 bytesWritten += drwav__write_or_count(pWav, "adtl", 4);
4360
4361 for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
4362 drwav_metadata* pMetadata = &pMetadatas[iMetadata];
4363 drwav_uint32 subchunkSize = 0;
4364
4365 switch (pMetadata->type)
4366 {
4369 {
4370 if (pMetadata->data.labelOrNote.stringLength > 0) {
4371 const char *pID = NULL;
4372
4373 if (pMetadata->type == drwav_metadata_type_list_label) {
4374 pID = "labl";
4375 }
4376 else if (pMetadata->type == drwav_metadata_type_list_note) {
4377 pID = "note";
4378 }
4379
4380 DRWAV_ASSERT(pID != NULL);
4381 DRWAV_ASSERT(pMetadata->data.labelOrNote.pString != NULL);
4382
4383 subchunkSize = DRWAV_LIST_LABEL_OR_NOTE_BYTES;
4384
4385 bytesWritten += drwav__write_or_count(pWav, pID, 4);
4386 subchunkSize += pMetadata->data.labelOrNote.stringLength + 1;
4387 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, subchunkSize);
4388
4389 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelOrNote.cuePointId);
4390 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.labelOrNote.pString, pMetadata->data.labelOrNote.stringLength);
4391 bytesWritten += drwav__write_or_count_byte(pWav, '\0');
4392 }
4393 } break;
4394
4396 {
4397 subchunkSize = DRWAV_LIST_LABELLED_TEXT_BYTES;
4398
4399 bytesWritten += drwav__write_or_count(pWav, "ltxt", 4);
4400 if (pMetadata->data.labelledCueRegion.stringLength > 0) {
4401 subchunkSize += pMetadata->data.labelledCueRegion.stringLength + 1;
4402 }
4403 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, subchunkSize);
4404 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelledCueRegion.cuePointId);
4405 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelledCueRegion.sampleLength);
4406 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.labelledCueRegion.purposeId, 4);
4407 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.country);
4408 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.language);
4409 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.dialect);
4410 bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.codePage);
4411
4412 if (pMetadata->data.labelledCueRegion.stringLength > 0) {
4413 DRWAV_ASSERT(pMetadata->data.labelledCueRegion.pString != NULL);
4414
4415 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.labelledCueRegion.pString, pMetadata->data.labelledCueRegion.stringLength);
4416 bytesWritten += drwav__write_or_count_byte(pWav, '\0');
4417 }
4418 } break;
4419
4421 {
4423 subchunkSize = pMetadata->data.unknown.dataSizeInBytes;
4424
4425 DRWAV_ASSERT(pMetadata->data.unknown.pData != NULL);
4426 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.id, 4);
4427 bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, subchunkSize);
4428 bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.pData, subchunkSize);
4429 }
4430 } break;
4431
4432 default: break;
4433 }
4434
4435 if ((subchunkSize % 2) != 0) {
4436 bytesWritten += drwav__write_or_count_byte(pWav, 0);
4437 }
4438 }
4439 }
4440
4441 DRWAV_ASSERT((bytesWritten % 2) == 0);
4442
4443 return bytesWritten;
4444}
4445
4446DRWAV_PRIVATE drwav_uint32 drwav__riff_chunk_size_riff(drwav_uint64 dataChunkSize, drwav_metadata* pMetadata, drwav_uint32 metadataCount)
4447{
4448 drwav_uint64 chunkSize = 4 + 24 + (drwav_uint64)drwav__write_or_count_metadata(NULL, pMetadata, metadataCount) + 8 + dataChunkSize + drwav__chunk_padding_size_riff(dataChunkSize); /* 4 = "WAVE". 24 = "fmt " chunk. 8 = "data" + u32 data size. */
4449 if (chunkSize > 0xFFFFFFFFUL) {
4450 chunkSize = 0xFFFFFFFFUL;
4451 }
4452
4453 return (drwav_uint32)chunkSize; /* Safe cast due to the clamp above. */
4454}
4455
4456DRWAV_PRIVATE drwav_uint32 drwav__data_chunk_size_riff(drwav_uint64 dataChunkSize)
4457{
4458 if (dataChunkSize <= 0xFFFFFFFFUL) {
4459 return (drwav_uint32)dataChunkSize;
4460 } else {
4461 return 0xFFFFFFFFUL;
4462 }
4463}
4464
4465DRWAV_PRIVATE drwav_uint64 drwav__riff_chunk_size_w64(drwav_uint64 dataChunkSize)
4466{
4467 drwav_uint64 dataSubchunkPaddingSize = drwav__chunk_padding_size_w64(dataChunkSize);
4468
4469 return 80 + 24 + dataChunkSize + dataSubchunkPaddingSize; /* +24 because W64 includes the size of the GUID and size fields. */
4470}
4471
4472DRWAV_PRIVATE drwav_uint64 drwav__data_chunk_size_w64(drwav_uint64 dataChunkSize)
4473{
4474 return 24 + dataChunkSize; /* +24 because W64 includes the size of the GUID and size fields. */
4475}
4476
4477DRWAV_PRIVATE drwav_uint64 drwav__riff_chunk_size_rf64(drwav_uint64 dataChunkSize, drwav_metadata *metadata, drwav_uint32 numMetadata)
4478{
4479 drwav_uint64 chunkSize = 4 + 36 + 24 + (drwav_uint64)drwav__write_or_count_metadata(NULL, metadata, numMetadata) + 8 + dataChunkSize + drwav__chunk_padding_size_riff(dataChunkSize); /* 4 = "WAVE". 36 = "ds64" chunk. 24 = "fmt " chunk. 8 = "data" + u32 data size. */
4480 if (chunkSize > 0xFFFFFFFFUL) {
4481 chunkSize = 0xFFFFFFFFUL;
4482 }
4483
4484 return chunkSize;
4485}
4486
4487DRWAV_PRIVATE drwav_uint64 drwav__data_chunk_size_rf64(drwav_uint64 dataChunkSize)
4488{
4489 return dataChunkSize;
4490}
4491
4492
4493
4494DRWAV_PRIVATE drwav_bool32 drwav_preinit_write(drwav* pWav, const drwav_data_format* pFormat, drwav_bool32 isSequential, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
4495{
4496 if (pWav == NULL || onWrite == NULL) {
4497 return DRWAV_FALSE;
4498 }
4499
4500 if (!isSequential && onSeek == NULL) {
4501 return DRWAV_FALSE; /* <-- onSeek is required when in non-sequential mode. */
4502 }
4503
4504 /* Not currently supporting compressed formats. Will need to add support for the "fact" chunk before we enable this. */
4505 if (pFormat->format == DR_WAVE_FORMAT_EXTENSIBLE) {
4506 return DRWAV_FALSE;
4507 }
4508 if (pFormat->format == DR_WAVE_FORMAT_ADPCM || pFormat->format == DR_WAVE_FORMAT_DVI_ADPCM) {
4509 return DRWAV_FALSE;
4510 }
4511
4512 DRWAV_ZERO_MEMORY(pWav, sizeof(*pWav));
4513 pWav->onWrite = onWrite;
4514 pWav->onSeek = onSeek;
4515 pWav->pUserData = pUserData;
4516 pWav->allocationCallbacks = drwav_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
4517
4518 if (pWav->allocationCallbacks.onFree == NULL || (pWav->allocationCallbacks.onMalloc == NULL && pWav->allocationCallbacks.onRealloc == NULL)) {
4519 return DRWAV_FALSE; /* Invalid allocation callbacks. */
4520 }
4521
4522 pWav->fmt.formatTag = (drwav_uint16)pFormat->format;
4523 pWav->fmt.channels = (drwav_uint16)pFormat->channels;
4524 pWav->fmt.sampleRate = pFormat->sampleRate;
4525 pWav->fmt.avgBytesPerSec = (drwav_uint32)((pFormat->bitsPerSample * pFormat->sampleRate * pFormat->channels) / 8);
4526 pWav->fmt.blockAlign = (drwav_uint16)((pFormat->channels * pFormat->bitsPerSample) / 8);
4527 pWav->fmt.bitsPerSample = (drwav_uint16)pFormat->bitsPerSample;
4528 pWav->fmt.extendedSize = 0;
4529 pWav->isSequentialWrite = isSequential;
4530
4531 return DRWAV_TRUE;
4532}
4533
4534
4535DRWAV_PRIVATE drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount)
4536{
4537 /* The function assumes drwav_preinit_write() was called beforehand. */
4538
4539 size_t runningPos = 0;
4540 drwav_uint64 initialDataChunkSize = 0;
4541 drwav_uint64 chunkSizeFMT;
4542
4543 /*
4544 The initial values for the "RIFF" and "data" chunks depends on whether or not we are initializing in sequential mode or not. In
4545 sequential mode we set this to its final values straight away since they can be calculated from the total sample count. In non-
4546 sequential mode we initialize it all to zero and fill it out in drwav_uninit() using a backwards seek.
4547 */
4548 if (pWav->isSequentialWrite) {
4549 initialDataChunkSize = (totalSampleCount * pWav->fmt.bitsPerSample) / 8;
4550
4551 /*
4552 The RIFF container has a limit on the number of samples. drwav is not allowing this. There's no practical limits for Wave64
4553 so for the sake of simplicity I'm not doing any validation for that.
4554 */
4555 if (pFormat->container == drwav_container_riff) {
4556 if (initialDataChunkSize > (0xFFFFFFFFUL - 36)) {
4557 return DRWAV_FALSE; /* Not enough room to store every sample. */
4558 }
4559 }
4560 }
4561
4562 pWav->dataChunkDataSizeTargetWrite = initialDataChunkSize;
4563
4564
4565 /* "RIFF" chunk. */
4566 if (pFormat->container == drwav_container_riff) {
4567 drwav_uint32 chunkSizeRIFF = 36 + (drwav_uint32)initialDataChunkSize; /* +36 = "WAVE" + [sizeof "fmt " chunk] + [data chunk header] */
4568 runningPos += drwav__write(pWav, "RIFF", 4);
4569 runningPos += drwav__write_u32ne_to_le(pWav, chunkSizeRIFF);
4570 runningPos += drwav__write(pWav, "WAVE", 4);
4571 } else if (pFormat->container == drwav_container_w64) {
4572 drwav_uint64 chunkSizeRIFF = 80 + 24 + initialDataChunkSize; /* +24 because W64 includes the size of the GUID and size fields. */
4573 runningPos += drwav__write(pWav, drwavGUID_W64_RIFF, 16);
4574 runningPos += drwav__write_u64ne_to_le(pWav, chunkSizeRIFF);
4575 runningPos += drwav__write(pWav, drwavGUID_W64_WAVE, 16);
4576 } else if (pFormat->container == drwav_container_rf64) {
4577 runningPos += drwav__write(pWav, "RF64", 4);
4578 runningPos += drwav__write_u32ne_to_le(pWav, 0xFFFFFFFF); /* Always 0xFFFFFFFF for RF64. Set to a proper value in the "ds64" chunk. */
4579 runningPos += drwav__write(pWav, "WAVE", 4);
4580 } else {
4581 return DRWAV_FALSE; /* Container not supported for writing. */
4582 }
4583
4584
4585 /* "ds64" chunk (RF64 only). */
4586 if (pFormat->container == drwav_container_rf64) {
4587 drwav_uint32 initialds64ChunkSize = 28; /* 28 = [Size of RIFF (8 bytes)] + [Size of DATA (8 bytes)] + [Sample Count (8 bytes)] + [Table Length (4 bytes)]. Table length always set to 0. */
4588 drwav_uint64 initialRiffChunkSize = 8 + initialds64ChunkSize + initialDataChunkSize; /* +8 for the ds64 header. */
4589
4590 runningPos += drwav__write(pWav, "ds64", 4);
4591 runningPos += drwav__write_u32ne_to_le(pWav, initialds64ChunkSize); /* Size of ds64. */
4592 runningPos += drwav__write_u64ne_to_le(pWav, initialRiffChunkSize); /* Size of RIFF. Set to true value at the end. */
4593 runningPos += drwav__write_u64ne_to_le(pWav, initialDataChunkSize); /* Size of DATA. Set to true value at the end. */
4594 runningPos += drwav__write_u64ne_to_le(pWav, totalSampleCount); /* Sample count. */
4595 runningPos += drwav__write_u32ne_to_le(pWav, 0); /* Table length. Always set to zero in our case since we're not doing any other chunks than "DATA". */
4596 }
4597
4598
4599 /* "fmt " chunk. */
4600 if (pFormat->container == drwav_container_riff || pFormat->container == drwav_container_rf64) {
4601 chunkSizeFMT = 16;
4602 runningPos += drwav__write(pWav, "fmt ", 4);
4603 runningPos += drwav__write_u32ne_to_le(pWav, (drwav_uint32)chunkSizeFMT);
4604 } else if (pFormat->container == drwav_container_w64) {
4605 chunkSizeFMT = 40;
4606 runningPos += drwav__write(pWav, drwavGUID_W64_FMT, 16);
4607 runningPos += drwav__write_u64ne_to_le(pWav, chunkSizeFMT);
4608 }
4609
4610 runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.formatTag);
4611 runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.channels);
4612 runningPos += drwav__write_u32ne_to_le(pWav, pWav->fmt.sampleRate);
4613 runningPos += drwav__write_u32ne_to_le(pWav, pWav->fmt.avgBytesPerSec);
4614 runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.blockAlign);
4615 runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.bitsPerSample);
4616
4617 /* TODO: is a 'fact' chunk required for DR_WAVE_FORMAT_IEEE_FLOAT? */
4618
4619 if (!pWav->isSequentialWrite && pWav->pMetadata != NULL && pWav->metadataCount > 0 && (pFormat->container == drwav_container_riff || pFormat->container == drwav_container_rf64)) {
4620 runningPos += drwav__write_or_count_metadata(pWav, pWav->pMetadata, pWav->metadataCount);
4621 }
4622
4623 pWav->dataChunkDataPos = runningPos;
4624
4625 /* "data" chunk. */
4626 if (pFormat->container == drwav_container_riff) {
4627 drwav_uint32 chunkSizeDATA = (drwav_uint32)initialDataChunkSize;
4628 runningPos += drwav__write(pWav, "data", 4);
4629 runningPos += drwav__write_u32ne_to_le(pWav, chunkSizeDATA);
4630 } else if (pFormat->container == drwav_container_w64) {
4631 drwav_uint64 chunkSizeDATA = 24 + initialDataChunkSize; /* +24 because W64 includes the size of the GUID and size fields. */
4632 runningPos += drwav__write(pWav, drwavGUID_W64_DATA, 16);
4633 runningPos += drwav__write_u64ne_to_le(pWav, chunkSizeDATA);
4634 } else if (pFormat->container == drwav_container_rf64) {
4635 runningPos += drwav__write(pWav, "data", 4);
4636 runningPos += drwav__write_u32ne_to_le(pWav, 0xFFFFFFFF); /* Always set to 0xFFFFFFFF for RF64. The true size of the data chunk is specified in the ds64 chunk. */
4637 }
4638
4639 /* Set some properties for the client's convenience. */
4640 pWav->container = pFormat->container;
4641 pWav->channels = (drwav_uint16)pFormat->channels;
4642 pWav->sampleRate = pFormat->sampleRate;
4643 pWav->bitsPerSample = (drwav_uint16)pFormat->bitsPerSample;
4644 pWav->translatedFormatTag = (drwav_uint16)pFormat->format;
4645 pWav->dataChunkDataPos = runningPos;
4646
4647 return DRWAV_TRUE;
4648}
4649
4650
4651DRWAV_API drwav_bool32 drwav_init_write(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
4652{
4653 if (!drwav_preinit_write(pWav, pFormat, DRWAV_FALSE, onWrite, onSeek, pUserData, pAllocationCallbacks)) {
4654 return DRWAV_FALSE;
4655 }
4656
4657 return drwav_init_write__internal(pWav, pFormat, 0); /* DRWAV_FALSE = Not Sequential */
4658}
4659
4660DRWAV_API drwav_bool32 drwav_init_write_sequential(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
4661{
4662 if (!drwav_preinit_write(pWav, pFormat, DRWAV_TRUE, onWrite, NULL, pUserData, pAllocationCallbacks)) {
4663 return DRWAV_FALSE;
4664 }
4665
4666 return drwav_init_write__internal(pWav, pFormat, totalSampleCount); /* DRWAV_TRUE = Sequential */
4667}
4668
4669DRWAV_API drwav_bool32 drwav_init_write_sequential_pcm_frames(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
4670{
4671 if (pFormat == NULL) {
4672 return DRWAV_FALSE;
4673 }
4674
4675 return drwav_init_write_sequential(pWav, pFormat, totalPCMFrameCount*pFormat->channels, onWrite, pUserData, pAllocationCallbacks);
4676}
4677
4678DRWAV_API drwav_bool32 drwav_init_write_with_metadata(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks, drwav_metadata* pMetadata, drwav_uint32 metadataCount)
4679{
4680 if (!drwav_preinit_write(pWav, pFormat, DRWAV_FALSE, onWrite, onSeek, pUserData, pAllocationCallbacks)) {
4681 return DRWAV_FALSE;
4682 }
4683
4684 pWav->pMetadata = pMetadata;
4685 pWav->metadataCount = metadataCount;
4686
4687 return drwav_init_write__internal(pWav, pFormat, 0);
4688}
4689
4690
4691DRWAV_API drwav_uint64 drwav_target_write_size_bytes(const drwav_data_format* pFormat, drwav_uint64 totalFrameCount, drwav_metadata* pMetadata, drwav_uint32 metadataCount)
4692{
4693 /* Casting totalFrameCount to drwav_int64 for VC6 compatibility. No issues in practice because nobody is going to exhaust the whole 63 bits. */
4694 drwav_uint64 targetDataSizeBytes = (drwav_uint64)((drwav_int64)totalFrameCount * pFormat->channels * pFormat->bitsPerSample/8.0);
4695 drwav_uint64 riffChunkSizeBytes;
4696 drwav_uint64 fileSizeBytes = 0;
4697
4698 if (pFormat->container == drwav_container_riff) {
4699 riffChunkSizeBytes = drwav__riff_chunk_size_riff(targetDataSizeBytes, pMetadata, metadataCount);
4700 fileSizeBytes = (8 + riffChunkSizeBytes); /* +8 because WAV doesn't include the size of the ChunkID and ChunkSize fields. */
4701 } else if (pFormat->container == drwav_container_w64) {
4702 riffChunkSizeBytes = drwav__riff_chunk_size_w64(targetDataSizeBytes);
4703 fileSizeBytes = riffChunkSizeBytes;
4704 } else if (pFormat->container == drwav_container_rf64) {
4705 riffChunkSizeBytes = drwav__riff_chunk_size_rf64(targetDataSizeBytes, pMetadata, metadataCount);
4706 fileSizeBytes = (8 + riffChunkSizeBytes); /* +8 because WAV doesn't include the size of the ChunkID and ChunkSize fields. */
4707 }
4708
4709 return fileSizeBytes;
4710}
4711
4712
4713#ifndef DR_WAV_NO_STDIO
4714
4715/* Errno */
4716/* drwav_result_from_errno() is only used for fopen() and wfopen() so putting it inside DR_WAV_NO_STDIO for now. If something else needs this later we can move it out. */
4717#include <errno.h>
4718DRWAV_PRIVATE drwav_result drwav_result_from_errno(int e)
4719{
4720 switch (e)
4721 {
4722 case 0: return DRWAV_SUCCESS;
4723 #ifdef EPERM
4724 case EPERM: return DRWAV_INVALID_OPERATION;
4725 #endif
4726 #ifdef ENOENT
4727 case ENOENT: return DRWAV_DOES_NOT_EXIST;
4728 #endif
4729 #ifdef ESRCH
4730 case ESRCH: return DRWAV_DOES_NOT_EXIST;
4731 #endif
4732 #ifdef EINTR
4733 case EINTR: return DRWAV_INTERRUPT;
4734 #endif
4735 #ifdef EIO
4736 case EIO: return DRWAV_IO_ERROR;
4737 #endif
4738 #ifdef ENXIO
4739 case ENXIO: return DRWAV_DOES_NOT_EXIST;
4740 #endif
4741 #ifdef E2BIG
4742 case E2BIG: return DRWAV_INVALID_ARGS;
4743 #endif
4744 #ifdef ENOEXEC
4745 case ENOEXEC: return DRWAV_INVALID_FILE;
4746 #endif
4747 #ifdef EBADF
4748 case EBADF: return DRWAV_INVALID_FILE;
4749 #endif
4750 #ifdef ECHILD
4751 case ECHILD: return DRWAV_ERROR;
4752 #endif
4753 #ifdef EAGAIN
4754 case EAGAIN: return DRWAV_UNAVAILABLE;
4755 #endif
4756 #ifdef ENOMEM
4757 case ENOMEM: return DRWAV_OUT_OF_MEMORY;
4758 #endif
4759 #ifdef EACCES
4760 case EACCES: return DRWAV_ACCESS_DENIED;
4761 #endif
4762 #ifdef EFAULT
4763 case EFAULT: return DRWAV_BAD_ADDRESS;
4764 #endif
4765 #ifdef ENOTBLK
4766 case ENOTBLK: return DRWAV_ERROR;
4767 #endif
4768 #ifdef EBUSY
4769 case EBUSY: return DRWAV_BUSY;
4770 #endif
4771 #ifdef EEXIST
4772 case EEXIST: return DRWAV_ALREADY_EXISTS;
4773 #endif
4774 #ifdef EXDEV
4775 case EXDEV: return DRWAV_ERROR;
4776 #endif
4777 #ifdef ENODEV
4778 case ENODEV: return DRWAV_DOES_NOT_EXIST;
4779 #endif
4780 #ifdef ENOTDIR
4781 case ENOTDIR: return DRWAV_NOT_DIRECTORY;
4782 #endif
4783 #ifdef EISDIR
4784 case EISDIR: return DRWAV_IS_DIRECTORY;
4785 #endif
4786 #ifdef EINVAL
4787 case EINVAL: return DRWAV_INVALID_ARGS;
4788 #endif
4789 #ifdef ENFILE
4790 case ENFILE: return DRWAV_TOO_MANY_OPEN_FILES;
4791 #endif
4792 #ifdef EMFILE
4793 case EMFILE: return DRWAV_TOO_MANY_OPEN_FILES;
4794 #endif
4795 #ifdef ENOTTY
4796 case ENOTTY: return DRWAV_INVALID_OPERATION;
4797 #endif
4798 #ifdef ETXTBSY
4799 case ETXTBSY: return DRWAV_BUSY;
4800 #endif
4801 #ifdef EFBIG
4802 case EFBIG: return DRWAV_TOO_BIG;
4803 #endif
4804 #ifdef ENOSPC
4805 case ENOSPC: return DRWAV_NO_SPACE;
4806 #endif
4807 #ifdef ESPIPE
4808 case ESPIPE: return DRWAV_BAD_SEEK;
4809 #endif
4810 #ifdef EROFS
4811 case EROFS: return DRWAV_ACCESS_DENIED;
4812 #endif
4813 #ifdef EMLINK
4814 case EMLINK: return DRWAV_TOO_MANY_LINKS;
4815 #endif
4816 #ifdef EPIPE
4817 case EPIPE: return DRWAV_BAD_PIPE;
4818 #endif
4819 #ifdef EDOM
4820 case EDOM: return DRWAV_OUT_OF_RANGE;
4821 #endif
4822 #ifdef ERANGE
4823 case ERANGE: return DRWAV_OUT_OF_RANGE;
4824 #endif
4825 #ifdef EDEADLK
4826 case EDEADLK: return DRWAV_DEADLOCK;
4827 #endif
4828 #ifdef ENAMETOOLONG
4829 case ENAMETOOLONG: return DRWAV_PATH_TOO_LONG;
4830 #endif
4831 #ifdef ENOLCK
4832 case ENOLCK: return DRWAV_ERROR;
4833 #endif
4834 #ifdef ENOSYS
4835 case ENOSYS: return DRWAV_NOT_IMPLEMENTED;
4836 #endif
4837 #if defined(ENOTEMPTY) && ENOTEMPTY != EEXIST /* In AIX, ENOTEMPTY and EEXIST use the same value. */
4838 case ENOTEMPTY: return DRWAV_DIRECTORY_NOT_EMPTY;
4839 #endif
4840 #ifdef ELOOP
4841 case ELOOP: return DRWAV_TOO_MANY_LINKS;
4842 #endif
4843 #ifdef ENOMSG
4844 case ENOMSG: return DRWAV_NO_MESSAGE;
4845 #endif
4846 #ifdef EIDRM
4847 case EIDRM: return DRWAV_ERROR;
4848 #endif
4849 #ifdef ECHRNG
4850 case ECHRNG: return DRWAV_ERROR;
4851 #endif
4852 #ifdef EL2NSYNC
4853 case EL2NSYNC: return DRWAV_ERROR;
4854 #endif
4855 #ifdef EL3HLT
4856 case EL3HLT: return DRWAV_ERROR;
4857 #endif
4858 #ifdef EL3RST
4859 case EL3RST: return DRWAV_ERROR;
4860 #endif
4861 #ifdef ELNRNG
4862 case ELNRNG: return DRWAV_OUT_OF_RANGE;
4863 #endif
4864 #ifdef EUNATCH
4865 case EUNATCH: return DRWAV_ERROR;
4866 #endif
4867 #ifdef ENOCSI
4868 case ENOCSI: return DRWAV_ERROR;
4869 #endif
4870 #ifdef EL2HLT
4871 case EL2HLT: return DRWAV_ERROR;
4872 #endif
4873 #ifdef EBADE
4874 case EBADE: return DRWAV_ERROR;
4875 #endif
4876 #ifdef EBADR
4877 case EBADR: return DRWAV_ERROR;
4878 #endif
4879 #ifdef EXFULL
4880 case EXFULL: return DRWAV_ERROR;
4881 #endif
4882 #ifdef ENOANO
4883 case ENOANO: return DRWAV_ERROR;
4884 #endif
4885 #ifdef EBADRQC
4886 case EBADRQC: return DRWAV_ERROR;
4887 #endif
4888 #ifdef EBADSLT
4889 case EBADSLT: return DRWAV_ERROR;
4890 #endif
4891 #ifdef EBFONT
4892 case EBFONT: return DRWAV_INVALID_FILE;
4893 #endif
4894 #ifdef ENOSTR
4895 case ENOSTR: return DRWAV_ERROR;
4896 #endif
4897 #ifdef ENODATA
4898 case ENODATA: return DRWAV_NO_DATA_AVAILABLE;
4899 #endif
4900 #ifdef ETIME
4901 case ETIME: return DRWAV_TIMEOUT;
4902 #endif
4903 #ifdef ENOSR
4904 case ENOSR: return DRWAV_NO_DATA_AVAILABLE;
4905 #endif
4906 #ifdef ENONET
4907 case ENONET: return DRWAV_NO_NETWORK;
4908 #endif
4909 #ifdef ENOPKG
4910 case ENOPKG: return DRWAV_ERROR;
4911 #endif
4912 #ifdef EREMOTE
4913 case EREMOTE: return DRWAV_ERROR;
4914 #endif
4915 #ifdef ENOLINK
4916 case ENOLINK: return DRWAV_ERROR;
4917 #endif
4918 #ifdef EADV
4919 case EADV: return DRWAV_ERROR;
4920 #endif
4921 #ifdef ESRMNT
4922 case ESRMNT: return DRWAV_ERROR;
4923 #endif
4924 #ifdef ECOMM
4925 case ECOMM: return DRWAV_ERROR;
4926 #endif
4927 #ifdef EPROTO
4928 case EPROTO: return DRWAV_ERROR;
4929 #endif
4930 #ifdef EMULTIHOP
4931 case EMULTIHOP: return DRWAV_ERROR;
4932 #endif
4933 #ifdef EDOTDOT
4934 case EDOTDOT: return DRWAV_ERROR;
4935 #endif
4936 #ifdef EBADMSG
4937 case EBADMSG: return DRWAV_BAD_MESSAGE;
4938 #endif
4939 #ifdef EOVERFLOW
4940 case EOVERFLOW: return DRWAV_TOO_BIG;
4941 #endif
4942 #ifdef ENOTUNIQ
4943 case ENOTUNIQ: return DRWAV_NOT_UNIQUE;
4944 #endif
4945 #ifdef EBADFD
4946 case EBADFD: return DRWAV_ERROR;
4947 #endif
4948 #ifdef EREMCHG
4949 case EREMCHG: return DRWAV_ERROR;
4950 #endif
4951 #ifdef ELIBACC
4952 case ELIBACC: return DRWAV_ACCESS_DENIED;
4953 #endif
4954 #ifdef ELIBBAD
4955 case ELIBBAD: return DRWAV_INVALID_FILE;
4956 #endif
4957 #ifdef ELIBSCN
4958 case ELIBSCN: return DRWAV_INVALID_FILE;
4959 #endif
4960 #ifdef ELIBMAX
4961 case ELIBMAX: return DRWAV_ERROR;
4962 #endif
4963 #ifdef ELIBEXEC
4964 case ELIBEXEC: return DRWAV_ERROR;
4965 #endif
4966 #ifdef EILSEQ
4967 case EILSEQ: return DRWAV_INVALID_DATA;
4968 #endif
4969 #ifdef ERESTART
4970 case ERESTART: return DRWAV_ERROR;
4971 #endif
4972 #ifdef ESTRPIPE
4973 case ESTRPIPE: return DRWAV_ERROR;
4974 #endif
4975 #ifdef EUSERS
4976 case EUSERS: return DRWAV_ERROR;
4977 #endif
4978 #ifdef ENOTSOCK
4979 case ENOTSOCK: return DRWAV_NOT_SOCKET;
4980 #endif
4981 #ifdef EDESTADDRREQ
4982 case EDESTADDRREQ: return DRWAV_NO_ADDRESS;
4983 #endif
4984 #ifdef EMSGSIZE
4985 case EMSGSIZE: return DRWAV_TOO_BIG;
4986 #endif
4987 #ifdef EPROTOTYPE
4988 case EPROTOTYPE: return DRWAV_BAD_PROTOCOL;
4989 #endif
4990 #ifdef ENOPROTOOPT
4991 case ENOPROTOOPT: return DRWAV_PROTOCOL_UNAVAILABLE;
4992 #endif
4993 #ifdef EPROTONOSUPPORT
4994 case EPROTONOSUPPORT: return DRWAV_PROTOCOL_NOT_SUPPORTED;
4995 #endif
4996 #ifdef ESOCKTNOSUPPORT
4997 case ESOCKTNOSUPPORT: return DRWAV_SOCKET_NOT_SUPPORTED;
4998 #endif
4999 #ifdef EOPNOTSUPP
5000 case EOPNOTSUPP: return DRWAV_INVALID_OPERATION;
5001 #endif
5002 #ifdef EPFNOSUPPORT
5003 case EPFNOSUPPORT: return DRWAV_PROTOCOL_FAMILY_NOT_SUPPORTED;
5004 #endif
5005 #ifdef EAFNOSUPPORT
5006 case EAFNOSUPPORT: return DRWAV_ADDRESS_FAMILY_NOT_SUPPORTED;
5007 #endif
5008 #ifdef EADDRINUSE
5009 case EADDRINUSE: return DRWAV_ALREADY_IN_USE;
5010 #endif
5011 #ifdef EADDRNOTAVAIL
5012 case EADDRNOTAVAIL: return DRWAV_ERROR;
5013 #endif
5014 #ifdef ENETDOWN
5015 case ENETDOWN: return DRWAV_NO_NETWORK;
5016 #endif
5017 #ifdef ENETUNREACH
5018 case ENETUNREACH: return DRWAV_NO_NETWORK;
5019 #endif
5020 #ifdef ENETRESET
5021 case ENETRESET: return DRWAV_NO_NETWORK;
5022 #endif
5023 #ifdef ECONNABORTED
5024 case ECONNABORTED: return DRWAV_NO_NETWORK;
5025 #endif
5026 #ifdef ECONNRESET
5027 case ECONNRESET: return DRWAV_CONNECTION_RESET;
5028 #endif
5029 #ifdef ENOBUFS
5030 case ENOBUFS: return DRWAV_NO_SPACE;
5031 #endif
5032 #ifdef EISCONN
5033 case EISCONN: return DRWAV_ALREADY_CONNECTED;
5034 #endif
5035 #ifdef ENOTCONN
5036 case ENOTCONN: return DRWAV_NOT_CONNECTED;
5037 #endif
5038 #ifdef ESHUTDOWN
5039 case ESHUTDOWN: return DRWAV_ERROR;
5040 #endif
5041 #ifdef ETOOMANYREFS
5042 case ETOOMANYREFS: return DRWAV_ERROR;
5043 #endif
5044 #ifdef ETIMEDOUT
5045 case ETIMEDOUT: return DRWAV_TIMEOUT;
5046 #endif
5047 #ifdef ECONNREFUSED
5048 case ECONNREFUSED: return DRWAV_CONNECTION_REFUSED;
5049 #endif
5050 #ifdef EHOSTDOWN
5051 case EHOSTDOWN: return DRWAV_NO_HOST;
5052 #endif
5053 #ifdef EHOSTUNREACH
5054 case EHOSTUNREACH: return DRWAV_NO_HOST;
5055 #endif
5056 #ifdef EALREADY
5057 case EALREADY: return DRWAV_IN_PROGRESS;
5058 #endif
5059 #ifdef EINPROGRESS
5060 case EINPROGRESS: return DRWAV_IN_PROGRESS;
5061 #endif
5062 #ifdef ESTALE
5063 case ESTALE: return DRWAV_INVALID_FILE;
5064 #endif
5065 #ifdef EUCLEAN
5066 case EUCLEAN: return DRWAV_ERROR;
5067 #endif
5068 #ifdef ENOTNAM
5069 case ENOTNAM: return DRWAV_ERROR;
5070 #endif
5071 #ifdef ENAVAIL
5072 case ENAVAIL: return DRWAV_ERROR;
5073 #endif
5074 #ifdef EISNAM
5075 case EISNAM: return DRWAV_ERROR;
5076 #endif
5077 #ifdef EREMOTEIO
5078 case EREMOTEIO: return DRWAV_IO_ERROR;
5079 #endif
5080 #ifdef EDQUOT
5081 case EDQUOT: return DRWAV_NO_SPACE;
5082 #endif
5083 #ifdef ENOMEDIUM
5084 case ENOMEDIUM: return DRWAV_DOES_NOT_EXIST;
5085 #endif
5086 #ifdef EMEDIUMTYPE
5087 case EMEDIUMTYPE: return DRWAV_ERROR;
5088 #endif
5089 #ifdef ECANCELED
5090 case ECANCELED: return DRWAV_CANCELLED;
5091 #endif
5092 #ifdef ENOKEY
5093 case ENOKEY: return DRWAV_ERROR;
5094 #endif
5095 #ifdef EKEYEXPIRED
5096 case EKEYEXPIRED: return DRWAV_ERROR;
5097 #endif
5098 #ifdef EKEYREVOKED
5099 case EKEYREVOKED: return DRWAV_ERROR;
5100 #endif
5101 #ifdef EKEYREJECTED
5102 case EKEYREJECTED: return DRWAV_ERROR;
5103 #endif
5104 #ifdef EOWNERDEAD
5105 case EOWNERDEAD: return DRWAV_ERROR;
5106 #endif
5107 #ifdef ENOTRECOVERABLE
5108 case ENOTRECOVERABLE: return DRWAV_ERROR;
5109 #endif
5110 #ifdef ERFKILL
5111 case ERFKILL: return DRWAV_ERROR;
5112 #endif
5113 #ifdef EHWPOISON
5114 case EHWPOISON: return DRWAV_ERROR;
5115 #endif
5116 default: return DRWAV_ERROR;
5117 }
5118}
5119/* End Errno */
5120
5121/* fopen */
5122DRWAV_PRIVATE drwav_result drwav_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
5123{
5124#if defined(_MSC_VER) && _MSC_VER >= 1400
5125 errno_t err;
5126#endif
5127
5128 if (ppFile != NULL) {
5129 *ppFile = NULL; /* Safety. */
5130 }
5131
5132 if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
5133 return DRWAV_INVALID_ARGS;
5134 }
5135
5136#if defined(_MSC_VER) && _MSC_VER >= 1400
5137 err = fopen_s(ppFile, pFilePath, pOpenMode);
5138 if (err != 0) {
5139 return drwav_result_from_errno(err);
5140 }
5141#else
5142#if defined(_WIN32) || defined(__APPLE__)
5143 *ppFile = fopen(pFilePath, pOpenMode);
5144#else
5145 #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
5146 *ppFile = fopen64(pFilePath, pOpenMode);
5147 #else
5148 *ppFile = fopen(pFilePath, pOpenMode);
5149 #endif
5150#endif
5151 if (*ppFile == NULL) {
5152 drwav_result result = drwav_result_from_errno(errno);
5153 if (result == DRWAV_SUCCESS) {
5154 result = DRWAV_ERROR; /* Just a safety check to make sure we never ever return success when pFile == NULL. */
5155 }
5156
5157 return result;
5158 }
5159#endif
5160
5161 return DRWAV_SUCCESS;
5162}
5163
5164/*
5165_wfopen() isn't always available in all compilation environments.
5166
5167 * Windows only.
5168 * MSVC seems to support it universally as far back as VC6 from what I can tell (haven't checked further back).
5169 * MinGW-64 (both 32- and 64-bit) seems to support it.
5170 * MinGW wraps it in !defined(__STRICT_ANSI__).
5171 * OpenWatcom wraps it in !defined(_NO_EXT_KEYS).
5172
5173This can be reviewed as compatibility issues arise. The preference is to use _wfopen_s() and _wfopen() as opposed to the wcsrtombs()
5174fallback, so if you notice your compiler not detecting this properly I'm happy to look at adding support.
5175*/
5176#if defined(_WIN32)
5177 #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
5178 #define DRWAV_HAS_WFOPEN
5179 #endif
5180#endif
5181
5182#ifndef DR_WAV_NO_WCHAR
5183DRWAV_PRIVATE drwav_result drwav_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const drwav_allocation_callbacks* pAllocationCallbacks)
5184{
5185 if (ppFile != NULL) {
5186 *ppFile = NULL; /* Safety. */
5187 }
5188
5189 if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
5190 return DRWAV_INVALID_ARGS;
5191 }
5192
5193#if defined(DRWAV_HAS_WFOPEN)
5194 {
5195 /* Use _wfopen() on Windows. */
5196 #if defined(_MSC_VER) && _MSC_VER >= 1400
5197 errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
5198 if (err != 0) {
5199 return drwav_result_from_errno(err);
5200 }
5201 #else
5202 *ppFile = _wfopen(pFilePath, pOpenMode);
5203 if (*ppFile == NULL) {
5204 return drwav_result_from_errno(errno);
5205 }
5206 #endif
5207 (void)pAllocationCallbacks;
5208 }
5209#else
5210 /*
5211 Use fopen() on anything other than Windows. Requires a conversion. This is annoying because
5212 fopen() is locale specific. The only real way I can think of to do this is with wcsrtombs(). Note
5213 that wcstombs() is apparently not thread-safe because it uses a static global mbstate_t object for
5214 maintaining state. I've checked this with -std=c89 and it works, but if somebody get's a compiler
5215 error I'll look into improving compatibility.
5216 */
5217
5218 /*
5219 Some compilers don't support wchar_t or wcsrtombs() which we're using below. In this case we just
5220 need to abort with an error. If you encounter a compiler lacking such support, add it to this list
5221 and submit a bug report and it'll be added to the library upstream.
5222 */
5223 #if defined(__DJGPP__)
5224 {
5225 /* Nothing to do here. This will fall through to the error check below. */
5226 }
5227 #else
5228 {
5229 mbstate_t mbs;
5230 size_t lenMB;
5231 const wchar_t* pFilePathTemp = pFilePath;
5232 char* pFilePathMB = NULL;
5233 char pOpenModeMB[32] = {0};
5234
5235 /* Get the length first. */
5236 DRWAV_ZERO_OBJECT(&mbs);
5237 lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
5238 if (lenMB == (size_t)-1) {
5239 return drwav_result_from_errno(errno);
5240 }
5241
5242 pFilePathMB = (char*)drwav__malloc_from_callbacks(lenMB + 1, pAllocationCallbacks);
5243 if (pFilePathMB == NULL) {
5244 return DRWAV_OUT_OF_MEMORY;
5245 }
5246
5247 pFilePathTemp = pFilePath;
5248 DRWAV_ZERO_OBJECT(&mbs);
5249 wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
5250
5251 /* The open mode should always consist of ASCII characters so we should be able to do a trivial conversion. */
5252 {
5253 size_t i = 0;
5254 for (;;) {
5255 if (pOpenMode[i] == 0) {
5256 pOpenModeMB[i] = '\0';
5257 break;
5258 }
5259
5260 pOpenModeMB[i] = (char)pOpenMode[i];
5261 i += 1;
5262 }
5263 }
5264
5265 *ppFile = fopen(pFilePathMB, pOpenModeMB);
5266
5267 drwav__free_from_callbacks(pFilePathMB, pAllocationCallbacks);
5268 }
5269 #endif
5270
5271 if (*ppFile == NULL) {
5272 return DRWAV_ERROR;
5273 }
5274#endif
5275
5276 return DRWAV_SUCCESS;
5277}
5278#endif
5279/* End fopen */
5280
5281
5282DRWAV_PRIVATE size_t drwav__on_read_stdio(void* pUserData, void* pBufferOut, size_t bytesToRead)
5283{
5284 return fread(pBufferOut, 1, bytesToRead, (FILE*)pUserData);
5285}
5286
5287DRWAV_PRIVATE size_t drwav__on_write_stdio(void* pUserData, const void* pData, size_t bytesToWrite)
5288{
5289 return fwrite(pData, 1, bytesToWrite, (FILE*)pUserData);
5290}
5291
5292DRWAV_PRIVATE drwav_bool32 drwav__on_seek_stdio(void* pUserData, int offset, drwav_seek_origin origin)
5293{
5294 int whence = SEEK_SET;
5295 if (origin == DRWAV_SEEK_CUR) {
5296 whence = SEEK_CUR;
5297 } else if (origin == DRWAV_SEEK_END) {
5298 whence = SEEK_END;
5299 }
5300
5301 return fseek((FILE*)pUserData, offset, whence) == 0;
5302}
5303
5304DRWAV_PRIVATE drwav_bool32 drwav__on_tell_stdio(void* pUserData, drwav_int64* pCursor)
5305{
5306 FILE* pFileStdio = (FILE*)pUserData;
5307 drwav_int64 result;
5308
5309 /* These were all validated at a higher level. */
5310 DRWAV_ASSERT(pFileStdio != NULL);
5311 DRWAV_ASSERT(pCursor != NULL);
5312
5313#if defined(_WIN32) && !defined(NXDK)
5314 #if defined(_MSC_VER) && _MSC_VER > 1200
5315 result = _ftelli64(pFileStdio);
5316 #else
5317 result = ftell(pFileStdio);
5318 #endif
5319#else
5320 result = ftell(pFileStdio);
5321#endif
5322
5323 *pCursor = result;
5324
5325 return DRWAV_TRUE;
5326}
5327
5328DRWAV_API drwav_bool32 drwav_init_file(drwav* pWav, const char* filename, const drwav_allocation_callbacks* pAllocationCallbacks)
5329{
5330 return drwav_init_file_ex(pWav, filename, NULL, NULL, 0, pAllocationCallbacks);
5331}
5332
5333
5334DRWAV_PRIVATE drwav_bool32 drwav_init_file__internal_FILE(drwav* pWav, FILE* pFile, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
5335{
5336 drwav_bool32 result;
5337
5338 result = drwav_preinit(pWav, drwav__on_read_stdio, drwav__on_seek_stdio, drwav__on_tell_stdio, (void*)pFile, pAllocationCallbacks);
5339 if (result != DRWAV_TRUE) {
5340 fclose(pFile);
5341 return result;
5342 }
5343
5344 result = drwav_init__internal(pWav, onChunk, pChunkUserData, flags);
5345 if (result != DRWAV_TRUE) {
5346 fclose(pFile);
5347 return result;
5348 }
5349
5350 return DRWAV_TRUE;
5351}
5352
5353DRWAV_API drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
5354{
5355 FILE* pFile;
5356 if (drwav_fopen(&pFile, filename, "rb") != DRWAV_SUCCESS) {
5357 return DRWAV_FALSE;
5358 }
5359
5360 /* This takes ownership of the FILE* object. */
5361 return drwav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, pAllocationCallbacks);
5362}
5363
5364#ifndef DR_WAV_NO_WCHAR
5365DRWAV_API drwav_bool32 drwav_init_file_w(drwav* pWav, const wchar_t* filename, const drwav_allocation_callbacks* pAllocationCallbacks)
5366{
5367 return drwav_init_file_ex_w(pWav, filename, NULL, NULL, 0, pAllocationCallbacks);
5368}
5369
5370DRWAV_API drwav_bool32 drwav_init_file_ex_w(drwav* pWav, const wchar_t* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
5371{
5372 FILE* pFile;
5373 if (drwav_wfopen(&pFile, filename, L"rb", pAllocationCallbacks) != DRWAV_SUCCESS) {
5374 return DRWAV_FALSE;
5375 }
5376
5377 /* This takes ownership of the FILE* object. */
5378 return drwav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, pAllocationCallbacks);
5379}
5380#endif
5381
5382DRWAV_API drwav_bool32 drwav_init_file_with_metadata(drwav* pWav, const char* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
5383{
5384 FILE* pFile;
5385 if (drwav_fopen(&pFile, filename, "rb") != DRWAV_SUCCESS) {
5386 return DRWAV_FALSE;
5387 }
5388
5389 /* This takes ownership of the FILE* object. */
5390 return drwav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags | DRWAV_WITH_METADATA, pAllocationCallbacks);
5391}
5392
5393#ifndef DR_WAV_NO_WCHAR
5394DRWAV_API drwav_bool32 drwav_init_file_with_metadata_w(drwav* pWav, const wchar_t* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
5395{
5396 FILE* pFile;
5397 if (drwav_wfopen(&pFile, filename, L"rb", pAllocationCallbacks) != DRWAV_SUCCESS) {
5398 return DRWAV_FALSE;
5399 }
5400
5401 /* This takes ownership of the FILE* object. */
5402 return drwav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags | DRWAV_WITH_METADATA, pAllocationCallbacks);
5403}
5404#endif
5405
5406
5407DRWAV_PRIVATE drwav_bool32 drwav_init_file_write__internal_FILE(drwav* pWav, FILE* pFile, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
5408{
5409 drwav_bool32 result;
5410
5411 result = drwav_preinit_write(pWav, pFormat, isSequential, drwav__on_write_stdio, drwav__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
5412 if (result != DRWAV_TRUE) {
5413 fclose(pFile);
5414 return result;
5415 }
5416
5417 result = drwav_init_write__internal(pWav, pFormat, totalSampleCount);
5418 if (result != DRWAV_TRUE) {
5419 fclose(pFile);
5420 return result;
5421 }
5422
5423 return DRWAV_TRUE;
5424}
5425
5426DRWAV_PRIVATE drwav_bool32 drwav_init_file_write__internal(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
5427{
5428 FILE* pFile;
5429 if (drwav_fopen(&pFile, filename, "wb") != DRWAV_SUCCESS) {
5430 return DRWAV_FALSE;
5431 }
5432
5433 /* This takes ownership of the FILE* object. */
5434 return drwav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks);
5435}
5436
5437#ifndef DR_WAV_NO_WCHAR
5438DRWAV_PRIVATE drwav_bool32 drwav_init_file_write_w__internal(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
5439{
5440 FILE* pFile;
5441 if (drwav_wfopen(&pFile, filename, L"wb", pAllocationCallbacks) != DRWAV_SUCCESS) {
5442 return DRWAV_FALSE;
5443 }
5444
5445 /* This takes ownership of the FILE* object. */
5446 return drwav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks);
5447}
5448#endif
5449
5450DRWAV_API drwav_bool32 drwav_init_file_write(drwav* pWav, const char* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks)
5451{
5452 return drwav_init_file_write__internal(pWav, filename, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks);
5453}
5454
5455DRWAV_API drwav_bool32 drwav_init_file_write_sequential(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks)
5456{
5457 return drwav_init_file_write__internal(pWav, filename, pFormat, totalSampleCount, DRWAV_TRUE, pAllocationCallbacks);
5458}
5459
5460DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks)
5461{
5462 if (pFormat == NULL) {
5463 return DRWAV_FALSE;
5464 }
5465
5466 return drwav_init_file_write_sequential(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
5467}
5468
5469#ifndef DR_WAV_NO_WCHAR
5470DRWAV_API drwav_bool32 drwav_init_file_write_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks)
5471{
5472 return drwav_init_file_write_w__internal(pWav, filename, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks);
5473}
5474
5475DRWAV_API drwav_bool32 drwav_init_file_write_sequential_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks)
5476{
5477 return drwav_init_file_write_w__internal(pWav, filename, pFormat, totalSampleCount, DRWAV_TRUE, pAllocationCallbacks);
5478}
5479
5480DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks)
5481{
5482 if (pFormat == NULL) {
5483 return DRWAV_FALSE;
5484 }
5485
5486 return drwav_init_file_write_sequential_w(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
5487}
5488#endif
5489#endif /* DR_WAV_NO_STDIO */
5490
5491
5492DRWAV_PRIVATE size_t drwav__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead)
5493{
5494 drwav* pWav = (drwav*)pUserData;
5495 size_t bytesRemaining;
5496
5497 DRWAV_ASSERT(pWav != NULL);
5498 DRWAV_ASSERT(pWav->memoryStream.dataSize >= pWav->memoryStream.currentReadPos);
5499
5500 bytesRemaining = pWav->memoryStream.dataSize - pWav->memoryStream.currentReadPos;
5501 if (bytesToRead > bytesRemaining) {
5502 bytesToRead = bytesRemaining;
5503 }
5504
5505 if (bytesToRead > 0) {
5506 DRWAV_COPY_MEMORY(pBufferOut, pWav->memoryStream.data + pWav->memoryStream.currentReadPos, bytesToRead);
5507 pWav->memoryStream.currentReadPos += bytesToRead;
5508 }
5509
5510 return bytesToRead;
5511}
5512
5513DRWAV_PRIVATE drwav_bool32 drwav__on_seek_memory(void* pUserData, int offset, drwav_seek_origin origin)
5514{
5515 drwav* pWav = (drwav*)pUserData;
5516 drwav_int64 newCursor;
5517
5518 DRWAV_ASSERT(pWav != NULL);
5519
5520 if (origin == DRWAV_SEEK_SET) {
5521 newCursor = 0;
5522 } else if (origin == DRWAV_SEEK_CUR) {
5523 newCursor = (drwav_int64)pWav->memoryStream.currentReadPos;
5524 } else if (origin == DRWAV_SEEK_END) {
5525 newCursor = (drwav_int64)pWav->memoryStream.dataSize;
5526 } else {
5527 DRWAV_ASSERT(!"Invalid seek origin");
5528 return DRWAV_FALSE;
5529 }
5530
5531 newCursor += offset;
5532
5533 if (newCursor < 0) {
5534 return DRWAV_FALSE; /* Trying to seek prior to the start of the buffer. */
5535 }
5536 if ((size_t)newCursor > pWav->memoryStream.dataSize) {
5537 return DRWAV_FALSE; /* Trying to seek beyond the end of the buffer. */
5538 }
5539
5540 pWav->memoryStream.currentReadPos = (size_t)newCursor;
5541
5542 return DRWAV_TRUE;
5543}
5544
5545DRWAV_PRIVATE size_t drwav__on_write_memory(void* pUserData, const void* pDataIn, size_t bytesToWrite)
5546{
5547 drwav* pWav = (drwav*)pUserData;
5548 size_t bytesRemaining;
5549
5550 DRWAV_ASSERT(pWav != NULL);
5552
5553 bytesRemaining = pWav->memoryStreamWrite.dataCapacity - pWav->memoryStreamWrite.currentWritePos;
5554 if (bytesRemaining < bytesToWrite) {
5555 /* Need to reallocate. */
5556 void* pNewData;
5557 size_t newDataCapacity = (pWav->memoryStreamWrite.dataCapacity == 0) ? 256 : pWav->memoryStreamWrite.dataCapacity * 2;
5558
5559 /* If doubling wasn't enough, just make it the minimum required size to write the data. */
5560 if ((newDataCapacity - pWav->memoryStreamWrite.currentWritePos) < bytesToWrite) {
5561 newDataCapacity = pWav->memoryStreamWrite.currentWritePos + bytesToWrite;
5562 }
5563
5564 pNewData = drwav__realloc_from_callbacks(*pWav->memoryStreamWrite.ppData, newDataCapacity, pWav->memoryStreamWrite.dataCapacity, &pWav->allocationCallbacks);
5565 if (pNewData == NULL) {
5566 return 0;
5567 }
5568
5569 *pWav->memoryStreamWrite.ppData = pNewData;
5570 pWav->memoryStreamWrite.dataCapacity = newDataCapacity;
5571 }
5572
5573 DRWAV_COPY_MEMORY(((drwav_uint8*)(*pWav->memoryStreamWrite.ppData)) + pWav->memoryStreamWrite.currentWritePos, pDataIn, bytesToWrite);
5574
5575 pWav->memoryStreamWrite.currentWritePos += bytesToWrite;
5578 }
5579
5581
5582 return bytesToWrite;
5583}
5584
5585DRWAV_PRIVATE drwav_bool32 drwav__on_seek_memory_write(void* pUserData, int offset, drwav_seek_origin origin)
5586{
5587 drwav* pWav = (drwav*)pUserData;
5588 drwav_int64 newCursor;
5589
5590 DRWAV_ASSERT(pWav != NULL);
5591
5592 if (origin == DRWAV_SEEK_SET) {
5593 newCursor = 0;
5594 } else if (origin == DRWAV_SEEK_CUR) {
5596 } else if (origin == DRWAV_SEEK_END) {
5597 newCursor = (drwav_int64)pWav->memoryStreamWrite.dataSize;
5598 } else {
5599 DRWAV_ASSERT(!"Invalid seek origin");
5600 return DRWAV_FALSE;
5601 }
5602
5603 newCursor += offset;
5604
5605 if (newCursor < 0) {
5606 return DRWAV_FALSE; /* Trying to seek prior to the start of the buffer. */
5607 }
5608 if ((size_t)newCursor > pWav->memoryStreamWrite.dataSize) {
5609 return DRWAV_FALSE; /* Trying to seek beyond the end of the buffer. */
5610 }
5611
5612 pWav->memoryStreamWrite.currentWritePos = (size_t)newCursor;
5613
5614 return DRWAV_TRUE;
5615}
5616
5617DRWAV_PRIVATE drwav_bool32 drwav__on_tell_memory(void* pUserData, drwav_int64* pCursor)
5618{
5619 drwav* pWav = (drwav*)pUserData;
5620
5621 DRWAV_ASSERT(pWav != NULL);
5622 DRWAV_ASSERT(pCursor != NULL);
5623
5624 *pCursor = (drwav_int64)pWav->memoryStream.currentReadPos;
5625 return DRWAV_TRUE;
5626}
5627
5628DRWAV_API drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize, const drwav_allocation_callbacks* pAllocationCallbacks)
5629{
5630 return drwav_init_memory_ex(pWav, data, dataSize, NULL, NULL, 0, pAllocationCallbacks);
5631}
5632
5633DRWAV_API drwav_bool32 drwav_init_memory_ex(drwav* pWav, const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
5634{
5635 if (data == NULL || dataSize == 0) {
5636 return DRWAV_FALSE;
5637 }
5638
5639 if (!drwav_preinit(pWav, drwav__on_read_memory, drwav__on_seek_memory, drwav__on_tell_memory, pWav, pAllocationCallbacks)) {
5640 return DRWAV_FALSE;
5641 }
5642
5643 pWav->memoryStream.data = (const drwav_uint8*)data;
5644 pWav->memoryStream.dataSize = dataSize;
5645 pWav->memoryStream.currentReadPos = 0;
5646
5647 return drwav_init__internal(pWav, onChunk, pChunkUserData, flags);
5648}
5649
5650DRWAV_API drwav_bool32 drwav_init_memory_with_metadata(drwav* pWav, const void* data, size_t dataSize, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
5651{
5652 if (data == NULL || dataSize == 0) {
5653 return DRWAV_FALSE;
5654 }
5655
5656 if (!drwav_preinit(pWav, drwav__on_read_memory, drwav__on_seek_memory, drwav__on_tell_memory, pWav, pAllocationCallbacks)) {
5657 return DRWAV_FALSE;
5658 }
5659
5660 pWav->memoryStream.data = (const drwav_uint8*)data;
5661 pWav->memoryStream.dataSize = dataSize;
5662 pWav->memoryStream.currentReadPos = 0;
5663
5664 return drwav_init__internal(pWav, NULL, NULL, flags | DRWAV_WITH_METADATA);
5665}
5666
5667
5668DRWAV_PRIVATE 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, const drwav_allocation_callbacks* pAllocationCallbacks)
5669{
5670 if (ppData == NULL || pDataSize == NULL) {
5671 return DRWAV_FALSE;
5672 }
5673
5674 *ppData = NULL; /* Important because we're using realloc()! */
5675 *pDataSize = 0;
5676
5677 if (!drwav_preinit_write(pWav, pFormat, isSequential, drwav__on_write_memory, drwav__on_seek_memory_write, pWav, pAllocationCallbacks)) {
5678 return DRWAV_FALSE;
5679 }
5680
5681 pWav->memoryStreamWrite.ppData = ppData;
5682 pWav->memoryStreamWrite.pDataSize = pDataSize;
5683 pWav->memoryStreamWrite.dataSize = 0;
5686
5687 return drwav_init_write__internal(pWav, pFormat, totalSampleCount);
5688}
5689
5690DRWAV_API drwav_bool32 drwav_init_memory_write(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks)
5691{
5692 return drwav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks);
5693}
5694
5695DRWAV_API drwav_bool32 drwav_init_memory_write_sequential(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks)
5696{
5697 return drwav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, totalSampleCount, DRWAV_TRUE, pAllocationCallbacks);
5698}
5699
5700DRWAV_API drwav_bool32 drwav_init_memory_write_sequential_pcm_frames(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks)
5701{
5702 if (pFormat == NULL) {
5703 return DRWAV_FALSE;
5704 }
5705
5706 return drwav_init_memory_write_sequential(pWav, ppData, pDataSize, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
5707}
5708
5709
5710
5712{
5713 drwav_result result = DRWAV_SUCCESS;
5714
5715 if (pWav == NULL) {
5716 return DRWAV_INVALID_ARGS;
5717 }
5718
5719 /*
5720 If the drwav object was opened in write mode we'll need to finalize a few things:
5721 - Make sure the "data" chunk is aligned to 16-bits for RIFF containers, or 64 bits for W64 containers.
5722 - Set the size of the "data" chunk.
5723 */
5724 if (pWav->onWrite != NULL) {
5725 drwav_uint32 paddingSize = 0;
5726
5727 /* Padding. Do not adjust pWav->dataChunkDataSize - this should not include the padding. */
5729 paddingSize = drwav__chunk_padding_size_riff(pWav->dataChunkDataSize);
5730 } else {
5731 paddingSize = drwav__chunk_padding_size_w64(pWav->dataChunkDataSize);
5732 }
5733
5734 if (paddingSize > 0) {
5735 drwav_uint64 paddingData = 0;
5736 drwav__write(pWav, &paddingData, paddingSize); /* Byte order does not matter for this. */
5737 }
5738
5739 /*
5740 Chunk sizes. When using sequential mode, these will have been filled in at initialization time. We only need
5741 to do this when using non-sequential mode.
5742 */
5743 if (pWav->onSeek && !pWav->isSequentialWrite) {
5744 if (pWav->container == drwav_container_riff) {
5745 /* The "RIFF" chunk size. */
5746 if (pWav->onSeek(pWav->pUserData, 4, DRWAV_SEEK_SET)) {
5747 drwav_uint32 riffChunkSize = drwav__riff_chunk_size_riff(pWav->dataChunkDataSize, pWav->pMetadata, pWav->metadataCount);
5748 drwav__write_u32ne_to_le(pWav, riffChunkSize);
5749 }
5750
5751 /* The "data" chunk size. */
5752 if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos - 4, DRWAV_SEEK_SET)) {
5753 drwav_uint32 dataChunkSize = drwav__data_chunk_size_riff(pWav->dataChunkDataSize);
5754 drwav__write_u32ne_to_le(pWav, dataChunkSize);
5755 }
5756 } else if (pWav->container == drwav_container_w64) {
5757 /* The "RIFF" chunk size. */
5758 if (pWav->onSeek(pWav->pUserData, 16, DRWAV_SEEK_SET)) {
5759 drwav_uint64 riffChunkSize = drwav__riff_chunk_size_w64(pWav->dataChunkDataSize);
5760 drwav__write_u64ne_to_le(pWav, riffChunkSize);
5761 }
5762
5763 /* The "data" chunk size. */
5764 if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos - 8, DRWAV_SEEK_SET)) {
5765 drwav_uint64 dataChunkSize = drwav__data_chunk_size_w64(pWav->dataChunkDataSize);
5766 drwav__write_u64ne_to_le(pWav, dataChunkSize);
5767 }
5768 } else if (pWav->container == drwav_container_rf64) {
5769 /* We only need to update the ds64 chunk. The "RIFF" and "data" chunks always have their sizes set to 0xFFFFFFFF for RF64. */
5770 int ds64BodyPos = 12 + 8;
5771
5772 /* The "RIFF" chunk size. */
5773 if (pWav->onSeek(pWav->pUserData, ds64BodyPos + 0, DRWAV_SEEK_SET)) {
5774 drwav_uint64 riffChunkSize = drwav__riff_chunk_size_rf64(pWav->dataChunkDataSize, pWav->pMetadata, pWav->metadataCount);
5775 drwav__write_u64ne_to_le(pWav, riffChunkSize);
5776 }
5777
5778 /* The "data" chunk size. */
5779 if (pWav->onSeek(pWav->pUserData, ds64BodyPos + 8, DRWAV_SEEK_SET)) {
5780 drwav_uint64 dataChunkSize = drwav__data_chunk_size_rf64(pWav->dataChunkDataSize);
5781 drwav__write_u64ne_to_le(pWav, dataChunkSize);
5782 }
5783 }
5784 }
5785
5786 /* Validation for sequential mode. */
5787 if (pWav->isSequentialWrite) {
5789 result = DRWAV_INVALID_FILE;
5790 }
5791 }
5792 } else {
5794 }
5795
5796#ifndef DR_WAV_NO_STDIO
5797 /*
5798 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()
5799 was used by looking at the onRead and onSeek callbacks.
5800 */
5801 if (pWav->onRead == drwav__on_read_stdio || pWav->onWrite == drwav__on_write_stdio) {
5802 fclose((FILE*)pWav->pUserData);
5803 }
5804#endif
5805
5806 return result;
5807}
5808
5809
5810
5811DRWAV_API size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut)
5812{
5813 size_t bytesRead;
5814 drwav_uint32 bytesPerFrame;
5815
5816 if (pWav == NULL || bytesToRead == 0) {
5817 return 0; /* Invalid args. */
5818 }
5819
5820 if (bytesToRead > pWav->bytesRemaining) {
5821 bytesToRead = (size_t)pWav->bytesRemaining;
5822 }
5823
5824 if (bytesToRead == 0) {
5825 return 0; /* At end. */
5826 }
5827
5828 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
5829 if (bytesPerFrame == 0) {
5830 return 0; /* Could not determine the bytes per frame. */
5831 }
5832
5833 if (pBufferOut != NULL) {
5834 bytesRead = pWav->onRead(pWav->pUserData, pBufferOut, bytesToRead);
5835 } else {
5836 /* We need to seek. If we fail, we need to read-and-discard to make sure we get a good byte count. */
5837 bytesRead = 0;
5838 while (bytesRead < bytesToRead) {
5839 size_t bytesToSeek = (bytesToRead - bytesRead);
5840 if (bytesToSeek > 0x7FFFFFFF) {
5841 bytesToSeek = 0x7FFFFFFF;
5842 }
5843
5844 if (pWav->onSeek(pWav->pUserData, (int)bytesToSeek, DRWAV_SEEK_CUR) == DRWAV_FALSE) {
5845 break;
5846 }
5847
5848 bytesRead += bytesToSeek;
5849 }
5850
5851 /* When we get here we may need to read-and-discard some data. */
5852 while (bytesRead < bytesToRead) {
5853 drwav_uint8 buffer[4096];
5854 size_t bytesSeeked;
5855 size_t bytesToSeek = (bytesToRead - bytesRead);
5856 if (bytesToSeek > sizeof(buffer)) {
5857 bytesToSeek = sizeof(buffer);
5858 }
5859
5860 bytesSeeked = pWav->onRead(pWav->pUserData, buffer, bytesToSeek);
5861 bytesRead += bytesSeeked;
5862
5863 if (bytesSeeked < bytesToSeek) {
5864 break; /* Reached the end. */
5865 }
5866 }
5867 }
5868
5869 pWav->readCursorInPCMFrames += bytesRead / bytesPerFrame;
5870
5871 pWav->bytesRemaining -= bytesRead;
5872 return bytesRead;
5873}
5874
5875
5876
5877DRWAV_API drwav_uint64 drwav_read_pcm_frames_le(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
5878{
5879 drwav_uint32 bytesPerFrame;
5880 drwav_uint64 bytesToRead; /* Intentionally uint64 instead of size_t so we can do a check that we're not reading too much on 32-bit builds. */
5881 drwav_uint64 framesRemainingInFile;
5882
5883 if (pWav == NULL || framesToRead == 0) {
5884 return 0;
5885 }
5886
5887 /* Cannot use this function for compressed formats. */
5888 if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
5889 return 0;
5890 }
5891
5892 framesRemainingInFile = pWav->totalPCMFrameCount - pWav->readCursorInPCMFrames;
5893 if (framesToRead > framesRemainingInFile) {
5894 framesToRead = framesRemainingInFile;
5895 }
5896
5897 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
5898 if (bytesPerFrame == 0) {
5899 return 0;
5900 }
5901
5902 /* Don't try to read more samples than can potentially fit in the output buffer. */
5903 bytesToRead = framesToRead * bytesPerFrame;
5904 if (bytesToRead > DRWAV_SIZE_MAX) {
5905 bytesToRead = (DRWAV_SIZE_MAX / bytesPerFrame) * bytesPerFrame; /* Round the number of bytes to read to a clean frame boundary. */
5906 }
5907
5908 /*
5909 Doing an explicit check here just to make it clear that we don't want to be attempt to read anything if there's no bytes to read. There
5910 *could* be a time where it evaluates to 0 due to overflowing.
5911 */
5912 if (bytesToRead == 0) {
5913 return 0;
5914 }
5915
5916 return drwav_read_raw(pWav, (size_t)bytesToRead, pBufferOut) / bytesPerFrame;
5917}
5918
5919DRWAV_API drwav_uint64 drwav_read_pcm_frames_be(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
5920{
5921 drwav_uint64 framesRead = drwav_read_pcm_frames_le(pWav, framesToRead, pBufferOut);
5922
5923 if (pBufferOut != NULL) {
5924 drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
5925 if (bytesPerFrame == 0) {
5926 return 0; /* Could not get the bytes per frame which means bytes per sample cannot be determined and we don't know how to byte swap. */
5927 }
5928
5929 drwav__bswap_samples(pBufferOut, framesRead*pWav->channels, bytesPerFrame/pWav->channels);
5930 }
5931
5932 return framesRead;
5933}
5934
5935DRWAV_API drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
5936{
5937 drwav_uint64 framesRead = 0;
5938
5939 if (drwav_is_container_be(pWav->container)) {
5940 /*
5941 Special case for AIFF. AIFF is a big-endian encoded format, but it supports a format that is
5942 PCM in little-endian encoding. In this case, we fall through this branch and treate it as
5943 little-endian.
5944 */
5945 if (pWav->container != drwav_container_aiff || pWav->aiff.isLE == DRWAV_FALSE) {
5946 if (drwav__is_little_endian()) {
5947 framesRead = drwav_read_pcm_frames_be(pWav, framesToRead, pBufferOut);
5948 } else {
5949 framesRead = drwav_read_pcm_frames_le(pWav, framesToRead, pBufferOut);
5950 }
5951
5952 goto post_process;
5953 }
5954 }
5955
5956 /* Getting here means the data should be considered little-endian. */
5957 if (drwav__is_little_endian()) {
5958 framesRead = drwav_read_pcm_frames_le(pWav, framesToRead, pBufferOut);
5959 } else {
5960 framesRead = drwav_read_pcm_frames_be(pWav, framesToRead, pBufferOut);
5961 }
5962
5963 /*
5964 Here is where we check if we need to do a signed/unsigned conversion for AIFF. The reason we need to do this
5965 is because dr_wav always assumes an 8-bit sample is unsigned, whereas AIFF can have signed 8-bit formats.
5966 */
5967 post_process:
5968 {
5969 if (pWav->container == drwav_container_aiff && pWav->bitsPerSample == 8 && pWav->aiff.isUnsigned == DRWAV_FALSE) {
5970 if (pBufferOut != NULL) {
5971 drwav_uint64 iSample;
5972
5973 for (iSample = 0; iSample < framesRead * pWav->channels; iSample += 1) {
5974 ((drwav_uint8*)pBufferOut)[iSample] += 128;
5975 }
5976 }
5977 }
5978 }
5979
5980 return framesRead;
5981}
5982
5983
5984
5985DRWAV_PRIVATE drwav_bool32 drwav_seek_to_first_pcm_frame(drwav* pWav)
5986{
5987 if (pWav->onWrite != NULL) {
5988 return DRWAV_FALSE; /* No seeking in write mode. */
5989 }
5990
5991 if (!pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos, DRWAV_SEEK_SET)) {
5992 return DRWAV_FALSE;
5993 }
5994
5995 if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
5996 /* Cached data needs to be cleared for compressed formats. */
5998 DRWAV_ZERO_OBJECT(&pWav->msadpcm);
5999 } else if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
6000 DRWAV_ZERO_OBJECT(&pWav->ima);
6001 } else {
6002 DRWAV_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. */
6003 }
6004 }
6005
6006 pWav->readCursorInPCMFrames = 0;
6007 pWav->bytesRemaining = pWav->dataChunkDataSize;
6008
6009 return DRWAV_TRUE;
6010}
6011
6013{
6014 /* Seeking should be compatible with wave files > 2GB. */
6015
6016 if (pWav == NULL || pWav->onSeek == NULL) {
6017 return DRWAV_FALSE;
6018 }
6019
6020 /* No seeking in write mode. */
6021 if (pWav->onWrite != NULL) {
6022 return DRWAV_FALSE;
6023 }
6024
6025 /* If there are no samples, just return DRWAV_TRUE without doing anything. */
6026 if (pWav->totalPCMFrameCount == 0) {
6027 return DRWAV_TRUE;
6028 }
6029
6030 /* Make sure the sample is clamped. */
6031 if (targetFrameIndex > pWav->totalPCMFrameCount) {
6032 targetFrameIndex = pWav->totalPCMFrameCount;
6033 }
6034
6035 /*
6036 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
6037 to seek back to the start.
6038 */
6039 if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
6040 /* TODO: This can be optimized. */
6041
6042 /*
6043 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,
6044 we first need to seek back to the start and then just do the same thing as a forward seek.
6045 */
6046 if (targetFrameIndex < pWav->readCursorInPCMFrames) {
6047 if (!drwav_seek_to_first_pcm_frame(pWav)) {
6048 return DRWAV_FALSE;
6049 }
6050 }
6051
6052 if (targetFrameIndex > pWav->readCursorInPCMFrames) {
6053 drwav_uint64 offsetInFrames = targetFrameIndex - pWav->readCursorInPCMFrames;
6054
6055 drwav_int16 devnull[2048];
6056 while (offsetInFrames > 0) {
6057 drwav_uint64 framesRead = 0;
6058 drwav_uint64 framesToRead = offsetInFrames;
6059 if (framesToRead > drwav_countof(devnull)/pWav->channels) {
6060 framesToRead = drwav_countof(devnull)/pWav->channels;
6061 }
6062
6064 framesRead = drwav_read_pcm_frames_s16__msadpcm(pWav, framesToRead, devnull);
6065 } else if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
6066 framesRead = drwav_read_pcm_frames_s16__ima(pWav, framesToRead, devnull);
6067 } else {
6068 DRWAV_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. */
6069 }
6070
6071 if (framesRead != framesToRead) {
6072 return DRWAV_FALSE;
6073 }
6074
6075 offsetInFrames -= framesRead;
6076 }
6077 }
6078 } else {
6079 drwav_uint64 totalSizeInBytes;
6080 drwav_uint64 currentBytePos;
6081 drwav_uint64 targetBytePos;
6082 drwav_uint64 offset;
6083 drwav_uint32 bytesPerFrame;
6084
6085 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
6086 if (bytesPerFrame == 0) {
6087 return DRWAV_FALSE; /* Not able to calculate offset. */
6088 }
6089
6090 totalSizeInBytes = pWav->totalPCMFrameCount * bytesPerFrame;
6091 /*DRWAV_ASSERT(totalSizeInBytes >= pWav->bytesRemaining);*/
6092
6093 currentBytePos = totalSizeInBytes - pWav->bytesRemaining;
6094 targetBytePos = targetFrameIndex * bytesPerFrame;
6095
6096 if (currentBytePos < targetBytePos) {
6097 /* Offset forwards. */
6098 offset = (targetBytePos - currentBytePos);
6099 } else {
6100 /* Offset backwards. */
6101 if (!drwav_seek_to_first_pcm_frame(pWav)) {
6102 return DRWAV_FALSE;
6103 }
6104 offset = targetBytePos;
6105 }
6106
6107 while (offset > 0) {
6108 int offset32 = ((offset > INT_MAX) ? INT_MAX : (int)offset);
6109 if (!pWav->onSeek(pWav->pUserData, offset32, DRWAV_SEEK_CUR)) {
6110 return DRWAV_FALSE;
6111 }
6112
6113 pWav->readCursorInPCMFrames += offset32 / bytesPerFrame;
6114 pWav->bytesRemaining -= offset32;
6115 offset -= offset32;
6116 }
6117 }
6118
6119 return DRWAV_TRUE;
6120}
6121
6123{
6124 if (pCursor == NULL) {
6125 return DRWAV_INVALID_ARGS;
6126 }
6127
6128 *pCursor = 0; /* Safety. */
6129
6130 if (pWav == NULL) {
6131 return DRWAV_INVALID_ARGS;
6132 }
6133
6134 *pCursor = pWav->readCursorInPCMFrames;
6135
6136 return DRWAV_SUCCESS;
6137}
6138
6140{
6141 if (pLength == NULL) {
6142 return DRWAV_INVALID_ARGS;
6143 }
6144
6145 *pLength = 0; /* Safety. */
6146
6147 if (pWav == NULL) {
6148 return DRWAV_INVALID_ARGS;
6149 }
6150
6151 *pLength = pWav->totalPCMFrameCount;
6152
6153 return DRWAV_SUCCESS;
6154}
6155
6156
6157DRWAV_API size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData)
6158{
6159 size_t bytesWritten;
6160
6161 if (pWav == NULL || bytesToWrite == 0 || pData == NULL) {
6162 return 0;
6163 }
6164
6165 bytesWritten = pWav->onWrite(pWav->pUserData, pData, bytesToWrite);
6166 pWav->dataChunkDataSize += bytesWritten;
6167
6168 return bytesWritten;
6169}
6170
6171DRWAV_API drwav_uint64 drwav_write_pcm_frames_le(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
6172{
6173 drwav_uint64 bytesToWrite;
6174 drwav_uint64 bytesWritten;
6175 const drwav_uint8* pRunningData;
6176
6177 if (pWav == NULL || framesToWrite == 0 || pData == NULL) {
6178 return 0;
6179 }
6180
6181 bytesToWrite = ((framesToWrite * pWav->channels * pWav->bitsPerSample) / 8);
6182 if (bytesToWrite > DRWAV_SIZE_MAX) {
6183 return 0;
6184 }
6185
6186 bytesWritten = 0;
6187 pRunningData = (const drwav_uint8*)pData;
6188
6189 while (bytesToWrite > 0) {
6190 size_t bytesJustWritten;
6191 drwav_uint64 bytesToWriteThisIteration;
6192
6193 bytesToWriteThisIteration = bytesToWrite;
6194 DRWAV_ASSERT(bytesToWriteThisIteration <= DRWAV_SIZE_MAX); /* <-- This is checked above. */
6195
6196 bytesJustWritten = drwav_write_raw(pWav, (size_t)bytesToWriteThisIteration, pRunningData);
6197 if (bytesJustWritten == 0) {
6198 break;
6199 }
6200
6201 bytesToWrite -= bytesJustWritten;
6202 bytesWritten += bytesJustWritten;
6203 pRunningData += bytesJustWritten;
6204 }
6205
6206 return (bytesWritten * 8) / pWav->bitsPerSample / pWav->channels;
6207}
6208
6209DRWAV_API drwav_uint64 drwav_write_pcm_frames_be(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
6210{
6211 drwav_uint64 bytesToWrite;
6212 drwav_uint64 bytesWritten;
6213 drwav_uint32 bytesPerSample;
6214 const drwav_uint8* pRunningData;
6215
6216 if (pWav == NULL || framesToWrite == 0 || pData == NULL) {
6217 return 0;
6218 }
6219
6220 bytesToWrite = ((framesToWrite * pWav->channels * pWav->bitsPerSample) / 8);
6221 if (bytesToWrite > DRWAV_SIZE_MAX) {
6222 return 0;
6223 }
6224
6225 bytesWritten = 0;
6226 pRunningData = (const drwav_uint8*)pData;
6227
6228 bytesPerSample = drwav_get_bytes_per_pcm_frame(pWav) / pWav->channels;
6229 if (bytesPerSample == 0) {
6230 return 0; /* Cannot determine bytes per sample, or bytes per sample is less than one byte. */
6231 }
6232
6233 while (bytesToWrite > 0) {
6234 drwav_uint8 temp[4096];
6235 drwav_uint32 sampleCount;
6236 size_t bytesJustWritten;
6237 drwav_uint64 bytesToWriteThisIteration;
6238
6239 bytesToWriteThisIteration = bytesToWrite;
6240 DRWAV_ASSERT(bytesToWriteThisIteration <= DRWAV_SIZE_MAX); /* <-- This is checked above. */
6241
6242 /*
6243 WAV files are always little-endian. We need to byte swap on big-endian architectures. Since our input buffer is read-only we need
6244 to use an intermediary buffer for the conversion.
6245 */
6246 sampleCount = sizeof(temp)/bytesPerSample;
6247
6248 if (bytesToWriteThisIteration > ((drwav_uint64)sampleCount)*bytesPerSample) {
6249 bytesToWriteThisIteration = ((drwav_uint64)sampleCount)*bytesPerSample;
6250 }
6251
6252 DRWAV_COPY_MEMORY(temp, pRunningData, (size_t)bytesToWriteThisIteration);
6253 drwav__bswap_samples(temp, sampleCount, bytesPerSample);
6254
6255 bytesJustWritten = drwav_write_raw(pWav, (size_t)bytesToWriteThisIteration, temp);
6256 if (bytesJustWritten == 0) {
6257 break;
6258 }
6259
6260 bytesToWrite -= bytesJustWritten;
6261 bytesWritten += bytesJustWritten;
6262 pRunningData += bytesJustWritten;
6263 }
6264
6265 return (bytesWritten * 8) / pWav->bitsPerSample / pWav->channels;
6266}
6267
6268DRWAV_API drwav_uint64 drwav_write_pcm_frames(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
6269{
6270 if (drwav__is_little_endian()) {
6271 return drwav_write_pcm_frames_le(pWav, framesToWrite, pData);
6272 } else {
6273 return drwav_write_pcm_frames_be(pWav, framesToWrite, pData);
6274 }
6275}
6276
6277
6278DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__msadpcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
6279{
6280 drwav_uint64 totalFramesRead = 0;
6281
6282 static const drwav_int32 adaptationTable[] = {
6283 230, 230, 230, 230, 307, 409, 512, 614,
6284 768, 614, 512, 409, 307, 230, 230, 230
6285 };
6286 static const drwav_int32 coeff1Table[] = { 256, 512, 0, 192, 240, 460, 392 };
6287 static const drwav_int32 coeff2Table[] = { 0, -256, 0, 64, 0, -208, -232 };
6288
6289 DRWAV_ASSERT(pWav != NULL);
6290 DRWAV_ASSERT(framesToRead > 0);
6291
6292 /* TODO: Lots of room for optimization here. */
6293
6294 while (pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
6295 DRWAV_ASSERT(framesToRead > 0); /* This loop iteration will never get hit with framesToRead == 0 because it's asserted at the top, and we check for 0 inside the loop just below. */
6296
6297 /* If there are no cached frames we need to load a new block. */
6298 if (pWav->msadpcm.cachedFrameCount == 0 && pWav->msadpcm.bytesRemainingInBlock == 0) {
6299 if (pWav->channels == 1) {
6300 /* Mono. */
6301 drwav_uint8 header[7];
6302 if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
6303 return totalFramesRead;
6304 }
6305 pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
6306
6307 pWav->msadpcm.predictor[0] = header[0];
6308 pWav->msadpcm.delta[0] = drwav_bytes_to_s16(header + 1);
6309 pWav->msadpcm.prevFrames[0][1] = (drwav_int32)drwav_bytes_to_s16(header + 3);
6310 pWav->msadpcm.prevFrames[0][0] = (drwav_int32)drwav_bytes_to_s16(header + 5);
6311 pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][0];
6312 pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[0][1];
6313 pWav->msadpcm.cachedFrameCount = 2;
6314
6315 /* The predictor is used as an index into coeff1Table so we'll need to validate to ensure it never overflows. */
6316 if (pWav->msadpcm.predictor[0] >= drwav_countof(coeff1Table) || pWav->msadpcm.predictor[0] >= drwav_countof(coeff2Table)) {
6317 return totalFramesRead; /* Invalid file. */
6318 }
6319 } else {
6320 /* Stereo. */
6321 drwav_uint8 header[14];
6322 if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
6323 return totalFramesRead;
6324 }
6325 pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
6326
6327 pWav->msadpcm.predictor[0] = header[0];
6328 pWav->msadpcm.predictor[1] = header[1];
6329 pWav->msadpcm.delta[0] = drwav_bytes_to_s16(header + 2);
6330 pWav->msadpcm.delta[1] = drwav_bytes_to_s16(header + 4);
6331 pWav->msadpcm.prevFrames[0][1] = (drwav_int32)drwav_bytes_to_s16(header + 6);
6332 pWav->msadpcm.prevFrames[1][1] = (drwav_int32)drwav_bytes_to_s16(header + 8);
6333 pWav->msadpcm.prevFrames[0][0] = (drwav_int32)drwav_bytes_to_s16(header + 10);
6334 pWav->msadpcm.prevFrames[1][0] = (drwav_int32)drwav_bytes_to_s16(header + 12);
6335
6336 pWav->msadpcm.cachedFrames[0] = pWav->msadpcm.prevFrames[0][0];
6337 pWav->msadpcm.cachedFrames[1] = pWav->msadpcm.prevFrames[1][0];
6338 pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][1];
6339 pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[1][1];
6340 pWav->msadpcm.cachedFrameCount = 2;
6341
6342 /* The predictor is used as an index into coeff1Table so we'll need to validate to ensure it never overflows. */
6343 if (pWav->msadpcm.predictor[0] >= drwav_countof(coeff1Table) || pWav->msadpcm.predictor[0] >= drwav_countof(coeff2Table) ||
6344 pWav->msadpcm.predictor[1] >= drwav_countof(coeff1Table) || pWav->msadpcm.predictor[1] >= drwav_countof(coeff2Table)) {
6345 return totalFramesRead; /* Invalid file. */
6346 }
6347 }
6348 }
6349
6350 /* Output anything that's cached. */
6351 while (framesToRead > 0 && pWav->msadpcm.cachedFrameCount > 0 && pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
6352 if (pBufferOut != NULL) {
6353 drwav_uint32 iSample = 0;
6354 for (iSample = 0; iSample < pWav->channels; iSample += 1) {
6355 pBufferOut[iSample] = (drwav_int16)pWav->msadpcm.cachedFrames[(drwav_countof(pWav->msadpcm.cachedFrames) - (pWav->msadpcm.cachedFrameCount*pWav->channels)) + iSample];
6356 }
6357
6358 pBufferOut += pWav->channels;
6359 }
6360
6361 framesToRead -= 1;
6362 totalFramesRead += 1;
6363 pWav->readCursorInPCMFrames += 1;
6364 pWav->msadpcm.cachedFrameCount -= 1;
6365 }
6366
6367 if (framesToRead == 0) {
6368 break;
6369 }
6370
6371
6372 /*
6373 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
6374 loop iteration which will trigger the loading of a new block.
6375 */
6376 if (pWav->msadpcm.cachedFrameCount == 0) {
6377 if (pWav->msadpcm.bytesRemainingInBlock == 0) {
6378 continue;
6379 } else {
6380 drwav_uint8 nibbles;
6381 drwav_int32 nibble0;
6382 drwav_int32 nibble1;
6383
6384 if (pWav->onRead(pWav->pUserData, &nibbles, 1) != 1) {
6385 return totalFramesRead;
6386 }
6387 pWav->msadpcm.bytesRemainingInBlock -= 1;
6388
6389 /* TODO: Optimize away these if statements. */
6390 nibble0 = ((nibbles & 0xF0) >> 4); if ((nibbles & 0x80)) { nibble0 |= 0xFFFFFFF0UL; }
6391 nibble1 = ((nibbles & 0x0F) >> 0); if ((nibbles & 0x08)) { nibble1 |= 0xFFFFFFF0UL; }
6392
6393 if (pWav->channels == 1) {
6394 /* Mono. */
6395 drwav_int32 newSample0;
6396 drwav_int32 newSample1;
6397
6398 /* The predictor is read from the file and then indexed into a table. Check that it's in bounds. */
6399 if (pWav->msadpcm.predictor[0] >= drwav_countof(coeff1Table) || pWav->msadpcm.predictor[0] >= drwav_countof(coeff2Table)) {
6400 return totalFramesRead;
6401 }
6402
6403 newSample0 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
6404 newSample0 += nibble0 * pWav->msadpcm.delta[0];
6405 newSample0 = drwav_clamp(newSample0, -32768, 32767);
6406
6407 pWav->msadpcm.delta[0] = (drwav_int32)drwav_clamp(((drwav_int64)adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8, 16, 0x7FFFFFFF);
6408
6409 pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
6410 pWav->msadpcm.prevFrames[0][1] = newSample0;
6411
6412
6413 newSample1 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
6414 newSample1 += nibble1 * pWav->msadpcm.delta[0];
6415 newSample1 = drwav_clamp(newSample1, -32768, 32767);
6416
6417 pWav->msadpcm.delta[0] = (drwav_int32)drwav_clamp(((drwav_int64)adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[0]) >> 8, 16, 0x7FFFFFFF);
6418
6419 pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
6420 pWav->msadpcm.prevFrames[0][1] = newSample1;
6421
6422 pWav->msadpcm.cachedFrames[2] = newSample0;
6423 pWav->msadpcm.cachedFrames[3] = newSample1;
6424 pWav->msadpcm.cachedFrameCount = 2;
6425 } else {
6426 /* Stereo. */
6427 drwav_int32 newSample0;
6428 drwav_int32 newSample1;
6429
6430 /* Left. */
6431 if (pWav->msadpcm.predictor[0] >= drwav_countof(coeff1Table) || pWav->msadpcm.predictor[0] >= drwav_countof(coeff2Table)) {
6432 return totalFramesRead; /* Out of bounds. Invalid file. */
6433 }
6434
6435 newSample0 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
6436 newSample0 += nibble0 * pWav->msadpcm.delta[0];
6437 newSample0 = drwav_clamp(newSample0, -32768, 32767);
6438
6439 pWav->msadpcm.delta[0] = (drwav_int32)drwav_clamp(((drwav_int64)adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8, 16, 0x7FFFFFFF);
6440
6441 pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
6442 pWav->msadpcm.prevFrames[0][1] = newSample0;
6443
6444
6445 /* Right. */
6446 if (pWav->msadpcm.predictor[1] >= drwav_countof(coeff1Table) || pWav->msadpcm.predictor[1] >= drwav_countof(coeff2Table)) {
6447 return totalFramesRead; /* Out of bounds. Invalid file. */
6448 }
6449
6450 newSample1 = ((pWav->msadpcm.prevFrames[1][1] * coeff1Table[pWav->msadpcm.predictor[1]]) + (pWav->msadpcm.prevFrames[1][0] * coeff2Table[pWav->msadpcm.predictor[1]])) >> 8;
6451 newSample1 += nibble1 * pWav->msadpcm.delta[1];
6452 newSample1 = drwav_clamp(newSample1, -32768, 32767);
6453
6454 pWav->msadpcm.delta[1] = (drwav_int32)drwav_clamp(((drwav_int64)adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[1]) >> 8, 16, 0x7FFFFFFF);
6455
6456 pWav->msadpcm.prevFrames[1][0] = pWav->msadpcm.prevFrames[1][1];
6457 pWav->msadpcm.prevFrames[1][1] = newSample1;
6458
6459 pWav->msadpcm.cachedFrames[2] = newSample0;
6460 pWav->msadpcm.cachedFrames[3] = newSample1;
6461 pWav->msadpcm.cachedFrameCount = 1;
6462 }
6463 }
6464 }
6465 }
6466
6467 return totalFramesRead;
6468}
6469
6470
6471DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__ima(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
6472{
6473 drwav_uint64 totalFramesRead = 0;
6474 drwav_uint32 iChannel;
6475
6476 static const drwav_int32 indexTable[16] = {
6477 -1, -1, -1, -1, 2, 4, 6, 8,
6478 -1, -1, -1, -1, 2, 4, 6, 8
6479 };
6480
6481 static const drwav_int32 stepTable[89] = {
6482 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
6483 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
6484 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
6485 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
6486 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
6487 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
6488 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
6489 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
6490 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
6491 };
6492
6493 DRWAV_ASSERT(pWav != NULL);
6494 DRWAV_ASSERT(framesToRead > 0);
6495
6496 /* TODO: Lots of room for optimization here. */
6497
6498 while (pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
6499 DRWAV_ASSERT(framesToRead > 0); /* This loop iteration will never get hit with framesToRead == 0 because it's asserted at the top, and we check for 0 inside the loop just below. */
6500
6501 /* If there are no cached samples we need to load a new block. */
6502 if (pWav->ima.cachedFrameCount == 0 && pWav->ima.bytesRemainingInBlock == 0) {
6503 if (pWav->channels == 1) {
6504 /* Mono. */
6505 drwav_uint8 header[4];
6506 if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
6507 return totalFramesRead;
6508 }
6509 pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
6510
6511 if (header[2] >= drwav_countof(stepTable)) {
6513 pWav->ima.bytesRemainingInBlock = 0;
6514 return totalFramesRead; /* Invalid data. */
6515 }
6516
6517 pWav->ima.predictor[0] = (drwav_int16)drwav_bytes_to_u16(header + 0);
6518 pWav->ima.stepIndex[0] = drwav_clamp(header[2], 0, (drwav_int32)drwav_countof(stepTable)-1); /* Clamp not necessary because we checked above, but adding here to silence a static analysis warning. */
6519 pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[0];
6520 pWav->ima.cachedFrameCount = 1;
6521 } else {
6522 /* Stereo. */
6523 drwav_uint8 header[8];
6524 if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
6525 return totalFramesRead;
6526 }
6527 pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
6528
6529 if (header[2] >= drwav_countof(stepTable) || header[6] >= drwav_countof(stepTable)) {
6531 pWav->ima.bytesRemainingInBlock = 0;
6532 return totalFramesRead; /* Invalid data. */
6533 }
6534
6535 pWav->ima.predictor[0] = drwav_bytes_to_s16(header + 0);
6536 pWav->ima.stepIndex[0] = drwav_clamp(header[2], 0, (drwav_int32)drwav_countof(stepTable)-1); /* Clamp not necessary because we checked above, but adding here to silence a static analysis warning. */
6537 pWav->ima.predictor[1] = drwav_bytes_to_s16(header + 4);
6538 pWav->ima.stepIndex[1] = drwav_clamp(header[6], 0, (drwav_int32)drwav_countof(stepTable)-1); /* Clamp not necessary because we checked above, but adding here to silence a static analysis warning. */
6539
6540 pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 2] = pWav->ima.predictor[0];
6541 pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[1];
6542 pWav->ima.cachedFrameCount = 1;
6543 }
6544 }
6545
6546 /* Output anything that's cached. */
6547 while (framesToRead > 0 && pWav->ima.cachedFrameCount > 0 && pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
6548 if (pBufferOut != NULL) {
6549 drwav_uint32 iSample;
6550 for (iSample = 0; iSample < pWav->channels; iSample += 1) {
6551 pBufferOut[iSample] = (drwav_int16)pWav->ima.cachedFrames[(drwav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + iSample];
6552 }
6553 pBufferOut += pWav->channels;
6554 }
6555
6556 framesToRead -= 1;
6557 totalFramesRead += 1;
6558 pWav->readCursorInPCMFrames += 1;
6559 pWav->ima.cachedFrameCount -= 1;
6560 }
6561
6562 if (framesToRead == 0) {
6563 break;
6564 }
6565
6566 /*
6567 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
6568 loop iteration which will trigger the loading of a new block.
6569 */
6570 if (pWav->ima.cachedFrameCount == 0) {
6571 if (pWav->ima.bytesRemainingInBlock == 0) {
6572 continue;
6573 } else {
6574 /*
6575 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
6576 left channel, 4 bytes for the right channel.
6577 */
6578 pWav->ima.cachedFrameCount = 8;
6579 for (iChannel = 0; iChannel < pWav->channels; ++iChannel) {
6580 drwav_uint32 iByte;
6581 drwav_uint8 nibbles[4];
6582 if (pWav->onRead(pWav->pUserData, &nibbles, 4) != 4) {
6583 pWav->ima.cachedFrameCount = 0;
6584 return totalFramesRead;
6585 }
6586 pWav->ima.bytesRemainingInBlock -= 4;
6587
6588 for (iByte = 0; iByte < 4; ++iByte) {
6589 drwav_uint8 nibble0 = ((nibbles[iByte] & 0x0F) >> 0);
6590 drwav_uint8 nibble1 = ((nibbles[iByte] & 0xF0) >> 4);
6591
6592 drwav_int32 step = stepTable[pWav->ima.stepIndex[iChannel]];
6593 drwav_int32 predictor = pWav->ima.predictor[iChannel];
6594
6595 drwav_int32 diff = step >> 3;
6596 if (nibble0 & 1) diff += step >> 2;
6597 if (nibble0 & 2) diff += step >> 1;
6598 if (nibble0 & 4) diff += step;
6599 if (nibble0 & 8) diff = -diff;
6600
6601 predictor = drwav_clamp(predictor + diff, -32768, 32767);
6602 pWav->ima.predictor[iChannel] = predictor;
6603 pWav->ima.stepIndex[iChannel] = drwav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble0], 0, (drwav_int32)drwav_countof(stepTable)-1);
6604 pWav->ima.cachedFrames[(drwav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + (iByte*2+0)*pWav->channels + iChannel] = predictor;
6605
6606
6607 step = stepTable[pWav->ima.stepIndex[iChannel]];
6608 predictor = pWav->ima.predictor[iChannel];
6609
6610 diff = step >> 3;
6611 if (nibble1 & 1) diff += step >> 2;
6612 if (nibble1 & 2) diff += step >> 1;
6613 if (nibble1 & 4) diff += step;
6614 if (nibble1 & 8) diff = -diff;
6615
6616 predictor = drwav_clamp(predictor + diff, -32768, 32767);
6617 pWav->ima.predictor[iChannel] = predictor;
6618 pWav->ima.stepIndex[iChannel] = drwav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble1], 0, (drwav_int32)drwav_countof(stepTable)-1);
6619 pWav->ima.cachedFrames[(drwav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + (iByte*2+1)*pWav->channels + iChannel] = predictor;
6620 }
6621 }
6622 }
6623 }
6624 }
6625
6626 return totalFramesRead;
6627}
6628
6629
6630#ifndef DR_WAV_NO_CONVERSION_API
6631static const unsigned short g_drwavAlawTable[256] = {
6632 0xEA80, 0xEB80, 0xE880, 0xE980, 0xEE80, 0xEF80, 0xEC80, 0xED80, 0xE280, 0xE380, 0xE080, 0xE180, 0xE680, 0xE780, 0xE480, 0xE580,
6633 0xF540, 0xF5C0, 0xF440, 0xF4C0, 0xF740, 0xF7C0, 0xF640, 0xF6C0, 0xF140, 0xF1C0, 0xF040, 0xF0C0, 0xF340, 0xF3C0, 0xF240, 0xF2C0,
6634 0xAA00, 0xAE00, 0xA200, 0xA600, 0xBA00, 0xBE00, 0xB200, 0xB600, 0x8A00, 0x8E00, 0x8200, 0x8600, 0x9A00, 0x9E00, 0x9200, 0x9600,
6635 0xD500, 0xD700, 0xD100, 0xD300, 0xDD00, 0xDF00, 0xD900, 0xDB00, 0xC500, 0xC700, 0xC100, 0xC300, 0xCD00, 0xCF00, 0xC900, 0xCB00,
6636 0xFEA8, 0xFEB8, 0xFE88, 0xFE98, 0xFEE8, 0xFEF8, 0xFEC8, 0xFED8, 0xFE28, 0xFE38, 0xFE08, 0xFE18, 0xFE68, 0xFE78, 0xFE48, 0xFE58,
6637 0xFFA8, 0xFFB8, 0xFF88, 0xFF98, 0xFFE8, 0xFFF8, 0xFFC8, 0xFFD8, 0xFF28, 0xFF38, 0xFF08, 0xFF18, 0xFF68, 0xFF78, 0xFF48, 0xFF58,
6638 0xFAA0, 0xFAE0, 0xFA20, 0xFA60, 0xFBA0, 0xFBE0, 0xFB20, 0xFB60, 0xF8A0, 0xF8E0, 0xF820, 0xF860, 0xF9A0, 0xF9E0, 0xF920, 0xF960,
6639 0xFD50, 0xFD70, 0xFD10, 0xFD30, 0xFDD0, 0xFDF0, 0xFD90, 0xFDB0, 0xFC50, 0xFC70, 0xFC10, 0xFC30, 0xFCD0, 0xFCF0, 0xFC90, 0xFCB0,
6640 0x1580, 0x1480, 0x1780, 0x1680, 0x1180, 0x1080, 0x1380, 0x1280, 0x1D80, 0x1C80, 0x1F80, 0x1E80, 0x1980, 0x1880, 0x1B80, 0x1A80,
6641 0x0AC0, 0x0A40, 0x0BC0, 0x0B40, 0x08C0, 0x0840, 0x09C0, 0x0940, 0x0EC0, 0x0E40, 0x0FC0, 0x0F40, 0x0CC0, 0x0C40, 0x0DC0, 0x0D40,
6642 0x5600, 0x5200, 0x5E00, 0x5A00, 0x4600, 0x4200, 0x4E00, 0x4A00, 0x7600, 0x7200, 0x7E00, 0x7A00, 0x6600, 0x6200, 0x6E00, 0x6A00,
6643 0x2B00, 0x2900, 0x2F00, 0x2D00, 0x2300, 0x2100, 0x2700, 0x2500, 0x3B00, 0x3900, 0x3F00, 0x3D00, 0x3300, 0x3100, 0x3700, 0x3500,
6644 0x0158, 0x0148, 0x0178, 0x0168, 0x0118, 0x0108, 0x0138, 0x0128, 0x01D8, 0x01C8, 0x01F8, 0x01E8, 0x0198, 0x0188, 0x01B8, 0x01A8,
6645 0x0058, 0x0048, 0x0078, 0x0068, 0x0018, 0x0008, 0x0038, 0x0028, 0x00D8, 0x00C8, 0x00F8, 0x00E8, 0x0098, 0x0088, 0x00B8, 0x00A8,
6646 0x0560, 0x0520, 0x05E0, 0x05A0, 0x0460, 0x0420, 0x04E0, 0x04A0, 0x0760, 0x0720, 0x07E0, 0x07A0, 0x0660, 0x0620, 0x06E0, 0x06A0,
6647 0x02B0, 0x0290, 0x02F0, 0x02D0, 0x0230, 0x0210, 0x0270, 0x0250, 0x03B0, 0x0390, 0x03F0, 0x03D0, 0x0330, 0x0310, 0x0370, 0x0350
6648};
6649
6650static const unsigned short g_drwavMulawTable[256] = {
6651 0x8284, 0x8684, 0x8A84, 0x8E84, 0x9284, 0x9684, 0x9A84, 0x9E84, 0xA284, 0xA684, 0xAA84, 0xAE84, 0xB284, 0xB684, 0xBA84, 0xBE84,
6652 0xC184, 0xC384, 0xC584, 0xC784, 0xC984, 0xCB84, 0xCD84, 0xCF84, 0xD184, 0xD384, 0xD584, 0xD784, 0xD984, 0xDB84, 0xDD84, 0xDF84,
6653 0xE104, 0xE204, 0xE304, 0xE404, 0xE504, 0xE604, 0xE704, 0xE804, 0xE904, 0xEA04, 0xEB04, 0xEC04, 0xED04, 0xEE04, 0xEF04, 0xF004,
6654 0xF0C4, 0xF144, 0xF1C4, 0xF244, 0xF2C4, 0xF344, 0xF3C4, 0xF444, 0xF4C4, 0xF544, 0xF5C4, 0xF644, 0xF6C4, 0xF744, 0xF7C4, 0xF844,
6655 0xF8A4, 0xF8E4, 0xF924, 0xF964, 0xF9A4, 0xF9E4, 0xFA24, 0xFA64, 0xFAA4, 0xFAE4, 0xFB24, 0xFB64, 0xFBA4, 0xFBE4, 0xFC24, 0xFC64,
6656 0xFC94, 0xFCB4, 0xFCD4, 0xFCF4, 0xFD14, 0xFD34, 0xFD54, 0xFD74, 0xFD94, 0xFDB4, 0xFDD4, 0xFDF4, 0xFE14, 0xFE34, 0xFE54, 0xFE74,
6657 0xFE8C, 0xFE9C, 0xFEAC, 0xFEBC, 0xFECC, 0xFEDC, 0xFEEC, 0xFEFC, 0xFF0C, 0xFF1C, 0xFF2C, 0xFF3C, 0xFF4C, 0xFF5C, 0xFF6C, 0xFF7C,
6658 0xFF88, 0xFF90, 0xFF98, 0xFFA0, 0xFFA8, 0xFFB0, 0xFFB8, 0xFFC0, 0xFFC8, 0xFFD0, 0xFFD8, 0xFFE0, 0xFFE8, 0xFFF0, 0xFFF8, 0x0000,
6659 0x7D7C, 0x797C, 0x757C, 0x717C, 0x6D7C, 0x697C, 0x657C, 0x617C, 0x5D7C, 0x597C, 0x557C, 0x517C, 0x4D7C, 0x497C, 0x457C, 0x417C,
6660 0x3E7C, 0x3C7C, 0x3A7C, 0x387C, 0x367C, 0x347C, 0x327C, 0x307C, 0x2E7C, 0x2C7C, 0x2A7C, 0x287C, 0x267C, 0x247C, 0x227C, 0x207C,
6661 0x1EFC, 0x1DFC, 0x1CFC, 0x1BFC, 0x1AFC, 0x19FC, 0x18FC, 0x17FC, 0x16FC, 0x15FC, 0x14FC, 0x13FC, 0x12FC, 0x11FC, 0x10FC, 0x0FFC,
6662 0x0F3C, 0x0EBC, 0x0E3C, 0x0DBC, 0x0D3C, 0x0CBC, 0x0C3C, 0x0BBC, 0x0B3C, 0x0ABC, 0x0A3C, 0x09BC, 0x093C, 0x08BC, 0x083C, 0x07BC,
6663 0x075C, 0x071C, 0x06DC, 0x069C, 0x065C, 0x061C, 0x05DC, 0x059C, 0x055C, 0x051C, 0x04DC, 0x049C, 0x045C, 0x041C, 0x03DC, 0x039C,
6664 0x036C, 0x034C, 0x032C, 0x030C, 0x02EC, 0x02CC, 0x02AC, 0x028C, 0x026C, 0x024C, 0x022C, 0x020C, 0x01EC, 0x01CC, 0x01AC, 0x018C,
6665 0x0174, 0x0164, 0x0154, 0x0144, 0x0134, 0x0124, 0x0114, 0x0104, 0x00F4, 0x00E4, 0x00D4, 0x00C4, 0x00B4, 0x00A4, 0x0094, 0x0084,
6666 0x0078, 0x0070, 0x0068, 0x0060, 0x0058, 0x0050, 0x0048, 0x0040, 0x0038, 0x0030, 0x0028, 0x0020, 0x0018, 0x0010, 0x0008, 0x0000
6667};
6668
6669static DRWAV_INLINE drwav_int16 drwav__alaw_to_s16(drwav_uint8 sampleIn)
6670{
6671 return (short)g_drwavAlawTable[sampleIn];
6672}
6673
6674static DRWAV_INLINE drwav_int16 drwav__mulaw_to_s16(drwav_uint8 sampleIn)
6675{
6676 return (short)g_drwavMulawTable[sampleIn];
6677}
6678
6679
6680
6681DRWAV_PRIVATE void drwav__pcm_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
6682{
6683 size_t i;
6684
6685 /* Special case for 8-bit sample data because it's treated as unsigned. */
6686 if (bytesPerSample == 1) {
6687 drwav_u8_to_s16(pOut, pIn, totalSampleCount);
6688 return;
6689 }
6690
6691
6692 /* Slightly more optimal implementation for common formats. */
6693 if (bytesPerSample == 2) {
6694 for (i = 0; i < totalSampleCount; ++i) {
6695 *pOut++ = ((const drwav_int16*)pIn)[i];
6696 }
6697 return;
6698 }
6699 if (bytesPerSample == 3) {
6700 drwav_s24_to_s16(pOut, pIn, totalSampleCount);
6701 return;
6702 }
6703 if (bytesPerSample == 4) {
6704 drwav_s32_to_s16(pOut, (const drwav_int32*)pIn, totalSampleCount);
6705 return;
6706 }
6707
6708
6709 /* Anything more than 64 bits per sample is not supported. */
6710 if (bytesPerSample > 8) {
6711 DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
6712 return;
6713 }
6714
6715
6716 /* Generic, slow converter. */
6717 for (i = 0; i < totalSampleCount; ++i) {
6718 drwav_uint64 sample = 0;
6719 unsigned int shift = (8 - bytesPerSample) * 8;
6720
6721 unsigned int j;
6722 for (j = 0; j < bytesPerSample; j += 1) {
6723 DRWAV_ASSERT(j < 8);
6724 sample |= (drwav_uint64)(pIn[j]) << shift;
6725 shift += 8;
6726 }
6727
6728 pIn += j;
6729 *pOut++ = (drwav_int16)((drwav_int64)sample >> 48);
6730 }
6731}
6732
6733DRWAV_PRIVATE void drwav__ieee_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
6734{
6735 if (bytesPerSample == 4) {
6736 drwav_f32_to_s16(pOut, (const float*)pIn, totalSampleCount);
6737 return;
6738 } else if (bytesPerSample == 8) {
6739 drwav_f64_to_s16(pOut, (const double*)pIn, totalSampleCount);
6740 return;
6741 } else {
6742 /* Only supporting 32- and 64-bit float. Output silence in all other cases. Contributions welcome for 16-bit float. */
6743 DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
6744 return;
6745 }
6746}
6747
6748DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__pcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
6749{
6750 drwav_uint64 totalFramesRead;
6751 drwav_uint8 sampleData[4096] = {0};
6752 drwav_uint32 bytesPerFrame;
6753 drwav_uint32 bytesPerSample;
6754 drwav_uint64 samplesRead;
6755
6756 /* Fast path. */
6757 if ((pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 16) || pBufferOut == NULL) {
6758 return drwav_read_pcm_frames(pWav, framesToRead, pBufferOut);
6759 }
6760
6761 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
6762 if (bytesPerFrame == 0) {
6763 return 0;
6764 }
6765
6766 bytesPerSample = bytesPerFrame / pWav->channels;
6767 if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
6768 return 0; /* Only byte-aligned formats are supported. */
6769 }
6770
6771 totalFramesRead = 0;
6772
6773 while (framesToRead > 0) {
6774 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
6775 drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
6776 if (framesRead == 0) {
6777 break;
6778 }
6779
6780 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
6781
6782 /* Validation to ensure we don't read too much from out intermediary buffer. This is to protect from invalid files. */
6783 samplesRead = framesRead * pWav->channels;
6784 if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
6785 DRWAV_ASSERT(DRWAV_FALSE); /* This should never happen with a valid file. */
6786 break;
6787 }
6788
6789 drwav__pcm_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
6790
6791 pBufferOut += samplesRead;
6792 framesToRead -= framesRead;
6793 totalFramesRead += framesRead;
6794 }
6795
6796 return totalFramesRead;
6797}
6798
6799DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__ieee(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
6800{
6801 drwav_uint64 totalFramesRead;
6802 drwav_uint8 sampleData[4096] = {0};
6803 drwav_uint32 bytesPerFrame;
6804 drwav_uint32 bytesPerSample;
6805 drwav_uint64 samplesRead;
6806
6807 if (pBufferOut == NULL) {
6808 return drwav_read_pcm_frames(pWav, framesToRead, NULL);
6809 }
6810
6811 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
6812 if (bytesPerFrame == 0) {
6813 return 0;
6814 }
6815
6816 bytesPerSample = bytesPerFrame / pWav->channels;
6817 if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
6818 return 0; /* Only byte-aligned formats are supported. */
6819 }
6820
6821 totalFramesRead = 0;
6822
6823 while (framesToRead > 0) {
6824 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
6825 drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
6826 if (framesRead == 0) {
6827 break;
6828 }
6829
6830 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
6831
6832 /* Validation to ensure we don't read too much from out intermediary buffer. This is to protect from invalid files. */
6833 samplesRead = framesRead * pWav->channels;
6834 if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
6835 DRWAV_ASSERT(DRWAV_FALSE); /* This should never happen with a valid file. */
6836 break;
6837 }
6838
6839 drwav__ieee_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample); /* Safe cast. */
6840
6841 pBufferOut += samplesRead;
6842 framesToRead -= framesRead;
6843 totalFramesRead += framesRead;
6844 }
6845
6846 return totalFramesRead;
6847}
6848
6849DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__alaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
6850{
6851 drwav_uint64 totalFramesRead;
6852 drwav_uint8 sampleData[4096] = {0};
6853 drwav_uint32 bytesPerFrame;
6854 drwav_uint32 bytesPerSample;
6855 drwav_uint64 samplesRead;
6856
6857 if (pBufferOut == NULL) {
6858 return drwav_read_pcm_frames(pWav, framesToRead, NULL);
6859 }
6860
6861 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
6862 if (bytesPerFrame == 0) {
6863 return 0;
6864 }
6865
6866 bytesPerSample = bytesPerFrame / pWav->channels;
6867 if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
6868 return 0; /* Only byte-aligned formats are supported. */
6869 }
6870
6871 totalFramesRead = 0;
6872
6873 while (framesToRead > 0) {
6874 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
6875 drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
6876 if (framesRead == 0) {
6877 break;
6878 }
6879
6880 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
6881
6882 /* Validation to ensure we don't read too much from out intermediary buffer. This is to protect from invalid files. */
6883 samplesRead = framesRead * pWav->channels;
6884 if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
6885 DRWAV_ASSERT(DRWAV_FALSE); /* This should never happen with a valid file. */
6886 break;
6887 }
6888
6889 drwav_alaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead);
6890
6891 /*
6892 For some reason libsndfile seems to be returning samples of the opposite sign for a-law, but only
6893 with AIFF files. For WAV files it seems to be the same as dr_wav. This is resulting in dr_wav's
6894 automated tests failing. I'm not sure which is correct, but will assume dr_wav. If we're enforcing
6895 libsndfile compatibility we'll swap the signs here.
6896 */
6897 #ifdef DR_WAV_LIBSNDFILE_COMPAT
6898 {
6899 if (pWav->container == drwav_container_aiff) {
6900 drwav_uint64 iSample;
6901 for (iSample = 0; iSample < samplesRead; iSample += 1) {
6902 pBufferOut[iSample] = -pBufferOut[iSample];
6903 }
6904 }
6905 }
6906 #endif
6907
6908 pBufferOut += samplesRead;
6909 framesToRead -= framesRead;
6910 totalFramesRead += framesRead;
6911 }
6912
6913 return totalFramesRead;
6914}
6915
6916DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__mulaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
6917{
6918 drwav_uint64 totalFramesRead;
6919 drwav_uint8 sampleData[4096] = {0};
6920 drwav_uint32 bytesPerFrame;
6921 drwav_uint32 bytesPerSample;
6922 drwav_uint64 samplesRead;
6923
6924 if (pBufferOut == NULL) {
6925 return drwav_read_pcm_frames(pWav, framesToRead, NULL);
6926 }
6927
6928 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
6929 if (bytesPerFrame == 0) {
6930 return 0;
6931 }
6932
6933 bytesPerSample = bytesPerFrame / pWav->channels;
6934 if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
6935 return 0; /* Only byte-aligned formats are supported. */
6936 }
6937
6938 totalFramesRead = 0;
6939
6940 while (framesToRead > 0) {
6941 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
6942 drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
6943 if (framesRead == 0) {
6944 break;
6945 }
6946
6947 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
6948
6949 /* Validation to ensure we don't read too much from out intermediary buffer. This is to protect from invalid files. */
6950 samplesRead = framesRead * pWav->channels;
6951 if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
6952 DRWAV_ASSERT(DRWAV_FALSE); /* This should never happen with a valid file. */
6953 break;
6954 }
6955
6956 drwav_mulaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead);
6957
6958 /*
6959 Just like with alaw, for some reason the signs between libsndfile and dr_wav are opposite. We just need to
6960 swap the sign if we're compiling with libsndfile compatiblity so our automated tests don't fail.
6961 */
6962 #ifdef DR_WAV_LIBSNDFILE_COMPAT
6963 {
6964 if (pWav->container == drwav_container_aiff) {
6965 drwav_uint64 iSample;
6966 for (iSample = 0; iSample < samplesRead; iSample += 1) {
6967 pBufferOut[iSample] = -pBufferOut[iSample];
6968 }
6969 }
6970 }
6971 #endif
6972
6973 pBufferOut += samplesRead;
6974 framesToRead -= framesRead;
6975 totalFramesRead += framesRead;
6976 }
6977
6978 return totalFramesRead;
6979}
6980
6982{
6983 if (pWav == NULL || framesToRead == 0) {
6984 return 0;
6985 }
6986
6987 if (pBufferOut == NULL) {
6988 return drwav_read_pcm_frames(pWav, framesToRead, NULL);
6989 }
6990
6991 /* Don't try to read more samples than can potentially fit in the output buffer. */
6992 if (framesToRead * pWav->channels * sizeof(drwav_int16) > DRWAV_SIZE_MAX) {
6993 framesToRead = DRWAV_SIZE_MAX / sizeof(drwav_int16) / pWav->channels;
6994 }
6995
6997 return drwav_read_pcm_frames_s16__pcm(pWav, framesToRead, pBufferOut);
6998 }
6999
7001 return drwav_read_pcm_frames_s16__ieee(pWav, framesToRead, pBufferOut);
7002 }
7003
7005 return drwav_read_pcm_frames_s16__alaw(pWav, framesToRead, pBufferOut);
7006 }
7007
7009 return drwav_read_pcm_frames_s16__mulaw(pWav, framesToRead, pBufferOut);
7010 }
7011
7013 return drwav_read_pcm_frames_s16__msadpcm(pWav, framesToRead, pBufferOut);
7014 }
7015
7017 return drwav_read_pcm_frames_s16__ima(pWav, framesToRead, pBufferOut);
7018 }
7019
7020 return 0;
7021}
7022
7024{
7025 drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToRead, pBufferOut);
7026 if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_FALSE) {
7027 drwav__bswap_samples_s16(pBufferOut, framesRead*pWav->channels);
7028 }
7029
7030 return framesRead;
7031}
7032
7034{
7035 drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToRead, pBufferOut);
7036 if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_TRUE) {
7037 drwav__bswap_samples_s16(pBufferOut, framesRead*pWav->channels);
7038 }
7039
7040 return framesRead;
7041}
7042
7043
7044DRWAV_API void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
7045{
7046 int r;
7047 size_t i;
7048 for (i = 0; i < sampleCount; ++i) {
7049 int x = pIn[i];
7050 r = x << 8;
7051 r = r - 32768;
7052 pOut[i] = (short)r;
7053 }
7054}
7055
7056DRWAV_API void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
7057{
7058 int r;
7059 size_t i;
7060 for (i = 0; i < sampleCount; ++i) {
7061 int x = ((int)(((unsigned int)(((const drwav_uint8*)pIn)[i*3+0]) << 8) | ((unsigned int)(((const drwav_uint8*)pIn)[i*3+1]) << 16) | ((unsigned int)(((const drwav_uint8*)pIn)[i*3+2])) << 24)) >> 8;
7062 r = x >> 8;
7063 pOut[i] = (short)r;
7064 }
7065}
7066
7067DRWAV_API void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCount)
7068{
7069 int r;
7070 size_t i;
7071 for (i = 0; i < sampleCount; ++i) {
7072 int x = pIn[i];
7073 r = x >> 16;
7074 pOut[i] = (short)r;
7075 }
7076}
7077
7078DRWAV_API void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount)
7079{
7080 int r;
7081 size_t i;
7082 for (i = 0; i < sampleCount; ++i) {
7083 float x = pIn[i];
7084 float c;
7085 c = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
7086 c = c + 1;
7087 r = (int)(c * 32767.5f);
7088 r = r - 32768;
7089 pOut[i] = (short)r;
7090 }
7091}
7092
7093DRWAV_API void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount)
7094{
7095 int r;
7096 size_t i;
7097 for (i = 0; i < sampleCount; ++i) {
7098 double x = pIn[i];
7099 double c;
7100 c = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
7101 c = c + 1;
7102 r = (int)(c * 32767.5);
7103 r = r - 32768;
7104 pOut[i] = (short)r;
7105 }
7106}
7107
7108DRWAV_API void drwav_alaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
7109{
7110 size_t i;
7111 for (i = 0; i < sampleCount; ++i) {
7112 pOut[i] = drwav__alaw_to_s16(pIn[i]);
7113 }
7114}
7115
7116DRWAV_API void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
7117{
7118 size_t i;
7119 for (i = 0; i < sampleCount; ++i) {
7120 pOut[i] = drwav__mulaw_to_s16(pIn[i]);
7121 }
7122}
7123
7124
7125DRWAV_PRIVATE void drwav__pcm_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample)
7126{
7127 unsigned int i;
7128
7129 /* Special case for 8-bit sample data because it's treated as unsigned. */
7130 if (bytesPerSample == 1) {
7131 drwav_u8_to_f32(pOut, pIn, sampleCount);
7132 return;
7133 }
7134
7135 /* Slightly more optimal implementation for common formats. */
7136 if (bytesPerSample == 2) {
7137 drwav_s16_to_f32(pOut, (const drwav_int16*)pIn, sampleCount);
7138 return;
7139 }
7140 if (bytesPerSample == 3) {
7141 drwav_s24_to_f32(pOut, pIn, sampleCount);
7142 return;
7143 }
7144 if (bytesPerSample == 4) {
7145 drwav_s32_to_f32(pOut, (const drwav_int32*)pIn, sampleCount);
7146 return;
7147 }
7148
7149
7150 /* Anything more than 64 bits per sample is not supported. */
7151 if (bytesPerSample > 8) {
7152 DRWAV_ZERO_MEMORY(pOut, sampleCount * sizeof(*pOut));
7153 return;
7154 }
7155
7156
7157 /* Generic, slow converter. */
7158 for (i = 0; i < sampleCount; ++i) {
7159 drwav_uint64 sample = 0;
7160 unsigned int shift = (8 - bytesPerSample) * 8;
7161
7162 unsigned int j;
7163 for (j = 0; j < bytesPerSample; j += 1) {
7164 DRWAV_ASSERT(j < 8);
7165 sample |= (drwav_uint64)(pIn[j]) << shift;
7166 shift += 8;
7167 }
7168
7169 pIn += j;
7170 *pOut++ = (float)((drwav_int64)sample / 9223372036854775807.0);
7171 }
7172}
7173
7174DRWAV_PRIVATE void drwav__ieee_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample)
7175{
7176 if (bytesPerSample == 4) {
7177 unsigned int i;
7178 for (i = 0; i < sampleCount; ++i) {
7179 *pOut++ = ((const float*)pIn)[i];
7180 }
7181 return;
7182 } else if (bytesPerSample == 8) {
7183 drwav_f64_to_f32(pOut, (const double*)pIn, sampleCount);
7184 return;
7185 } else {
7186 /* Only supporting 32- and 64-bit float. Output silence in all other cases. Contributions welcome for 16-bit float. */
7187 DRWAV_ZERO_MEMORY(pOut, sampleCount * sizeof(*pOut));
7188 return;
7189 }
7190}
7191
7192
7193DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__pcm(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
7194{
7195 drwav_uint64 totalFramesRead;
7196 drwav_uint8 sampleData[4096] = {0};
7197 drwav_uint32 bytesPerFrame;
7198 drwav_uint32 bytesPerSample;
7199 drwav_uint64 samplesRead;
7200
7201 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
7202 if (bytesPerFrame == 0) {
7203 return 0;
7204 }
7205
7206 bytesPerSample = bytesPerFrame / pWav->channels;
7207 if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
7208 return 0; /* Only byte-aligned formats are supported. */
7209 }
7210
7211 totalFramesRead = 0;
7212
7213 while (framesToRead > 0) {
7214 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
7215 drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
7216 if (framesRead == 0) {
7217 break;
7218 }
7219
7220 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
7221
7222 /* Validation to ensure we don't read too much from out intermediary buffer. This is to protect from invalid files. */
7223 samplesRead = framesRead * pWav->channels;
7224 if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
7225 DRWAV_ASSERT(DRWAV_FALSE); /* This should never happen with a valid file. */
7226 break;
7227 }
7228
7229 drwav__pcm_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
7230
7231 pBufferOut += samplesRead;
7232 framesToRead -= framesRead;
7233 totalFramesRead += framesRead;
7234 }
7235
7236 return totalFramesRead;
7237}
7238
7239DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__msadpcm_ima(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
7240{
7241 /*
7242 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
7243 want to duplicate that code.
7244 */
7245 drwav_uint64 totalFramesRead;
7246 drwav_int16 samples16[2048];
7247
7248 totalFramesRead = 0;
7249
7250 while (framesToRead > 0) {
7251 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, drwav_countof(samples16)/pWav->channels);
7252 drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToReadThisIteration, samples16);
7253 if (framesRead == 0) {
7254 break;
7255 }
7256
7257 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
7258
7259 drwav_s16_to_f32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels)); /* <-- Safe cast because we're clamping to 2048. */
7260
7261 pBufferOut += framesRead*pWav->channels;
7262 framesToRead -= framesRead;
7263 totalFramesRead += framesRead;
7264 }
7265
7266 return totalFramesRead;
7267}
7268
7269DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__ieee(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
7270{
7271 drwav_uint64 totalFramesRead;
7272 drwav_uint8 sampleData[4096] = {0};
7273 drwav_uint32 bytesPerFrame;
7274 drwav_uint32 bytesPerSample;
7275 drwav_uint64 samplesRead;
7276
7277 /* Fast path. */
7278 if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT && pWav->bitsPerSample == 32) {
7279 return drwav_read_pcm_frames(pWav, framesToRead, pBufferOut);
7280 }
7281
7282 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
7283 if (bytesPerFrame == 0) {
7284 return 0;
7285 }
7286
7287 bytesPerSample = bytesPerFrame / pWav->channels;
7288 if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
7289 return 0; /* Only byte-aligned formats are supported. */
7290 }
7291
7292 totalFramesRead = 0;
7293
7294 while (framesToRead > 0) {
7295 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
7296 drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
7297 if (framesRead == 0) {
7298 break;
7299 }
7300
7301 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
7302
7303 /* Validation to ensure we don't read too much from out intermediary buffer. This is to protect from invalid files. */
7304 samplesRead = framesRead * pWav->channels;
7305 if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
7306 DRWAV_ASSERT(DRWAV_FALSE); /* This should never happen with a valid file. */
7307 break;
7308 }
7309
7310 drwav__ieee_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
7311
7312 pBufferOut += samplesRead;
7313 framesToRead -= framesRead;
7314 totalFramesRead += framesRead;
7315 }
7316
7317 return totalFramesRead;
7318}
7319
7320DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__alaw(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
7321{
7322 drwav_uint64 totalFramesRead;
7323 drwav_uint8 sampleData[4096] = {0};
7324 drwav_uint32 bytesPerFrame;
7325 drwav_uint32 bytesPerSample;
7326 drwav_uint64 samplesRead;
7327
7328 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
7329 if (bytesPerFrame == 0) {
7330 return 0;
7331 }
7332
7333 bytesPerSample = bytesPerFrame / pWav->channels;
7334 if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
7335 return 0; /* Only byte-aligned formats are supported. */
7336 }
7337
7338 totalFramesRead = 0;
7339
7340 while (framesToRead > 0) {
7341 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
7342 drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
7343 if (framesRead == 0) {
7344 break;
7345 }
7346
7347 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
7348
7349 /* Validation to ensure we don't read too much from out intermediary buffer. This is to protect from invalid files. */
7350 samplesRead = framesRead * pWav->channels;
7351 if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
7352 DRWAV_ASSERT(DRWAV_FALSE); /* This should never happen with a valid file. */
7353 break;
7354 }
7355
7356 drwav_alaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead);
7357
7358 #ifdef DR_WAV_LIBSNDFILE_COMPAT
7359 {
7360 if (pWav->container == drwav_container_aiff) {
7361 drwav_uint64 iSample;
7362 for (iSample = 0; iSample < samplesRead; iSample += 1) {
7363 pBufferOut[iSample] = -pBufferOut[iSample];
7364 }
7365 }
7366 }
7367 #endif
7368
7369 pBufferOut += samplesRead;
7370 framesToRead -= framesRead;
7371 totalFramesRead += framesRead;
7372 }
7373
7374 return totalFramesRead;
7375}
7376
7377DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__mulaw(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
7378{
7379 drwav_uint64 totalFramesRead;
7380 drwav_uint8 sampleData[4096] = {0};
7381 drwav_uint32 bytesPerFrame;
7382 drwav_uint32 bytesPerSample;
7383 drwav_uint64 samplesRead;
7384
7385 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
7386 if (bytesPerFrame == 0) {
7387 return 0;
7388 }
7389
7390 bytesPerSample = bytesPerFrame / pWav->channels;
7391 if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
7392 return 0; /* Only byte-aligned formats are supported. */
7393 }
7394
7395 totalFramesRead = 0;
7396
7397 while (framesToRead > 0) {
7398 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
7399 drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
7400 if (framesRead == 0) {
7401 break;
7402 }
7403
7404 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
7405
7406 /* Validation to ensure we don't read too much from out intermediary buffer. This is to protect from invalid files. */
7407 samplesRead = framesRead * pWav->channels;
7408 if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
7409 DRWAV_ASSERT(DRWAV_FALSE); /* This should never happen with a valid file. */
7410 break;
7411 }
7412
7413 drwav_mulaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead);
7414
7415 #ifdef DR_WAV_LIBSNDFILE_COMPAT
7416 {
7417 if (pWav->container == drwav_container_aiff) {
7418 drwav_uint64 iSample;
7419 for (iSample = 0; iSample < samplesRead; iSample += 1) {
7420 pBufferOut[iSample] = -pBufferOut[iSample];
7421 }
7422 }
7423 }
7424 #endif
7425
7426 pBufferOut += samplesRead;
7427 framesToRead -= framesRead;
7428 totalFramesRead += framesRead;
7429 }
7430
7431 return totalFramesRead;
7432}
7433
7434DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
7435{
7436 if (pWav == NULL || framesToRead == 0) {
7437 return 0;
7438 }
7439
7440 if (pBufferOut == NULL) {
7441 return drwav_read_pcm_frames(pWav, framesToRead, NULL);
7442 }
7443
7444 /* Don't try to read more samples than can potentially fit in the output buffer. */
7445 if (framesToRead * pWav->channels * sizeof(float) > DRWAV_SIZE_MAX) {
7446 framesToRead = DRWAV_SIZE_MAX / sizeof(float) / pWav->channels;
7447 }
7448
7450 return drwav_read_pcm_frames_f32__pcm(pWav, framesToRead, pBufferOut);
7451 }
7452
7454 return drwav_read_pcm_frames_f32__msadpcm_ima(pWav, framesToRead, pBufferOut);
7455 }
7456
7458 return drwav_read_pcm_frames_f32__ieee(pWav, framesToRead, pBufferOut);
7459 }
7460
7462 return drwav_read_pcm_frames_f32__alaw(pWav, framesToRead, pBufferOut);
7463 }
7464
7466 return drwav_read_pcm_frames_f32__mulaw(pWav, framesToRead, pBufferOut);
7467 }
7468
7469 return 0;
7470}
7471
7472DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32le(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
7473{
7474 drwav_uint64 framesRead = drwav_read_pcm_frames_f32(pWav, framesToRead, pBufferOut);
7475 if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_FALSE) {
7476 drwav__bswap_samples_f32(pBufferOut, framesRead*pWav->channels);
7477 }
7478
7479 return framesRead;
7480}
7481
7482DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32be(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
7483{
7484 drwav_uint64 framesRead = drwav_read_pcm_frames_f32(pWav, framesToRead, pBufferOut);
7485 if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_TRUE) {
7486 drwav__bswap_samples_f32(pBufferOut, framesRead*pWav->channels);
7487 }
7488
7489 return framesRead;
7490}
7491
7492
7493DRWAV_API void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
7494{
7495 size_t i;
7496
7497 if (pOut == NULL || pIn == NULL) {
7498 return;
7499 }
7500
7501#ifdef DR_WAV_LIBSNDFILE_COMPAT
7502 /*
7503 It appears libsndfile uses slightly different logic for the u8 -> f32 conversion to dr_wav, which in my opinion is incorrect. It appears
7504 libsndfile performs the conversion something like "f32 = (u8 / 256) * 2 - 1", however I think it should be "f32 = (u8 / 255) * 2 - 1" (note
7505 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
7506 correctness testing. This is disabled by default.
7507 */
7508 for (i = 0; i < sampleCount; ++i) {
7509 *pOut++ = (pIn[i] / 256.0f) * 2 - 1;
7510 }
7511#else
7512 for (i = 0; i < sampleCount; ++i) {
7513 float x = pIn[i];
7514 x = x * 0.00784313725490196078f; /* 0..255 to 0..2 */
7515 x = x - 1; /* 0..2 to -1..1 */
7516
7517 *pOut++ = x;
7518 }
7519#endif
7520}
7521
7522DRWAV_API void drwav_s16_to_f32(float* pOut, const drwav_int16* pIn, size_t sampleCount)
7523{
7524 size_t i;
7525
7526 if (pOut == NULL || pIn == NULL) {
7527 return;
7528 }
7529
7530 for (i = 0; i < sampleCount; ++i) {
7531 *pOut++ = pIn[i] * 0.000030517578125f;
7532 }
7533}
7534
7535DRWAV_API void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
7536{
7537 size_t i;
7538
7539 if (pOut == NULL || pIn == NULL) {
7540 return;
7541 }
7542
7543 for (i = 0; i < sampleCount; ++i) {
7544 double x;
7545 drwav_uint32 a = ((drwav_uint32)(pIn[i*3+0]) << 8);
7546 drwav_uint32 b = ((drwav_uint32)(pIn[i*3+1]) << 16);
7547 drwav_uint32 c = ((drwav_uint32)(pIn[i*3+2]) << 24);
7548
7549 x = (double)((drwav_int32)(a | b | c) >> 8);
7550 *pOut++ = (float)(x * 0.00000011920928955078125);
7551 }
7552}
7553
7554DRWAV_API void drwav_s32_to_f32(float* pOut, const drwav_int32* pIn, size_t sampleCount)
7555{
7556 size_t i;
7557 if (pOut == NULL || pIn == NULL) {
7558 return;
7559 }
7560
7561 for (i = 0; i < sampleCount; ++i) {
7562 *pOut++ = (float)(pIn[i] / 2147483648.0);
7563 }
7564}
7565
7566DRWAV_API void drwav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount)
7567{
7568 size_t i;
7569
7570 if (pOut == NULL || pIn == NULL) {
7571 return;
7572 }
7573
7574 for (i = 0; i < sampleCount; ++i) {
7575 *pOut++ = (float)pIn[i];
7576 }
7577}
7578
7579DRWAV_API void drwav_alaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
7580{
7581 size_t i;
7582
7583 if (pOut == NULL || pIn == NULL) {
7584 return;
7585 }
7586
7587 for (i = 0; i < sampleCount; ++i) {
7588 *pOut++ = drwav__alaw_to_s16(pIn[i]) / 32768.0f;
7589 }
7590}
7591
7592DRWAV_API void drwav_mulaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
7593{
7594 size_t i;
7595
7596 if (pOut == NULL || pIn == NULL) {
7597 return;
7598 }
7599
7600 for (i = 0; i < sampleCount; ++i) {
7601 *pOut++ = drwav__mulaw_to_s16(pIn[i]) / 32768.0f;
7602 }
7603}
7604
7605
7606
7607DRWAV_PRIVATE void drwav__pcm_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
7608{
7609 unsigned int i;
7610
7611 /* Special case for 8-bit sample data because it's treated as unsigned. */
7612 if (bytesPerSample == 1) {
7613 drwav_u8_to_s32(pOut, pIn, totalSampleCount);
7614 return;
7615 }
7616
7617 /* Slightly more optimal implementation for common formats. */
7618 if (bytesPerSample == 2) {
7619 drwav_s16_to_s32(pOut, (const drwav_int16*)pIn, totalSampleCount);
7620 return;
7621 }
7622 if (bytesPerSample == 3) {
7623 drwav_s24_to_s32(pOut, pIn, totalSampleCount);
7624 return;
7625 }
7626 if (bytesPerSample == 4) {
7627 for (i = 0; i < totalSampleCount; ++i) {
7628 *pOut++ = ((const drwav_int32*)pIn)[i];
7629 }
7630 return;
7631 }
7632
7633
7634 /* Anything more than 64 bits per sample is not supported. */
7635 if (bytesPerSample > 8) {
7636 DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
7637 return;
7638 }
7639
7640
7641 /* Generic, slow converter. */
7642 for (i = 0; i < totalSampleCount; ++i) {
7643 drwav_uint64 sample = 0;
7644 unsigned int shift = (8 - bytesPerSample) * 8;
7645
7646 unsigned int j;
7647 for (j = 0; j < bytesPerSample; j += 1) {
7648 DRWAV_ASSERT(j < 8);
7649 sample |= (drwav_uint64)(pIn[j]) << shift;
7650 shift += 8;
7651 }
7652
7653 pIn += j;
7654 *pOut++ = (drwav_int32)((drwav_int64)sample >> 32);
7655 }
7656}
7657
7658DRWAV_PRIVATE void drwav__ieee_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
7659{
7660 if (bytesPerSample == 4) {
7661 drwav_f32_to_s32(pOut, (const float*)pIn, totalSampleCount);
7662 return;
7663 } else if (bytesPerSample == 8) {
7664 drwav_f64_to_s32(pOut, (const double*)pIn, totalSampleCount);
7665 return;
7666 } else {
7667 /* Only supporting 32- and 64-bit float. Output silence in all other cases. Contributions welcome for 16-bit float. */
7668 DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
7669 return;
7670 }
7671}
7672
7673
7674DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__pcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
7675{
7676 drwav_uint64 totalFramesRead;
7677 drwav_uint8 sampleData[4096] = {0};
7678 drwav_uint32 bytesPerFrame;
7679 drwav_uint32 bytesPerSample;
7680 drwav_uint64 samplesRead;
7681
7682 /* Fast path. */
7683 if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 32) {
7684 return drwav_read_pcm_frames(pWav, framesToRead, pBufferOut);
7685 }
7686
7687 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
7688 if (bytesPerFrame == 0) {
7689 return 0;
7690 }
7691
7692 bytesPerSample = bytesPerFrame / pWav->channels;
7693 if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
7694 return 0; /* Only byte-aligned formats are supported. */
7695 }
7696
7697 totalFramesRead = 0;
7698
7699 while (framesToRead > 0) {
7700 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
7701 drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
7702 if (framesRead == 0) {
7703 break;
7704 }
7705
7706 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
7707
7708 /* Validation to ensure we don't read too much from out intermediary buffer. This is to protect from invalid files. */
7709 samplesRead = framesRead * pWav->channels;
7710 if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
7711 DRWAV_ASSERT(DRWAV_FALSE); /* This should never happen with a valid file. */
7712 break;
7713 }
7714
7715 drwav__pcm_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
7716
7717 pBufferOut += samplesRead;
7718 framesToRead -= framesRead;
7719 totalFramesRead += framesRead;
7720 }
7721
7722 return totalFramesRead;
7723}
7724
7725DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__msadpcm_ima(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
7726{
7727 /*
7728 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
7729 want to duplicate that code.
7730 */
7731 drwav_uint64 totalFramesRead = 0;
7732 drwav_int16 samples16[2048];
7733
7734 while (framesToRead > 0) {
7735 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, drwav_countof(samples16)/pWav->channels);
7736 drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToReadThisIteration, samples16);
7737 if (framesRead == 0) {
7738 break;
7739 }
7740
7741 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
7742
7743 drwav_s16_to_s32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels)); /* <-- Safe cast because we're clamping to 2048. */
7744
7745 pBufferOut += framesRead*pWav->channels;
7746 framesToRead -= framesRead;
7747 totalFramesRead += framesRead;
7748 }
7749
7750 return totalFramesRead;
7751}
7752
7753DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__ieee(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
7754{
7755 drwav_uint64 totalFramesRead;
7756 drwav_uint8 sampleData[4096] = {0};
7757 drwav_uint32 bytesPerFrame;
7758 drwav_uint32 bytesPerSample;
7759 drwav_uint64 samplesRead;
7760
7761 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
7762 if (bytesPerFrame == 0) {
7763 return 0;
7764 }
7765
7766 bytesPerSample = bytesPerFrame / pWav->channels;
7767 if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
7768 return 0; /* Only byte-aligned formats are supported. */
7769 }
7770
7771 totalFramesRead = 0;
7772
7773 while (framesToRead > 0) {
7774 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
7775 drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
7776 if (framesRead == 0) {
7777 break;
7778 }
7779
7780 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
7781
7782 /* Validation to ensure we don't read too much from out intermediary buffer. This is to protect from invalid files. */
7783 samplesRead = framesRead * pWav->channels;
7784 if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
7785 DRWAV_ASSERT(DRWAV_FALSE); /* This should never happen with a valid file. */
7786 break;
7787 }
7788
7789 drwav__ieee_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
7790
7791 pBufferOut += samplesRead;
7792 framesToRead -= framesRead;
7793 totalFramesRead += framesRead;
7794 }
7795
7796 return totalFramesRead;
7797}
7798
7799DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__alaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
7800{
7801 drwav_uint64 totalFramesRead;
7802 drwav_uint8 sampleData[4096] = {0};
7803 drwav_uint32 bytesPerFrame;
7804 drwav_uint32 bytesPerSample;
7805 drwav_uint64 samplesRead;
7806
7807 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
7808 if (bytesPerFrame == 0) {
7809 return 0;
7810 }
7811
7812 bytesPerSample = bytesPerFrame / pWav->channels;
7813 if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
7814 return 0; /* Only byte-aligned formats are supported. */
7815 }
7816
7817 totalFramesRead = 0;
7818
7819 while (framesToRead > 0) {
7820 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
7821 drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
7822 if (framesRead == 0) {
7823 break;
7824 }
7825
7826 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
7827
7828 /* Validation to ensure we don't read too much from out intermediary buffer. This is to protect from invalid files. */
7829 samplesRead = framesRead * pWav->channels;
7830 if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
7831 DRWAV_ASSERT(DRWAV_FALSE); /* This should never happen with a valid file. */
7832 break;
7833 }
7834
7835 drwav_alaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead);
7836
7837 #ifdef DR_WAV_LIBSNDFILE_COMPAT
7838 {
7839 if (pWav->container == drwav_container_aiff) {
7840 drwav_uint64 iSample;
7841 for (iSample = 0; iSample < samplesRead; iSample += 1) {
7842 pBufferOut[iSample] = -pBufferOut[iSample];
7843 }
7844 }
7845 }
7846 #endif
7847
7848 pBufferOut += samplesRead;
7849 framesToRead -= framesRead;
7850 totalFramesRead += framesRead;
7851 }
7852
7853 return totalFramesRead;
7854}
7855
7856DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__mulaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
7857{
7858 drwav_uint64 totalFramesRead;
7859 drwav_uint8 sampleData[4096] = {0};
7860 drwav_uint32 bytesPerFrame;
7861 drwav_uint32 bytesPerSample;
7862 drwav_uint64 samplesRead;
7863
7864 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
7865 if (bytesPerFrame == 0) {
7866 return 0;
7867 }
7868
7869 bytesPerSample = bytesPerFrame / pWav->channels;
7870 if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
7871 return 0; /* Only byte-aligned formats are supported. */
7872 }
7873
7874 totalFramesRead = 0;
7875
7876 while (framesToRead > 0) {
7877 drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
7878 drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
7879 if (framesRead == 0) {
7880 break;
7881 }
7882
7883 DRWAV_ASSERT(framesRead <= framesToReadThisIteration); /* If this fails it means there's a bug in drwav_read_pcm_frames(). */
7884
7885 /* Validation to ensure we don't read too much from out intermediary buffer. This is to protect from invalid files. */
7886 samplesRead = framesRead * pWav->channels;
7887 if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
7888 DRWAV_ASSERT(DRWAV_FALSE); /* This should never happen with a valid file. */
7889 break;
7890 }
7891
7892 drwav_mulaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead);
7893
7894 #ifdef DR_WAV_LIBSNDFILE_COMPAT
7895 {
7896 if (pWav->container == drwav_container_aiff) {
7897 drwav_uint64 iSample;
7898 for (iSample = 0; iSample < samplesRead; iSample += 1) {
7899 pBufferOut[iSample] = -pBufferOut[iSample];
7900 }
7901 }
7902 }
7903 #endif
7904
7905 pBufferOut += samplesRead;
7906 framesToRead -= framesRead;
7907 totalFramesRead += framesRead;
7908 }
7909
7910 return totalFramesRead;
7911}
7912
7914{
7915 if (pWav == NULL || framesToRead == 0) {
7916 return 0;
7917 }
7918
7919 if (pBufferOut == NULL) {
7920 return drwav_read_pcm_frames(pWav, framesToRead, NULL);
7921 }
7922
7923 /* Don't try to read more samples than can potentially fit in the output buffer. */
7924 if (framesToRead * pWav->channels * sizeof(drwav_int32) > DRWAV_SIZE_MAX) {
7925 framesToRead = DRWAV_SIZE_MAX / sizeof(drwav_int32) / pWav->channels;
7926 }
7927
7929 return drwav_read_pcm_frames_s32__pcm(pWav, framesToRead, pBufferOut);
7930 }
7931
7933 return drwav_read_pcm_frames_s32__msadpcm_ima(pWav, framesToRead, pBufferOut);
7934 }
7935
7937 return drwav_read_pcm_frames_s32__ieee(pWav, framesToRead, pBufferOut);
7938 }
7939
7941 return drwav_read_pcm_frames_s32__alaw(pWav, framesToRead, pBufferOut);
7942 }
7943
7945 return drwav_read_pcm_frames_s32__mulaw(pWav, framesToRead, pBufferOut);
7946 }
7947
7948 return 0;
7949}
7950
7952{
7953 drwav_uint64 framesRead = drwav_read_pcm_frames_s32(pWav, framesToRead, pBufferOut);
7954 if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_FALSE) {
7955 drwav__bswap_samples_s32(pBufferOut, framesRead*pWav->channels);
7956 }
7957
7958 return framesRead;
7959}
7960
7962{
7963 drwav_uint64 framesRead = drwav_read_pcm_frames_s32(pWav, framesToRead, pBufferOut);
7964 if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_TRUE) {
7965 drwav__bswap_samples_s32(pBufferOut, framesRead*pWav->channels);
7966 }
7967
7968 return framesRead;
7969}
7970
7971
7972DRWAV_API void drwav_u8_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
7973{
7974 size_t i;
7975
7976 if (pOut == NULL || pIn == NULL) {
7977 return;
7978 }
7979
7980 for (i = 0; i < sampleCount; ++i) {
7981 *pOut++ = ((int)pIn[i] - 128) << 24;
7982 }
7983}
7984
7985DRWAV_API void drwav_s16_to_s32(drwav_int32* pOut, const drwav_int16* pIn, size_t sampleCount)
7986{
7987 size_t i;
7988
7989 if (pOut == NULL || pIn == NULL) {
7990 return;
7991 }
7992
7993 for (i = 0; i < sampleCount; ++i) {
7994 *pOut++ = pIn[i] << 16;
7995 }
7996}
7997
7998DRWAV_API void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
7999{
8000 size_t i;
8001
8002 if (pOut == NULL || pIn == NULL) {
8003 return;
8004 }
8005
8006 for (i = 0; i < sampleCount; ++i) {
8007 unsigned int s0 = pIn[i*3 + 0];
8008 unsigned int s1 = pIn[i*3 + 1];
8009 unsigned int s2 = pIn[i*3 + 2];
8010
8011 drwav_int32 sample32 = (drwav_int32)((s0 << 8) | (s1 << 16) | (s2 << 24));
8012 *pOut++ = sample32;
8013 }
8014}
8015
8016DRWAV_API void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t sampleCount)
8017{
8018 size_t i;
8019
8020 if (pOut == NULL || pIn == NULL) {
8021 return;
8022 }
8023
8024 for (i = 0; i < sampleCount; ++i) {
8025 *pOut++ = (drwav_int32)(2147483648.0f * pIn[i]);
8026 }
8027}
8028
8029DRWAV_API void drwav_f64_to_s32(drwav_int32* pOut, const double* pIn, size_t sampleCount)
8030{
8031 size_t i;
8032
8033 if (pOut == NULL || pIn == NULL) {
8034 return;
8035 }
8036
8037 for (i = 0; i < sampleCount; ++i) {
8038 *pOut++ = (drwav_int32)(2147483648.0 * pIn[i]);
8039 }
8040}
8041
8042DRWAV_API void drwav_alaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
8043{
8044 size_t i;
8045
8046 if (pOut == NULL || pIn == NULL) {
8047 return;
8048 }
8049
8050 for (i = 0; i < sampleCount; ++i) {
8051 *pOut++ = ((drwav_int32)drwav__alaw_to_s16(pIn[i])) << 16;
8052 }
8053}
8054
8055DRWAV_API void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
8056{
8057 size_t i;
8058
8059 if (pOut == NULL || pIn == NULL) {
8060 return;
8061 }
8062
8063 for (i= 0; i < sampleCount; ++i) {
8064 *pOut++ = ((drwav_int32)drwav__mulaw_to_s16(pIn[i])) << 16;
8065 }
8066}
8067
8068
8069
8070DRWAV_PRIVATE drwav_int16* drwav__read_pcm_frames_and_close_s16(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount)
8071{
8072 drwav_uint64 sampleDataSize;
8073 drwav_int16* pSampleData;
8074 drwav_uint64 framesRead;
8075
8076 DRWAV_ASSERT(pWav != NULL);
8077
8078 /* Check for overflow before multiplication. */
8079 if (pWav->channels == 0 || pWav->totalPCMFrameCount > DRWAV_SIZE_MAX / pWav->channels / sizeof(drwav_int16)) {
8080 drwav_uninit(pWav);
8081 return NULL; /* Overflow or invalid channels. */
8082 }
8083
8084 sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(drwav_int16);
8085 if (sampleDataSize > DRWAV_SIZE_MAX) {
8086 drwav_uninit(pWav);
8087 return NULL; /* File's too big. */
8088 }
8089
8090 pSampleData = (drwav_int16*)drwav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks); /* <-- Safe cast due to the check above. */
8091 if (pSampleData == NULL) {
8092 drwav_uninit(pWav);
8093 return NULL; /* Failed to allocate memory. */
8094 }
8095
8096 framesRead = drwav_read_pcm_frames_s16(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
8097 if (framesRead != pWav->totalPCMFrameCount) {
8098 drwav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
8099 drwav_uninit(pWav);
8100 return NULL; /* There was an error reading the samples. */
8101 }
8102
8103 drwav_uninit(pWav);
8104
8105 if (sampleRate) {
8106 *sampleRate = pWav->sampleRate;
8107 }
8108 if (channels) {
8109 *channels = pWav->channels;
8110 }
8111 if (totalFrameCount) {
8112 *totalFrameCount = pWav->totalPCMFrameCount;
8113 }
8114
8115 return pSampleData;
8116}
8117
8118DRWAV_PRIVATE float* drwav__read_pcm_frames_and_close_f32(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount)
8119{
8120 drwav_uint64 sampleDataSize;
8121 float* pSampleData;
8122 drwav_uint64 framesRead;
8123
8124 DRWAV_ASSERT(pWav != NULL);
8125
8126 /* Check for overflow before multiplication. */
8127 if (pWav->channels == 0 || pWav->totalPCMFrameCount > DRWAV_SIZE_MAX / pWav->channels / sizeof(float)) {
8128 drwav_uninit(pWav);
8129 return NULL; /* Overflow or invalid channels. */
8130 }
8131
8132 sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(float);
8133 if (sampleDataSize > DRWAV_SIZE_MAX) {
8134 drwav_uninit(pWav);
8135 return NULL; /* File's too big. */
8136 }
8137
8138 pSampleData = (float*)drwav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks); /* <-- Safe cast due to the check above. */
8139 if (pSampleData == NULL) {
8140 drwav_uninit(pWav);
8141 return NULL; /* Failed to allocate memory. */
8142 }
8143
8144 framesRead = drwav_read_pcm_frames_f32(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
8145 if (framesRead != pWav->totalPCMFrameCount) {
8146 drwav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
8147 drwav_uninit(pWav);
8148 return NULL; /* There was an error reading the samples. */
8149 }
8150
8151 drwav_uninit(pWav);
8152
8153 if (sampleRate) {
8154 *sampleRate = pWav->sampleRate;
8155 }
8156 if (channels) {
8157 *channels = pWav->channels;
8158 }
8159 if (totalFrameCount) {
8160 *totalFrameCount = pWav->totalPCMFrameCount;
8161 }
8162
8163 return pSampleData;
8164}
8165
8166DRWAV_PRIVATE drwav_int32* drwav__read_pcm_frames_and_close_s32(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount)
8167{
8168 drwav_uint64 sampleDataSize;
8169 drwav_int32* pSampleData;
8170 drwav_uint64 framesRead;
8171
8172 DRWAV_ASSERT(pWav != NULL);
8173
8174 /* Check for overflow before multiplication. */
8175 if (pWav->channels == 0 || pWav->totalPCMFrameCount > DRWAV_SIZE_MAX / pWav->channels / sizeof(drwav_int32)) {
8176 drwav_uninit(pWav);
8177 return NULL; /* Overflow or invalid channels. */
8178 }
8179
8180 sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(drwav_int32);
8181 if (sampleDataSize > DRWAV_SIZE_MAX) {
8182 drwav_uninit(pWav);
8183 return NULL; /* File's too big. */
8184 }
8185
8186 pSampleData = (drwav_int32*)drwav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks); /* <-- Safe cast due to the check above. */
8187 if (pSampleData == NULL) {
8188 drwav_uninit(pWav);
8189 return NULL; /* Failed to allocate memory. */
8190 }
8191
8192 framesRead = drwav_read_pcm_frames_s32(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
8193 if (framesRead != pWav->totalPCMFrameCount) {
8194 drwav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
8195 drwav_uninit(pWav);
8196 return NULL; /* There was an error reading the samples. */
8197 }
8198
8199 drwav_uninit(pWav);
8200
8201 if (sampleRate) {
8202 *sampleRate = pWav->sampleRate;
8203 }
8204 if (channels) {
8205 *channels = pWav->channels;
8206 }
8207 if (totalFrameCount) {
8208 *totalFrameCount = pWav->totalPCMFrameCount;
8209 }
8210
8211 return pSampleData;
8212}
8213
8214
8215
8216DRWAV_API drwav_int16* drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
8217{
8218 drwav wav;
8219
8220 if (channelsOut) {
8221 *channelsOut = 0;
8222 }
8223 if (sampleRateOut) {
8224 *sampleRateOut = 0;
8225 }
8226 if (totalFrameCountOut) {
8227 *totalFrameCountOut = 0;
8228 }
8229
8230 if (!drwav_init(&wav, onRead, onSeek, onTell, pUserData, pAllocationCallbacks)) {
8231 return NULL;
8232 }
8233
8234 return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
8235}
8236
8237DRWAV_API float* drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
8238{
8239 drwav wav;
8240
8241 if (channelsOut) {
8242 *channelsOut = 0;
8243 }
8244 if (sampleRateOut) {
8245 *sampleRateOut = 0;
8246 }
8247 if (totalFrameCountOut) {
8248 *totalFrameCountOut = 0;
8249 }
8250
8251 if (!drwav_init(&wav, onRead, onSeek, onTell, pUserData, pAllocationCallbacks)) {
8252 return NULL;
8253 }
8254
8255 return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
8256}
8257
8258DRWAV_API drwav_int32* drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
8259{
8260 drwav wav;
8261
8262 if (channelsOut) {
8263 *channelsOut = 0;
8264 }
8265 if (sampleRateOut) {
8266 *sampleRateOut = 0;
8267 }
8268 if (totalFrameCountOut) {
8269 *totalFrameCountOut = 0;
8270 }
8271
8272 if (!drwav_init(&wav, onRead, onSeek, onTell, pUserData, pAllocationCallbacks)) {
8273 return NULL;
8274 }
8275
8276 return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
8277}
8278
8279#ifndef DR_WAV_NO_STDIO
8280DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
8281{
8282 drwav wav;
8283
8284 if (channelsOut) {
8285 *channelsOut = 0;
8286 }
8287 if (sampleRateOut) {
8288 *sampleRateOut = 0;
8289 }
8290 if (totalFrameCountOut) {
8291 *totalFrameCountOut = 0;
8292 }
8293
8294 if (!drwav_init_file(&wav, filename, pAllocationCallbacks)) {
8295 return NULL;
8296 }
8297
8298 return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
8299}
8300
8301DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
8302{
8303 drwav wav;
8304
8305 if (channelsOut) {
8306 *channelsOut = 0;
8307 }
8308 if (sampleRateOut) {
8309 *sampleRateOut = 0;
8310 }
8311 if (totalFrameCountOut) {
8312 *totalFrameCountOut = 0;
8313 }
8314
8315 if (!drwav_init_file(&wav, filename, pAllocationCallbacks)) {
8316 return NULL;
8317 }
8318
8319 return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
8320}
8321
8322DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
8323{
8324 drwav wav;
8325
8326 if (channelsOut) {
8327 *channelsOut = 0;
8328 }
8329 if (sampleRateOut) {
8330 *sampleRateOut = 0;
8331 }
8332 if (totalFrameCountOut) {
8333 *totalFrameCountOut = 0;
8334 }
8335
8336 if (!drwav_init_file(&wav, filename, pAllocationCallbacks)) {
8337 return NULL;
8338 }
8339
8340 return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
8341}
8342
8343
8344#ifndef DR_WAV_NO_WCHAR
8345DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
8346{
8347 drwav wav;
8348
8349 if (sampleRateOut) {
8350 *sampleRateOut = 0;
8351 }
8352 if (channelsOut) {
8353 *channelsOut = 0;
8354 }
8355 if (totalFrameCountOut) {
8356 *totalFrameCountOut = 0;
8357 }
8358
8359 if (!drwav_init_file_w(&wav, filename, pAllocationCallbacks)) {
8360 return NULL;
8361 }
8362
8363 return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
8364}
8365
8366DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
8367{
8368 drwav wav;
8369
8370 if (sampleRateOut) {
8371 *sampleRateOut = 0;
8372 }
8373 if (channelsOut) {
8374 *channelsOut = 0;
8375 }
8376 if (totalFrameCountOut) {
8377 *totalFrameCountOut = 0;
8378 }
8379
8380 if (!drwav_init_file_w(&wav, filename, pAllocationCallbacks)) {
8381 return NULL;
8382 }
8383
8384 return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
8385}
8386
8387DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
8388{
8389 drwav wav;
8390
8391 if (sampleRateOut) {
8392 *sampleRateOut = 0;
8393 }
8394 if (channelsOut) {
8395 *channelsOut = 0;
8396 }
8397 if (totalFrameCountOut) {
8398 *totalFrameCountOut = 0;
8399 }
8400
8401 if (!drwav_init_file_w(&wav, filename, pAllocationCallbacks)) {
8402 return NULL;
8403 }
8404
8405 return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
8406}
8407#endif /* DR_WAV_NO_WCHAR */
8408#endif /* DR_WAV_NO_STDIO */
8409
8410DRWAV_API 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, const drwav_allocation_callbacks* pAllocationCallbacks)
8411{
8412 drwav wav;
8413
8414 if (channelsOut) {
8415 *channelsOut = 0;
8416 }
8417 if (sampleRateOut) {
8418 *sampleRateOut = 0;
8419 }
8420 if (totalFrameCountOut) {
8421 *totalFrameCountOut = 0;
8422 }
8423
8424 if (!drwav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
8425 return NULL;
8426 }
8427
8428 return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
8429}
8430
8431DRWAV_API float* drwav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
8432{
8433 drwav wav;
8434
8435 if (channelsOut) {
8436 *channelsOut = 0;
8437 }
8438 if (sampleRateOut) {
8439 *sampleRateOut = 0;
8440 }
8441 if (totalFrameCountOut) {
8442 *totalFrameCountOut = 0;
8443 }
8444
8445 if (!drwav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
8446 return NULL;
8447 }
8448
8449 return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
8450}
8451
8452DRWAV_API 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, const drwav_allocation_callbacks* pAllocationCallbacks)
8453{
8454 drwav wav;
8455
8456 if (channelsOut) {
8457 *channelsOut = 0;
8458 }
8459 if (sampleRateOut) {
8460 *sampleRateOut = 0;
8461 }
8462 if (totalFrameCountOut) {
8463 *totalFrameCountOut = 0;
8464 }
8465
8466 if (!drwav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
8467 return NULL;
8468 }
8469
8470 return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
8471}
8472#endif /* DR_WAV_NO_CONVERSION_API */
8473
8474
8475DRWAV_API void drwav_free(void* p, const drwav_allocation_callbacks* pAllocationCallbacks)
8476{
8477 if (pAllocationCallbacks != NULL) {
8478 drwav__free_from_callbacks(p, pAllocationCallbacks);
8479 } else {
8480 drwav__free_default(p, NULL);
8481 }
8482}
8483
8485{
8486 return ((drwav_uint16)data[0] << 0) | ((drwav_uint16)data[1] << 8);
8487}
8488
8490{
8491 return (drwav_int16)drwav_bytes_to_u16(data);
8492}
8493
8495{
8496 return drwav_bytes_to_u32_le(data);
8497}
8498
8499DRWAV_API float drwav_bytes_to_f32(const drwav_uint8* data)
8500{
8501 union {
8502 drwav_uint32 u32;
8503 float f32;
8504 } value;
8505
8506 value.u32 = drwav_bytes_to_u32(data);
8507 return value.f32;
8508}
8509
8511{
8512 return (drwav_int32)drwav_bytes_to_u32(data);
8513}
8514
8516{
8517 return
8518 ((drwav_uint64)data[0] << 0) | ((drwav_uint64)data[1] << 8) | ((drwav_uint64)data[2] << 16) | ((drwav_uint64)data[3] << 24) |
8519 ((drwav_uint64)data[4] << 32) | ((drwav_uint64)data[5] << 40) | ((drwav_uint64)data[6] << 48) | ((drwav_uint64)data[7] << 56);
8520}
8521
8523{
8524 return (drwav_int64)drwav_bytes_to_u64(data);
8525}
8526
8527
8529{
8530 int i;
8531 for (i = 0; i < 16; i += 1) {
8532 if (a[i] != b[i]) {
8533 return DRWAV_FALSE;
8534 }
8535 }
8536
8537 return DRWAV_TRUE;
8538}
8539
8541{
8542 return
8543 a[0] == b[0] &&
8544 a[1] == b[1] &&
8545 a[2] == b[2] &&
8546 a[3] == b[3];
8547}
8548
8549#ifdef __MRC__
8550/* Undo the pragma at the beginning of this file. */
8551#pragma options opt reset
8552#endif
8553
8554#endif /* dr_wav_c */
8555#endif /* DR_WAV_IMPLEMENTATION */
8556
8557/*
8558REVISION HISTORY
8559================
8560v0.14.5 - 2026-03-03
8561 - Fix a crash when loading files with a malformed "smpl" chunk.
8562 - Fix a signed overflow bug with the MS-ADPCM decoder.
8563
8564v0.14.4 - 2026-01-17
8565 - Fix some compilation warnings.
8566
8567v0.14.3 - 2025-12-14
8568 - Fix a possible out-of-bounds read when reading from MS-ADPCM encoded files.
8569 - Fix a possible integer overflow error.
8570
8571v0.14.2 - 2025-12-02
8572 - Fix a compilation warning.
8573
8574v0.14.1 - 2025-09-10
8575 - Fix an error with the NXDK build.
8576
8577v0.14.0 - 2025-07-23
8578 - API CHANGE: Seek origin enums have been renamed to the following:
8579 - drwav_seek_origin_start -> DRWAV_SEEK_SET
8580 - drwav_seek_origin_current -> DRWAV_SEEK_CUR
8581 - DRWAV_SEEK_END (new)
8582 - API CHANGE: A new seek origin has been added to allow seeking from the end of the file. If you implement your own `onSeek` callback, you must now handle `DRWAV_SEEK_END`. If you only use `*_init_file()` or `*_init_memory()`, you need not change anything.
8583 - API CHANGE: An `onTell` callback has been added to the following functions:
8584 - drwav_init()
8585 - drwav_init_ex()
8586 - drwav_init_with_metadata()
8587 - drwav_open_and_read_pcm_frames_s16()
8588 - drwav_open_and_read_pcm_frames_f32()
8589 - drwav_open_and_read_pcm_frames_s32()
8590 - API CHANGE: The `firstSampleByteOffset`, `lastSampleByteOffset` and `sampleByteOffset` members of `drwav_cue_point` have been renamed to `firstSampleOffset`, `lastSampleOffset` and `sampleOffset`, respectively.
8591 - Fix a static analysis warning.
8592 - Fix compilation for AIX OS.
8593
8594v0.13.17 - 2024-12-17
8595 - Fix a possible crash when reading from MS-ADPCM encoded files.
8596 - Improve detection of ARM64EC
8597
8598v0.13.16 - 2024-02-27
8599 - Fix a Wdouble-promotion warning.
8600
8601v0.13.15 - 2024-01-23
8602 - Relax some unnecessary validation that prevented some files from loading.
8603
8604v0.13.14 - 2023-12-02
8605 - Fix a warning about an unused variable.
8606
8607v0.13.13 - 2023-11-02
8608 - Fix a warning when compiling with Clang.
8609
8610v0.13.12 - 2023-08-07
8611 - Fix a possible crash in drwav_read_pcm_frames().
8612
8613v0.13.11 - 2023-07-07
8614 - AIFF compatibility improvements.
8615
8616v0.13.10 - 2023-05-29
8617 - Fix a bug where drwav_init_with_metadata() does not decode any frames after initializtion.
8618
8619v0.13.9 - 2023-05-22
8620 - Add support for AIFF decoding (writing and metadata not supported).
8621 - Add support for RIFX decoding (writing and metadata not supported).
8622 - Fix a bug where metadata is not processed if it's located before the "fmt " chunk.
8623 - Add a workaround for a type of malformed WAV file where the size of the "RIFF" and "data" chunks
8624 are incorrectly set to 0xFFFFFFFF.
8625
8626v0.13.8 - 2023-03-25
8627 - Fix a possible null pointer dereference.
8628 - Fix a crash when loading files with badly formed metadata.
8629
8630v0.13.7 - 2022-09-17
8631 - Fix compilation with DJGPP.
8632 - Add support for disabling wchar_t with DR_WAV_NO_WCHAR.
8633
8634v0.13.6 - 2022-04-10
8635 - Fix compilation error on older versions of GCC.
8636 - Remove some dependencies on the standard library.
8637
8638v0.13.5 - 2022-01-26
8639 - Fix an error when seeking to the end of the file.
8640
8641v0.13.4 - 2021-12-08
8642 - Fix some static analysis warnings.
8643
8644v0.13.3 - 2021-11-24
8645 - Fix an incorrect assertion when trying to endian swap 1-byte sample formats. This is now a no-op
8646 rather than a failed assertion.
8647 - Fix a bug with parsing of the bext chunk.
8648 - Fix some static analysis warnings.
8649
8650v0.13.2 - 2021-10-02
8651 - Fix a possible buffer overflow when reading from compressed formats.
8652
8653v0.13.1 - 2021-07-31
8654 - Fix platform detection for ARM64.
8655
8656v0.13.0 - 2021-07-01
8657 - Improve support for reading and writing metadata. Use the `_with_metadata()` APIs to initialize
8658 a WAV decoder and store the metadata within the `drwav` object. Use the `pMetadata` and
8659 `metadataCount` members of the `drwav` object to read the data. The old way of handling metadata
8660 via a callback is still usable and valid.
8661 - API CHANGE: drwav_target_write_size_bytes() now takes extra parameters for calculating the
8662 required write size when writing metadata.
8663 - Add drwav_get_cursor_in_pcm_frames()
8664 - Add drwav_get_length_in_pcm_frames()
8665 - Fix a bug where drwav_read_raw() can call the read callback with a byte count of zero.
8666
8667v0.12.20 - 2021-06-11
8668 - Fix some undefined behavior.
8669
8670v0.12.19 - 2021-02-21
8671 - Fix a warning due to referencing _MSC_VER when it is undefined.
8672 - Minor improvements to the management of some internal state concerning the data chunk cursor.
8673
8674v0.12.18 - 2021-01-31
8675 - Clean up some static analysis warnings.
8676
8677v0.12.17 - 2021-01-17
8678 - Minor fix to sample code in documentation.
8679 - Correctly qualify a private API as private rather than public.
8680 - Code cleanup.
8681
8682v0.12.16 - 2020-12-02
8683 - Fix a bug when trying to read more bytes than can fit in a size_t.
8684
8685v0.12.15 - 2020-11-21
8686 - Fix compilation with OpenWatcom.
8687
8688v0.12.14 - 2020-11-13
8689 - Minor code clean up.
8690
8691v0.12.13 - 2020-11-01
8692 - Improve compiler support for older versions of GCC.
8693
8694v0.12.12 - 2020-09-28
8695 - Add support for RF64.
8696 - Fix a bug in writing mode where the size of the RIFF chunk incorrectly includes the header section.
8697
8698v0.12.11 - 2020-09-08
8699 - Fix a compilation error on older compilers.
8700
8701v0.12.10 - 2020-08-24
8702 - Fix a bug when seeking with ADPCM formats.
8703
8704v0.12.9 - 2020-08-02
8705 - Simplify sized types.
8706
8707v0.12.8 - 2020-07-25
8708 - Fix a compilation warning.
8709
8710v0.12.7 - 2020-07-15
8711 - Fix some bugs on big-endian architectures.
8712 - Fix an error in s24 to f32 conversion.
8713
8714v0.12.6 - 2020-06-23
8715 - Change drwav_read_*() to allow NULL to be passed in as the output buffer which is equivalent to a forward seek.
8716 - Fix a buffer overflow when trying to decode invalid IMA-ADPCM files.
8717 - Add include guard for the implementation section.
8718
8719v0.12.5 - 2020-05-27
8720 - Minor documentation fix.
8721
8722v0.12.4 - 2020-05-16
8723 - Replace assert() with DRWAV_ASSERT().
8724 - Add compile-time and run-time version querying.
8725 - DRWAV_VERSION_MINOR
8726 - DRWAV_VERSION_MAJOR
8727 - DRWAV_VERSION_REVISION
8728 - DRWAV_VERSION_STRING
8729 - drwav_version()
8730 - drwav_version_string()
8731
8732v0.12.3 - 2020-04-30
8733 - Fix compilation errors with VC6.
8734
8735v0.12.2 - 2020-04-21
8736 - Fix a bug where drwav_init_file() does not close the file handle after attempting to load an erroneous file.
8737
8738v0.12.1 - 2020-04-13
8739 - Fix some pedantic warnings.
8740
8741v0.12.0 - 2020-04-04
8742 - API CHANGE: Add container and format parameters to the chunk callback.
8743 - Minor documentation updates.
8744
8745v0.11.5 - 2020-03-07
8746 - Fix compilation error with Visual Studio .NET 2003.
8747
8748v0.11.4 - 2020-01-29
8749 - Fix some static analysis warnings.
8750 - Fix a bug when reading f32 samples from an A-law encoded stream.
8751
8752v0.11.3 - 2020-01-12
8753 - Minor changes to some f32 format conversion routines.
8754 - Minor bug fix for ADPCM conversion when end of file is reached.
8755
8756v0.11.2 - 2019-12-02
8757 - Fix a possible crash when using custom memory allocators without a custom realloc() implementation.
8758 - Fix an integer overflow bug.
8759 - Fix a null pointer dereference bug.
8760 - Add limits to sample rate, channels and bits per sample to tighten up some validation.
8761
8762v0.11.1 - 2019-10-07
8763 - Internal code clean up.
8764
8765v0.11.0 - 2019-10-06
8766 - API CHANGE: Add support for user defined memory allocation routines. This system allows the program to specify their own memory allocation
8767 routines with a user data pointer for client-specific contextual data. This adds an extra parameter to the end of the following APIs:
8768 - drwav_init()
8769 - drwav_init_ex()
8770 - drwav_init_file()
8771 - drwav_init_file_ex()
8772 - drwav_init_file_w()
8773 - drwav_init_file_w_ex()
8774 - drwav_init_memory()
8775 - drwav_init_memory_ex()
8776 - drwav_init_write()
8777 - drwav_init_write_sequential()
8778 - drwav_init_write_sequential_pcm_frames()
8779 - drwav_init_file_write()
8780 - drwav_init_file_write_sequential()
8781 - drwav_init_file_write_sequential_pcm_frames()
8782 - drwav_init_file_write_w()
8783 - drwav_init_file_write_sequential_w()
8784 - drwav_init_file_write_sequential_pcm_frames_w()
8785 - drwav_init_memory_write()
8786 - drwav_init_memory_write_sequential()
8787 - drwav_init_memory_write_sequential_pcm_frames()
8788 - drwav_open_and_read_pcm_frames_s16()
8789 - drwav_open_and_read_pcm_frames_f32()
8790 - drwav_open_and_read_pcm_frames_s32()
8791 - drwav_open_file_and_read_pcm_frames_s16()
8792 - drwav_open_file_and_read_pcm_frames_f32()
8793 - drwav_open_file_and_read_pcm_frames_s32()
8794 - drwav_open_file_and_read_pcm_frames_s16_w()
8795 - drwav_open_file_and_read_pcm_frames_f32_w()
8796 - drwav_open_file_and_read_pcm_frames_s32_w()
8797 - drwav_open_memory_and_read_pcm_frames_s16()
8798 - drwav_open_memory_and_read_pcm_frames_f32()
8799 - drwav_open_memory_and_read_pcm_frames_s32()
8800 Set this extra parameter to NULL to use defaults which is the same as the previous behaviour. Setting this NULL will use
8801 DRWAV_MALLOC, DRWAV_REALLOC and DRWAV_FREE.
8802 - Add support for reading and writing PCM frames in an explicit endianness. New APIs:
8803 - drwav_read_pcm_frames_le()
8804 - drwav_read_pcm_frames_be()
8805 - drwav_read_pcm_frames_s16le()
8806 - drwav_read_pcm_frames_s16be()
8807 - drwav_read_pcm_frames_f32le()
8808 - drwav_read_pcm_frames_f32be()
8809 - drwav_read_pcm_frames_s32le()
8810 - drwav_read_pcm_frames_s32be()
8811 - drwav_write_pcm_frames_le()
8812 - drwav_write_pcm_frames_be()
8813 - Remove deprecated APIs.
8814 - API CHANGE: The following APIs now return native-endian data. Previously they returned little-endian data.
8815 - drwav_read_pcm_frames()
8816 - drwav_read_pcm_frames_s16()
8817 - drwav_read_pcm_frames_s32()
8818 - drwav_read_pcm_frames_f32()
8819 - drwav_open_and_read_pcm_frames_s16()
8820 - drwav_open_and_read_pcm_frames_s32()
8821 - drwav_open_and_read_pcm_frames_f32()
8822 - drwav_open_file_and_read_pcm_frames_s16()
8823 - drwav_open_file_and_read_pcm_frames_s32()
8824 - drwav_open_file_and_read_pcm_frames_f32()
8825 - drwav_open_file_and_read_pcm_frames_s16_w()
8826 - drwav_open_file_and_read_pcm_frames_s32_w()
8827 - drwav_open_file_and_read_pcm_frames_f32_w()
8828 - drwav_open_memory_and_read_pcm_frames_s16()
8829 - drwav_open_memory_and_read_pcm_frames_s32()
8830 - drwav_open_memory_and_read_pcm_frames_f32()
8831
8832v0.10.1 - 2019-08-31
8833 - Correctly handle partial trailing ADPCM blocks.
8834
8835v0.10.0 - 2019-08-04
8836 - Remove deprecated APIs.
8837 - Add wchar_t variants for file loading APIs:
8838 drwav_init_file_w()
8839 drwav_init_file_ex_w()
8840 drwav_init_file_write_w()
8841 drwav_init_file_write_sequential_w()
8842 - Add drwav_target_write_size_bytes() which calculates the total size in bytes of a WAV file given a format and sample count.
8843 - Add APIs for specifying the PCM frame count instead of the sample count when opening in sequential write mode:
8844 drwav_init_write_sequential_pcm_frames()
8845 drwav_init_file_write_sequential_pcm_frames()
8846 drwav_init_file_write_sequential_pcm_frames_w()
8847 drwav_init_memory_write_sequential_pcm_frames()
8848 - Deprecate drwav_open*() and drwav_close():
8849 drwav_open()
8850 drwav_open_ex()
8851 drwav_open_write()
8852 drwav_open_write_sequential()
8853 drwav_open_file()
8854 drwav_open_file_ex()
8855 drwav_open_file_write()
8856 drwav_open_file_write_sequential()
8857 drwav_open_memory()
8858 drwav_open_memory_ex()
8859 drwav_open_memory_write()
8860 drwav_open_memory_write_sequential()
8861 drwav_close()
8862 - Minor documentation updates.
8863
8864v0.9.2 - 2019-05-21
8865 - Fix warnings.
8866
8867v0.9.1 - 2019-05-05
8868 - Add support for C89.
8869 - Change license to choice of public domain or MIT-0.
8870
8871v0.9.0 - 2018-12-16
8872 - API CHANGE: Add new reading APIs for reading by PCM frames instead of samples. Old APIs have been deprecated and
8873 will be removed in v0.10.0. Deprecated APIs and their replacements:
8874 drwav_read() -> drwav_read_pcm_frames()
8875 drwav_read_s16() -> drwav_read_pcm_frames_s16()
8876 drwav_read_f32() -> drwav_read_pcm_frames_f32()
8877 drwav_read_s32() -> drwav_read_pcm_frames_s32()
8878 drwav_seek_to_sample() -> drwav_seek_to_pcm_frame()
8879 drwav_write() -> drwav_write_pcm_frames()
8880 drwav_open_and_read_s16() -> drwav_open_and_read_pcm_frames_s16()
8881 drwav_open_and_read_f32() -> drwav_open_and_read_pcm_frames_f32()
8882 drwav_open_and_read_s32() -> drwav_open_and_read_pcm_frames_s32()
8883 drwav_open_file_and_read_s16() -> drwav_open_file_and_read_pcm_frames_s16()
8884 drwav_open_file_and_read_f32() -> drwav_open_file_and_read_pcm_frames_f32()
8885 drwav_open_file_and_read_s32() -> drwav_open_file_and_read_pcm_frames_s32()
8886 drwav_open_memory_and_read_s16() -> drwav_open_memory_and_read_pcm_frames_s16()
8887 drwav_open_memory_and_read_f32() -> drwav_open_memory_and_read_pcm_frames_f32()
8888 drwav_open_memory_and_read_s32() -> drwav_open_memory_and_read_pcm_frames_s32()
8889 drwav::totalSampleCount -> drwav::totalPCMFrameCount
8890 - API CHANGE: Rename drwav_open_and_read_file_*() to drwav_open_file_and_read_*().
8891 - API CHANGE: Rename drwav_open_and_read_memory_*() to drwav_open_memory_and_read_*().
8892 - Add built-in support for smpl chunks.
8893 - Add support for firing a callback for each chunk in the file at initialization time.
8894 - This is enabled through the drwav_init_ex(), etc. family of APIs.
8895 - Handle invalid FMT chunks more robustly.
8896
8897v0.8.5 - 2018-09-11
8898 - Const correctness.
8899 - Fix a potential stack overflow.
8900
8901v0.8.4 - 2018-08-07
8902 - Improve 64-bit detection.
8903
8904v0.8.3 - 2018-08-05
8905 - Fix C++ build on older versions of GCC.
8906
8907v0.8.2 - 2018-08-02
8908 - Fix some big-endian bugs.
8909
8910v0.8.1 - 2018-06-29
8911 - Add support for sequential writing APIs.
8912 - Disable seeking in write mode.
8913 - Fix bugs with Wave64.
8914 - Fix typos.
8915
8916v0.8 - 2018-04-27
8917 - Bug fix.
8918 - Start using major.minor.revision versioning.
8919
8920v0.7f - 2018-02-05
8921 - Restrict ADPCM formats to a maximum of 2 channels.
8922
8923v0.7e - 2018-02-02
8924 - Fix a crash.
8925
8926v0.7d - 2018-02-01
8927 - Fix a crash.
8928
8929v0.7c - 2018-02-01
8930 - Set drwav.bytesPerSample to 0 for all compressed formats.
8931 - Fix a crash when reading 16-bit floating point WAV files. In this case dr_wav will output silence for
8932 all format conversion reading APIs (*_s16, *_s32, *_f32 APIs).
8933 - Fix some divide-by-zero errors.
8934
8935v0.7b - 2018-01-22
8936 - Fix errors with seeking of compressed formats.
8937 - Fix compilation error when DR_WAV_NO_CONVERSION_API
8938
8939v0.7a - 2017-11-17
8940 - Fix some GCC warnings.
8941
8942v0.7 - 2017-11-04
8943 - Add writing APIs.
8944
8945v0.6 - 2017-08-16
8946 - API CHANGE: Rename dr_* types to drwav_*.
8947 - Add support for custom implementations of malloc(), realloc(), etc.
8948 - Add support for Microsoft ADPCM.
8949 - Add support for IMA ADPCM (DVI, format code 0x11).
8950 - Optimizations to drwav_read_s16().
8951 - Bug fixes.
8952
8953v0.5g - 2017-07-16
8954 - Change underlying type for booleans to unsigned.
8955
8956v0.5f - 2017-04-04
8957 - Fix a minor bug with drwav_open_and_read_s16() and family.
8958
8959v0.5e - 2016-12-29
8960 - Added support for reading samples as signed 16-bit integers. Use the _s16() family of APIs for this.
8961 - Minor fixes to documentation.
8962
8963v0.5d - 2016-12-28
8964 - Use drwav_int* and drwav_uint* sized types to improve compiler support.
8965
8966v0.5c - 2016-11-11
8967 - Properly handle JUNK chunks that come before the FMT chunk.
8968
8969v0.5b - 2016-10-23
8970 - A minor change to drwav_bool8 and drwav_bool32 types.
8971
8972v0.5a - 2016-10-11
8973 - Fixed a bug with drwav_open_and_read() and family due to incorrect argument ordering.
8974 - Improve A-law and mu-law efficiency.
8975
8976v0.5 - 2016-09-29
8977 - API CHANGE. Swap the order of "channels" and "sampleRate" parameters in drwav_open_and_read*(). Rationale for this is to
8978 keep it consistent with dr_audio and dr_flac.
8979
8980v0.4b - 2016-09-18
8981 - Fixed a typo in documentation.
8982
8983v0.4a - 2016-09-18
8984 - Fixed a typo.
8985 - Change date format to ISO 8601 (YYYY-MM-DD)
8986
8987v0.4 - 2016-07-13
8988 - API CHANGE. Make onSeek consistent with dr_flac.
8989 - API CHANGE. Rename drwav_seek() to drwav_seek_to_sample() for clarity and consistency with dr_flac.
8990 - Added support for Sony Wave64.
8991
8992v0.3a - 2016-05-28
8993 - API CHANGE. Return drwav_bool32 instead of int in onSeek callback.
8994 - Fixed a memory leak.
8995
8996v0.3 - 2016-05-22
8997 - Lots of API changes for consistency.
8998
8999v0.2a - 2016-05-16
9000 - Fixed Linux/GCC build.
9001
9002v0.2 - 2016-05-11
9003 - Added support for reading data as signed 32-bit PCM for consistency with dr_flac.
9004
9005v0.1a - 2016-05-07
9006 - Fixed a bug in drwav_open_file() where the file handle would not be closed if the loader failed to initialize.
9007
9008v0.1 - 2016-05-04
9009 - Initial versioned release.
9010*/
9011
9012/*
9013This software is available as a choice of the following licenses. Choose
9014whichever you prefer.
9015
9016===============================================================================
9017ALTERNATIVE 1 - Public Domain (www.unlicense.org)
9018===============================================================================
9019This is free and unencumbered software released into the public domain.
9020
9021Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
9022software, either in source code form or as a compiled binary, for any purpose,
9023commercial or non-commercial, and by any means.
9024
9025In jurisdictions that recognize copyright laws, the author or authors of this
9026software dedicate any and all copyright interest in the software to the public
9027domain. We make this dedication for the benefit of the public at large and to
9028the detriment of our heirs and successors. We intend this dedication to be an
9029overt act of relinquishment in perpetuity of all present and future rights to
9030this software under copyright law.
9031
9032THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
9033IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9034FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
9035AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
9036ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
9037WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
9038
9039For more information, please refer to <http://unlicense.org/>
9040
9041===============================================================================
9042ALTERNATIVE 2 - MIT No Attribution
9043===============================================================================
9044Copyright 2023 David Reid
9045
9046Permission is hereby granted, free of charge, to any person obtaining a copy of
9047this software and associated documentation files (the "Software"), to deal in
9048the Software without restriction, including without limitation the rights to
9049use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
9050of the Software, and to permit persons to whom the Software is furnished to do
9051so.
9052
9053THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
9054IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9055FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
9056AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
9057LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9058OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
9059SOFTWARE.
9060*/
size_t size_t
drwav_uint64 drwav_read_pcm_frames_s32be(drwav *pWav, drwav_uint64 framesToRead, drwav_int32 *pBufferOut)
#define DRWAV_BUSY
Definition dr_wav.h:243
void drwav_u8_to_s16(drwav_int16 *pOut, const drwav_uint8 *pIn, size_t sampleCount)
#define DRWAV_API
Definition dr_wav.h:216
drwav_uint8 drwav_bool8
Definition dr_wav.h:184
drwav_bool32 drwav_init_file_with_metadata_w(drwav *pWav, const wchar_t *filename, drwav_uint32 flags, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_metadata_location
Definition dr_wav.h:822
@ drwav_metadata_location_invalid
Definition dr_wav.h:823
@ drwav_metadata_location_inside_info_list
Definition dr_wav.h:825
@ drwav_metadata_location_inside_adtl_list
Definition dr_wav.h:826
@ drwav_metadata_location_top_level
Definition dr_wav.h:824
#define DRWAV_OUT_OF_RANGE
Definition dr_wav.h:229
#define DRWAV_FALSE
Definition dr_wav.h:187
#define DRWAV_TIMEOUT
Definition dr_wav.h:258
drwav_container
Definition dr_wav.h:314
@ drwav_container_w64
Definition dr_wav.h:317
@ drwav_container_aiff
Definition dr_wav.h:319
@ drwav_container_riff
Definition dr_wav.h:315
@ drwav_container_rf64
Definition dr_wav.h:318
@ drwav_container_rifx
Definition dr_wav.h:316
#define DRWAV_VERSION_MINOR
Definition dr_wav.h:149
#define DRWAV_TOO_BIG
Definition dr_wav.h:235
#define DRWAV_SOCKET_NOT_SUPPORTED
Definition dr_wav.h:268
#define DRWAV_ACCESS_DENIED
Definition dr_wav.h:230
drwav_int32 drwav_bytes_to_s32(const drwav_uint8 *data)
drwav_int16 drwav_bytes_to_s16(const drwav_uint8 *data)
drwav_bool32 drwav_init_write_sequential(drwav *pWav, const drwav_data_format *pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void *pUserData, const drwav_allocation_callbacks *pAllocationCallbacks)
const char * drwav_version_string(void)
drwav_uint64 drwav_read_pcm_frames_f32be(drwav *pWav, drwav_uint64 framesToRead, float *pBufferOut)
#define DRWAV_TOO_MANY_LINKS
Definition dr_wav.h:252
void drwav_s16_to_s32(drwav_int32 *pOut, const drwav_int16 *pIn, size_t sampleCount)
drwav_bool32(* drwav_tell_proc)(void *pUserData, drwav_int64 *pCursor)
Definition dr_wav.h:432
void drwav_alaw_to_s32(drwav_int32 *pOut, const drwav_uint8 *pIn, size_t sampleCount)
drwav_smpl_loop_type
Definition dr_wav.h:565
@ drwav_smpl_loop_type_backward
Definition dr_wav.h:568
@ drwav_smpl_loop_type_pingpong
Definition dr_wav.h:567
@ drwav_smpl_loop_type_forward
Definition dr_wav.h:566
#define DRWAV_SEQUENTIAL
Definition dr_wav.h:290
drwav_bool32 drwav_init_write_with_metadata(drwav *pWav, const drwav_data_format *pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void *pUserData, const drwav_allocation_callbacks *pAllocationCallbacks, drwav_metadata *pMetadata, drwav_uint32 metadataCount)
drwav_bool32 drwav_init_memory(drwav *pWav, const void *data, size_t dataSize, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_int32 drwav_result
Definition dr_wav.h:223
void drwav_f32_to_s32(drwav_int32 *pOut, const float *pIn, size_t sampleCount)
#define DRWAV_INVALID_DATA
Definition dr_wav.h:257
void drwav_s24_to_s16(drwav_int16 *pOut, const drwav_uint8 *pIn, size_t sampleCount)
drwav_bool32 drwav_init_memory_with_metadata(drwav *pWav, const void *data, size_t dataSize, drwav_uint32 flags, const drwav_allocation_callbacks *pAllocationCallbacks)
#define DRWAV_NO_ADDRESS
Definition dr_wav.h:262
void drwav_s24_to_s32(drwav_int32 *pOut, const drwav_uint8 *pIn, size_t sampleCount)
#define DRWAV_IO_ERROR
Definition dr_wav.h:244
#define DRWAV_UNAVAILABLE
Definition dr_wav.h:246
float * drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void *pUserData, unsigned int *channelsOut, unsigned int *sampleRateOut, drwav_uint64 *totalFrameCountOut, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_bool32 drwav_init_file_with_metadata(drwav *pWav, const char *filename, drwav_uint32 flags, const drwav_allocation_callbacks *pAllocationCallbacks)
void drwav_u8_to_f32(float *pOut, const drwav_uint8 *pIn, size_t sampleCount)
drwav_uint64 drwav_read_pcm_frames_s16be(drwav *pWav, drwav_uint64 framesToRead, drwav_int16 *pBufferOut)
drwav_bool32 drwav_init_memory_write_sequential_pcm_frames(drwav *pWav, void **ppData, size_t *pDataSize, const drwav_data_format *pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_uint16 drwav_fmt_get_format(const drwav_fmt *pFMT)
drwav_bool32(* drwav_seek_proc)(void *pUserData, int offset, drwav_seek_origin origin)
Definition dr_wav.h:422
drwav_uint64 drwav_read_pcm_frames(drwav *pWav, drwav_uint64 framesToRead, void *pBufferOut)
drwav_uint64 drwav_write_pcm_frames(drwav *pWav, drwav_uint64 framesToWrite, const void *pData)
#define DRWAV_ADDRESS_FAMILY_NOT_SUPPORTED
Definition dr_wav.h:267
#define DRWAV_ERROR
Definition dr_wav.h:225
drwav_bool32 drwav_init_memory_ex(drwav *pWav, const void *data, size_t dataSize, drwav_chunk_proc onChunk, void *pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_bool32 drwav_init_file_write_sequential(drwav *pWav, const char *filename, const drwav_data_format *pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_uint32 drwav_bool32
Definition dr_wav.h:185
#define DRWAV_NOT_DIRECTORY
Definition dr_wav.h:238
drwav_bool32 drwav_init_memory_write_sequential(drwav *pWav, void **ppData, size_t *pDataSize, const drwav_data_format *pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks *pAllocationCallbacks)
void drwav_mulaw_to_s16(drwav_int16 *pOut, const drwav_uint8 *pIn, size_t sampleCount)
void drwav_f32_to_s16(drwav_int16 *pOut, const float *pIn, size_t sampleCount)
#define DR_WAVE_FORMAT_DVI_ADPCM
Definition dr_wav.h:286
#define DRWAV_VERSION_STRING
Definition dr_wav.h:151
drwav_bool32 drwav_init_write(drwav *pWav, const drwav_data_format *pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void *pUserData, const drwav_allocation_callbacks *pAllocationCallbacks)
#define DRWAV_INVALID_ARGS
Definition dr_wav.h:226
#define DRWAV_PROTOCOL_UNAVAILABLE
Definition dr_wav.h:264
void drwav_alaw_to_s16(drwav_int16 *pOut, const drwav_uint8 *pIn, size_t sampleCount)
#define DR_WAVE_FORMAT_EXTENSIBLE
Definition dr_wav.h:287
drwav_uint32 drwav_uintptr
Definition dr_wav.h:182
drwav_uint64 drwav_read_pcm_frames_s16le(drwav *pWav, drwav_uint64 framesToRead, drwav_int16 *pBufferOut)
void drwav_f64_to_s32(drwav_int32 *pOut, const double *pIn, size_t sampleCount)
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, const drwav_allocation_callbacks *pAllocationCallbacks)
void drwav_f64_to_s16(drwav_int16 *pOut, const double *pIn, size_t sampleCount)
#define DRWAV_ALREADY_IN_USE
Definition dr_wav.h:247
#define DRWAV_PROTOCOL_FAMILY_NOT_SUPPORTED
Definition dr_wav.h:266
float * drwav_open_memory_and_read_pcm_frames_f32(const void *data, size_t dataSize, unsigned int *channelsOut, unsigned int *sampleRateOut, drwav_uint64 *totalFrameCountOut, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_bool32 drwav_init_file_write_sequential_pcm_frames_w(drwav *pWav, const wchar_t *filename, const drwav_data_format *pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_bool32 drwav_init_file_write_sequential_w(drwav *pWav, const wchar_t *filename, const drwav_data_format *pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_bool32 drwav_init_write_sequential_pcm_frames(drwav *pWav, const drwav_data_format *pFormat, drwav_uint64 totalPCMFrameCount, drwav_write_proc onWrite, void *pUserData, const drwav_allocation_callbacks *pAllocationCallbacks)
#define DR_WAVE_FORMAT_MULAW
Definition dr_wav.h:285
#define DRWAV_PRIVATE
Definition dr_wav.h:217
drwav_bool32 drwav_fourcc_equal(const drwav_uint8 *a, const char *b)
#define DRWAV_OUT_OF_MEMORY
Definition dr_wav.h:228
signed int drwav_int32
Definition dr_wav.h:160
drwav_uint64(* drwav_chunk_proc)(void *pChunkUserData, drwav_read_proc onRead, drwav_seek_proc onSeek, void *pReadSeekUserData, const drwav_chunk_header *pChunkHeader, drwav_container container, const drwav_fmt *pFMT)
Definition dr_wav.h:458
drwav_bool32 drwav_init_ex(drwav *pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, drwav_chunk_proc onChunk, void *pReadSeekTellUserData, void *pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_uint64 drwav_write_pcm_frames_le(drwav *pWav, drwav_uint64 framesToWrite, const void *pData)
size_t drwav_write_raw(drwav *pWav, size_t bytesToWrite, const void *pData)
drwav_result drwav_get_length_in_pcm_frames(drwav *pWav, drwav_uint64 *pLength)
drwav_bool32 drwav_init_file(drwav *pWav, const char *filename, const drwav_allocation_callbacks *pAllocationCallbacks)
#define DRWAV_NO_NETWORK
Definition dr_wav.h:259
#define DRWAV_BAD_MESSAGE
Definition dr_wav.h:255
#define DRWAV_PATH_TOO_LONG
Definition dr_wav.h:236
drwav_uint64 drwav_read_pcm_frames_s16(drwav *pWav, drwav_uint64 framesToRead, drwav_int16 *pBufferOut)
#define DRWAV_NOT_SOCKET
Definition dr_wav.h:261
void drwav_f64_to_f32(float *pOut, const double *pIn, size_t sampleCount)
signed short drwav_int16
Definition dr_wav.h:158
float drwav_bytes_to_f32(const drwav_uint8 *data)
drwav_bool32 drwav_seek_to_pcm_frame(drwav *pWav, drwav_uint64 targetFrameIndex)
#define DRWAV_NO_SPACE
Definition dr_wav.h:242
void drwav_s24_to_f32(float *pOut, const drwav_uint8 *pIn, size_t sampleCount)
drwav_uint64 drwav_bytes_to_u64(const drwav_uint8 *data)
drwav_int16 * drwav_open_file_and_read_pcm_frames_s16(const char *filename, unsigned int *channelsOut, unsigned int *sampleRateOut, drwav_uint64 *totalFrameCountOut, const drwav_allocation_callbacks *pAllocationCallbacks)
#define DR_WAVE_FORMAT_PCM
Definition dr_wav.h:281
#define DRWAV_NO_DATA_AVAILABLE
Definition dr_wav.h:256
drwav_bool32 drwav_init_file_write_w(drwav *pWav, const wchar_t *filename, const drwav_data_format *pFormat, const drwav_allocation_callbacks *pAllocationCallbacks)
unsigned int drwav_uint32
Definition dr_wav.h:161
drwav_uint64 drwav_read_pcm_frames_be(drwav *pWav, drwav_uint64 framesToRead, void *pBufferOut)
void drwav_mulaw_to_s32(drwav_int32 *pOut, const drwav_uint8 *pIn, size_t sampleCount)
drwav_bool32 drwav_init_file_w(drwav *pWav, const wchar_t *filename, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_bool32 drwav_init_file_write(drwav *pWav, const char *filename, const drwav_data_format *pFormat, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_int16 * drwav_open_file_and_read_pcm_frames_s16_w(const wchar_t *filename, unsigned int *channelsOut, unsigned int *sampleRateOut, drwav_uint64 *totalFrameCountOut, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_uint32 drwav_bytes_to_u32(const drwav_uint8 *data)
#define DRWAV_INVALID_FILE
Definition dr_wav.h:234
drwav_int32 * drwav_open_file_and_read_pcm_frames_s32(const char *filename, unsigned int *channelsOut, unsigned int *sampleRateOut, drwav_uint64 *totalFrameCountOut, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_bool32 drwav_init_file_ex(drwav *pWav, const char *filename, drwav_chunk_proc onChunk, void *pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks *pAllocationCallbacks)
#define DRWAV_NOT_CONNECTED
Definition dr_wav.h:271
drwav_int32 * drwav_open_file_and_read_pcm_frames_s32_w(const wchar_t *filename, unsigned int *channelsOut, unsigned int *sampleRateOut, drwav_uint64 *totalFrameCountOut, const drwav_allocation_callbacks *pAllocationCallbacks)
#define DRWAV_BAD_PROTOCOL
Definition dr_wav.h:263
void drwav_mulaw_to_f32(float *pOut, const drwav_uint8 *pIn, size_t sampleCount)
#define DRWAV_DOES_NOT_EXIST
Definition dr_wav.h:231
#define DRWAV_IS_DIRECTORY
Definition dr_wav.h:239
#define DRWAV_BAD_ADDRESS
Definition dr_wav.h:248
#define DRWAV_BAD_SEEK
Definition dr_wav.h:249
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, const drwav_allocation_callbacks *pAllocationCallbacks)
#define DRWAV_CANCELLED
Definition dr_wav.h:275
drwav_bool32 drwav_init_with_metadata(drwav *pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void *pUserData, drwav_uint32 flags, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_seek_origin
Definition dr_wav.h:307
@ DRWAV_SEEK_CUR
Definition dr_wav.h:309
@ DRWAV_SEEK_END
Definition dr_wav.h:310
@ DRWAV_SEEK_SET
Definition dr_wav.h:308
#define DRWAV_ALREADY_EXISTS
Definition dr_wav.h:232
drwav_bool32 drwav_init(drwav *pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void *pUserData, const drwav_allocation_callbacks *pAllocationCallbacks)
#define DR_WAVE_FORMAT_ALAW
Definition dr_wav.h:284
drwav_result drwav_get_cursor_in_pcm_frames(drwav *pWav, drwav_uint64 *pCursor)
#define DRWAV_VERSION_MAJOR
Definition dr_wav.h:148
#define DRWAV_TRUE
Definition dr_wav.h:186
drwav_int64 drwav_bytes_to_s64(const drwav_uint8 *data)
#define DR_WAVE_FORMAT_ADPCM
Definition dr_wav.h:282
#define DRWAV_NOT_IMPLEMENTED
Definition dr_wav.h:253
void drwav_s32_to_f32(float *pOut, const drwav_int32 *pIn, size_t sampleCount)
#define DRWAV_SUCCESS
Definition dr_wav.h:224
drwav_bool32 drwav_init_file_write_sequential_pcm_frames(drwav *pWav, const char *filename, const drwav_data_format *pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks *pAllocationCallbacks)
signed char drwav_int8
Definition dr_wav.h:156
#define DRWAV_NO_MESSAGE
Definition dr_wav.h:254
drwav_int32 * drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void *pUserData, unsigned int *channelsOut, unsigned int *sampleRateOut, drwav_uint64 *totalFrameCountOut, const drwav_allocation_callbacks *pAllocationCallbacks)
float * drwav_open_file_and_read_pcm_frames_f32_w(const wchar_t *filename, unsigned int *channelsOut, unsigned int *sampleRateOut, drwav_uint64 *totalFrameCountOut, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_metadata * drwav_take_ownership_of_metadata(drwav *pWav)
drwav_bool32 drwav_guid_equal(const drwav_uint8 a[16], const drwav_uint8 b[16])
size_t(* drwav_write_proc)(void *pUserData, const void *pData, size_t bytesToWrite)
Definition dr_wav.h:408
#define DRWAV_BAD_PIPE
Definition dr_wav.h:250
#define DRWAV_CONNECTION_RESET
Definition dr_wav.h:269
#define DRWAV_ALREADY_CONNECTED
Definition dr_wav.h:270
drwav_uint16 drwav_bytes_to_u16(const drwav_uint8 *data)
void drwav_u8_to_s32(drwav_int32 *pOut, const drwav_uint8 *pIn, size_t sampleCount)
#define DRWAV_TOO_MANY_OPEN_FILES
Definition dr_wav.h:233
#define DRWAV_VERSION_REVISION
Definition dr_wav.h:150
#define DRWAV_NOT_UNIQUE
Definition dr_wav.h:260
signed long long drwav_int64
Definition dr_wav.h:173
void drwav_s32_to_s16(drwav_int16 *pOut, const drwav_int32 *pIn, size_t sampleCount)
#define DRWAV_PROTOCOL_NOT_SUPPORTED
Definition dr_wav.h:265
drwav_uint64 drwav_read_pcm_frames_f32le(drwav *pWav, drwav_uint64 framesToRead, float *pBufferOut)
drwav_int16 * drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_tell_proc onTell, void *pUserData, unsigned int *channelsOut, unsigned int *sampleRateOut, drwav_uint64 *totalFrameCountOut, const drwav_allocation_callbacks *pAllocationCallbacks)
unsigned long long drwav_uint64
Definition dr_wav.h:174
size_t drwav_read_raw(drwav *pWav, size_t bytesToRead, void *pBufferOut)
#define DRWAV_DIRECTORY_NOT_EMPTY
Definition dr_wav.h:240
#define DRWAV_CONNECTION_REFUSED
Definition dr_wav.h:272
drwav_bool32 drwav_init_memory_write(drwav *pWav, void **ppData, size_t *pDataSize, const drwav_data_format *pFormat, const drwav_allocation_callbacks *pAllocationCallbacks)
#define DRWAV_DEADLOCK
Definition dr_wav.h:251
drwav_uint64 drwav_read_pcm_frames_s32le(drwav *pWav, drwav_uint64 framesToRead, drwav_int32 *pBufferOut)
#define DR_WAVE_FORMAT_IEEE_FLOAT
Definition dr_wav.h:283
void drwav_alaw_to_f32(float *pOut, const drwav_uint8 *pIn, size_t sampleCount)
#define DRWAV_WITH_METADATA
Definition dr_wav.h:291
unsigned char drwav_uint8
Definition dr_wav.h:157
float * drwav_open_file_and_read_pcm_frames_f32(const char *filename, unsigned int *channelsOut, unsigned int *sampleRateOut, drwav_uint64 *totalFrameCountOut, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_uint64 drwav_target_write_size_bytes(const drwav_data_format *pFormat, drwav_uint64 totalFrameCount, drwav_metadata *pMetadata, drwav_uint32 metadataCount)
#define DRWAV_INTERRUPT
Definition dr_wav.h:245
void drwav_free(void *p, const drwav_allocation_callbacks *pAllocationCallbacks)
drwav_bool32 drwav_init_file_ex_w(drwav *pWav, const wchar_t *filename, drwav_chunk_proc onChunk, void *pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks *pAllocationCallbacks)
void drwav_s16_to_f32(float *pOut, const drwav_int16 *pIn, size_t sampleCount)
drwav_metadata_type
Definition dr_wav.h:489
@ drwav_metadata_type_list_all_adtl
Definition dr_wav.h:550
@ drwav_metadata_type_list_info_tracknumber
Definition dr_wav.h:527
@ drwav_metadata_type_list_all_info_strings
Definition dr_wav.h:535
@ drwav_metadata_type_none
Definition dr_wav.h:490
@ drwav_metadata_type_list_info_artist
Definition dr_wav.h:522
@ drwav_metadata_type_list_info_comment
Definition dr_wav.h:523
@ drwav_metadata_type_list_info_date
Definition dr_wav.h:524
@ drwav_metadata_type_bext
Definition dr_wav.h:506
@ drwav_metadata_type_list_info_genre
Definition dr_wav.h:525
@ drwav_metadata_type_list_info_album
Definition dr_wav.h:526
@ drwav_metadata_type_list_label
Definition dr_wav.h:515
@ drwav_metadata_type_list_info_organization
Definition dr_wav.h:529
@ drwav_metadata_type_list_info_description
Definition dr_wav.h:532
@ drwav_metadata_type_acid
Definition dr_wav.h:505
@ drwav_metadata_type_unknown
Definition dr_wav.h:499
@ drwav_metadata_type_list_info_software
Definition dr_wav.h:519
@ drwav_metadata_type_cue
Definition dr_wav.h:504
@ drwav_metadata_type_list_info_medium
Definition dr_wav.h:531
@ drwav_metadata_type_list_labelled_cue_region
Definition dr_wav.h:517
@ drwav_metadata_type_list_info_location
Definition dr_wav.h:528
@ drwav_metadata_type_smpl
Definition dr_wav.h:502
@ drwav_metadata_type_list_info_keywords
Definition dr_wav.h:530
@ drwav_metadata_type_list_info_title
Definition dr_wav.h:521
@ drwav_metadata_type_list_info_copyright
Definition dr_wav.h:520
@ drwav_metadata_type_all_including_unknown
Definition dr_wav.h:555
@ drwav_metadata_type_all
Definition dr_wav.h:554
@ drwav_metadata_type_inst
Definition dr_wav.h:503
@ drwav_metadata_type_list_note
Definition dr_wav.h:516
drwav_uint64 drwav_read_pcm_frames_f32(drwav *pWav, drwav_uint64 framesToRead, float *pBufferOut)
drwav_uint64 drwav_read_pcm_frames_s32(drwav *pWav, drwav_uint64 framesToRead, drwav_int32 *pBufferOut)
#define DRWAV_INVALID_OPERATION
Definition dr_wav.h:227
size_t(* drwav_read_proc)(void *pUserData, void *pBufferOut, size_t bytesToRead)
Definition dr_wav.h:395
drwav_uint64 drwav_write_pcm_frames_be(drwav *pWav, drwav_uint64 framesToWrite, const void *pData)
drwav_result drwav_uninit(drwav *pWav)
unsigned short drwav_uint16
Definition dr_wav.h:159
#define DRWAV_IN_PROGRESS
Definition dr_wav.h:274
#define DRWAV_NO_HOST
Definition dr_wav.h:273
void drwav_version(drwav_uint32 *pMajor, drwav_uint32 *pMinor, drwav_uint32 *pRevision)
drwav_acid_flag
Definition dr_wav.h:677
@ drwav_acid_flag_acidizer
Definition dr_wav.h:682
@ drwav_acid_flag_one_shot
Definition dr_wav.h:678
@ drwav_acid_flag_root_note_set
Definition dr_wav.h:679
@ drwav_acid_flag_stretch
Definition dr_wav.h:680
@ drwav_acid_flag_disk_based
Definition dr_wav.h:681
drwav_uint64 drwav_read_pcm_frames_le(drwav *pWav, drwav_uint64 framesToRead, void *pBufferOut)
#define DRWAV_AT_END
Definition dr_wav.h:277
double sign(const double &v)
Invert a symmetric and positive definite matrix using Cholesky decomposition (defined in Math....
Definition math.cpp:657
const drwav_uint8 * data
Definition dr_wav.h:464
size_t currentReadPos
Definition dr_wav.h:466
drwav_uint16 reserved1
Definition dr_wav.h:694
drwav_uint16 midiUnityNote
Definition dr_wav.h:691
drwav_uint32 flags
Definition dr_wav.h:688
float tempo
Definition dr_wav.h:705
drwav_uint32 numBeats
Definition dr_wav.h:698
drwav_uint16 meterNumerator
Definition dr_wav.h:702
float reserved2
Definition dr_wav.h:695
drwav_uint16 meterDenominator
Definition dr_wav.h:701
void *(* onRealloc)(void *p, size_t sz, void *pUserData)
Definition dr_wav.h:301
void(* onFree)(void *p, void *pUserData)
Definition dr_wav.h:302
void *(* onMalloc)(size_t sz, void *pUserData)
Definition dr_wav.h:300
drwav_uint16 version
Definition dr_wav.h:746
char * pOriginatorName
Definition dr_wav.h:741
char * pCodingHistory
Definition dr_wav.h:752
drwav_uint16 maxTruePeakLevel
Definition dr_wav.h:761
drwav_uint16 loudnessValue
Definition dr_wav.h:759
char pOriginationTime[8]
Definition dr_wav.h:744
char pOriginationDate[10]
Definition dr_wav.h:743
char * pOriginatorReference
Definition dr_wav.h:742
drwav_uint16 maxShortTermLoudness
Definition dr_wav.h:763
drwav_uint16 maxMomentaryLoudness
Definition dr_wav.h:762
char * pDescription
Definition dr_wav.h:740
drwav_uint32 codingHistorySize
Definition dr_wav.h:753
drwav_uint16 loudnessRange
Definition dr_wav.h:760
drwav_uint64 timeReference
Definition dr_wav.h:745
drwav_uint8 * pUMID
Definition dr_wav.h:756
drwav_uint8 fourcc[4]
Definition dr_wav.h:326
drwav_uint8 guid[16]
Definition dr_wav.h:327
drwav_uint64 sizeInBytes
Definition dr_wav.h:331
union drwav_chunk_header::@95 id
unsigned int paddingSize
Definition dr_wav.h:337
drwav_uint32 blockStart
Definition dr_wav.h:659
drwav_uint32 sampleOffset
Definition dr_wav.h:662
drwav_uint32 id
Definition dr_wav.h:647
drwav_uint8 dataChunkId[4]
Definition dr_wav.h:653
drwav_uint32 playOrderPosition
Definition dr_wav.h:650
drwav_uint32 chunkStart
Definition dr_wav.h:656
drwav_uint32 cuePointCount
Definition dr_wav.h:667
drwav_cue_point * pCuePoints
Definition dr_wav.h:668
drwav_uint32 bitsPerSample
Definition dr_wav.h:485
drwav_uint32 channels
Definition dr_wav.h:483
drwav_uint32 format
Definition dr_wav.h:482
drwav_container container
Definition dr_wav.h:481
drwav_uint32 sampleRate
Definition dr_wav.h:484
drwav_uint16 bitsPerSample
Definition dr_wav.h:361
drwav_uint16 formatTag
Definition dr_wav.h:346
drwav_uint32 avgBytesPerSec
Definition dr_wav.h:355
drwav_uint32 channelMask
Definition dr_wav.h:374
drwav_uint32 sampleRate
Definition dr_wav.h:352
drwav_uint16 blockAlign
Definition dr_wav.h:358
drwav_uint16 channels
Definition dr_wav.h:349
drwav_uint8 subFormat[16]
Definition dr_wav.h:377
drwav_uint16 validBitsPerSample
Definition dr_wav.h:371
drwav_uint16 extendedSize
Definition dr_wav.h:364
drwav_int8 highVelocity
Definition dr_wav.h:635
drwav_int8 lowNote
Definition dr_wav.h:632
drwav_int8 midiUnityNote
Definition dr_wav.h:629
drwav_int8 highNote
Definition dr_wav.h:633
drwav_int8 gainDecibels
Definition dr_wav.h:631
drwav_int8 lowVelocity
Definition dr_wav.h:634
drwav_int8 fineTuneCents
Definition dr_wav.h:630
drwav_uint32 stringLength
Definition dr_wav.h:776
drwav_uint32 stringLength
Definition dr_wav.h:721
drwav_uint32 cuePointId
Definition dr_wav.h:718
drwav_list_label_or_note labelOrNote
Definition dr_wav.h:852
drwav_bext bext
Definition dr_wav.h:851
drwav_smpl smpl
Definition dr_wav.h:848
drwav_acid acid
Definition dr_wav.h:849
drwav_metadata_type type
Definition dr_wav.h:843
union drwav_metadata::@96 data
drwav_list_info_text infoText
Definition dr_wav.h:854
drwav_unknown_metadata unknown
Definition dr_wav.h:855
drwav_inst inst
Definition dr_wav.h:850
drwav_cue cue
Definition dr_wav.h:847
drwav_list_labelled_cue_region labelledCueRegion
Definition dr_wav.h:853
drwav_uint32 sampleFraction
Definition dr_wav.h:586
drwav_uint32 cuePointId
Definition dr_wav.h:574
drwav_uint32 type
Definition dr_wav.h:577
drwav_uint32 playCount
Definition dr_wav.h:589
drwav_uint32 firstSampleOffset
Definition dr_wav.h:580
drwav_uint32 lastSampleOffset
Definition dr_wav.h:583
drwav_uint32 manufacturerId
Definition dr_wav.h:595
drwav_uint32 samplePeriodNanoseconds
Definition dr_wav.h:599
drwav_uint32 midiPitchFraction
Definition dr_wav.h:605
drwav_uint32 smpteOffset
Definition dr_wav.h:609
drwav_uint8 * pSamplerSpecificData
Definition dr_wav.h:618
drwav_uint32 smpteFormat
Definition dr_wav.h:608
drwav_uint32 sampleLoopCount
Definition dr_wav.h:612
drwav_uint32 samplerSpecificDataSizeInBytes
Definition dr_wav.h:615
drwav_uint32 productId
Definition dr_wav.h:596
drwav_smpl_loop * pLoops
Definition dr_wav.h:617
drwav_uint32 midiUnityNote
Definition dr_wav.h:602
drwav_uint8 id[4]
Definition dr_wav.h:831
drwav_metadata_location chunkLocation
Definition dr_wav.h:832
drwav_uint32 dataSizeInBytes
Definition dr_wav.h:833
drwav_uint8 * pData
Definition dr_wav.h:834
drwav_uint32 metadataCount
Definition dr_wav.h:928
struct drwav::@97 msadpcm
drwav_uint64 dataChunkDataSizeTargetWrite
Definition dr_wav.h:920
drwav_uint16 predictor[2]
Definition dr_wav.h:940
drwav_write_proc onWrite
Definition dr_wav.h:865
drwav_container container
Definition dr_wav.h:881
drwav_int32 prevFrames[2][2]
Definition dr_wav.h:944
drwav_uint64 readCursorInPCMFrames
Definition dr_wav.h:913
drwav_int32 cachedFrames[4]
Definition dr_wav.h:942
drwav_tell_proc onTell
Definition dr_wav.h:871
drwav_int32 stepIndex[2]
Definition dr_wav.h:952
struct drwav::@98 ima
drwav_uint16 channels
Definition dr_wav.h:891
drwav_int32 delta[2]
Definition dr_wav.h:941
drwav__memory_stream memoryStream
Definition dr_wav.h:932
drwav_allocation_callbacks allocationCallbacks
Definition dr_wav.h:877
drwav__memory_stream_write memoryStreamWrite
Definition dr_wav.h:933
drwav_bool32 isSequentialWrite
Definition dr_wav.h:923
drwav_uint32 sampleRate
Definition dr_wav.h:888
drwav_seek_proc onSeek
Definition dr_wav.h:868
drwav_bool8 isUnsigned
Definition dr_wav.h:961
drwav_uint16 translatedFormatTag
Definition dr_wav.h:897
drwav_fmt fmt
Definition dr_wav.h:885
void * pUserData
Definition dr_wav.h:874
drwav_uint64 dataChunkDataSize
Definition dr_wav.h:904
struct drwav::@99 aiff
drwav_uint32 bytesRemainingInBlock
Definition dr_wav.h:939
drwav_read_proc onRead
Definition dr_wav.h:862
drwav_uint16 bitsPerSample
Definition dr_wav.h:894
drwav_bool8 isLE
Definition dr_wav.h:960
drwav_uint64 dataChunkDataPos
Definition dr_wav.h:907
drwav_uint64 totalPCMFrameCount
Definition dr_wav.h:900
drwav_metadata * pMetadata
Definition dr_wav.h:927
drwav_uint32 cachedFrameCount
Definition dr_wav.h:943
drwav_uint64 bytesRemaining
Definition dr_wav.h:910
int diff(std::string contextName, folderType fType, bool verbose)