Fix compilation with newer versions of DUMB
[alure.git] / src / decoders / dr_flac.h
blobfa727acadb32fd433393519f5af0a9785cf373bb
1 // FLAC audio decoder. Public domain. See "unlicense" statement at the end of this file.
2 // dr_flac - v0.10.0 - 2018-09-11
3 //
4 // David Reid - mackron@gmail.com
6 // USAGE
7 //
8 // dr_flac is a single-file library. To use it, do something like the following in one .c file.
9 // #define DR_FLAC_IMPLEMENTATION
10 // #include "dr_flac.h"
12 // You can then #include this file in other parts of the program as you would with any other header file. To decode audio data,
13 // do something like the following:
15 // drflac* pFlac = drflac_open_file("MySong.flac");
16 // if (pFlac == NULL) {
17 // // Failed to open FLAC file
18 // }
20 // drflac_int32* pSamples = malloc(pFlac->totalSampleCount * sizeof(drflac_int32));
21 // drflac_uint64 numberOfInterleavedSamplesActuallyRead = drflac_read_s32(pFlac, pFlac->totalSampleCount, pSamples);
23 // The drflac object represents the decoder. It is a transparent type so all the information you need, such as the number of
24 // channels and the bits per sample, should be directly accessible - just make sure you don't change their values. Samples are
25 // always output as interleaved signed 32-bit PCM. In the example above a native FLAC stream was opened, however dr_flac has
26 // seamless support for Ogg encapsulated FLAC streams as well.
28 // You do not need to decode the entire stream in one go - you just specify how many samples you'd like at any given time and
29 // the decoder will give you as many samples as it can, up to the amount requested. Later on when you need the next batch of
30 // samples, just call it again. Example:
32 // while (drflac_read_s32(pFlac, chunkSize, pChunkSamples) > 0) {
33 // do_something();
34 // }
36 // You can seek to a specific sample with drflac_seek_to_sample(). The given sample is based on interleaving. So for example,
37 // if you were to seek to the sample at index 0 in a stereo stream, you'll be seeking to the first sample of the left channel.
38 // The sample at index 1 will be the first sample of the right channel. The sample at index 2 will be the second sample of the
39 // left channel, etc.
42 // If you just want to quickly decode an entire FLAC file in one go you can do something like this:
44 // unsigned int channels;
45 // unsigned int sampleRate;
46 // drflac_uint64 totalSampleCount;
47 // drflac_int32* pSampleData = drflac_open_and_decode_file_s32("MySong.flac", &channels, &sampleRate, &totalSampleCount);
48 // if (pSampleData == NULL) {
49 // // Failed to open and decode FLAC file.
50 // }
52 // ...
54 // drflac_free(pSampleData);
57 // You can read samples as signed 16-bit integer and 32-bit floating-point PCM with the *_s16() and *_f32() family of APIs
58 // respectively, but note that these should be considered lossy.
61 // If you need access to metadata (album art, etc.), use drflac_open_with_metadata(), drflac_open_file_with_metdata() or
62 // drflac_open_memory_with_metadata(). The rationale for keeping these APIs separate is that they're slightly slower than the
63 // normal versions and also just a little bit harder to use.
65 // dr_flac reports metadata to the application through the use of a callback, and every metadata block is reported before
66 // drflac_open_with_metdata() returns.
69 // The main opening APIs (drflac_open(), etc.) will fail if the header is not present. The presents a problem in certain
70 // scenarios such as broadcast style streams like internet radio where the header may not be present because the user has
71 // started playback mid-stream. To handle this, use the relaxed APIs: drflac_open_relaxed() and drflac_open_with_metadata_relaxed().
73 // It is not recommended to use these APIs for file based streams because a missing header would usually indicate a
74 // corrupted or perverse file. In addition, these APIs can take a long time to initialize because they may need to spend
75 // a lot of time finding the first frame.
79 // OPTIONS
80 // #define these options before including this file.
82 // #define DR_FLAC_NO_STDIO
83 // Disable drflac_open_file() and family.
85 // #define DR_FLAC_NO_OGG
86 // Disables support for Ogg/FLAC streams.
88 // #define DR_FLAC_BUFFER_SIZE <number>
89 // Defines the size of the internal buffer to store data from onRead(). This buffer is used to reduce the number of calls
90 // back to the client for more data. Larger values means more memory, but better performance. My tests show diminishing
91 // returns after about 4KB (which is the default). Consider reducing this if you have a very efficient implementation of
92 // onRead(), or increase it if it's very inefficient. Must be a multiple of 8.
94 // #define DR_FLAC_NO_CRC
95 // Disables CRC checks. This will offer a performance boost when CRC is unnecessary.
97 // #define DR_FLAC_NO_SIMD
98 // Disables SIMD optimizations (SSE on x86/x64 architectures). Use this if you are having compatibility issues with your
99 // compiler.
103 // QUICK NOTES
104 // - dr_flac does not currently support changing the sample rate nor channel count mid stream.
105 // - Audio data is output as signed 32-bit PCM, regardless of the bits per sample the FLAC stream is encoded as.
106 // - This has not been tested on big-endian architectures.
107 // - dr_flac is not thread-safe, but its APIs can be called from any thread so long as you do your own synchronization.
108 // - When using Ogg encapsulation, a corrupted metadata block will result in drflac_open_with_metadata() and drflac_open()
109 // returning inconsistent samples.
111 #ifndef dr_flac_h
112 #define dr_flac_h
114 #include <stddef.h>
116 #if defined(_MSC_VER) && _MSC_VER < 1600
117 typedef signed char drflac_int8;
118 typedef unsigned char drflac_uint8;
119 typedef signed short drflac_int16;
120 typedef unsigned short drflac_uint16;
121 typedef signed int drflac_int32;
122 typedef unsigned int drflac_uint32;
123 typedef signed __int64 drflac_int64;
124 typedef unsigned __int64 drflac_uint64;
125 #else
126 #include <stdint.h>
127 typedef int8_t drflac_int8;
128 typedef uint8_t drflac_uint8;
129 typedef int16_t drflac_int16;
130 typedef uint16_t drflac_uint16;
131 typedef int32_t drflac_int32;
132 typedef uint32_t drflac_uint32;
133 typedef int64_t drflac_int64;
134 typedef uint64_t drflac_uint64;
135 #endif
136 typedef drflac_uint8 drflac_bool8;
137 typedef drflac_uint32 drflac_bool32;
138 #define DRFLAC_TRUE 1
139 #define DRFLAC_FALSE 0
141 // As data is read from the client it is placed into an internal buffer for fast access. This controls the
142 // size of that buffer. Larger values means more speed, but also more memory. In my testing there is diminishing
143 // returns after about 4KB, but you can fiddle with this to suit your own needs. Must be a multiple of 8.
144 #ifndef DR_FLAC_BUFFER_SIZE
145 #define DR_FLAC_BUFFER_SIZE 4096
146 #endif
148 #ifdef __cplusplus
149 extern "C" {
150 #endif
152 // Check if we can enable 64-bit optimizations.
153 #if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
154 #define DRFLAC_64BIT
155 #endif
157 #ifdef DRFLAC_64BIT
158 typedef drflac_uint64 drflac_cache_t;
159 #else
160 typedef drflac_uint32 drflac_cache_t;
161 #endif
163 // The various metadata block types.
164 #define DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO 0
165 #define DRFLAC_METADATA_BLOCK_TYPE_PADDING 1
166 #define DRFLAC_METADATA_BLOCK_TYPE_APPLICATION 2
167 #define DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE 3
168 #define DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT 4
169 #define DRFLAC_METADATA_BLOCK_TYPE_CUESHEET 5
170 #define DRFLAC_METADATA_BLOCK_TYPE_PICTURE 6
171 #define DRFLAC_METADATA_BLOCK_TYPE_INVALID 127
173 // The various picture types specified in the PICTURE block.
174 #define DRFLAC_PICTURE_TYPE_OTHER 0
175 #define DRFLAC_PICTURE_TYPE_FILE_ICON 1
176 #define DRFLAC_PICTURE_TYPE_OTHER_FILE_ICON 2
177 #define DRFLAC_PICTURE_TYPE_COVER_FRONT 3
178 #define DRFLAC_PICTURE_TYPE_COVER_BACK 4
179 #define DRFLAC_PICTURE_TYPE_LEAFLET_PAGE 5
180 #define DRFLAC_PICTURE_TYPE_MEDIA 6
181 #define DRFLAC_PICTURE_TYPE_LEAD_ARTIST 7
182 #define DRFLAC_PICTURE_TYPE_ARTIST 8
183 #define DRFLAC_PICTURE_TYPE_CONDUCTOR 9
184 #define DRFLAC_PICTURE_TYPE_BAND 10
185 #define DRFLAC_PICTURE_TYPE_COMPOSER 11
186 #define DRFLAC_PICTURE_TYPE_LYRICIST 12
187 #define DRFLAC_PICTURE_TYPE_RECORDING_LOCATION 13
188 #define DRFLAC_PICTURE_TYPE_DURING_RECORDING 14
189 #define DRFLAC_PICTURE_TYPE_DURING_PERFORMANCE 15
190 #define DRFLAC_PICTURE_TYPE_SCREEN_CAPTURE 16
191 #define DRFLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH 17
192 #define DRFLAC_PICTURE_TYPE_ILLUSTRATION 18
193 #define DRFLAC_PICTURE_TYPE_BAND_LOGOTYPE 19
194 #define DRFLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE 20
196 typedef enum
198 drflac_container_native,
199 drflac_container_ogg,
200 drflac_container_unknown
201 } drflac_container;
203 typedef enum
205 drflac_seek_origin_start,
206 drflac_seek_origin_current
207 } drflac_seek_origin;
209 // Packing is important on this structure because we map this directly to the raw data within the SEEKTABLE metadata block.
210 #pragma pack(2)
211 typedef struct
213 drflac_uint64 firstSample;
214 drflac_uint64 frameOffset; // The offset from the first byte of the header of the first frame.
215 drflac_uint16 sampleCount;
216 } drflac_seekpoint;
217 #pragma pack()
219 typedef struct
221 drflac_uint16 minBlockSize;
222 drflac_uint16 maxBlockSize;
223 drflac_uint32 minFrameSize;
224 drflac_uint32 maxFrameSize;
225 drflac_uint32 sampleRate;
226 drflac_uint8 channels;
227 drflac_uint8 bitsPerSample;
228 drflac_uint64 totalSampleCount;
229 drflac_uint8 md5[16];
230 } drflac_streaminfo;
232 typedef struct
234 // The metadata type. Use this to know how to interpret the data below.
235 drflac_uint32 type;
237 // A pointer to the raw data. This points to a temporary buffer so don't hold on to it. It's best to
238 // not modify the contents of this buffer. Use the structures below for more meaningful and structured
239 // information about the metadata. It's possible for this to be null.
240 const void* pRawData;
242 // The size in bytes of the block and the buffer pointed to by pRawData if it's non-NULL.
243 drflac_uint32 rawDataSize;
245 union
247 drflac_streaminfo streaminfo;
249 struct
251 int unused;
252 } padding;
254 struct
256 drflac_uint32 id;
257 const void* pData;
258 drflac_uint32 dataSize;
259 } application;
261 struct
263 drflac_uint32 seekpointCount;
264 const drflac_seekpoint* pSeekpoints;
265 } seektable;
267 struct
269 drflac_uint32 vendorLength;
270 const char* vendor;
271 drflac_uint32 commentCount;
272 const void* pComments;
273 } vorbis_comment;
275 struct
277 char catalog[128];
278 drflac_uint64 leadInSampleCount;
279 drflac_bool32 isCD;
280 drflac_uint8 trackCount;
281 const void* pTrackData;
282 } cuesheet;
284 struct
286 drflac_uint32 type;
287 drflac_uint32 mimeLength;
288 const char* mime;
289 drflac_uint32 descriptionLength;
290 const char* description;
291 drflac_uint32 width;
292 drflac_uint32 height;
293 drflac_uint32 colorDepth;
294 drflac_uint32 indexColorCount;
295 drflac_uint32 pictureDataSize;
296 const drflac_uint8* pPictureData;
297 } picture;
298 } data;
299 } drflac_metadata;
302 // Callback for when data needs to be read from the client.
304 // pUserData [in] The user data that was passed to drflac_open() and family.
305 // pBufferOut [out] The output buffer.
306 // bytesToRead [in] The number of bytes to read.
308 // Returns the number of bytes actually read.
310 // A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until
311 // either the entire bytesToRead is filled or you have reached the end of the stream.
312 typedef size_t (* drflac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
314 // Callback for when data needs to be seeked.
316 // pUserData [in] The user data that was passed to drflac_open() and family.
317 // offset [in] The number of bytes to move, relative to the origin. Will never be negative.
318 // origin [in] The origin of the seek - the current position or the start of the stream.
320 // Returns whether or not the seek was successful.
322 // The offset will never be negative. Whether or not it is relative to the beginning or current position is determined
323 // by the "origin" parameter which will be either drflac_seek_origin_start or drflac_seek_origin_current.
324 typedef drflac_bool32 (* drflac_seek_proc)(void* pUserData, int offset, drflac_seek_origin origin);
326 // Callback for when a metadata block is read.
328 // pUserData [in] The user data that was passed to drflac_open() and family.
329 // pMetadata [in] A pointer to a structure containing the data of the metadata block.
331 // Use pMetadata->type to determine which metadata block is being handled and how to read the data.
332 typedef void (* drflac_meta_proc)(void* pUserData, drflac_metadata* pMetadata);
335 // Structure for internal use. Only used for decoders opened with drflac_open_memory.
336 typedef struct
338 const drflac_uint8* data;
339 size_t dataSize;
340 size_t currentReadPos;
341 } drflac__memory_stream;
343 // Structure for internal use. Used for bit streaming.
344 typedef struct
346 // The function to call when more data needs to be read.
347 drflac_read_proc onRead;
349 // The function to call when the current read position needs to be moved.
350 drflac_seek_proc onSeek;
352 // The user data to pass around to onRead and onSeek.
353 void* pUserData;
356 // The number of unaligned bytes in the L2 cache. This will always be 0 until the end of the stream is hit. At the end of the
357 // stream there will be a number of bytes that don't cleanly fit in an L1 cache line, so we use this variable to know whether
358 // or not the bistreamer needs to run on a slower path to read those last bytes. This will never be more than sizeof(drflac_cache_t).
359 size_t unalignedByteCount;
361 // The content of the unaligned bytes.
362 drflac_cache_t unalignedCache;
364 // The index of the next valid cache line in the "L2" cache.
365 drflac_uint32 nextL2Line;
367 // The number of bits that have been consumed by the cache. This is used to determine how many valid bits are remaining.
368 drflac_uint32 consumedBits;
370 // The cached data which was most recently read from the client. There are two levels of cache. Data flows as such:
371 // Client -> L2 -> L1. The L2 -> L1 movement is aligned and runs on a fast path in just a few instructions.
372 drflac_cache_t cacheL2[DR_FLAC_BUFFER_SIZE/sizeof(drflac_cache_t)];
373 drflac_cache_t cache;
375 // CRC-16. This is updated whenever bits are read from the bit stream. Manually set this to 0 to reset the CRC. For FLAC, this
376 // is reset to 0 at the beginning of each frame.
377 drflac_uint16 crc16;
378 drflac_cache_t crc16Cache; // A cache for optimizing CRC calculations. This is filled when when the L1 cache is reloaded.
379 drflac_uint32 crc16CacheIgnoredBytes; // The number of bytes to ignore when updating the CRC-16 from the CRC-16 cache.
380 } drflac_bs;
382 typedef struct
384 // The type of the subframe: SUBFRAME_CONSTANT, SUBFRAME_VERBATIM, SUBFRAME_FIXED or SUBFRAME_LPC.
385 drflac_uint8 subframeType;
387 // The number of wasted bits per sample as specified by the sub-frame header.
388 drflac_uint8 wastedBitsPerSample;
390 // The order to use for the prediction stage for SUBFRAME_FIXED and SUBFRAME_LPC.
391 drflac_uint8 lpcOrder;
393 // The number of bits per sample for this subframe. This is not always equal to the current frame's bit per sample because
394 // an extra bit is required for side channels when interchannel decorrelation is being used.
395 drflac_uint32 bitsPerSample;
397 // A pointer to the buffer containing the decoded samples in the subframe. This pointer is an offset from drflac::pExtraData. Note that
398 // it's a signed 32-bit integer for each value.
399 drflac_int32* pDecodedSamples;
400 } drflac_subframe;
402 typedef struct
404 // If the stream uses variable block sizes, this will be set to the index of the first sample. If fixed block sizes are used, this will
405 // always be set to 0.
406 drflac_uint64 sampleNumber;
408 // If the stream uses fixed block sizes, this will be set to the frame number. If variable block sizes are used, this will always be 0.
409 drflac_uint32 frameNumber;
411 // The sample rate of this frame.
412 drflac_uint32 sampleRate;
414 // The number of samples in each sub-frame within this frame.
415 drflac_uint16 blockSize;
417 // The channel assignment of this frame. This is not always set to the channel count. If interchannel decorrelation is being used this
418 // will be set to DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE, DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE or DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE.
419 drflac_uint8 channelAssignment;
421 // The number of bits per sample within this frame.
422 drflac_uint8 bitsPerSample;
424 // The frame's CRC.
425 drflac_uint8 crc8;
426 } drflac_frame_header;
428 typedef struct
430 // The header.
431 drflac_frame_header header;
433 // The number of samples left to be read in this frame. This is initially set to the block size multiplied by the channel count. As samples
434 // are read, this will be decremented. When it reaches 0, the decoder will see this frame as fully consumed and load the next frame.
435 drflac_uint32 samplesRemaining;
437 // The list of sub-frames within the frame. There is one sub-frame for each channel, and there's a maximum of 8 channels.
438 drflac_subframe subframes[8];
439 } drflac_frame;
441 typedef struct
443 // The function to call when a metadata block is read.
444 drflac_meta_proc onMeta;
446 // The user data posted to the metadata callback function.
447 void* pUserDataMD;
450 // The sample rate. Will be set to something like 44100.
451 drflac_uint32 sampleRate;
453 // The number of channels. This will be set to 1 for monaural streams, 2 for stereo, etc. Maximum 8. This is set based on the
454 // value specified in the STREAMINFO block.
455 drflac_uint8 channels;
457 // The bits per sample. Will be set to something like 16, 24, etc.
458 drflac_uint8 bitsPerSample;
460 // The maximum block size, in samples. This number represents the number of samples in each channel (not combined).
461 drflac_uint16 maxBlockSize;
463 // The total number of samples making up the stream. This includes every channel. For example, if the stream has 2 channels,
464 // with each channel having a total of 4096, this value will be set to 2*4096 = 8192. Can be 0 in which case it's still a
465 // valid stream, but just means the total sample count is unknown. Likely the case with streams like internet radio.
466 drflac_uint64 totalSampleCount;
469 // The container type. This is set based on whether or not the decoder was opened from a native or Ogg stream.
470 drflac_container container;
472 // The number of seekpoints in the seektable.
473 drflac_uint32 seekpointCount;
476 // Information about the frame the decoder is currently sitting on.
477 drflac_frame currentFrame;
479 // The index of the sample the decoder is currently sitting on. This is only used for seeking.
480 drflac_uint64 currentSample;
482 // The position of the first frame in the stream. This is only ever used for seeking.
483 drflac_uint64 firstFramePos;
486 // A hack to avoid a malloc() when opening a decoder with drflac_open_memory().
487 drflac__memory_stream memoryStream;
490 // A pointer to the decoded sample data. This is an offset of pExtraData.
491 drflac_int32* pDecodedSamples;
493 // A pointer to the seek table. This is an offset of pExtraData, or NULL if there is no seek table.
494 drflac_seekpoint* pSeekpoints;
496 // Internal use only. Only used with Ogg containers. Points to a drflac_oggbs object. This is an offset of pExtraData.
497 void* _oggbs;
499 // The bit streamer. The raw FLAC data is fed through this object.
500 drflac_bs bs;
502 // Variable length extra data. We attach this to the end of the object so we can avoid unnecessary mallocs.
503 drflac_uint8 pExtraData[1];
504 } drflac;
507 // Opens a FLAC decoder.
509 // onRead [in] The function to call when data needs to be read from the client.
510 // onSeek [in] The function to call when the read position of the client data needs to move.
511 // pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek.
513 // Returns a pointer to an object representing the decoder.
515 // Close the decoder with drflac_close().
517 // This function will automatically detect whether or not you are attempting to open a native or Ogg encapsulated
518 // FLAC, both of which should work seamlessly without any manual intervention. Ogg encapsulation also works with
519 // multiplexed streams which basically means it can play FLAC encoded audio tracks in videos.
521 // This is the lowest level function for opening a FLAC stream. You can also use drflac_open_file() and drflac_open_memory()
522 // to open the stream from a file or from a block of memory respectively.
524 // The STREAMINFO block must be present for this to succeed. Use drflac_open_relaxed() to open a FLAC stream where
525 // the header may not be present.
527 // See also: drflac_open_file(), drflac_open_memory(), drflac_open_with_metadata(), drflac_close()
528 drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData);
530 // The same as drflac_open(), except attempts to open the stream even when a header block is not present.
532 // Because the header is not necessarily available, the caller must explicitly define the container (Native or Ogg). Do
533 // not set this to drflac_container_unknown - that is for internal use only.
535 // Opening in relaxed mode will continue reading data from onRead until it finds a valid frame. If a frame is never
536 // found it will continue forever. To abort, force your onRead callback to return 0, which dr_flac will use as an
537 // indicator that the end of the stream was found.
538 drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData);
540 // Opens a FLAC decoder and notifies the caller of the metadata chunks (album art, etc.).
542 // onRead [in] The function to call when data needs to be read from the client.
543 // onSeek [in] The function to call when the read position of the client data needs to move.
544 // onMeta [in] The function to call for every metadata block.
545 // pUserData [in, optional] A pointer to application defined data that will be passed to onRead, onSeek and onMeta.
547 // Returns a pointer to an object representing the decoder.
549 // Close the decoder with drflac_close().
551 // This is slower than drflac_open(), so avoid this one if you don't need metadata. Internally, this will do a DRFLAC_MALLOC()
552 // and DRFLAC_FREE() for every metadata block except for STREAMINFO and PADDING blocks.
554 // The caller is notified of the metadata via the onMeta callback. All metadata blocks will be handled before the function
555 // returns.
557 // The STREAMINFO block must be present for this to succeed. Use drflac_open_with_metadata_relaxed() to open a FLAC
558 // stream where the header may not be present.
560 // Note that this will behave inconsistently with drflac_open() if the stream is an Ogg encapsulated stream and a metadata
561 // block is corrupted. This is due to the way the Ogg stream recovers from corrupted pages. When drflac_open_with_metadata()
562 // is being used, the open routine will try to read the contents of the metadata block, whereas drflac_open() will simply
563 // seek past it (for the sake of efficiency). This inconsistency can result in different samples being returned depending on
564 // whether or not the stream is being opened with metadata.
566 // See also: drflac_open_file_with_metadata(), drflac_open_memory_with_metadata(), drflac_open(), drflac_close()
567 drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData);
569 // The same as drflac_open_with_metadata(), except attempts to open the stream even when a header block is not present.
571 // See also: drflac_open_with_metadata(), drflac_open_relaxed()
572 drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData);
574 // Closes the given FLAC decoder.
576 // pFlac [in] The decoder to close.
578 // This will destroy the decoder object.
579 void drflac_close(drflac* pFlac);
582 // Reads sample data from the given FLAC decoder, output as interleaved signed 32-bit PCM.
584 // pFlac [in] The decoder.
585 // samplesToRead [in] The number of samples to read.
586 // pBufferOut [out, optional] A pointer to the buffer that will receive the decoded samples.
588 // Returns the number of samples actually read.
590 // pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of samples
591 // seeked.
592 drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int32* pBufferOut);
594 // Same as drflac_read_s32(), except outputs samples as 16-bit integer PCM rather than 32-bit.
596 // pFlac [in] The decoder.
597 // samplesToRead [in] The number of samples to read.
598 // pBufferOut [out, optional] A pointer to the buffer that will receive the decoded samples.
600 // Returns the number of samples actually read.
602 // pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of samples
603 // seeked.
605 // Note that this is lossy for streams where the bits per sample is larger than 16.
606 drflac_uint64 drflac_read_s16(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int16* pBufferOut);
608 // Same as drflac_read_s32(), except outputs samples as 32-bit floating-point PCM.
610 // pFlac [in] The decoder.
611 // samplesToRead [in] The number of samples to read.
612 // pBufferOut [out, optional] A pointer to the buffer that will receive the decoded samples.
614 // Returns the number of samples actually read.
616 // pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of samples
617 // seeked.
619 // Note that this should be considered lossy due to the nature of floating point numbers not being able to exactly
620 // represent every possible number.
621 drflac_uint64 drflac_read_f32(drflac* pFlac, drflac_uint64 samplesToRead, float* pBufferOut);
623 // Seeks to the sample at the given index.
625 // pFlac [in] The decoder.
626 // sampleIndex [in] The index of the sample to seek to. See notes below.
628 // Returns DRFLAC_TRUE if successful; DRFLAC_FALSE otherwise.
630 // The sample index is based on interleaving. In a stereo stream, for example, the sample at index 0 is the first sample
631 // in the left channel; the sample at index 1 is the first sample on the right channel, and so on.
633 // When seeking, you will likely want to ensure it's rounded to a multiple of the channel count. You can do this with
634 // something like drflac_seek_to_sample(pFlac, (mySampleIndex + (mySampleIndex % pFlac->channels)))
635 drflac_bool32 drflac_seek_to_sample(drflac* pFlac, drflac_uint64 sampleIndex);
639 #ifndef DR_FLAC_NO_STDIO
640 // Opens a FLAC decoder from the file at the given path.
642 // filename [in] The path of the file to open, either absolute or relative to the current directory.
644 // Returns a pointer to an object representing the decoder.
646 // Close the decoder with drflac_close().
648 // This will hold a handle to the file until the decoder is closed with drflac_close(). Some platforms will restrict the
649 // number of files a process can have open at any given time, so keep this mind if you have many decoders open at the
650 // same time.
652 // See also: drflac_open(), drflac_open_file_with_metadata(), drflac_close()
653 drflac* drflac_open_file(const char* filename);
655 // Opens a FLAC decoder from the file at the given path and notifies the caller of the metadata chunks (album art, etc.)
657 // Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
658 drflac* drflac_open_file_with_metadata(const char* filename, drflac_meta_proc onMeta, void* pUserData);
659 #endif
661 // Opens a FLAC decoder from a pre-allocated block of memory
663 // This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for
664 // the lifetime of the decoder.
665 drflac* drflac_open_memory(const void* data, size_t dataSize);
667 // Opens a FLAC decoder from a pre-allocated block of memory and notifies the caller of the metadata chunks (album art, etc.)
669 // Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
670 drflac* drflac_open_memory_with_metadata(const void* data, size_t dataSize, drflac_meta_proc onMeta, void* pUserData);
674 //// High Level APIs ////
676 // Opens a FLAC stream from the given callbacks and fully decodes it in a single operation. The return value is a
677 // pointer to the sample data as interleaved signed 32-bit PCM. The returned data must be freed with DRFLAC_FREE().
679 // Sometimes a FLAC file won't keep track of the total sample count. In this situation the function will continuously
680 // read samples into a dynamically sized buffer on the heap until no samples are left.
682 // Do not call this function on a broadcast type of stream (like internet radio streams and whatnot).
683 drflac_int32* drflac_open_and_decode_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
685 // Same as drflac_open_and_decode_s32(), except returns signed 16-bit integer samples.
686 drflac_int16* drflac_open_and_decode_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
688 // Same as drflac_open_and_decode_s32(), except returns 32-bit floating-point samples.
689 float* drflac_open_and_decode_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
691 #ifndef DR_FLAC_NO_STDIO
692 // Same as drflac_open_and_decode_s32() except opens the decoder from a file.
693 drflac_int32* drflac_open_and_decode_file_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
695 // Same as drflac_open_and_decode_file_s32(), except returns signed 16-bit integer samples.
696 drflac_int16* drflac_open_and_decode_file_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
698 // Same as drflac_open_and_decode_file_f32(), except returns 32-bit floating-point samples.
699 float* drflac_open_and_decode_file_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
700 #endif
702 // Same as drflac_open_and_decode_s32() except opens the decoder from a block of memory.
703 drflac_int32* drflac_open_and_decode_memory_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
705 // Same as drflac_open_and_decode_memory_s32(), except returns signed 16-bit integer samples.
706 drflac_int16* drflac_open_and_decode_memory_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
708 // Same as drflac_open_and_decode_memory_s32(), except returns 32-bit floating-point samples.
709 float* drflac_open_and_decode_memory_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
711 // Frees memory that was allocated internally by dr_flac.
712 void drflac_free(void* p);
715 // Structure representing an iterator for vorbis comments in a VORBIS_COMMENT metadata block.
716 typedef struct
718 drflac_uint32 countRemaining;
719 const char* pRunningData;
720 } drflac_vorbis_comment_iterator;
722 // Initializes a vorbis comment iterator. This can be used for iterating over the vorbis comments in a VORBIS_COMMENT
723 // metadata block.
724 void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments);
726 // Goes to the next vorbis comment in the given iterator. If null is returned it means there are no more comments. The
727 // returned string is NOT null terminated.
728 const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut);
731 // Structure representing an iterator for cuesheet tracks in a CUESHEET metadata block.
732 typedef struct
734 drflac_uint32 countRemaining;
735 const char* pRunningData;
736 } drflac_cuesheet_track_iterator;
738 // Packing is important on this structure because we map this directly to the raw data within the CUESHEET metadata block.
739 #pragma pack(4)
740 typedef struct
742 drflac_uint64 offset;
743 drflac_uint8 index;
744 drflac_uint8 reserved[3];
745 } drflac_cuesheet_track_index;
746 #pragma pack()
748 typedef struct
750 drflac_uint64 offset;
751 drflac_uint8 trackNumber;
752 char ISRC[12];
753 drflac_bool8 isAudio;
754 drflac_bool8 preEmphasis;
755 drflac_uint8 indexCount;
756 const drflac_cuesheet_track_index* pIndexPoints;
757 } drflac_cuesheet_track;
759 // Initializes a cuesheet track iterator. This can be used for iterating over the cuesheet tracks in a CUESHEET metadata
760 // block.
761 void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData);
763 // Goes to the next cuesheet track in the given iterator. If DRFLAC_FALSE is returned it means there are no more comments.
764 drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack);
768 #ifdef __cplusplus
770 #endif
771 #endif //dr_flac_h
774 ///////////////////////////////////////////////////////////////////////////////
776 // IMPLEMENTATION
778 ///////////////////////////////////////////////////////////////////////////////
779 #ifdef DR_FLAC_IMPLEMENTATION
780 #ifdef __linux__
781 #ifndef _BSD_SOURCE
782 #define _BSD_SOURCE
783 #endif
784 #ifndef __USE_BSD
785 #define __USE_BSD
786 #endif
787 #include <endian.h>
788 #endif
790 #include <stdlib.h>
791 #include <string.h>
793 // CPU architecture.
794 #if defined(__x86_64__) || defined(_M_X64)
795 #define DRFLAC_X64
796 #elif defined(__i386) || defined(_M_IX86)
797 #define DRFLAC_X86
798 #elif defined(__arm__) || defined(_M_ARM)
799 #define DRFLAC_ARM
800 #endif
802 // Compile-time CPU feature support.
803 #if !defined(DR_FLAC_NO_SIMD) && (defined(DRFLAC_X86) || defined(DRFLAC_X64))
804 #if defined(_MSC_VER) && !defined(__clang__)
805 #if _MSC_VER >= 1400
806 #include <intrin.h>
807 static void drflac__cpuid(int info[4], int fid)
809 __cpuid(info, fid);
811 #else
812 #define DRFLAC_NO_CPUID
813 #endif
814 #else
815 #if defined(__GNUC__) || defined(__clang__)
816 static void drflac__cpuid(int info[4], int fid)
818 // It looks like the -fPIC option uses the ebx register which GCC complains about. We can work around this by just using a different register, the
819 // specific register of which I'm letting the compiler decide on. The "k" prefix is used to specify a 32-bit register. The {...} syntax is for
820 // supporting different assembly dialects.
822 // What's basically happening is that we're saving and restoring the ebx register manually.
823 #if defined(DRFLAC_X86) && defined(__PIC__)
824 __asm__ __volatile__ (
825 "xchg{l} {%%}ebx, %k1;"
826 "cpuid;"
827 "xchg{l} {%%}ebx, %k1;"
828 : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
830 #else
831 __asm__ __volatile__ (
832 "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
834 #endif
836 #else
837 #define DRFLAC_NO_CPUID
838 #endif
839 #endif
840 #else
841 #define DRFLAC_NO_CPUID
842 #endif
845 #if defined(_MSC_VER) && _MSC_VER >= 1500 && (defined(DRFLAC_X86) || defined(DRFLAC_X64))
846 #define DRFLAC_HAS_LZCNT_INTRINSIC
847 #elif (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
848 #define DRFLAC_HAS_LZCNT_INTRINSIC
849 #elif defined(__clang__)
850 #if __has_builtin(__builtin_clzll) || __has_builtin(__builtin_clzl)
851 #define DRFLAC_HAS_LZCNT_INTRINSIC
852 #endif
853 #endif
855 #if defined(_MSC_VER) && _MSC_VER >= 1300
856 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
857 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
858 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
859 #elif defined(__clang__)
860 #if __has_builtin(__builtin_bswap16)
861 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
862 #endif
863 #if __has_builtin(__builtin_bswap32)
864 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
865 #endif
866 #if __has_builtin(__builtin_bswap64)
867 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
868 #endif
869 #elif defined(__GNUC__)
870 #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
871 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
872 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
873 #endif
874 #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
875 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
876 #endif
877 #endif
880 // Standard library stuff.
881 #ifndef DRFLAC_ASSERT
882 #include <assert.h>
883 #define DRFLAC_ASSERT(expression) assert(expression)
884 #endif
885 #ifndef DRFLAC_MALLOC
886 #define DRFLAC_MALLOC(sz) malloc((sz))
887 #endif
888 #ifndef DRFLAC_REALLOC
889 #define DRFLAC_REALLOC(p, sz) realloc((p), (sz))
890 #endif
891 #ifndef DRFLAC_FREE
892 #define DRFLAC_FREE(p) free((p))
893 #endif
894 #ifndef DRFLAC_COPY_MEMORY
895 #define DRFLAC_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
896 #endif
897 #ifndef DRFLAC_ZERO_MEMORY
898 #define DRFLAC_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
899 #endif
901 #define DRFLAC_MAX_SIMD_VECTOR_SIZE 64 // 64 for AVX-512 in the future.
903 #ifdef _MSC_VER
904 #define DRFLAC_INLINE __forceinline
905 #else
906 #ifdef __GNUC__
907 #define DRFLAC_INLINE inline __attribute__((always_inline))
908 #else
909 #define DRFLAC_INLINE inline
910 #endif
911 #endif
913 typedef drflac_int32 drflac_result;
914 #define DRFLAC_SUCCESS 0
915 #define DRFLAC_ERROR -1 // A generic error.
916 #define DRFLAC_INVALID_ARGS -2
917 #define DRFLAC_END_OF_STREAM -128
918 #define DRFLAC_CRC_MISMATCH -129
920 #define DRFLAC_SUBFRAME_CONSTANT 0
921 #define DRFLAC_SUBFRAME_VERBATIM 1
922 #define DRFLAC_SUBFRAME_FIXED 8
923 #define DRFLAC_SUBFRAME_LPC 32
924 #define DRFLAC_SUBFRAME_RESERVED 255
926 #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE 0
927 #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 1
929 #define DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT 0
930 #define DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE 8
931 #define DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE 9
932 #define DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE 10
935 #define drflac_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
936 #define drflac_assert DRFLAC_ASSERT
937 #define drflac_copy_memory DRFLAC_COPY_MEMORY
938 #define drflac_zero_memory DRFLAC_ZERO_MEMORY
941 // CPU caps.
942 static drflac_bool32 drflac__gIsLZCNTSupported = DRFLAC_FALSE;
943 #ifndef DRFLAC_NO_CPUID
944 static drflac_bool32 drflac__gIsSSE42Supported = DRFLAC_FALSE;
945 static void drflac__init_cpu_caps()
947 int info[4] = {0};
949 // LZCNT
950 drflac__cpuid(info, 0x80000001);
951 drflac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0;
953 // SSE4.2
954 drflac__cpuid(info, 1);
955 drflac__gIsSSE42Supported = (info[2] & (1 << 19)) != 0;
957 #endif
960 //// Endian Management ////
961 static DRFLAC_INLINE drflac_bool32 drflac__is_little_endian()
963 #if defined(DRFLAC_X86) || defined(DRFLAC_X64)
964 return DRFLAC_TRUE;
965 #else
966 int n = 1;
967 return (*(char*)&n) == 1;
968 #endif
971 static DRFLAC_INLINE drflac_uint16 drflac__swap_endian_uint16(drflac_uint16 n)
973 #ifdef DRFLAC_HAS_BYTESWAP16_INTRINSIC
974 #if defined(_MSC_VER)
975 return _byteswap_ushort(n);
976 #elif defined(__GNUC__) || defined(__clang__)
977 return __builtin_bswap16(n);
978 #else
979 #error "This compiler does not support the byte swap intrinsic."
980 #endif
981 #else
982 return ((n & 0xFF00) >> 8) |
983 ((n & 0x00FF) << 8);
984 #endif
987 static DRFLAC_INLINE drflac_uint32 drflac__swap_endian_uint32(drflac_uint32 n)
989 #ifdef DRFLAC_HAS_BYTESWAP32_INTRINSIC
990 #if defined(_MSC_VER)
991 return _byteswap_ulong(n);
992 #elif defined(__GNUC__) || defined(__clang__)
993 return __builtin_bswap32(n);
994 #else
995 #error "This compiler does not support the byte swap intrinsic."
996 #endif
997 #else
998 return ((n & 0xFF000000) >> 24) |
999 ((n & 0x00FF0000) >> 8) |
1000 ((n & 0x0000FF00) << 8) |
1001 ((n & 0x000000FF) << 24);
1002 #endif
1005 static DRFLAC_INLINE drflac_uint64 drflac__swap_endian_uint64(drflac_uint64 n)
1007 #ifdef DRFLAC_HAS_BYTESWAP64_INTRINSIC
1008 #if defined(_MSC_VER)
1009 return _byteswap_uint64(n);
1010 #elif defined(__GNUC__) || defined(__clang__)
1011 return __builtin_bswap64(n);
1012 #else
1013 #error "This compiler does not support the byte swap intrinsic."
1014 #endif
1015 #else
1016 return ((n & (drflac_uint64)0xFF00000000000000) >> 56) |
1017 ((n & (drflac_uint64)0x00FF000000000000) >> 40) |
1018 ((n & (drflac_uint64)0x0000FF0000000000) >> 24) |
1019 ((n & (drflac_uint64)0x000000FF00000000) >> 8) |
1020 ((n & (drflac_uint64)0x00000000FF000000) << 8) |
1021 ((n & (drflac_uint64)0x0000000000FF0000) << 24) |
1022 ((n & (drflac_uint64)0x000000000000FF00) << 40) |
1023 ((n & (drflac_uint64)0x00000000000000FF) << 56);
1024 #endif
1028 static DRFLAC_INLINE drflac_uint16 drflac__be2host_16(drflac_uint16 n)
1030 #ifdef __linux__
1031 return be16toh(n);
1032 #else
1033 if (drflac__is_little_endian()) {
1034 return drflac__swap_endian_uint16(n);
1037 return n;
1038 #endif
1041 static DRFLAC_INLINE drflac_uint32 drflac__be2host_32(drflac_uint32 n)
1043 #ifdef __linux__
1044 return be32toh(n);
1045 #else
1046 if (drflac__is_little_endian()) {
1047 return drflac__swap_endian_uint32(n);
1050 return n;
1051 #endif
1054 static DRFLAC_INLINE drflac_uint64 drflac__be2host_64(drflac_uint64 n)
1056 #ifdef __linux__
1057 return be64toh(n);
1058 #else
1059 if (drflac__is_little_endian()) {
1060 return drflac__swap_endian_uint64(n);
1063 return n;
1064 #endif
1068 static DRFLAC_INLINE drflac_uint32 drflac__le2host_32(drflac_uint32 n)
1070 #ifdef __linux__
1071 return le32toh(n);
1072 #else
1073 if (!drflac__is_little_endian()) {
1074 return drflac__swap_endian_uint32(n);
1077 return n;
1078 #endif
1082 static DRFLAC_INLINE drflac_uint32 drflac__unsynchsafe_32(drflac_uint32 n)
1084 drflac_uint32 result = 0;
1085 result |= (n & 0x7F000000) >> 3;
1086 result |= (n & 0x007F0000) >> 2;
1087 result |= (n & 0x00007F00) >> 1;
1088 result |= (n & 0x0000007F) >> 0;
1090 return result;
1095 // The CRC code below is based on this document: http://zlib.net/crc_v3.txt
1096 static drflac_uint8 drflac__crc8_table[] = {
1097 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
1098 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
1099 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
1100 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
1101 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
1102 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
1103 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
1104 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
1105 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
1106 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
1107 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
1108 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
1109 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
1110 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
1111 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
1112 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
1115 static drflac_uint16 drflac__crc16_table[] = {
1116 0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
1117 0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022,
1118 0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072,
1119 0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041,
1120 0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2,
1121 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1,
1122 0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1,
1123 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
1124 0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192,
1125 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1,
1126 0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1,
1127 0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2,
1128 0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151,
1129 0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162,
1130 0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132,
1131 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101,
1132 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312,
1133 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
1134 0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371,
1135 0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342,
1136 0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1,
1137 0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
1138 0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2,
1139 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381,
1140 0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291,
1141 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2,
1142 0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2,
1143 0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1,
1144 0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252,
1145 0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261,
1146 0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231,
1147 0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202
1150 static DRFLAC_INLINE drflac_uint8 drflac_crc8_byte(drflac_uint8 crc, drflac_uint8 data)
1152 return drflac__crc8_table[crc ^ data];
1155 static DRFLAC_INLINE drflac_uint8 drflac_crc8(drflac_uint8 crc, drflac_uint32 data, drflac_uint32 count)
1157 drflac_assert(count <= 32);
1159 #ifdef DR_FLAC_NO_CRC
1160 (void)crc;
1161 (void)data;
1162 (void)count;
1163 return 0;
1164 #else
1165 #if 0
1166 // REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc8(crc, 0, 8);")
1167 drflac_uint8 p = 0x07;
1168 for (int i = count-1; i >= 0; --i) {
1169 drflac_uint8 bit = (data & (1 << i)) >> i;
1170 if (crc & 0x80) {
1171 crc = ((crc << 1) | bit) ^ p;
1172 } else {
1173 crc = ((crc << 1) | bit);
1176 return crc;
1177 #else
1178 drflac_uint32 wholeBytes = count >> 3;
1179 drflac_uint32 leftoverBits = count - (wholeBytes*8);
1181 static drflac_uint64 leftoverDataMaskTable[8] = {
1182 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
1184 drflac_uint64 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
1186 switch (wholeBytes) {
1187 case 4: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
1188 case 3: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
1189 case 2: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
1190 case 1: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
1191 case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc8_table[(crc >> (8 - leftoverBits)) ^ (data & leftoverDataMask)];
1193 return crc;
1194 #endif
1195 #endif
1198 static DRFLAC_INLINE drflac_uint16 drflac_crc16_byte(drflac_uint16 crc, drflac_uint8 data)
1200 return (crc << 8) ^ drflac__crc16_table[(drflac_uint8)(crc >> 8) ^ data];
1203 static DRFLAC_INLINE drflac_uint16 drflac_crc16_bytes(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 byteCount)
1205 switch (byteCount)
1207 #ifdef DRFLAC_64BIT
1208 case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
1209 case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
1210 case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
1211 case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
1212 #endif
1213 case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
1214 case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
1215 case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF));
1216 case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF));
1219 return crc;
1222 static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac_uint32 data, drflac_uint32 count)
1224 drflac_assert(count <= 64);
1226 #ifdef DR_FLAC_NO_CRC
1227 (void)crc;
1228 (void)data;
1229 (void)count;
1230 return 0;
1231 #else
1232 #if 0
1233 // REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc16(crc, 0, 16);")
1234 drflac_uint16 p = 0x8005;
1235 for (int i = count-1; i >= 0; --i) {
1236 drflac_uint16 bit = (data & (1ULL << i)) >> i;
1237 if (r & 0x8000) {
1238 r = ((r << 1) | bit) ^ p;
1239 } else {
1240 r = ((r << 1) | bit);
1244 return crc;
1245 #else
1246 drflac_uint32 wholeBytes = count >> 3;
1247 drflac_uint32 leftoverBits = count - (wholeBytes*8);
1249 static drflac_uint64 leftoverDataMaskTable[8] = {
1250 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
1252 drflac_uint64 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
1254 switch (wholeBytes) {
1255 default:
1256 case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
1257 case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
1258 case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
1259 case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
1260 case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
1262 return crc;
1263 #endif
1264 #endif
1267 static DRFLAC_INLINE drflac_uint16 drflac_crc16__64bit(drflac_uint16 crc, drflac_uint64 data, drflac_uint32 count)
1269 drflac_assert(count <= 64);
1271 #ifdef DR_FLAC_NO_CRC
1272 (void)crc;
1273 (void)data;
1274 (void)count;
1275 return 0;
1276 #else
1277 drflac_uint32 wholeBytes = count >> 3;
1278 drflac_uint32 leftoverBits = count - (wholeBytes*8);
1280 static drflac_uint64 leftoverDataMaskTable[8] = {
1281 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
1283 drflac_uint64 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
1285 switch (wholeBytes) {
1286 default:
1287 case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0xFF00000000000000 << leftoverBits)) >> (56 + leftoverBits)));
1288 case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x00FF000000000000 << leftoverBits)) >> (48 + leftoverBits)));
1289 case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x0000FF0000000000 << leftoverBits)) >> (40 + leftoverBits)));
1290 case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x000000FF00000000 << leftoverBits)) >> (32 + leftoverBits)));
1291 case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x00000000FF000000 << leftoverBits)) >> (24 + leftoverBits)));
1292 case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x0000000000FF0000 << leftoverBits)) >> (16 + leftoverBits)));
1293 case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x000000000000FF00 << leftoverBits)) >> ( 8 + leftoverBits)));
1294 case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x00000000000000FF << leftoverBits)) >> ( 0 + leftoverBits)));
1295 case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
1297 return crc;
1298 #endif
1302 static DRFLAC_INLINE drflac_uint16 drflac_crc16(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 count)
1304 #ifdef DRFLAC_64BIT
1305 return drflac_crc16__64bit(crc, data, count);
1306 #else
1307 return drflac_crc16__32bit(crc, data, count);
1308 #endif
1312 #ifdef DRFLAC_64BIT
1313 #define drflac__be2host__cache_line drflac__be2host_64
1314 #else
1315 #define drflac__be2host__cache_line drflac__be2host_32
1316 #endif
1318 // BIT READING ATTEMPT #2
1320 // This uses a 32- or 64-bit bit-shifted cache - as bits are read, the cache is shifted such that the first valid bit is sitting
1321 // on the most significant bit. It uses the notion of an L1 and L2 cache (borrowed from CPU architecture), where the L1 cache
1322 // is a 32- or 64-bit unsigned integer (depending on whether or not a 32- or 64-bit build is being compiled) and the L2 is an
1323 // array of "cache lines", with each cache line being the same size as the L1. The L2 is a buffer of about 4KB and is where data
1324 // from onRead() is read into.
1325 #define DRFLAC_CACHE_L1_SIZE_BYTES(bs) (sizeof((bs)->cache))
1326 #define DRFLAC_CACHE_L1_SIZE_BITS(bs) (sizeof((bs)->cache)*8)
1327 #define DRFLAC_CACHE_L1_BITS_REMAINING(bs) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (bs)->consumedBits)
1328 #define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~((~(drflac_cache_t)0) >> (_bitCount)))
1329 #define DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount))
1330 #define DRFLAC_CACHE_L1_SELECT(bs, _bitCount) (((bs)->cache) & DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount))
1331 #define DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)))
1332 #define DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, _bitCount)(DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> (DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)) & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1)))
1333 #define DRFLAC_CACHE_L2_SIZE_BYTES(bs) (sizeof((bs)->cacheL2))
1334 #define DRFLAC_CACHE_L2_LINE_COUNT(bs) (DRFLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0]))
1335 #define DRFLAC_CACHE_L2_LINES_REMAINING(bs) (DRFLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line)
1338 #ifndef DR_FLAC_NO_CRC
1339 static DRFLAC_INLINE void drflac__reset_crc16(drflac_bs* bs)
1341 bs->crc16 = 0;
1342 bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
1345 static DRFLAC_INLINE void drflac__update_crc16(drflac_bs* bs)
1347 bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache, DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bs->crc16CacheIgnoredBytes);
1348 bs->crc16CacheIgnoredBytes = 0;
1351 static DRFLAC_INLINE drflac_uint16 drflac__flush_crc16(drflac_bs* bs)
1353 // We should never be flushing in a situation where we are not aligned on a byte boundary.
1354 drflac_assert((DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7) == 0);
1356 // The bits that were read from the L1 cache need to be accumulated. The number of bytes needing to be accumulated is determined
1357 // by the number of bits that have been consumed.
1358 if (DRFLAC_CACHE_L1_BITS_REMAINING(bs) == 0) {
1359 drflac__update_crc16(bs);
1360 } else {
1361 // We only accumulate the consumed bits.
1362 bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache >> DRFLAC_CACHE_L1_BITS_REMAINING(bs), (bs->consumedBits >> 3) - bs->crc16CacheIgnoredBytes);
1364 // The bits that we just accumulated should never be accumulated again. We need to keep track of how many bytes were accumulated
1365 // so we can handle that later.
1366 bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
1369 return bs->crc16;
1371 #endif
1373 static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs)
1375 // Fast path. Try loading straight from L2.
1376 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
1377 bs->cache = bs->cacheL2[bs->nextL2Line++];
1378 return DRFLAC_TRUE;
1381 // If we get here it means we've run out of data in the L2 cache. We'll need to fetch more from the client, if there's
1382 // any left.
1383 if (bs->unalignedByteCount > 0) {
1384 return DRFLAC_FALSE; // If we have any unaligned bytes it means there's no more aligned bytes left in the client.
1387 size_t bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, DRFLAC_CACHE_L2_SIZE_BYTES(bs));
1389 bs->nextL2Line = 0;
1390 if (bytesRead == DRFLAC_CACHE_L2_SIZE_BYTES(bs)) {
1391 bs->cache = bs->cacheL2[bs->nextL2Line++];
1392 return DRFLAC_TRUE;
1396 // If we get here it means we were unable to retrieve enough data to fill the entire L2 cache. It probably
1397 // means we've just reached the end of the file. We need to move the valid data down to the end of the buffer
1398 // and adjust the index of the next line accordingly. Also keep in mind that the L2 cache must be aligned to
1399 // the size of the L1 so we'll need to seek backwards by any misaligned bytes.
1400 size_t alignedL1LineCount = bytesRead / DRFLAC_CACHE_L1_SIZE_BYTES(bs);
1402 // We need to keep track of any unaligned bytes for later use.
1403 bs->unalignedByteCount = bytesRead - (alignedL1LineCount * DRFLAC_CACHE_L1_SIZE_BYTES(bs));
1404 if (bs->unalignedByteCount > 0) {
1405 bs->unalignedCache = bs->cacheL2[alignedL1LineCount];
1408 if (alignedL1LineCount > 0) {
1409 size_t offset = DRFLAC_CACHE_L2_LINE_COUNT(bs) - alignedL1LineCount;
1410 for (size_t i = alignedL1LineCount; i > 0; --i) {
1411 bs->cacheL2[i-1 + offset] = bs->cacheL2[i-1];
1414 bs->nextL2Line = (drflac_uint32)offset;
1415 bs->cache = bs->cacheL2[bs->nextL2Line++];
1416 return DRFLAC_TRUE;
1417 } else {
1418 // If we get into this branch it means we weren't able to load any L1-aligned data.
1419 bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs);
1420 return DRFLAC_FALSE;
1424 static drflac_bool32 drflac__reload_cache(drflac_bs* bs)
1426 #ifndef DR_FLAC_NO_CRC
1427 drflac__update_crc16(bs);
1428 #endif
1430 // Fast path. Try just moving the next value in the L2 cache to the L1 cache.
1431 if (drflac__reload_l1_cache_from_l2(bs)) {
1432 bs->cache = drflac__be2host__cache_line(bs->cache);
1433 bs->consumedBits = 0;
1434 #ifndef DR_FLAC_NO_CRC
1435 bs->crc16Cache = bs->cache;
1436 #endif
1437 return DRFLAC_TRUE;
1440 // Slow path.
1442 // If we get here it means we have failed to load the L1 cache from the L2. Likely we've just reached the end of the stream and the last
1443 // few bytes did not meet the alignment requirements for the L2 cache. In this case we need to fall back to a slower path and read the
1444 // data from the unaligned cache.
1445 size_t bytesRead = bs->unalignedByteCount;
1446 if (bytesRead == 0) {
1447 bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); // <-- The stream has been exhausted, so marked the bits as consumed.
1448 return DRFLAC_FALSE;
1451 drflac_assert(bytesRead < DRFLAC_CACHE_L1_SIZE_BYTES(bs));
1452 bs->consumedBits = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bytesRead) * 8;
1454 bs->cache = drflac__be2host__cache_line(bs->unalignedCache);
1455 bs->cache &= DRFLAC_CACHE_L1_SELECTION_MASK(DRFLAC_CACHE_L1_BITS_REMAINING(bs)); // <-- Make sure the consumed bits are always set to zero. Other parts of the library depend on this property.
1456 bs->unalignedByteCount = 0; // <-- At this point the unaligned bytes have been moved into the cache and we thus have no more unaligned bytes.
1458 #ifndef DR_FLAC_NO_CRC
1459 bs->crc16Cache = bs->cache >> bs->consumedBits;
1460 bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
1461 #endif
1462 return DRFLAC_TRUE;
1465 static void drflac__reset_cache(drflac_bs* bs)
1467 bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs); // <-- This clears the L2 cache.
1468 bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); // <-- This clears the L1 cache.
1469 bs->cache = 0;
1470 bs->unalignedByteCount = 0; // <-- This clears the trailing unaligned bytes.
1471 bs->unalignedCache = 0;
1473 #ifndef DR_FLAC_NO_CRC
1474 bs->crc16Cache = 0;
1475 bs->crc16CacheIgnoredBytes = 0;
1476 #endif
1480 static DRFLAC_INLINE drflac_bool32 drflac__read_uint32(drflac_bs* bs, unsigned int bitCount, drflac_uint32* pResultOut)
1482 drflac_assert(bs != NULL);
1483 drflac_assert(pResultOut != NULL);
1484 drflac_assert(bitCount > 0);
1485 drflac_assert(bitCount <= 32);
1487 if (bs->consumedBits == DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
1488 if (!drflac__reload_cache(bs)) {
1489 return DRFLAC_FALSE;
1493 if (bitCount <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
1494 // If we want to load all 32-bits from a 32-bit cache we need to do it slightly differently because we can't do
1495 // a 32-bit shift on a 32-bit integer. This will never be the case on 64-bit caches, so we can have a slightly
1496 // more optimal solution for this.
1497 #ifdef DRFLAC_64BIT
1498 *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
1499 bs->consumedBits += bitCount;
1500 bs->cache <<= bitCount;
1501 #else
1502 if (bitCount < DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
1503 *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
1504 bs->consumedBits += bitCount;
1505 bs->cache <<= bitCount;
1506 } else {
1507 // Cannot shift by 32-bits, so need to do it differently.
1508 *pResultOut = (drflac_uint32)bs->cache;
1509 bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);
1510 bs->cache = 0;
1512 #endif
1514 return DRFLAC_TRUE;
1515 } else {
1516 // It straddles the cached data. It will never cover more than the next chunk. We just read the number in two parts and combine them.
1517 drflac_uint32 bitCountHi = DRFLAC_CACHE_L1_BITS_REMAINING(bs);
1518 drflac_uint32 bitCountLo = bitCount - bitCountHi;
1519 drflac_uint32 resultHi = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountHi);
1521 if (!drflac__reload_cache(bs)) {
1522 return DRFLAC_FALSE;
1525 *pResultOut = (resultHi << bitCountLo) | (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo);
1526 bs->consumedBits += bitCountLo;
1527 bs->cache <<= bitCountLo;
1528 return DRFLAC_TRUE;
1532 static drflac_bool32 drflac__read_int32(drflac_bs* bs, unsigned int bitCount, drflac_int32* pResult)
1534 drflac_assert(bs != NULL);
1535 drflac_assert(pResult != NULL);
1536 drflac_assert(bitCount > 0);
1537 drflac_assert(bitCount <= 32);
1539 drflac_uint32 result;
1540 if (!drflac__read_uint32(bs, bitCount, &result)) {
1541 return DRFLAC_FALSE;
1544 drflac_uint32 signbit = ((result >> (bitCount-1)) & 0x01);
1545 result |= (~signbit + 1) << bitCount;
1547 *pResult = (drflac_int32)result;
1548 return DRFLAC_TRUE;
1551 #ifdef DRFLAC_64BIT
1552 static drflac_bool32 drflac__read_uint64(drflac_bs* bs, unsigned int bitCount, drflac_uint64* pResultOut)
1554 drflac_assert(bitCount <= 64);
1555 drflac_assert(bitCount > 32);
1557 drflac_uint32 resultHi;
1558 if (!drflac__read_uint32(bs, bitCount - 32, &resultHi)) {
1559 return DRFLAC_FALSE;
1562 drflac_uint32 resultLo;
1563 if (!drflac__read_uint32(bs, 32, &resultLo)) {
1564 return DRFLAC_FALSE;
1567 *pResultOut = (((drflac_uint64)resultHi) << 32) | ((drflac_uint64)resultLo);
1568 return DRFLAC_TRUE;
1570 #endif
1572 // Function below is unused, but leaving it here in case I need to quickly add it again.
1573 #if 0
1574 static drflac_bool32 drflac__read_int64(drflac_bs* bs, unsigned int bitCount, drflac_int64* pResultOut)
1576 drflac_assert(bitCount <= 64);
1578 drflac_uint64 result;
1579 if (!drflac__read_uint64(bs, bitCount, &result)) {
1580 return DRFLAC_FALSE;
1583 drflac_uint64 signbit = ((result >> (bitCount-1)) & 0x01);
1584 result |= (~signbit + 1) << bitCount;
1586 *pResultOut = (drflac_int64)result;
1587 return DRFLAC_TRUE;
1589 #endif
1591 static drflac_bool32 drflac__read_uint16(drflac_bs* bs, unsigned int bitCount, drflac_uint16* pResult)
1593 drflac_assert(bs != NULL);
1594 drflac_assert(pResult != NULL);
1595 drflac_assert(bitCount > 0);
1596 drflac_assert(bitCount <= 16);
1598 drflac_uint32 result;
1599 if (!drflac__read_uint32(bs, bitCount, &result)) {
1600 return DRFLAC_FALSE;
1603 *pResult = (drflac_uint16)result;
1604 return DRFLAC_TRUE;
1607 #if 0
1608 static drflac_bool32 drflac__read_int16(drflac_bs* bs, unsigned int bitCount, drflac_int16* pResult)
1610 drflac_assert(bs != NULL);
1611 drflac_assert(pResult != NULL);
1612 drflac_assert(bitCount > 0);
1613 drflac_assert(bitCount <= 16);
1615 drflac_int32 result;
1616 if (!drflac__read_int32(bs, bitCount, &result)) {
1617 return DRFLAC_FALSE;
1620 *pResult = (drflac_int16)result;
1621 return DRFLAC_TRUE;
1623 #endif
1625 static drflac_bool32 drflac__read_uint8(drflac_bs* bs, unsigned int bitCount, drflac_uint8* pResult)
1627 drflac_assert(bs != NULL);
1628 drflac_assert(pResult != NULL);
1629 drflac_assert(bitCount > 0);
1630 drflac_assert(bitCount <= 8);
1632 drflac_uint32 result;
1633 if (!drflac__read_uint32(bs, bitCount, &result)) {
1634 return DRFLAC_FALSE;
1637 *pResult = (drflac_uint8)result;
1638 return DRFLAC_TRUE;
1641 static drflac_bool32 drflac__read_int8(drflac_bs* bs, unsigned int bitCount, drflac_int8* pResult)
1643 drflac_assert(bs != NULL);
1644 drflac_assert(pResult != NULL);
1645 drflac_assert(bitCount > 0);
1646 drflac_assert(bitCount <= 8);
1648 drflac_int32 result;
1649 if (!drflac__read_int32(bs, bitCount, &result)) {
1650 return DRFLAC_FALSE;
1653 *pResult = (drflac_int8)result;
1654 return DRFLAC_TRUE;
1658 static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek)
1660 if (bitsToSeek <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
1661 bs->consumedBits += (drflac_uint32)bitsToSeek;
1662 bs->cache <<= bitsToSeek;
1663 return DRFLAC_TRUE;
1664 } else {
1665 // It straddles the cached data. This function isn't called too frequently so I'm favouring simplicity here.
1666 bitsToSeek -= DRFLAC_CACHE_L1_BITS_REMAINING(bs);
1667 bs->consumedBits += DRFLAC_CACHE_L1_BITS_REMAINING(bs);
1668 bs->cache = 0;
1670 // Simple case. Seek in groups of the same number as bits that fit within a cache line.
1671 #ifdef DRFLAC_64BIT
1672 while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
1673 drflac_uint64 bin;
1674 if (!drflac__read_uint64(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
1675 return DRFLAC_FALSE;
1677 bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
1679 #else
1680 while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
1681 drflac_uint32 bin;
1682 if (!drflac__read_uint32(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
1683 return DRFLAC_FALSE;
1685 bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
1687 #endif
1689 // Whole leftover bytes.
1690 while (bitsToSeek >= 8) {
1691 drflac_uint8 bin;
1692 if (!drflac__read_uint8(bs, 8, &bin)) {
1693 return DRFLAC_FALSE;
1695 bitsToSeek -= 8;
1698 // Leftover bits.
1699 if (bitsToSeek > 0) {
1700 drflac_uint8 bin;
1701 if (!drflac__read_uint8(bs, (drflac_uint32)bitsToSeek, &bin)) {
1702 return DRFLAC_FALSE;
1704 bitsToSeek = 0; // <-- Necessary for the assert below.
1707 drflac_assert(bitsToSeek == 0);
1708 return DRFLAC_TRUE;
1713 // This function moves the bit streamer to the first bit after the sync code (bit 15 of the of the frame header). It will also update the CRC-16.
1714 static drflac_bool32 drflac__find_and_seek_to_next_sync_code(drflac_bs* bs)
1716 drflac_assert(bs != NULL);
1718 // The sync code is always aligned to 8 bits. This is convenient for us because it means we can do byte-aligned movements. The first
1719 // thing to do is align to the next byte.
1720 if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
1721 return DRFLAC_FALSE;
1724 for (;;) {
1725 #ifndef DR_FLAC_NO_CRC
1726 drflac__reset_crc16(bs);
1727 #endif
1729 drflac_uint8 hi;
1730 if (!drflac__read_uint8(bs, 8, &hi)) {
1731 return DRFLAC_FALSE;
1734 if (hi == 0xFF) {
1735 drflac_uint8 lo;
1736 if (!drflac__read_uint8(bs, 6, &lo)) {
1737 return DRFLAC_FALSE;
1740 if (lo == 0x3E) {
1741 return DRFLAC_TRUE;
1742 } else {
1743 if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
1744 return DRFLAC_FALSE;
1750 // Should never get here.
1751 //return DRFLAC_FALSE;
1755 #if !defined(DR_FLAC_NO_SIMD) && defined(DRFLAC_HAS_LZCNT_INTRINSIC)
1756 #define DRFLAC_IMPLEMENT_CLZ_LZCNT
1757 #endif
1758 #if defined(_MSC_VER) && _MSC_VER >= 1400 && (defined(DRFLAC_X64) || defined(DRFLAC_X86))
1759 #define DRFLAC_IMPLEMENT_CLZ_MSVC
1760 #endif
1762 static DRFLAC_INLINE drflac_uint32 drflac__clz_software(drflac_cache_t x)
1764 static drflac_uint32 clz_table_4[] = {
1767 3, 3,
1768 2, 2, 2, 2,
1769 1, 1, 1, 1, 1, 1, 1, 1
1772 drflac_uint32 n = clz_table_4[x >> (sizeof(x)*8 - 4)];
1773 if (n == 0) {
1774 #ifdef DRFLAC_64BIT
1775 if ((x & 0xFFFFFFFF00000000ULL) == 0) { n = 32; x <<= 32; }
1776 if ((x & 0xFFFF000000000000ULL) == 0) { n += 16; x <<= 16; }
1777 if ((x & 0xFF00000000000000ULL) == 0) { n += 8; x <<= 8; }
1778 if ((x & 0xF000000000000000ULL) == 0) { n += 4; x <<= 4; }
1779 #else
1780 if ((x & 0xFFFF0000) == 0) { n = 16; x <<= 16; }
1781 if ((x & 0xFF000000) == 0) { n += 8; x <<= 8; }
1782 if ((x & 0xF0000000) == 0) { n += 4; x <<= 4; }
1783 #endif
1784 n += clz_table_4[x >> (sizeof(x)*8 - 4)];
1787 return n - 1;
1790 #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
1791 static DRFLAC_INLINE drflac_bool32 drflac__is_lzcnt_supported()
1793 // If the compiler itself does not support the intrinsic then we'll need to return false.
1794 #ifdef DRFLAC_HAS_LZCNT_INTRINSIC
1795 return drflac__gIsLZCNTSupported;
1796 #else
1797 return DRFLAC_FALSE;
1798 #endif
1801 static DRFLAC_INLINE drflac_uint32 drflac__clz_lzcnt(drflac_cache_t x)
1803 #if defined(_MSC_VER) && !defined(__clang__)
1804 #ifdef DRFLAC_64BIT
1805 return (drflac_uint32)__lzcnt64(x);
1806 #else
1807 return (drflac_uint32)__lzcnt(x);
1808 #endif
1809 #else
1810 #if defined(__GNUC__) || defined(__clang__)
1811 #ifdef DRFLAC_64BIT
1812 return (drflac_uint32)__builtin_clzll((unsigned long long)x);
1813 #else
1814 return (drflac_uint32)__builtin_clzl((unsigned long)x);
1815 #endif
1816 #else
1817 // Unsupported compiler.
1818 #error "This compiler does not support the lzcnt intrinsic."
1819 #endif
1820 #endif
1822 #endif
1824 #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
1825 #include <intrin.h> // For BitScanReverse().
1827 static DRFLAC_INLINE drflac_uint32 drflac__clz_msvc(drflac_cache_t x)
1829 drflac_uint32 n;
1830 #ifdef DRFLAC_64BIT
1831 _BitScanReverse64((unsigned long*)&n, x);
1832 #else
1833 _BitScanReverse((unsigned long*)&n, x);
1834 #endif
1835 return sizeof(x)*8 - n - 1;
1837 #endif
1839 static DRFLAC_INLINE drflac_uint32 drflac__clz(drflac_cache_t x)
1841 // This function assumes at least one bit is set. Checking for 0 needs to be done at a higher level, outside this function.
1842 #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
1843 if (drflac__is_lzcnt_supported()) {
1844 return drflac__clz_lzcnt(x);
1845 } else
1846 #endif
1848 #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
1849 return drflac__clz_msvc(x);
1850 #else
1851 return drflac__clz_software(x);
1852 #endif
1857 static inline drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsigned int* pOffsetOut)
1859 drflac_uint32 zeroCounter = 0;
1860 while (bs->cache == 0) {
1861 zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
1862 if (!drflac__reload_cache(bs)) {
1863 return DRFLAC_FALSE;
1867 drflac_uint32 setBitOffsetPlus1 = drflac__clz(bs->cache);
1868 setBitOffsetPlus1 += 1;
1870 bs->consumedBits += setBitOffsetPlus1;
1871 bs->cache <<= setBitOffsetPlus1;
1873 *pOffsetOut = zeroCounter + setBitOffsetPlus1 - 1;
1874 return DRFLAC_TRUE;
1879 static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFromStart)
1881 drflac_assert(bs != NULL);
1882 drflac_assert(offsetFromStart > 0);
1884 // Seeking from the start is not quite as trivial as it sounds because the onSeek callback takes a signed 32-bit integer (which
1885 // is intentional because it simplifies the implementation of the onSeek callbacks), however offsetFromStart is unsigned 64-bit.
1886 // To resolve we just need to do an initial seek from the start, and then a series of offset seeks to make up the remainder.
1887 if (offsetFromStart > 0x7FFFFFFF) {
1888 drflac_uint64 bytesRemaining = offsetFromStart;
1889 if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start)) {
1890 return DRFLAC_FALSE;
1892 bytesRemaining -= 0x7FFFFFFF;
1894 while (bytesRemaining > 0x7FFFFFFF) {
1895 if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current)) {
1896 return DRFLAC_FALSE;
1898 bytesRemaining -= 0x7FFFFFFF;
1901 if (bytesRemaining > 0) {
1902 if (!bs->onSeek(bs->pUserData, (int)bytesRemaining, drflac_seek_origin_current)) {
1903 return DRFLAC_FALSE;
1906 } else {
1907 if (!bs->onSeek(bs->pUserData, (int)offsetFromStart, drflac_seek_origin_start)) {
1908 return DRFLAC_FALSE;
1912 // The cache should be reset to force a reload of fresh data from the client.
1913 drflac__reset_cache(bs);
1914 return DRFLAC_TRUE;
1918 static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64* pNumberOut, drflac_uint8* pCRCOut)
1920 drflac_assert(bs != NULL);
1921 drflac_assert(pNumberOut != NULL);
1923 drflac_uint8 crc = *pCRCOut;
1925 unsigned char utf8[7] = {0};
1926 if (!drflac__read_uint8(bs, 8, utf8)) {
1927 *pNumberOut = 0;
1928 return DRFLAC_END_OF_STREAM;
1930 crc = drflac_crc8(crc, utf8[0], 8);
1932 if ((utf8[0] & 0x80) == 0) {
1933 *pNumberOut = utf8[0];
1934 *pCRCOut = crc;
1935 return DRFLAC_SUCCESS;
1938 int byteCount = 1;
1939 if ((utf8[0] & 0xE0) == 0xC0) {
1940 byteCount = 2;
1941 } else if ((utf8[0] & 0xF0) == 0xE0) {
1942 byteCount = 3;
1943 } else if ((utf8[0] & 0xF8) == 0xF0) {
1944 byteCount = 4;
1945 } else if ((utf8[0] & 0xFC) == 0xF8) {
1946 byteCount = 5;
1947 } else if ((utf8[0] & 0xFE) == 0xFC) {
1948 byteCount = 6;
1949 } else if ((utf8[0] & 0xFF) == 0xFE) {
1950 byteCount = 7;
1951 } else {
1952 *pNumberOut = 0;
1953 return DRFLAC_CRC_MISMATCH; // Bad UTF-8 encoding.
1956 // Read extra bytes.
1957 drflac_assert(byteCount > 1);
1959 drflac_uint64 result = (drflac_uint64)(utf8[0] & (0xFF >> (byteCount + 1)));
1960 for (int i = 1; i < byteCount; ++i) {
1961 if (!drflac__read_uint8(bs, 8, utf8 + i)) {
1962 *pNumberOut = 0;
1963 return DRFLAC_END_OF_STREAM;
1965 crc = drflac_crc8(crc, utf8[i], 8);
1967 result = (result << 6) | (utf8[i] & 0x3F);
1970 *pNumberOut = result;
1971 *pCRCOut = crc;
1972 return DRFLAC_SUCCESS;
1978 // The next two functions are responsible for calculating the prediction.
1980 // When the bits per sample is >16 we need to use 64-bit integer arithmetic because otherwise we'll run out of precision. It's
1981 // safe to assume this will be slower on 32-bit platforms so we use a more optimal solution when the bits per sample is <=16.
1982 static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_32(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
1984 drflac_assert(order <= 32);
1986 // 32-bit version.
1988 // VC++ optimizes this to a single jmp. I've not yet verified this for other compilers.
1989 drflac_int32 prediction = 0;
1991 switch (order)
1993 case 32: prediction += coefficients[31] * pDecodedSamples[-32];
1994 case 31: prediction += coefficients[30] * pDecodedSamples[-31];
1995 case 30: prediction += coefficients[29] * pDecodedSamples[-30];
1996 case 29: prediction += coefficients[28] * pDecodedSamples[-29];
1997 case 28: prediction += coefficients[27] * pDecodedSamples[-28];
1998 case 27: prediction += coefficients[26] * pDecodedSamples[-27];
1999 case 26: prediction += coefficients[25] * pDecodedSamples[-26];
2000 case 25: prediction += coefficients[24] * pDecodedSamples[-25];
2001 case 24: prediction += coefficients[23] * pDecodedSamples[-24];
2002 case 23: prediction += coefficients[22] * pDecodedSamples[-23];
2003 case 22: prediction += coefficients[21] * pDecodedSamples[-22];
2004 case 21: prediction += coefficients[20] * pDecodedSamples[-21];
2005 case 20: prediction += coefficients[19] * pDecodedSamples[-20];
2006 case 19: prediction += coefficients[18] * pDecodedSamples[-19];
2007 case 18: prediction += coefficients[17] * pDecodedSamples[-18];
2008 case 17: prediction += coefficients[16] * pDecodedSamples[-17];
2009 case 16: prediction += coefficients[15] * pDecodedSamples[-16];
2010 case 15: prediction += coefficients[14] * pDecodedSamples[-15];
2011 case 14: prediction += coefficients[13] * pDecodedSamples[-14];
2012 case 13: prediction += coefficients[12] * pDecodedSamples[-13];
2013 case 12: prediction += coefficients[11] * pDecodedSamples[-12];
2014 case 11: prediction += coefficients[10] * pDecodedSamples[-11];
2015 case 10: prediction += coefficients[ 9] * pDecodedSamples[-10];
2016 case 9: prediction += coefficients[ 8] * pDecodedSamples[- 9];
2017 case 8: prediction += coefficients[ 7] * pDecodedSamples[- 8];
2018 case 7: prediction += coefficients[ 6] * pDecodedSamples[- 7];
2019 case 6: prediction += coefficients[ 5] * pDecodedSamples[- 6];
2020 case 5: prediction += coefficients[ 4] * pDecodedSamples[- 5];
2021 case 4: prediction += coefficients[ 3] * pDecodedSamples[- 4];
2022 case 3: prediction += coefficients[ 2] * pDecodedSamples[- 3];
2023 case 2: prediction += coefficients[ 1] * pDecodedSamples[- 2];
2024 case 1: prediction += coefficients[ 0] * pDecodedSamples[- 1];
2027 return (drflac_int32)(prediction >> shift);
2030 static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
2032 drflac_assert(order <= 32);
2034 // 64-bit version.
2036 // This method is faster on the 32-bit build when compiling with VC++. See note below.
2037 #ifndef DRFLAC_64BIT
2038 drflac_int64 prediction;
2039 if (order == 8)
2041 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
2042 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
2043 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
2044 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
2045 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
2046 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
2047 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
2048 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
2050 else if (order == 7)
2052 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
2053 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
2054 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
2055 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
2056 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
2057 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
2058 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
2060 else if (order == 3)
2062 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
2063 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
2064 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
2066 else if (order == 6)
2068 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
2069 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
2070 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
2071 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
2072 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
2073 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
2075 else if (order == 5)
2077 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
2078 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
2079 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
2080 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
2081 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
2083 else if (order == 4)
2085 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
2086 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
2087 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
2088 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
2090 else if (order == 12)
2092 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
2093 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
2094 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
2095 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
2096 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
2097 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
2098 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
2099 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
2100 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
2101 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
2102 prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
2103 prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
2105 else if (order == 2)
2107 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
2108 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
2110 else if (order == 1)
2112 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
2114 else if (order == 10)
2116 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
2117 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
2118 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
2119 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
2120 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
2121 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
2122 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
2123 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
2124 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
2125 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
2127 else if (order == 9)
2129 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
2130 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
2131 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
2132 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
2133 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
2134 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
2135 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
2136 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
2137 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
2139 else if (order == 11)
2141 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
2142 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
2143 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
2144 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
2145 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
2146 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
2147 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
2148 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
2149 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
2150 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
2151 prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
2153 else
2155 prediction = 0;
2156 for (int j = 0; j < (int)order; ++j) {
2157 prediction += coefficients[j] * (drflac_int64)pDecodedSamples[-j-1];
2160 #endif
2162 // VC++ optimizes this to a single jmp instruction, but only the 64-bit build. The 32-bit build generates less efficient code for some
2163 // reason. The ugly version above is faster so we'll just switch between the two depending on the target platform.
2164 #ifdef DRFLAC_64BIT
2165 drflac_int64 prediction = 0;
2167 switch (order)
2169 case 32: prediction += coefficients[31] * (drflac_int64)pDecodedSamples[-32];
2170 case 31: prediction += coefficients[30] * (drflac_int64)pDecodedSamples[-31];
2171 case 30: prediction += coefficients[29] * (drflac_int64)pDecodedSamples[-30];
2172 case 29: prediction += coefficients[28] * (drflac_int64)pDecodedSamples[-29];
2173 case 28: prediction += coefficients[27] * (drflac_int64)pDecodedSamples[-28];
2174 case 27: prediction += coefficients[26] * (drflac_int64)pDecodedSamples[-27];
2175 case 26: prediction += coefficients[25] * (drflac_int64)pDecodedSamples[-26];
2176 case 25: prediction += coefficients[24] * (drflac_int64)pDecodedSamples[-25];
2177 case 24: prediction += coefficients[23] * (drflac_int64)pDecodedSamples[-24];
2178 case 23: prediction += coefficients[22] * (drflac_int64)pDecodedSamples[-23];
2179 case 22: prediction += coefficients[21] * (drflac_int64)pDecodedSamples[-22];
2180 case 21: prediction += coefficients[20] * (drflac_int64)pDecodedSamples[-21];
2181 case 20: prediction += coefficients[19] * (drflac_int64)pDecodedSamples[-20];
2182 case 19: prediction += coefficients[18] * (drflac_int64)pDecodedSamples[-19];
2183 case 18: prediction += coefficients[17] * (drflac_int64)pDecodedSamples[-18];
2184 case 17: prediction += coefficients[16] * (drflac_int64)pDecodedSamples[-17];
2185 case 16: prediction += coefficients[15] * (drflac_int64)pDecodedSamples[-16];
2186 case 15: prediction += coefficients[14] * (drflac_int64)pDecodedSamples[-15];
2187 case 14: prediction += coefficients[13] * (drflac_int64)pDecodedSamples[-14];
2188 case 13: prediction += coefficients[12] * (drflac_int64)pDecodedSamples[-13];
2189 case 12: prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
2190 case 11: prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
2191 case 10: prediction += coefficients[ 9] * (drflac_int64)pDecodedSamples[-10];
2192 case 9: prediction += coefficients[ 8] * (drflac_int64)pDecodedSamples[- 9];
2193 case 8: prediction += coefficients[ 7] * (drflac_int64)pDecodedSamples[- 8];
2194 case 7: prediction += coefficients[ 6] * (drflac_int64)pDecodedSamples[- 7];
2195 case 6: prediction += coefficients[ 5] * (drflac_int64)pDecodedSamples[- 6];
2196 case 5: prediction += coefficients[ 4] * (drflac_int64)pDecodedSamples[- 5];
2197 case 4: prediction += coefficients[ 3] * (drflac_int64)pDecodedSamples[- 4];
2198 case 3: prediction += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 3];
2199 case 2: prediction += coefficients[ 1] * (drflac_int64)pDecodedSamples[- 2];
2200 case 1: prediction += coefficients[ 0] * (drflac_int64)pDecodedSamples[- 1];
2202 #endif
2204 return (drflac_int32)(prediction >> shift);
2207 #if 0
2208 // Reference implementation for reading and decoding samples with residual. This is intentionally left unoptimized for the
2209 // sake of readability and should only be used as a reference.
2210 static drflac_bool32 drflac__decode_samples_with_residual__rice__reference(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
2212 drflac_assert(bs != NULL);
2213 drflac_assert(count > 0);
2214 drflac_assert(pSamplesOut != NULL);
2216 for (drflac_uint32 i = 0; i < count; ++i) {
2217 drflac_uint32 zeroCounter = 0;
2218 for (;;) {
2219 drflac_uint8 bit;
2220 if (!drflac__read_uint8(bs, 1, &bit)) {
2221 return DRFLAC_FALSE;
2224 if (bit == 0) {
2225 zeroCounter += 1;
2226 } else {
2227 break;
2231 drflac_uint32 decodedRice;
2232 if (riceParam > 0) {
2233 if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
2234 return DRFLAC_FALSE;
2236 } else {
2237 decodedRice = 0;
2240 decodedRice |= (zeroCounter << riceParam);
2241 if ((decodedRice & 0x01)) {
2242 decodedRice = ~(decodedRice >> 1);
2243 } else {
2244 decodedRice = (decodedRice >> 1);
2248 if (bitsPerSample > 16) {
2249 pSamplesOut[i] = decodedRice + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + i);
2250 } else {
2251 pSamplesOut[i] = decodedRice + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + i);
2255 return DRFLAC_TRUE;
2257 #endif
2259 #if 0
2260 static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
2262 drflac_uint32 zeroCounter = 0;
2263 for (;;) {
2264 drflac_uint8 bit;
2265 if (!drflac__read_uint8(bs, 1, &bit)) {
2266 return DRFLAC_FALSE;
2269 if (bit == 0) {
2270 zeroCounter += 1;
2271 } else {
2272 break;
2276 drflac_uint32 decodedRice;
2277 if (riceParam > 0) {
2278 if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
2279 return DRFLAC_FALSE;
2281 } else {
2282 decodedRice = 0;
2285 *pZeroCounterOut = zeroCounter;
2286 *pRiceParamPartOut = decodedRice;
2287 return DRFLAC_TRUE;
2289 #endif
2291 static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
2293 drflac_assert(riceParam > 0); // <-- riceParam should never be 0. drflac__read_rice_parts__param_equals_zero() should be used instead for this case.
2295 drflac_cache_t riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParam);
2297 drflac_uint32 zeroCounter = 0;
2298 while (bs->cache == 0) {
2299 zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2300 if (!drflac__reload_cache(bs)) {
2301 return DRFLAC_FALSE;
2305 drflac_uint32 setBitOffsetPlus1 = drflac__clz(bs->cache);
2306 zeroCounter += setBitOffsetPlus1;
2307 setBitOffsetPlus1 += 1;
2310 drflac_uint32 riceParamPart;
2311 drflac_uint32 riceLength = setBitOffsetPlus1 + riceParam;
2312 if (riceLength < DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2313 riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength));
2315 bs->consumedBits += riceLength;
2316 bs->cache <<= riceLength;
2317 } else {
2318 bs->consumedBits += riceLength;
2319 bs->cache <<= setBitOffsetPlus1 & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1); // <-- Equivalent to "if (setBitOffsetPlus1 < DRFLAC_CACHE_L1_SIZE_BITS(bs)) { bs->cache <<= setBitOffsetPlus1; }"
2321 // It straddles the cached data. It will never cover more than the next chunk. We just read the number in two parts and combine them.
2322 drflac_uint32 bitCountLo = bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs);
2323 drflac_cache_t resultHi = DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, riceParam); // <-- Use DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE() if ever this function allows riceParam=0.
2325 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
2326 #ifndef DR_FLAC_NO_CRC
2327 drflac__update_crc16(bs);
2328 #endif
2329 bs->cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
2330 bs->consumedBits = 0;
2331 #ifndef DR_FLAC_NO_CRC
2332 bs->crc16Cache = bs->cache;
2333 #endif
2334 } else {
2335 // Slow path. We need to fetch more data from the client.
2336 if (!drflac__reload_cache(bs)) {
2337 return DRFLAC_FALSE;
2341 riceParamPart = (drflac_uint32)(resultHi | DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo));
2343 bs->consumedBits += bitCountLo;
2344 bs->cache <<= bitCountLo;
2347 *pZeroCounterOut = zeroCounter;
2348 *pRiceParamPartOut = riceParamPart;
2349 return DRFLAC_TRUE;
2352 static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts__param_equals_zero(drflac_bs* bs, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
2354 drflac_cache_t riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(0);
2356 drflac_uint32 zeroCounter = 0;
2357 while (bs->cache == 0) {
2358 zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2359 if (!drflac__reload_cache(bs)) {
2360 return DRFLAC_FALSE;
2364 drflac_uint32 setBitOffsetPlus1 = drflac__clz(bs->cache);
2365 zeroCounter += setBitOffsetPlus1;
2366 setBitOffsetPlus1 += 1;
2369 drflac_uint32 riceParamPart;
2370 drflac_uint32 riceLength = setBitOffsetPlus1;
2371 if (riceLength < DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2372 riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength));
2374 bs->consumedBits += riceLength;
2375 bs->cache <<= riceLength;
2376 } else {
2377 // It straddles the cached data. It will never cover more than the next chunk. We just read the number in two parts and combine them.
2378 drflac_uint32 bitCountLo = riceLength + bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs);
2380 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
2381 #ifndef DR_FLAC_NO_CRC
2382 drflac__update_crc16(bs);
2383 #endif
2384 bs->cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
2385 bs->consumedBits = 0;
2386 #ifndef DR_FLAC_NO_CRC
2387 bs->crc16Cache = bs->cache;
2388 #endif
2389 } else {
2390 // Slow path. We need to fetch more data from the client.
2391 if (!drflac__reload_cache(bs)) {
2392 return DRFLAC_FALSE;
2396 riceParamPart = (drflac_uint32)(DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo));
2398 bs->consumedBits += bitCountLo;
2399 bs->cache <<= bitCountLo;
2402 *pZeroCounterOut = zeroCounter;
2403 *pRiceParamPartOut = riceParamPart;
2404 return DRFLAC_TRUE;
2408 static drflac_bool32 drflac__decode_samples_with_residual__rice__simple(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
2410 drflac_assert(bs != NULL);
2411 drflac_assert(count > 0);
2412 drflac_assert(pSamplesOut != NULL);
2414 static drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
2416 drflac_uint32 zeroCountPart0;
2417 drflac_uint32 zeroCountPart1;
2418 drflac_uint32 zeroCountPart2;
2419 drflac_uint32 zeroCountPart3;
2420 drflac_uint32 riceParamPart0;
2421 drflac_uint32 riceParamPart1;
2422 drflac_uint32 riceParamPart2;
2423 drflac_uint32 riceParamPart3;
2424 drflac_uint32 i4 = 0;
2425 drflac_uint32 count4 = count >> 2;
2426 while (i4 < count4) {
2427 // Rice extraction.
2428 if (!drflac__read_rice_parts(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
2429 !drflac__read_rice_parts(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
2430 !drflac__read_rice_parts(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
2431 !drflac__read_rice_parts(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
2432 return DRFLAC_FALSE;
2435 riceParamPart0 |= (zeroCountPart0 << riceParam);
2436 riceParamPart1 |= (zeroCountPart1 << riceParam);
2437 riceParamPart2 |= (zeroCountPart2 << riceParam);
2438 riceParamPart3 |= (zeroCountPart3 << riceParam);
2440 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
2441 riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
2442 riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
2443 riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
2445 if (bitsPerSample > 16) {
2446 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 0);
2447 pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 1);
2448 pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 2);
2449 pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 3);
2450 } else {
2451 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 0);
2452 pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 1);
2453 pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 2);
2454 pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 3);
2457 i4 += 1;
2458 pSamplesOut += 4;
2461 drflac_uint32 i = i4 << 2;
2462 while (i < count) {
2463 // Rice extraction.
2464 if (!drflac__read_rice_parts(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
2465 return DRFLAC_FALSE;
2468 // Rice reconstruction.
2469 riceParamPart0 |= (zeroCountPart0 << riceParam);
2470 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
2471 //riceParamPart0 = (riceParamPart0 >> 1) ^ (~(riceParamPart0 & 0x01) + 1);
2473 // Sample reconstruction.
2474 if (bitsPerSample > 16) {
2475 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 0);
2476 } else {
2477 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 0);
2480 i += 1;
2481 pSamplesOut += 1;
2484 return DRFLAC_TRUE;
2487 static drflac_bool32 drflac__decode_samples_with_residual__rice__param_equals_zero(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
2489 drflac_assert(bs != NULL);
2490 drflac_assert(count > 0);
2491 drflac_assert(pSamplesOut != NULL);
2493 static drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
2495 drflac_uint32 zeroCountPart0;
2496 drflac_uint32 zeroCountPart1;
2497 drflac_uint32 zeroCountPart2;
2498 drflac_uint32 zeroCountPart3;
2499 drflac_uint32 riceParamPart0;
2500 drflac_uint32 riceParamPart1;
2501 drflac_uint32 riceParamPart2;
2502 drflac_uint32 riceParamPart3;
2503 drflac_uint32 i4 = 0;
2504 drflac_uint32 count4 = count >> 2;
2505 while (i4 < count4) {
2506 // Rice extraction.
2507 if (!drflac__read_rice_parts__param_equals_zero(bs, &zeroCountPart0, &riceParamPart0) ||
2508 !drflac__read_rice_parts__param_equals_zero(bs, &zeroCountPart1, &riceParamPart1) ||
2509 !drflac__read_rice_parts__param_equals_zero(bs, &zeroCountPart2, &riceParamPart2) ||
2510 !drflac__read_rice_parts__param_equals_zero(bs, &zeroCountPart3, &riceParamPart3)) {
2511 return DRFLAC_FALSE;
2514 riceParamPart0 |= zeroCountPart0;
2515 riceParamPart1 |= zeroCountPart1;
2516 riceParamPart2 |= zeroCountPart2;
2517 riceParamPart3 |= zeroCountPart3;
2519 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
2520 riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
2521 riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
2522 riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
2524 if (bitsPerSample > 16) {
2525 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 0);
2526 pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 1);
2527 pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 2);
2528 pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 3);
2529 } else {
2530 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 0);
2531 pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 1);
2532 pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 2);
2533 pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 3);
2536 i4 += 1;
2537 pSamplesOut += 4;
2540 drflac_uint32 i = i4 << 2;
2541 while (i < count) {
2542 // Rice extraction.
2543 if (!drflac__read_rice_parts__param_equals_zero(bs, &zeroCountPart0, &riceParamPart0)) {
2544 return DRFLAC_FALSE;
2547 // Rice reconstruction.
2548 riceParamPart0 |= zeroCountPart0;
2549 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
2551 // Sample reconstruction.
2552 if (bitsPerSample > 16) {
2553 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 0);
2554 } else {
2555 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 0);
2558 i += 1;
2559 pSamplesOut += 1;
2562 return DRFLAC_TRUE;
2565 static drflac_bool32 drflac__decode_samples_with_residual__rice(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
2567 #if 0
2568 return drflac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut);
2569 #else
2570 if (riceParam != 0) {
2571 return drflac__decode_samples_with_residual__rice__simple(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut);
2572 } else {
2573 return drflac__decode_samples_with_residual__rice__param_equals_zero(bs, bitsPerSample, count, order, shift, coefficients, pSamplesOut);
2575 #endif
2578 // Reads and seeks past a string of residual values as Rice codes. The decoder should be sitting on the first bit of the Rice codes.
2579 static drflac_bool32 drflac__read_and_seek_residual__rice(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam)
2581 drflac_assert(bs != NULL);
2582 drflac_assert(count > 0);
2584 drflac_uint32 zeroCountPart;
2585 drflac_uint32 riceParamPart;
2587 if (riceParam != 0) {
2588 for (drflac_uint32 i = 0; i < count; ++i) {
2589 if (!drflac__read_rice_parts(bs, riceParam, &zeroCountPart, &riceParamPart)) {
2590 return DRFLAC_FALSE;
2593 } else {
2594 for (drflac_uint32 i = 0; i < count; ++i) {
2595 if (!drflac__read_rice_parts__param_equals_zero(bs, &zeroCountPart, &riceParamPart)) {
2596 return DRFLAC_FALSE;
2601 return DRFLAC_TRUE;
2604 static drflac_bool32 drflac__decode_samples_with_residual__unencoded(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 unencodedBitsPerSample, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
2606 drflac_assert(bs != NULL);
2607 drflac_assert(count > 0);
2608 drflac_assert(unencodedBitsPerSample <= 31); // <-- unencodedBitsPerSample is a 5 bit number, so cannot exceed 31.
2609 drflac_assert(pSamplesOut != NULL);
2611 for (unsigned int i = 0; i < count; ++i) {
2612 if (unencodedBitsPerSample > 0) {
2613 if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i)) {
2614 return DRFLAC_FALSE;
2616 } else {
2617 pSamplesOut[i] = 0;
2620 if (bitsPerSample > 16) {
2621 pSamplesOut[i] += drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + i);
2622 } else {
2623 pSamplesOut[i] += drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + i);
2627 return DRFLAC_TRUE;
2631 // Reads and decodes the residual for the sub-frame the decoder is currently sitting on. This function should be called
2632 // when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be ignored. The
2633 // <blockSize> and <order> parameters are used to determine how many residual values need to be decoded.
2634 static drflac_bool32 drflac__decode_samples_with_residual(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 blockSize, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
2636 drflac_assert(bs != NULL);
2637 drflac_assert(blockSize != 0);
2638 drflac_assert(pDecodedSamples != NULL); // <-- Should we allow NULL, in which case we just seek past the residual rather than do a full decode?
2640 drflac_uint8 residualMethod;
2641 if (!drflac__read_uint8(bs, 2, &residualMethod)) {
2642 return DRFLAC_FALSE;
2645 if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
2646 return DRFLAC_FALSE; // Unknown or unsupported residual coding method.
2649 // Ignore the first <order> values.
2650 pDecodedSamples += order;
2653 drflac_uint8 partitionOrder;
2654 if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
2655 return DRFLAC_FALSE;
2658 // From the FLAC spec:
2659 // The Rice partition order in a Rice-coded residual section must be less than or equal to 8.
2660 if (partitionOrder > 8) {
2661 return DRFLAC_FALSE;
2664 // Validation check.
2665 if ((blockSize / (1 << partitionOrder)) <= order) {
2666 return DRFLAC_FALSE;
2669 drflac_uint32 samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
2670 drflac_uint32 partitionsRemaining = (1 << partitionOrder);
2671 for (;;) {
2672 drflac_uint8 riceParam = 0;
2673 if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
2674 if (!drflac__read_uint8(bs, 4, &riceParam)) {
2675 return DRFLAC_FALSE;
2677 if (riceParam == 15) {
2678 riceParam = 0xFF;
2680 } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
2681 if (!drflac__read_uint8(bs, 5, &riceParam)) {
2682 return DRFLAC_FALSE;
2684 if (riceParam == 31) {
2685 riceParam = 0xFF;
2689 if (riceParam != 0xFF) {
2690 if (!drflac__decode_samples_with_residual__rice(bs, bitsPerSample, samplesInPartition, riceParam, order, shift, coefficients, pDecodedSamples)) {
2691 return DRFLAC_FALSE;
2693 } else {
2694 unsigned char unencodedBitsPerSample = 0;
2695 if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
2696 return DRFLAC_FALSE;
2699 if (!drflac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, order, shift, coefficients, pDecodedSamples)) {
2700 return DRFLAC_FALSE;
2704 pDecodedSamples += samplesInPartition;
2707 if (partitionsRemaining == 1) {
2708 break;
2711 partitionsRemaining -= 1;
2713 if (partitionOrder != 0) {
2714 samplesInPartition = blockSize / (1 << partitionOrder);
2718 return DRFLAC_TRUE;
2721 // Reads and seeks past the residual for the sub-frame the decoder is currently sitting on. This function should be called
2722 // when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be set to 0. The
2723 // <blockSize> and <order> parameters are used to determine how many residual values need to be decoded.
2724 static drflac_bool32 drflac__read_and_seek_residual(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 order)
2726 drflac_assert(bs != NULL);
2727 drflac_assert(blockSize != 0);
2729 drflac_uint8 residualMethod;
2730 if (!drflac__read_uint8(bs, 2, &residualMethod)) {
2731 return DRFLAC_FALSE;
2734 if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
2735 return DRFLAC_FALSE; // Unknown or unsupported residual coding method.
2738 drflac_uint8 partitionOrder;
2739 if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
2740 return DRFLAC_FALSE;
2743 // From the FLAC spec:
2744 // The Rice partition order in a Rice-coded residual section must be less than or equal to 8.
2745 if (partitionOrder > 8) {
2746 return DRFLAC_FALSE;
2749 // Validation check.
2750 if ((blockSize / (1 << partitionOrder)) <= order) {
2751 return DRFLAC_FALSE;
2754 drflac_uint32 samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
2755 drflac_uint32 partitionsRemaining = (1 << partitionOrder);
2756 for (;;)
2758 drflac_uint8 riceParam = 0;
2759 if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
2760 if (!drflac__read_uint8(bs, 4, &riceParam)) {
2761 return DRFLAC_FALSE;
2763 if (riceParam == 15) {
2764 riceParam = 0xFF;
2766 } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
2767 if (!drflac__read_uint8(bs, 5, &riceParam)) {
2768 return DRFLAC_FALSE;
2770 if (riceParam == 31) {
2771 riceParam = 0xFF;
2775 if (riceParam != 0xFF) {
2776 if (!drflac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) {
2777 return DRFLAC_FALSE;
2779 } else {
2780 unsigned char unencodedBitsPerSample = 0;
2781 if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
2782 return DRFLAC_FALSE;
2785 if (!drflac__seek_bits(bs, unencodedBitsPerSample * samplesInPartition)) {
2786 return DRFLAC_FALSE;
2791 if (partitionsRemaining == 1) {
2792 break;
2795 partitionsRemaining -= 1;
2796 samplesInPartition = blockSize / (1 << partitionOrder);
2799 return DRFLAC_TRUE;
2803 static drflac_bool32 drflac__decode_samples__constant(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_int32* pDecodedSamples)
2805 // Only a single sample needs to be decoded here.
2806 drflac_int32 sample;
2807 if (!drflac__read_int32(bs, bitsPerSample, &sample)) {
2808 return DRFLAC_FALSE;
2811 // We don't really need to expand this, but it does simplify the process of reading samples. If this becomes a performance issue (unlikely)
2812 // we'll want to look at a more efficient way.
2813 for (drflac_uint32 i = 0; i < blockSize; ++i) {
2814 pDecodedSamples[i] = sample;
2817 return DRFLAC_TRUE;
2820 static drflac_bool32 drflac__decode_samples__verbatim(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_int32* pDecodedSamples)
2822 for (drflac_uint32 i = 0; i < blockSize; ++i) {
2823 drflac_int32 sample;
2824 if (!drflac__read_int32(bs, bitsPerSample, &sample)) {
2825 return DRFLAC_FALSE;
2828 pDecodedSamples[i] = sample;
2831 return DRFLAC_TRUE;
2834 static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
2836 drflac_int32 lpcCoefficientsTable[5][4] = {
2837 {0, 0, 0, 0},
2838 {1, 0, 0, 0},
2839 {2, -1, 0, 0},
2840 {3, -3, 1, 0},
2841 {4, -6, 4, -1}
2844 // Warm up samples and coefficients.
2845 for (drflac_uint32 i = 0; i < lpcOrder; ++i) {
2846 drflac_int32 sample;
2847 if (!drflac__read_int32(bs, bitsPerSample, &sample)) {
2848 return DRFLAC_FALSE;
2851 pDecodedSamples[i] = sample;
2855 if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, 0, lpcCoefficientsTable[lpcOrder], pDecodedSamples)) {
2856 return DRFLAC_FALSE;
2859 return DRFLAC_TRUE;
2862 static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
2864 drflac_uint8 i;
2866 // Warm up samples.
2867 for (i = 0; i < lpcOrder; ++i) {
2868 drflac_int32 sample;
2869 if (!drflac__read_int32(bs, bitsPerSample, &sample)) {
2870 return DRFLAC_FALSE;
2873 pDecodedSamples[i] = sample;
2876 drflac_uint8 lpcPrecision;
2877 if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
2878 return DRFLAC_FALSE;
2880 if (lpcPrecision == 15) {
2881 return DRFLAC_FALSE; // Invalid.
2883 lpcPrecision += 1;
2886 drflac_int8 lpcShift;
2887 if (!drflac__read_int8(bs, 5, &lpcShift)) {
2888 return DRFLAC_FALSE;
2892 drflac_int32 coefficients[32];
2893 for (i = 0; i < lpcOrder; ++i) {
2894 if (!drflac__read_int32(bs, lpcPrecision, coefficients + i)) {
2895 return DRFLAC_FALSE;
2899 if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, coefficients, pDecodedSamples)) {
2900 return DRFLAC_FALSE;
2903 return DRFLAC_TRUE;
2907 static drflac_bool32 drflac__read_next_frame_header(drflac_bs* bs, drflac_uint8 streaminfoBitsPerSample, drflac_frame_header* header)
2909 drflac_assert(bs != NULL);
2910 drflac_assert(header != NULL);
2912 const drflac_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000};
2913 const drflac_uint8 bitsPerSampleTable[8] = {0, 8, 12, (drflac_uint8)-1, 16, 20, 24, (drflac_uint8)-1}; // -1 = reserved.
2915 // Keep looping until we find a valid sync code.
2916 for (;;) {
2917 if (!drflac__find_and_seek_to_next_sync_code(bs)) {
2918 return DRFLAC_FALSE;
2921 drflac_uint8 crc8 = 0xCE; // 0xCE = drflac_crc8(0, 0x3FFE, 14);
2923 drflac_uint8 reserved = 0;
2924 if (!drflac__read_uint8(bs, 1, &reserved)) {
2925 return DRFLAC_FALSE;
2927 if (reserved == 1) {
2928 continue;
2930 crc8 = drflac_crc8(crc8, reserved, 1);
2933 drflac_uint8 blockingStrategy = 0;
2934 if (!drflac__read_uint8(bs, 1, &blockingStrategy)) {
2935 return DRFLAC_FALSE;
2937 crc8 = drflac_crc8(crc8, blockingStrategy, 1);
2940 drflac_uint8 blockSize = 0;
2941 if (!drflac__read_uint8(bs, 4, &blockSize)) {
2942 return DRFLAC_FALSE;
2944 if (blockSize == 0) {
2945 continue;
2947 crc8 = drflac_crc8(crc8, blockSize, 4);
2950 drflac_uint8 sampleRate = 0;
2951 if (!drflac__read_uint8(bs, 4, &sampleRate)) {
2952 return DRFLAC_FALSE;
2954 crc8 = drflac_crc8(crc8, sampleRate, 4);
2957 drflac_uint8 channelAssignment = 0;
2958 if (!drflac__read_uint8(bs, 4, &channelAssignment)) {
2959 return DRFLAC_FALSE;
2961 if (channelAssignment > 10) {
2962 continue;
2964 crc8 = drflac_crc8(crc8, channelAssignment, 4);
2967 drflac_uint8 bitsPerSample = 0;
2968 if (!drflac__read_uint8(bs, 3, &bitsPerSample)) {
2969 return DRFLAC_FALSE;
2971 if (bitsPerSample == 3 || bitsPerSample == 7) {
2972 continue;
2974 crc8 = drflac_crc8(crc8, bitsPerSample, 3);
2977 if (!drflac__read_uint8(bs, 1, &reserved)) {
2978 return DRFLAC_FALSE;
2980 if (reserved == 1) {
2981 continue;
2983 crc8 = drflac_crc8(crc8, reserved, 1);
2986 drflac_bool32 isVariableBlockSize = blockingStrategy == 1;
2987 if (isVariableBlockSize) {
2988 drflac_uint64 sampleNumber;
2989 drflac_result result = drflac__read_utf8_coded_number(bs, &sampleNumber, &crc8);
2990 if (result != DRFLAC_SUCCESS) {
2991 if (result == DRFLAC_END_OF_STREAM) {
2992 return DRFLAC_FALSE;
2993 } else {
2994 continue;
2997 header->frameNumber = 0;
2998 header->sampleNumber = sampleNumber;
2999 } else {
3000 drflac_uint64 frameNumber = 0;
3001 drflac_result result = drflac__read_utf8_coded_number(bs, &frameNumber, &crc8);
3002 if (result != DRFLAC_SUCCESS) {
3003 if (result == DRFLAC_END_OF_STREAM) {
3004 return DRFLAC_FALSE;
3005 } else {
3006 continue;
3009 header->frameNumber = (drflac_uint32)frameNumber; // <-- Safe cast.
3010 header->sampleNumber = 0;
3014 if (blockSize == 1) {
3015 header->blockSize = 192;
3016 } else if (blockSize >= 2 && blockSize <= 5) {
3017 header->blockSize = 576 * (1 << (blockSize - 2));
3018 } else if (blockSize == 6) {
3019 if (!drflac__read_uint16(bs, 8, &header->blockSize)) {
3020 return DRFLAC_FALSE;
3022 crc8 = drflac_crc8(crc8, header->blockSize, 8);
3023 header->blockSize += 1;
3024 } else if (blockSize == 7) {
3025 if (!drflac__read_uint16(bs, 16, &header->blockSize)) {
3026 return DRFLAC_FALSE;
3028 crc8 = drflac_crc8(crc8, header->blockSize, 16);
3029 header->blockSize += 1;
3030 } else {
3031 header->blockSize = 256 * (1 << (blockSize - 8));
3035 if (sampleRate <= 11) {
3036 header->sampleRate = sampleRateTable[sampleRate];
3037 } else if (sampleRate == 12) {
3038 if (!drflac__read_uint32(bs, 8, &header->sampleRate)) {
3039 return DRFLAC_FALSE;
3041 crc8 = drflac_crc8(crc8, header->sampleRate, 8);
3042 header->sampleRate *= 1000;
3043 } else if (sampleRate == 13) {
3044 if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
3045 return DRFLAC_FALSE;
3047 crc8 = drflac_crc8(crc8, header->sampleRate, 16);
3048 } else if (sampleRate == 14) {
3049 if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
3050 return DRFLAC_FALSE;
3052 crc8 = drflac_crc8(crc8, header->sampleRate, 16);
3053 header->sampleRate *= 10;
3054 } else {
3055 continue; // Invalid. Assume an invalid block.
3059 header->channelAssignment = channelAssignment;
3061 header->bitsPerSample = bitsPerSampleTable[bitsPerSample];
3062 if (header->bitsPerSample == 0) {
3063 header->bitsPerSample = streaminfoBitsPerSample;
3066 if (!drflac__read_uint8(bs, 8, &header->crc8)) {
3067 return DRFLAC_FALSE;
3070 #ifndef DR_FLAC_NO_CRC
3071 if (header->crc8 != crc8) {
3072 continue; // CRC mismatch. Loop back to the top and find the next sync code.
3074 #endif
3075 return DRFLAC_TRUE;
3079 static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe* pSubframe)
3081 drflac_uint8 header;
3082 if (!drflac__read_uint8(bs, 8, &header)) {
3083 return DRFLAC_FALSE;
3086 // First bit should always be 0.
3087 if ((header & 0x80) != 0) {
3088 return DRFLAC_FALSE;
3091 int type = (header & 0x7E) >> 1;
3092 if (type == 0) {
3093 pSubframe->subframeType = DRFLAC_SUBFRAME_CONSTANT;
3094 } else if (type == 1) {
3095 pSubframe->subframeType = DRFLAC_SUBFRAME_VERBATIM;
3096 } else {
3097 if ((type & 0x20) != 0) {
3098 pSubframe->subframeType = DRFLAC_SUBFRAME_LPC;
3099 pSubframe->lpcOrder = (type & 0x1F) + 1;
3100 } else if ((type & 0x08) != 0) {
3101 pSubframe->subframeType = DRFLAC_SUBFRAME_FIXED;
3102 pSubframe->lpcOrder = (type & 0x07);
3103 if (pSubframe->lpcOrder > 4) {
3104 pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
3105 pSubframe->lpcOrder = 0;
3107 } else {
3108 pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
3112 if (pSubframe->subframeType == DRFLAC_SUBFRAME_RESERVED) {
3113 return DRFLAC_FALSE;
3116 // Wasted bits per sample.
3117 pSubframe->wastedBitsPerSample = 0;
3118 if ((header & 0x01) == 1) {
3119 unsigned int wastedBitsPerSample;
3120 if (!drflac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) {
3121 return DRFLAC_FALSE;
3123 pSubframe->wastedBitsPerSample = (unsigned char)wastedBitsPerSample + 1;
3126 return DRFLAC_TRUE;
3129 static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex, drflac_int32* pDecodedSamplesOut)
3131 drflac_assert(bs != NULL);
3132 drflac_assert(frame != NULL);
3134 drflac_subframe* pSubframe = frame->subframes + subframeIndex;
3135 if (!drflac__read_subframe_header(bs, pSubframe)) {
3136 return DRFLAC_FALSE;
3139 // Side channels require an extra bit per sample. Took a while to figure that one out...
3140 pSubframe->bitsPerSample = frame->header.bitsPerSample;
3141 if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
3142 pSubframe->bitsPerSample += 1;
3143 } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
3144 pSubframe->bitsPerSample += 1;
3147 // Need to handle wasted bits per sample.
3148 if (pSubframe->wastedBitsPerSample >= pSubframe->bitsPerSample) {
3149 return DRFLAC_FALSE;
3151 pSubframe->bitsPerSample -= pSubframe->wastedBitsPerSample;
3152 pSubframe->pDecodedSamples = pDecodedSamplesOut;
3154 switch (pSubframe->subframeType)
3156 case DRFLAC_SUBFRAME_CONSTANT:
3158 drflac__decode_samples__constant(bs, frame->header.blockSize, pSubframe->bitsPerSample, pSubframe->pDecodedSamples);
3159 } break;
3161 case DRFLAC_SUBFRAME_VERBATIM:
3163 drflac__decode_samples__verbatim(bs, frame->header.blockSize, pSubframe->bitsPerSample, pSubframe->pDecodedSamples);
3164 } break;
3166 case DRFLAC_SUBFRAME_FIXED:
3168 drflac__decode_samples__fixed(bs, frame->header.blockSize, pSubframe->bitsPerSample, pSubframe->lpcOrder, pSubframe->pDecodedSamples);
3169 } break;
3171 case DRFLAC_SUBFRAME_LPC:
3173 drflac__decode_samples__lpc(bs, frame->header.blockSize, pSubframe->bitsPerSample, pSubframe->lpcOrder, pSubframe->pDecodedSamples);
3174 } break;
3176 default: return DRFLAC_FALSE;
3179 return DRFLAC_TRUE;
3182 static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex)
3184 drflac_assert(bs != NULL);
3185 drflac_assert(frame != NULL);
3187 drflac_subframe* pSubframe = frame->subframes + subframeIndex;
3188 if (!drflac__read_subframe_header(bs, pSubframe)) {
3189 return DRFLAC_FALSE;
3192 // Side channels require an extra bit per sample. Took a while to figure that one out...
3193 pSubframe->bitsPerSample = frame->header.bitsPerSample;
3194 if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
3195 pSubframe->bitsPerSample += 1;
3196 } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
3197 pSubframe->bitsPerSample += 1;
3200 // Need to handle wasted bits per sample.
3201 if (pSubframe->wastedBitsPerSample >= pSubframe->bitsPerSample) {
3202 return DRFLAC_FALSE;
3204 pSubframe->bitsPerSample -= pSubframe->wastedBitsPerSample;
3205 pSubframe->pDecodedSamples = NULL;
3207 switch (pSubframe->subframeType)
3209 case DRFLAC_SUBFRAME_CONSTANT:
3211 if (!drflac__seek_bits(bs, pSubframe->bitsPerSample)) {
3212 return DRFLAC_FALSE;
3214 } break;
3216 case DRFLAC_SUBFRAME_VERBATIM:
3218 unsigned int bitsToSeek = frame->header.blockSize * pSubframe->bitsPerSample;
3219 if (!drflac__seek_bits(bs, bitsToSeek)) {
3220 return DRFLAC_FALSE;
3222 } break;
3224 case DRFLAC_SUBFRAME_FIXED:
3226 unsigned int bitsToSeek = pSubframe->lpcOrder * pSubframe->bitsPerSample;
3227 if (!drflac__seek_bits(bs, bitsToSeek)) {
3228 return DRFLAC_FALSE;
3231 if (!drflac__read_and_seek_residual(bs, frame->header.blockSize, pSubframe->lpcOrder)) {
3232 return DRFLAC_FALSE;
3234 } break;
3236 case DRFLAC_SUBFRAME_LPC:
3238 unsigned int bitsToSeek = pSubframe->lpcOrder * pSubframe->bitsPerSample;
3239 if (!drflac__seek_bits(bs, bitsToSeek)) {
3240 return DRFLAC_FALSE;
3243 unsigned char lpcPrecision;
3244 if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
3245 return DRFLAC_FALSE;
3247 if (lpcPrecision == 15) {
3248 return DRFLAC_FALSE; // Invalid.
3250 lpcPrecision += 1;
3253 bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5; // +5 for shift.
3254 if (!drflac__seek_bits(bs, bitsToSeek)) {
3255 return DRFLAC_FALSE;
3258 if (!drflac__read_and_seek_residual(bs, frame->header.blockSize, pSubframe->lpcOrder)) {
3259 return DRFLAC_FALSE;
3261 } break;
3263 default: return DRFLAC_FALSE;
3266 return DRFLAC_TRUE;
3270 static DRFLAC_INLINE drflac_uint8 drflac__get_channel_count_from_channel_assignment(drflac_int8 channelAssignment)
3272 drflac_assert(channelAssignment <= 10);
3274 drflac_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2};
3275 return lookup[channelAssignment];
3278 static drflac_result drflac__decode_frame(drflac* pFlac)
3280 // This function should be called while the stream is sitting on the first byte after the frame header.
3281 drflac_zero_memory(pFlac->currentFrame.subframes, sizeof(pFlac->currentFrame.subframes));
3283 // The frame block size must never be larger than the maximum block size defined by the FLAC stream.
3284 if (pFlac->currentFrame.header.blockSize > pFlac->maxBlockSize) {
3285 return DRFLAC_ERROR;
3288 // The number of channels in the frame must match the channel count from the STREAMINFO block.
3289 int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment);
3290 if (channelCount != (int)pFlac->channels) {
3291 return DRFLAC_ERROR;
3294 for (int i = 0; i < channelCount; ++i) {
3295 if (!drflac__decode_subframe(&pFlac->bs, &pFlac->currentFrame, i, pFlac->pDecodedSamples + (pFlac->currentFrame.header.blockSize * i))) {
3296 return DRFLAC_ERROR;
3300 drflac_uint8 paddingSizeInBits = DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7;
3301 if (paddingSizeInBits > 0) {
3302 drflac_uint8 padding = 0;
3303 if (!drflac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding)) {
3304 return DRFLAC_END_OF_STREAM;
3308 #ifndef DR_FLAC_NO_CRC
3309 drflac_uint16 actualCRC16 = drflac__flush_crc16(&pFlac->bs);
3310 #endif
3311 drflac_uint16 desiredCRC16;
3312 if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
3313 return DRFLAC_END_OF_STREAM;
3316 #ifndef DR_FLAC_NO_CRC
3317 if (actualCRC16 != desiredCRC16) {
3318 return DRFLAC_CRC_MISMATCH; // CRC mismatch.
3320 #endif
3322 pFlac->currentFrame.samplesRemaining = pFlac->currentFrame.header.blockSize * channelCount;
3324 return DRFLAC_SUCCESS;
3327 static drflac_result drflac__seek_frame(drflac* pFlac)
3329 int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment);
3330 for (int i = 0; i < channelCount; ++i) {
3331 if (!drflac__seek_subframe(&pFlac->bs, &pFlac->currentFrame, i)) {
3332 return DRFLAC_ERROR;
3336 // Padding.
3337 if (!drflac__seek_bits(&pFlac->bs, DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7)) {
3338 return DRFLAC_ERROR;
3341 // CRC.
3342 #ifndef DR_FLAC_NO_CRC
3343 drflac_uint16 actualCRC16 = drflac__flush_crc16(&pFlac->bs);
3344 #endif
3345 drflac_uint16 desiredCRC16;
3346 if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
3347 return DRFLAC_END_OF_STREAM;
3350 #ifndef DR_FLAC_NO_CRC
3351 if (actualCRC16 != desiredCRC16) {
3352 return DRFLAC_CRC_MISMATCH; // CRC mismatch.
3354 #endif
3356 return DRFLAC_SUCCESS;
3359 static drflac_bool32 drflac__read_and_decode_next_frame(drflac* pFlac)
3361 drflac_assert(pFlac != NULL);
3363 for (;;) {
3364 if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) {
3365 return DRFLAC_FALSE;
3368 drflac_result result = drflac__decode_frame(pFlac);
3369 if (result != DRFLAC_SUCCESS) {
3370 if (result == DRFLAC_CRC_MISMATCH) {
3371 continue; // CRC mismatch. Skip to the next frame.
3372 } else {
3373 return DRFLAC_FALSE;
3377 return DRFLAC_TRUE;
3382 static void drflac__get_current_frame_sample_range(drflac* pFlac, drflac_uint64* pFirstSampleInFrameOut, drflac_uint64* pLastSampleInFrameOut)
3384 drflac_assert(pFlac != NULL);
3386 unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment);
3388 drflac_uint64 firstSampleInFrame = pFlac->currentFrame.header.sampleNumber;
3389 if (firstSampleInFrame == 0) {
3390 firstSampleInFrame = pFlac->currentFrame.header.frameNumber * pFlac->maxBlockSize*channelCount;
3393 drflac_uint64 lastSampleInFrame = firstSampleInFrame + (pFlac->currentFrame.header.blockSize*channelCount);
3394 if (lastSampleInFrame > 0) {
3395 lastSampleInFrame -= 1; // Needs to be zero based.
3398 if (pFirstSampleInFrameOut) *pFirstSampleInFrameOut = firstSampleInFrame;
3399 if (pLastSampleInFrameOut) *pLastSampleInFrameOut = lastSampleInFrame;
3402 static drflac_bool32 drflac__seek_to_first_frame(drflac* pFlac)
3404 drflac_assert(pFlac != NULL);
3406 drflac_bool32 result = drflac__seek_to_byte(&pFlac->bs, pFlac->firstFramePos);
3408 drflac_zero_memory(&pFlac->currentFrame, sizeof(pFlac->currentFrame));
3409 pFlac->currentSample = 0;
3411 return result;
3414 static DRFLAC_INLINE drflac_result drflac__seek_to_next_frame(drflac* pFlac)
3416 // This function should only ever be called while the decoder is sitting on the first byte past the FRAME_HEADER section.
3417 drflac_assert(pFlac != NULL);
3418 return drflac__seek_frame(pFlac);
3421 static drflac_bool32 drflac__seek_to_sample__brute_force(drflac* pFlac, drflac_uint64 sampleIndex)
3423 drflac_assert(pFlac != NULL);
3425 drflac_bool32 isMidFrame = DRFLAC_FALSE;
3427 // If we are seeking forward we start from the current position. Otherwise we need to start all the way from the start of the file.
3428 drflac_uint64 runningSampleCount;
3429 if (sampleIndex >= pFlac->currentSample) {
3430 // Seeking forward. Need to seek from the current position.
3431 runningSampleCount = pFlac->currentSample;
3433 // The frame header for the first frame may not yet have been read. We need to do that if necessary.
3434 if (pFlac->currentSample == 0 && pFlac->currentFrame.samplesRemaining == 0) {
3435 if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) {
3436 return DRFLAC_FALSE;
3438 } else {
3439 isMidFrame = DRFLAC_TRUE;
3441 } else {
3442 // Seeking backwards. Need to seek from the start of the file.
3443 runningSampleCount = 0;
3445 // Move back to the start.
3446 if (!drflac__seek_to_first_frame(pFlac)) {
3447 return DRFLAC_FALSE;
3450 // Decode the first frame in preparation for sample-exact seeking below.
3451 if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) {
3452 return DRFLAC_FALSE;
3456 // We need to as quickly as possible find the frame that contains the target sample. To do this, we iterate over each frame and inspect its
3457 // header. If based on the header we can determine that the frame contains the sample, we do a full decode of that frame.
3458 for (;;) {
3459 drflac_uint64 firstSampleInFrame = 0;
3460 drflac_uint64 lastSampleInFrame = 0;
3461 drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame);
3463 drflac_uint64 sampleCountInThisFrame = (lastSampleInFrame - firstSampleInFrame) + 1;
3464 if (sampleIndex < (runningSampleCount + sampleCountInThisFrame)) {
3465 // The sample should be in this frame. We need to fully decode it, however if it's an invalid frame (a CRC mismatch), we need to pretend
3466 // it never existed and keep iterating.
3467 drflac_uint64 samplesToDecode = sampleIndex - runningSampleCount;
3469 if (!isMidFrame) {
3470 drflac_result result = drflac__decode_frame(pFlac);
3471 if (result == DRFLAC_SUCCESS) {
3472 // The frame is valid. We just need to skip over some samples to ensure it's sample-exact.
3473 return drflac_read_s32(pFlac, samplesToDecode, NULL) == samplesToDecode; // <-- If this fails, something bad has happened (it should never fail).
3474 } else {
3475 if (result == DRFLAC_CRC_MISMATCH) {
3476 goto next_iteration; // CRC mismatch. Pretend this frame never existed.
3477 } else {
3478 return DRFLAC_FALSE;
3481 } else {
3482 // We started seeking mid-frame which means we need to skip the frame decoding part.
3483 return drflac_read_s32(pFlac, samplesToDecode, NULL) == samplesToDecode;
3485 } else {
3486 // It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this
3487 // frame never existed and leave the running sample count untouched.
3488 if (!isMidFrame) {
3489 drflac_result result = drflac__seek_to_next_frame(pFlac);
3490 if (result == DRFLAC_SUCCESS) {
3491 runningSampleCount += sampleCountInThisFrame;
3492 } else {
3493 if (result == DRFLAC_CRC_MISMATCH) {
3494 goto next_iteration; // CRC mismatch. Pretend this frame never existed.
3495 } else {
3496 return DRFLAC_FALSE;
3499 } else {
3500 // We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with
3501 // drflac__seek_to_next_frame() which only works if the decoder is sitting on the byte just after the frame header.
3502 runningSampleCount += pFlac->currentFrame.samplesRemaining;
3503 pFlac->currentFrame.samplesRemaining = 0;
3504 isMidFrame = DRFLAC_FALSE;
3508 next_iteration:
3509 // Grab the next frame in preparation for the next iteration.
3510 if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) {
3511 return DRFLAC_FALSE;
3517 static drflac_bool32 drflac__seek_to_sample__seek_table(drflac* pFlac, drflac_uint64 sampleIndex)
3519 drflac_assert(pFlac != NULL);
3521 if (pFlac->pSeekpoints == NULL || pFlac->seekpointCount == 0) {
3522 return DRFLAC_FALSE;
3526 drflac_uint32 iClosestSeekpoint = 0;
3527 for (drflac_uint32 iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
3528 if (pFlac->pSeekpoints[iSeekpoint].firstSample*pFlac->channels >= sampleIndex) {
3529 break;
3532 iClosestSeekpoint = iSeekpoint;
3536 drflac_bool32 isMidFrame = DRFLAC_FALSE;
3538 // At this point we should have found the seekpoint closest to our sample. If we are seeking forward and the closest seekpoint is _before_ the current sample, we
3539 // just seek forward from where we are. Otherwise we start seeking from the seekpoint's first sample.
3540 drflac_uint64 runningSampleCount;
3541 if ((sampleIndex >= pFlac->currentSample) && (pFlac->pSeekpoints[iClosestSeekpoint].firstSample*pFlac->channels <= pFlac->currentSample)) {
3542 // Optimized case. Just seek forward from where we are.
3543 runningSampleCount = pFlac->currentSample;
3545 // The frame header for the first frame may not yet have been read. We need to do that if necessary.
3546 if (pFlac->currentSample == 0 && pFlac->currentFrame.samplesRemaining == 0) {
3547 if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) {
3548 return DRFLAC_FALSE;
3550 } else {
3551 isMidFrame = DRFLAC_TRUE;
3553 } else {
3554 // Slower case. Seek to the start of the seekpoint and then seek forward from there.
3555 runningSampleCount = pFlac->pSeekpoints[iClosestSeekpoint].firstSample*pFlac->channels;
3557 if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFramePos + pFlac->pSeekpoints[iClosestSeekpoint].frameOffset)) {
3558 return DRFLAC_FALSE;
3561 // Grab the frame the seekpoint is sitting on in preparation for the sample-exact seeking below.
3562 if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) {
3563 return DRFLAC_FALSE;
3567 for (;;) {
3568 drflac_uint64 firstSampleInFrame = 0;
3569 drflac_uint64 lastSampleInFrame = 0;
3570 drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame);
3572 drflac_uint64 sampleCountInThisFrame = (lastSampleInFrame - firstSampleInFrame) + 1;
3573 if (sampleIndex < (runningSampleCount + sampleCountInThisFrame)) {
3574 // The sample should be in this frame. We need to fully decode it, but if it's an invalid frame (a CRC mismatch) we need to pretend
3575 // it never existed and keep iterating.
3576 drflac_uint64 samplesToDecode = sampleIndex - runningSampleCount;
3578 if (!isMidFrame) {
3579 drflac_result result = drflac__decode_frame(pFlac);
3580 if (result == DRFLAC_SUCCESS) {
3581 // The frame is valid. We just need to skip over some samples to ensure it's sample-exact.
3582 return drflac_read_s32(pFlac, samplesToDecode, NULL) == samplesToDecode; // <-- If this fails, something bad has happened (it should never fail).
3583 } else {
3584 if (result == DRFLAC_CRC_MISMATCH) {
3585 goto next_iteration; // CRC mismatch. Pretend this frame never existed.
3586 } else {
3587 return DRFLAC_FALSE;
3590 } else {
3591 // We started seeking mid-frame which means we need to skip the frame decoding part.
3592 return drflac_read_s32(pFlac, samplesToDecode, NULL) == samplesToDecode;
3594 } else {
3595 // It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this
3596 // frame never existed and leave the running sample count untouched.
3597 if (!isMidFrame) {
3598 drflac_result result = drflac__seek_to_next_frame(pFlac);
3599 if (result == DRFLAC_SUCCESS) {
3600 runningSampleCount += sampleCountInThisFrame;
3601 } else {
3602 if (result == DRFLAC_CRC_MISMATCH) {
3603 goto next_iteration; // CRC mismatch. Pretend this frame never existed.
3604 } else {
3605 return DRFLAC_FALSE;
3608 } else {
3609 // We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with
3610 // drflac__seek_to_next_frame() which only works if the decoder is sitting on the byte just after the frame header.
3611 runningSampleCount += pFlac->currentFrame.samplesRemaining;
3612 pFlac->currentFrame.samplesRemaining = 0;
3613 isMidFrame = DRFLAC_FALSE;
3617 next_iteration:
3618 // Grab the next frame in preparation for the next iteration.
3619 if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) {
3620 return DRFLAC_FALSE;
3626 #ifndef DR_FLAC_NO_OGG
3627 typedef struct
3629 drflac_uint8 capturePattern[4]; // Should be "OggS"
3630 drflac_uint8 structureVersion; // Always 0.
3631 drflac_uint8 headerType;
3632 drflac_uint64 granulePosition;
3633 drflac_uint32 serialNumber;
3634 drflac_uint32 sequenceNumber;
3635 drflac_uint32 checksum;
3636 drflac_uint8 segmentCount;
3637 drflac_uint8 segmentTable[255];
3638 } drflac_ogg_page_header;
3639 #endif
3641 typedef struct
3643 drflac_read_proc onRead;
3644 drflac_seek_proc onSeek;
3645 drflac_meta_proc onMeta;
3646 drflac_container container;
3647 void* pUserData;
3648 void* pUserDataMD;
3649 drflac_uint32 sampleRate;
3650 drflac_uint8 channels;
3651 drflac_uint8 bitsPerSample;
3652 drflac_uint64 totalSampleCount;
3653 drflac_uint16 maxBlockSize;
3654 drflac_uint64 runningFilePos;
3655 drflac_bool32 hasStreamInfoBlock;
3656 drflac_bool32 hasMetadataBlocks;
3657 drflac_bs bs; // <-- A bit streamer is required for loading data during initialization.
3658 drflac_frame_header firstFrameHeader; // <-- The header of the first frame that was read during relaxed initalization. Only set if there is no STREAMINFO block.
3660 #ifndef DR_FLAC_NO_OGG
3661 drflac_uint32 oggSerial;
3662 drflac_uint64 oggFirstBytePos;
3663 drflac_ogg_page_header oggBosHeader;
3664 #endif
3665 } drflac_init_info;
3667 static DRFLAC_INLINE void drflac__decode_block_header(drflac_uint32 blockHeader, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
3669 blockHeader = drflac__be2host_32(blockHeader);
3670 *isLastBlock = (blockHeader & (0x01 << 31)) >> 31;
3671 *blockType = (blockHeader & (0x7F << 24)) >> 24;
3672 *blockSize = (blockHeader & 0xFFFFFF);
3675 static DRFLAC_INLINE drflac_bool32 drflac__read_and_decode_block_header(drflac_read_proc onRead, void* pUserData, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
3677 drflac_uint32 blockHeader;
3678 if (onRead(pUserData, &blockHeader, 4) != 4) {
3679 return DRFLAC_FALSE;
3682 drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize);
3683 return DRFLAC_TRUE;
3686 drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, drflac_streaminfo* pStreamInfo)
3688 // min/max block size.
3689 drflac_uint32 blockSizes;
3690 if (onRead(pUserData, &blockSizes, 4) != 4) {
3691 return DRFLAC_FALSE;
3694 // min/max frame size.
3695 drflac_uint64 frameSizes = 0;
3696 if (onRead(pUserData, &frameSizes, 6) != 6) {
3697 return DRFLAC_FALSE;
3700 // Sample rate, channels, bits per sample and total sample count.
3701 drflac_uint64 importantProps;
3702 if (onRead(pUserData, &importantProps, 8) != 8) {
3703 return DRFLAC_FALSE;
3706 // MD5
3707 drflac_uint8 md5[16];
3708 if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5)) {
3709 return DRFLAC_FALSE;
3712 blockSizes = drflac__be2host_32(blockSizes);
3713 frameSizes = drflac__be2host_64(frameSizes);
3714 importantProps = drflac__be2host_64(importantProps);
3716 pStreamInfo->minBlockSize = (blockSizes & 0xFFFF0000) >> 16;
3717 pStreamInfo->maxBlockSize = blockSizes & 0x0000FFFF;
3718 pStreamInfo->minFrameSize = (drflac_uint32)((frameSizes & (drflac_uint64)0xFFFFFF0000000000) >> 40);
3719 pStreamInfo->maxFrameSize = (drflac_uint32)((frameSizes & (drflac_uint64)0x000000FFFFFF0000) >> 16);
3720 pStreamInfo->sampleRate = (drflac_uint32)((importantProps & (drflac_uint64)0xFFFFF00000000000) >> 44);
3721 pStreamInfo->channels = (drflac_uint8 )((importantProps & (drflac_uint64)0x00000E0000000000) >> 41) + 1;
3722 pStreamInfo->bitsPerSample = (drflac_uint8 )((importantProps & (drflac_uint64)0x000001F000000000) >> 36) + 1;
3723 pStreamInfo->totalSampleCount = (importantProps & (drflac_uint64)0x0000000FFFFFFFFF) * pStreamInfo->channels;
3724 drflac_copy_memory(pStreamInfo->md5, md5, sizeof(md5));
3726 return DRFLAC_TRUE;
3729 drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_uint64* pFirstFramePos, drflac_uint64* pSeektablePos, drflac_uint32* pSeektableSize)
3731 // We want to keep track of the byte position in the stream of the seektable. At the time of calling this function we know that
3732 // we'll be sitting on byte 42.
3733 drflac_uint64 runningFilePos = 42;
3734 drflac_uint64 seektablePos = 0;
3735 drflac_uint32 seektableSize = 0;
3737 for (;;) {
3738 drflac_uint8 isLastBlock = 0;
3739 drflac_uint8 blockType;
3740 drflac_uint32 blockSize;
3741 if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
3742 return DRFLAC_FALSE;
3744 runningFilePos += 4;
3747 drflac_metadata metadata;
3748 metadata.type = blockType;
3749 metadata.pRawData = NULL;
3750 metadata.rawDataSize = 0;
3752 switch (blockType)
3754 case DRFLAC_METADATA_BLOCK_TYPE_APPLICATION:
3756 if (blockSize < 4) {
3757 return DRFLAC_FALSE;
3760 if (onMeta) {
3761 void* pRawData = DRFLAC_MALLOC(blockSize);
3762 if (pRawData == NULL) {
3763 return DRFLAC_FALSE;
3766 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
3767 DRFLAC_FREE(pRawData);
3768 return DRFLAC_FALSE;
3771 metadata.pRawData = pRawData;
3772 metadata.rawDataSize = blockSize;
3773 metadata.data.application.id = drflac__be2host_32(*(drflac_uint32*)pRawData);
3774 metadata.data.application.pData = (const void*)((drflac_uint8*)pRawData + sizeof(drflac_uint32));
3775 metadata.data.application.dataSize = blockSize - sizeof(drflac_uint32);
3776 onMeta(pUserDataMD, &metadata);
3778 DRFLAC_FREE(pRawData);
3780 } break;
3782 case DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE:
3784 seektablePos = runningFilePos;
3785 seektableSize = blockSize;
3787 if (onMeta) {
3788 void* pRawData = DRFLAC_MALLOC(blockSize);
3789 if (pRawData == NULL) {
3790 return DRFLAC_FALSE;
3793 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
3794 DRFLAC_FREE(pRawData);
3795 return DRFLAC_FALSE;
3798 metadata.pRawData = pRawData;
3799 metadata.rawDataSize = blockSize;
3800 metadata.data.seektable.seekpointCount = blockSize/sizeof(drflac_seekpoint);
3801 metadata.data.seektable.pSeekpoints = (const drflac_seekpoint*)pRawData;
3803 // Endian swap.
3804 for (drflac_uint32 iSeekpoint = 0; iSeekpoint < metadata.data.seektable.seekpointCount; ++iSeekpoint) {
3805 drflac_seekpoint* pSeekpoint = (drflac_seekpoint*)pRawData + iSeekpoint;
3806 pSeekpoint->firstSample = drflac__be2host_64(pSeekpoint->firstSample);
3807 pSeekpoint->frameOffset = drflac__be2host_64(pSeekpoint->frameOffset);
3808 pSeekpoint->sampleCount = drflac__be2host_16(pSeekpoint->sampleCount);
3811 onMeta(pUserDataMD, &metadata);
3813 DRFLAC_FREE(pRawData);
3815 } break;
3817 case DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT:
3819 if (blockSize < 8) {
3820 return DRFLAC_FALSE;
3823 if (onMeta) {
3824 void* pRawData = DRFLAC_MALLOC(blockSize);
3825 if (pRawData == NULL) {
3826 return DRFLAC_FALSE;
3829 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
3830 DRFLAC_FREE(pRawData);
3831 return DRFLAC_FALSE;
3834 metadata.pRawData = pRawData;
3835 metadata.rawDataSize = blockSize;
3837 const char* pRunningData = (const char*)pRawData;
3838 const char* const pRunningDataEnd = (const char*)pRawData + blockSize;
3840 metadata.data.vorbis_comment.vendorLength = drflac__le2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
3842 // Need space for the rest of the block
3843 if ((pRunningDataEnd - pRunningData) - 4 < (drflac_int64)metadata.data.vorbis_comment.vendorLength) { // <-- Note the order of operations to avoid overflow to a valid value
3844 DRFLAC_FREE(pRawData);
3845 return DRFLAC_FALSE;
3847 metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength;
3848 metadata.data.vorbis_comment.commentCount = drflac__le2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
3850 // Need space for 'commentCount' comments after the block, which at minimum is a drflac_uint32 per comment
3851 if ((pRunningDataEnd - pRunningData) / sizeof(drflac_uint32) < metadata.data.vorbis_comment.commentCount) { // <-- Note the order of operations to avoid overflow to a valid value
3852 DRFLAC_FREE(pRawData);
3853 return DRFLAC_FALSE;
3855 metadata.data.vorbis_comment.pComments = pRunningData;
3857 // Check that the comments section is valid before passing it to the callback
3858 for (drflac_uint32 i = 0; i < metadata.data.vorbis_comment.commentCount; ++i) {
3859 if (pRunningDataEnd - pRunningData < 4) {
3860 DRFLAC_FREE(pRawData);
3861 return DRFLAC_FALSE;
3863 const drflac_uint32 commentLength = drflac__le2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
3864 if (pRunningDataEnd - pRunningData < (drflac_int64)commentLength) { // <-- Note the order of operations to avoid overflow to a valid value
3865 DRFLAC_FREE(pRawData);
3866 return DRFLAC_FALSE;
3868 pRunningData += commentLength;
3871 onMeta(pUserDataMD, &metadata);
3873 DRFLAC_FREE(pRawData);
3875 } break;
3877 case DRFLAC_METADATA_BLOCK_TYPE_CUESHEET:
3879 if (blockSize < 396) {
3880 return DRFLAC_FALSE;
3883 if (onMeta) {
3884 void* pRawData = DRFLAC_MALLOC(blockSize);
3885 if (pRawData == NULL) {
3886 return DRFLAC_FALSE;
3889 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
3890 DRFLAC_FREE(pRawData);
3891 return DRFLAC_FALSE;
3894 metadata.pRawData = pRawData;
3895 metadata.rawDataSize = blockSize;
3897 char* pRunningData = (char*)pRawData;
3898 const char* const pRunningDataEnd = (const char*)pRawData + blockSize;
3900 drflac_copy_memory(metadata.data.cuesheet.catalog, pRunningData, 128); pRunningData += 128;
3901 metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*(const drflac_uint64*)pRunningData); pRunningData += 8;
3902 metadata.data.cuesheet.isCD = (pRunningData[0] & 0x80) != 0; pRunningData += 259;
3903 metadata.data.cuesheet.trackCount = pRunningData[0]; pRunningData += 1;
3904 metadata.data.cuesheet.pTrackData = pRunningData;
3906 // Check that the cuesheet tracks are valid before passing it to the callback
3907 for (drflac_uint8 i = 0; i < metadata.data.cuesheet.trackCount; ++i) {
3908 if (pRunningDataEnd - pRunningData < 36) {
3909 DRFLAC_FREE(pRawData);
3910 return DRFLAC_FALSE;
3913 // Skip to the index point count
3914 pRunningData += 35;
3915 const drflac_uint8 indexCount = pRunningData[0]; pRunningData += 1;
3916 const drflac_uint32 indexPointSize = indexCount * sizeof(drflac_cuesheet_track_index);
3917 if (pRunningDataEnd - pRunningData < (drflac_int64)indexPointSize) {
3918 DRFLAC_FREE(pRawData);
3919 return DRFLAC_FALSE;
3922 // Endian swap.
3923 for (drflac_uint8 index = 0; index < indexCount; ++index) {
3924 drflac_cuesheet_track_index* pTrack = (drflac_cuesheet_track_index*)pRunningData;
3925 pRunningData += sizeof(drflac_cuesheet_track_index);
3926 pTrack->offset = drflac__be2host_64(pTrack->offset);
3930 onMeta(pUserDataMD, &metadata);
3932 DRFLAC_FREE(pRawData);
3934 } break;
3936 case DRFLAC_METADATA_BLOCK_TYPE_PICTURE:
3938 if (blockSize < 32) {
3939 return DRFLAC_FALSE;
3942 if (onMeta) {
3943 void* pRawData = DRFLAC_MALLOC(blockSize);
3944 if (pRawData == NULL) {
3945 return DRFLAC_FALSE;
3948 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
3949 DRFLAC_FREE(pRawData);
3950 return DRFLAC_FALSE;
3953 metadata.pRawData = pRawData;
3954 metadata.rawDataSize = blockSize;
3956 const char* pRunningData = (const char*)pRawData;
3957 const char* const pRunningDataEnd = (const char*)pRawData + blockSize;
3959 metadata.data.picture.type = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
3960 metadata.data.picture.mimeLength = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
3962 // Need space for the rest of the block
3963 if ((pRunningDataEnd - pRunningData) - 24 < (drflac_int64)metadata.data.picture.mimeLength) { // <-- Note the order of operations to avoid overflow to a valid value
3964 DRFLAC_FREE(pRawData);
3965 return DRFLAC_FALSE;
3967 metadata.data.picture.mime = pRunningData; pRunningData += metadata.data.picture.mimeLength;
3968 metadata.data.picture.descriptionLength = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
3970 // Need space for the rest of the block
3971 if ((pRunningDataEnd - pRunningData) - 20 < (drflac_int64)metadata.data.picture.descriptionLength) { // <-- Note the order of operations to avoid overflow to a valid value
3972 DRFLAC_FREE(pRawData);
3973 return DRFLAC_FALSE;
3975 metadata.data.picture.description = pRunningData; pRunningData += metadata.data.picture.descriptionLength;
3976 metadata.data.picture.width = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
3977 metadata.data.picture.height = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
3978 metadata.data.picture.colorDepth = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
3979 metadata.data.picture.indexColorCount = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
3980 metadata.data.picture.pictureDataSize = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
3981 metadata.data.picture.pPictureData = (const drflac_uint8*)pRunningData;
3983 // Need space for the picture after the block
3984 if (pRunningDataEnd - pRunningData < (drflac_int64)metadata.data.picture.pictureDataSize) { // <-- Note the order of operations to avoid overflow to a valid value
3985 DRFLAC_FREE(pRawData);
3986 return DRFLAC_FALSE;
3989 onMeta(pUserDataMD, &metadata);
3991 DRFLAC_FREE(pRawData);
3993 } break;
3995 case DRFLAC_METADATA_BLOCK_TYPE_PADDING:
3997 if (onMeta) {
3998 metadata.data.padding.unused = 0;
4000 // Padding doesn't have anything meaningful in it, so just skip over it, but make sure the caller is aware of it by firing the callback.
4001 if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
4002 isLastBlock = DRFLAC_TRUE; // An error occurred while seeking. Attempt to recover by treating this as the last block which will in turn terminate the loop.
4003 } else {
4004 onMeta(pUserDataMD, &metadata);
4007 } break;
4009 case DRFLAC_METADATA_BLOCK_TYPE_INVALID:
4011 // Invalid chunk. Just skip over this one.
4012 if (onMeta) {
4013 if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
4014 isLastBlock = DRFLAC_TRUE; // An error occurred while seeking. Attempt to recover by treating this as the last block which will in turn terminate the loop.
4017 } break;
4019 default:
4021 // It's an unknown chunk, but not necessarily invalid. There's a chance more metadata blocks might be defined later on, so we
4022 // can at the very least report the chunk to the application and let it look at the raw data.
4023 if (onMeta) {
4024 void* pRawData = DRFLAC_MALLOC(blockSize);
4025 if (pRawData == NULL) {
4026 return DRFLAC_FALSE;
4029 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
4030 DRFLAC_FREE(pRawData);
4031 return DRFLAC_FALSE;
4034 metadata.pRawData = pRawData;
4035 metadata.rawDataSize = blockSize;
4036 onMeta(pUserDataMD, &metadata);
4038 DRFLAC_FREE(pRawData);
4040 } break;
4043 // If we're not handling metadata, just skip over the block. If we are, it will have been handled earlier in the switch statement above.
4044 if (onMeta == NULL && blockSize > 0) {
4045 if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
4046 isLastBlock = DRFLAC_TRUE;
4050 runningFilePos += blockSize;
4051 if (isLastBlock) {
4052 break;
4056 *pSeektablePos = seektablePos;
4057 *pSeektableSize = seektableSize;
4058 *pFirstFramePos = runningFilePos;
4060 return DRFLAC_TRUE;
4063 drflac_bool32 drflac__init_private__native(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed)
4065 (void)onSeek;
4067 // Pre: The bit stream should be sitting just past the 4-byte id header.
4069 pInit->container = drflac_container_native;
4071 // The first metadata block should be the STREAMINFO block.
4072 drflac_uint8 isLastBlock;
4073 drflac_uint8 blockType;
4074 drflac_uint32 blockSize;
4075 if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
4076 return DRFLAC_FALSE;
4079 if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
4080 if (!relaxed) {
4081 // We're opening in strict mode and the first block is not the STREAMINFO block. Error.
4082 return DRFLAC_FALSE;
4083 } else {
4084 // Relaxed mode. To open from here we need to just find the first frame and set the sample rate, etc. to whatever is defined
4085 // for that frame.
4086 pInit->hasStreamInfoBlock = DRFLAC_FALSE;
4087 pInit->hasMetadataBlocks = DRFLAC_FALSE;
4089 if (!drflac__read_next_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) {
4090 return DRFLAC_FALSE; // Couldn't find a frame.
4093 if (pInit->firstFrameHeader.bitsPerSample == 0) {
4094 return DRFLAC_FALSE; // Failed to initialize because the first frame depends on the STREAMINFO block, which does not exist.
4097 pInit->sampleRate = pInit->firstFrameHeader.sampleRate;
4098 pInit->channels = drflac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment);
4099 pInit->bitsPerSample = pInit->firstFrameHeader.bitsPerSample;
4100 pInit->maxBlockSize = 65535; // <-- See notes here: https://xiph.org/flac/format.html#metadata_block_streaminfo
4101 return DRFLAC_TRUE;
4103 } else {
4104 drflac_streaminfo streaminfo;
4105 if (!drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
4106 return DRFLAC_FALSE;
4109 pInit->hasStreamInfoBlock = DRFLAC_TRUE;
4110 pInit->sampleRate = streaminfo.sampleRate;
4111 pInit->channels = streaminfo.channels;
4112 pInit->bitsPerSample = streaminfo.bitsPerSample;
4113 pInit->totalSampleCount = streaminfo.totalSampleCount;
4114 pInit->maxBlockSize = streaminfo.maxBlockSize; // Don't care about the min block size - only the max (used for determining the size of the memory allocation).
4115 pInit->hasMetadataBlocks = !isLastBlock;
4117 if (onMeta) {
4118 drflac_metadata metadata;
4119 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
4120 metadata.pRawData = NULL;
4121 metadata.rawDataSize = 0;
4122 metadata.data.streaminfo = streaminfo;
4123 onMeta(pUserDataMD, &metadata);
4126 return DRFLAC_TRUE;
4130 #ifndef DR_FLAC_NO_OGG
4131 #define DRFLAC_OGG_MAX_PAGE_SIZE 65307
4132 #define DRFLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199 // CRC-32 of "OggS".
4134 typedef enum
4136 drflac_ogg_recover_on_crc_mismatch,
4137 drflac_ogg_fail_on_crc_mismatch
4138 } drflac_ogg_crc_mismatch_recovery;
4141 static drflac_uint32 drflac__crc32_table[] = {
4142 0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L,
4143 0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L,
4144 0x2608EDB8L, 0x22C9F00FL, 0x2F8AD6D6L, 0x2B4BCB61L,
4145 0x350C9B64L, 0x31CD86D3L, 0x3C8EA00AL, 0x384FBDBDL,
4146 0x4C11DB70L, 0x48D0C6C7L, 0x4593E01EL, 0x4152FDA9L,
4147 0x5F15ADACL, 0x5BD4B01BL, 0x569796C2L, 0x52568B75L,
4148 0x6A1936C8L, 0x6ED82B7FL, 0x639B0DA6L, 0x675A1011L,
4149 0x791D4014L, 0x7DDC5DA3L, 0x709F7B7AL, 0x745E66CDL,
4150 0x9823B6E0L, 0x9CE2AB57L, 0x91A18D8EL, 0x95609039L,
4151 0x8B27C03CL, 0x8FE6DD8BL, 0x82A5FB52L, 0x8664E6E5L,
4152 0xBE2B5B58L, 0xBAEA46EFL, 0xB7A96036L, 0xB3687D81L,
4153 0xAD2F2D84L, 0xA9EE3033L, 0xA4AD16EAL, 0xA06C0B5DL,
4154 0xD4326D90L, 0xD0F37027L, 0xDDB056FEL, 0xD9714B49L,
4155 0xC7361B4CL, 0xC3F706FBL, 0xCEB42022L, 0xCA753D95L,
4156 0xF23A8028L, 0xF6FB9D9FL, 0xFBB8BB46L, 0xFF79A6F1L,
4157 0xE13EF6F4L, 0xE5FFEB43L, 0xE8BCCD9AL, 0xEC7DD02DL,
4158 0x34867077L, 0x30476DC0L, 0x3D044B19L, 0x39C556AEL,
4159 0x278206ABL, 0x23431B1CL, 0x2E003DC5L, 0x2AC12072L,
4160 0x128E9DCFL, 0x164F8078L, 0x1B0CA6A1L, 0x1FCDBB16L,
4161 0x018AEB13L, 0x054BF6A4L, 0x0808D07DL, 0x0CC9CDCAL,
4162 0x7897AB07L, 0x7C56B6B0L, 0x71159069L, 0x75D48DDEL,
4163 0x6B93DDDBL, 0x6F52C06CL, 0x6211E6B5L, 0x66D0FB02L,
4164 0x5E9F46BFL, 0x5A5E5B08L, 0x571D7DD1L, 0x53DC6066L,
4165 0x4D9B3063L, 0x495A2DD4L, 0x44190B0DL, 0x40D816BAL,
4166 0xACA5C697L, 0xA864DB20L, 0xA527FDF9L, 0xA1E6E04EL,
4167 0xBFA1B04BL, 0xBB60ADFCL, 0xB6238B25L, 0xB2E29692L,
4168 0x8AAD2B2FL, 0x8E6C3698L, 0x832F1041L, 0x87EE0DF6L,
4169 0x99A95DF3L, 0x9D684044L, 0x902B669DL, 0x94EA7B2AL,
4170 0xE0B41DE7L, 0xE4750050L, 0xE9362689L, 0xEDF73B3EL,
4171 0xF3B06B3BL, 0xF771768CL, 0xFA325055L, 0xFEF34DE2L,
4172 0xC6BCF05FL, 0xC27DEDE8L, 0xCF3ECB31L, 0xCBFFD686L,
4173 0xD5B88683L, 0xD1799B34L, 0xDC3ABDEDL, 0xD8FBA05AL,
4174 0x690CE0EEL, 0x6DCDFD59L, 0x608EDB80L, 0x644FC637L,
4175 0x7A089632L, 0x7EC98B85L, 0x738AAD5CL, 0x774BB0EBL,
4176 0x4F040D56L, 0x4BC510E1L, 0x46863638L, 0x42472B8FL,
4177 0x5C007B8AL, 0x58C1663DL, 0x558240E4L, 0x51435D53L,
4178 0x251D3B9EL, 0x21DC2629L, 0x2C9F00F0L, 0x285E1D47L,
4179 0x36194D42L, 0x32D850F5L, 0x3F9B762CL, 0x3B5A6B9BL,
4180 0x0315D626L, 0x07D4CB91L, 0x0A97ED48L, 0x0E56F0FFL,
4181 0x1011A0FAL, 0x14D0BD4DL, 0x19939B94L, 0x1D528623L,
4182 0xF12F560EL, 0xF5EE4BB9L, 0xF8AD6D60L, 0xFC6C70D7L,
4183 0xE22B20D2L, 0xE6EA3D65L, 0xEBA91BBCL, 0xEF68060BL,
4184 0xD727BBB6L, 0xD3E6A601L, 0xDEA580D8L, 0xDA649D6FL,
4185 0xC423CD6AL, 0xC0E2D0DDL, 0xCDA1F604L, 0xC960EBB3L,
4186 0xBD3E8D7EL, 0xB9FF90C9L, 0xB4BCB610L, 0xB07DABA7L,
4187 0xAE3AFBA2L, 0xAAFBE615L, 0xA7B8C0CCL, 0xA379DD7BL,
4188 0x9B3660C6L, 0x9FF77D71L, 0x92B45BA8L, 0x9675461FL,
4189 0x8832161AL, 0x8CF30BADL, 0x81B02D74L, 0x857130C3L,
4190 0x5D8A9099L, 0x594B8D2EL, 0x5408ABF7L, 0x50C9B640L,
4191 0x4E8EE645L, 0x4A4FFBF2L, 0x470CDD2BL, 0x43CDC09CL,
4192 0x7B827D21L, 0x7F436096L, 0x7200464FL, 0x76C15BF8L,
4193 0x68860BFDL, 0x6C47164AL, 0x61043093L, 0x65C52D24L,
4194 0x119B4BE9L, 0x155A565EL, 0x18197087L, 0x1CD86D30L,
4195 0x029F3D35L, 0x065E2082L, 0x0B1D065BL, 0x0FDC1BECL,
4196 0x3793A651L, 0x3352BBE6L, 0x3E119D3FL, 0x3AD08088L,
4197 0x2497D08DL, 0x2056CD3AL, 0x2D15EBE3L, 0x29D4F654L,
4198 0xC5A92679L, 0xC1683BCEL, 0xCC2B1D17L, 0xC8EA00A0L,
4199 0xD6AD50A5L, 0xD26C4D12L, 0xDF2F6BCBL, 0xDBEE767CL,
4200 0xE3A1CBC1L, 0xE760D676L, 0xEA23F0AFL, 0xEEE2ED18L,
4201 0xF0A5BD1DL, 0xF464A0AAL, 0xF9278673L, 0xFDE69BC4L,
4202 0x89B8FD09L, 0x8D79E0BEL, 0x803AC667L, 0x84FBDBD0L,
4203 0x9ABC8BD5L, 0x9E7D9662L, 0x933EB0BBL, 0x97FFAD0CL,
4204 0xAFB010B1L, 0xAB710D06L, 0xA6322BDFL, 0xA2F33668L,
4205 0xBCB4666DL, 0xB8757BDAL, 0xB5365D03L, 0xB1F740B4L
4208 static DRFLAC_INLINE drflac_uint32 drflac_crc32_byte(drflac_uint32 crc32, drflac_uint8 data)
4210 #ifndef DR_FLAC_NO_CRC
4211 return (crc32 << 8) ^ drflac__crc32_table[(drflac_uint8)((crc32 >> 24) & 0xFF) ^ data];
4212 #else
4213 (void)data;
4214 return crc32;
4215 #endif
4218 #if 0
4219 static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint32(drflac_uint32 crc32, drflac_uint32 data)
4221 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 24) & 0xFF));
4222 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 16) & 0xFF));
4223 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 8) & 0xFF));
4224 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 0) & 0xFF));
4225 return crc32;
4228 static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint64(drflac_uint32 crc32, drflac_uint64 data)
4230 crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 32) & 0xFFFFFFFF));
4231 crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 0) & 0xFFFFFFFF));
4232 return crc32;
4234 #endif
4236 static DRFLAC_INLINE drflac_uint32 drflac_crc32_buffer(drflac_uint32 crc32, drflac_uint8* pData, drflac_uint32 dataSize)
4238 // This can be optimized.
4239 for (drflac_uint32 i = 0; i < dataSize; ++i) {
4240 crc32 = drflac_crc32_byte(crc32, pData[i]);
4242 return crc32;
4246 static DRFLAC_INLINE drflac_bool32 drflac_ogg__is_capture_pattern(drflac_uint8 pattern[4])
4248 return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S';
4251 static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_header_size(drflac_ogg_page_header* pHeader)
4253 return 27 + pHeader->segmentCount;
4256 static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_body_size(drflac_ogg_page_header* pHeader)
4258 drflac_uint32 pageBodySize = 0;
4259 for (int i = 0; i < pHeader->segmentCount; ++i) {
4260 pageBodySize += pHeader->segmentTable[i];
4263 return pageBodySize;
4266 drflac_result drflac_ogg__read_page_header_after_capture_pattern(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32)
4268 drflac_assert(*pCRC32 == DRFLAC_OGG_CAPTURE_PATTERN_CRC32);
4270 drflac_uint8 data[23];
4271 if (onRead(pUserData, data, 23) != 23) {
4272 return DRFLAC_END_OF_STREAM;
4274 *pBytesRead += 23;
4276 pHeader->structureVersion = data[0];
4277 pHeader->headerType = data[1];
4278 drflac_copy_memory(&pHeader->granulePosition, &data[ 2], 8);
4279 drflac_copy_memory(&pHeader->serialNumber, &data[10], 4);
4280 drflac_copy_memory(&pHeader->sequenceNumber, &data[14], 4);
4281 drflac_copy_memory(&pHeader->checksum, &data[18], 4);
4282 pHeader->segmentCount = data[22];
4284 // Calculate the CRC. Note that for the calculation the checksum part of the page needs to be set to 0.
4285 data[18] = 0;
4286 data[19] = 0;
4287 data[20] = 0;
4288 data[21] = 0;
4290 drflac_uint32 i;
4291 for (i = 0; i < 23; ++i) {
4292 *pCRC32 = drflac_crc32_byte(*pCRC32, data[i]);
4296 if (onRead(pUserData, pHeader->segmentTable, pHeader->segmentCount) != pHeader->segmentCount) {
4297 return DRFLAC_END_OF_STREAM;
4299 *pBytesRead += pHeader->segmentCount;
4301 for (i = 0; i < pHeader->segmentCount; ++i) {
4302 *pCRC32 = drflac_crc32_byte(*pCRC32, pHeader->segmentTable[i]);
4305 return DRFLAC_SUCCESS;
4308 drflac_result drflac_ogg__read_page_header(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32)
4310 *pBytesRead = 0;
4312 drflac_uint8 id[4];
4313 if (onRead(pUserData, id, 4) != 4) {
4314 return DRFLAC_END_OF_STREAM;
4316 *pBytesRead += 4;
4318 // We need to read byte-by-byte until we find the OggS capture pattern.
4319 for (;;) {
4320 if (drflac_ogg__is_capture_pattern(id)) {
4321 *pCRC32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
4323 drflac_result result = drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32);
4324 if (result == DRFLAC_SUCCESS) {
4325 return DRFLAC_SUCCESS;
4326 } else {
4327 if (result == DRFLAC_CRC_MISMATCH) {
4328 continue;
4329 } else {
4330 return result;
4333 } else {
4334 // The first 4 bytes did not equal the capture pattern. Read the next byte and try again.
4335 id[0] = id[1];
4336 id[1] = id[2];
4337 id[2] = id[3];
4338 if (onRead(pUserData, &id[3], 1) != 1) {
4339 return DRFLAC_END_OF_STREAM;
4341 *pBytesRead += 1;
4347 // The main part of the Ogg encapsulation is the conversion from the physical Ogg bitstream to the native FLAC bitstream. It works
4348 // in three general stages: Ogg Physical Bitstream -> Ogg/FLAC Logical Bitstream -> FLAC Native Bitstream. dr_flac is designed
4349 // in such a way that the core sections assume everything is delivered in native format. Therefore, for each encapsulation type
4350 // dr_flac is supporting there needs to be a layer sitting on top of the onRead and onSeek callbacks that ensures the bits read from
4351 // the physical Ogg bitstream are converted and delivered in native FLAC format.
4352 typedef struct
4354 drflac_read_proc onRead; // The original onRead callback from drflac_open() and family.
4355 drflac_seek_proc onSeek; // The original onSeek callback from drflac_open() and family.
4356 void* pUserData; // The user data passed on onRead and onSeek. This is the user data that was passed on drflac_open() and family.
4357 drflac_uint64 currentBytePos; // The position of the byte we are sitting on in the physical byte stream. Used for efficient seeking.
4358 drflac_uint64 firstBytePos; // The position of the first byte in the physical bitstream. Points to the start of the "OggS" identifier of the FLAC bos page.
4359 drflac_uint32 serialNumber; // The serial number of the FLAC audio pages. This is determined by the initial header page that was read during initialization.
4360 drflac_ogg_page_header bosPageHeader; // Used for seeking.
4361 drflac_ogg_page_header currentPageHeader;
4362 drflac_uint32 bytesRemainingInPage;
4363 drflac_uint32 pageDataSize;
4364 drflac_uint8 pageData[DRFLAC_OGG_MAX_PAGE_SIZE];
4365 } drflac_oggbs; // oggbs = Ogg Bitstream
4367 static size_t drflac_oggbs__read_physical(drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead)
4369 size_t bytesActuallyRead = oggbs->onRead(oggbs->pUserData, bufferOut, bytesToRead);
4370 oggbs->currentBytePos += bytesActuallyRead;
4372 return bytesActuallyRead;
4375 static drflac_bool32 drflac_oggbs__seek_physical(drflac_oggbs* oggbs, drflac_uint64 offset, drflac_seek_origin origin)
4377 if (origin == drflac_seek_origin_start) {
4378 if (offset <= 0x7FFFFFFF) {
4379 if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_start)) {
4380 return DRFLAC_FALSE;
4382 oggbs->currentBytePos = offset;
4384 return DRFLAC_TRUE;
4385 } else {
4386 if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start)) {
4387 return DRFLAC_FALSE;
4389 oggbs->currentBytePos = offset;
4391 return drflac_oggbs__seek_physical(oggbs, offset - 0x7FFFFFFF, drflac_seek_origin_current);
4393 } else {
4394 while (offset > 0x7FFFFFFF) {
4395 if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current)) {
4396 return DRFLAC_FALSE;
4398 oggbs->currentBytePos += 0x7FFFFFFF;
4399 offset -= 0x7FFFFFFF;
4402 if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_current)) { // <-- Safe cast thanks to the loop above.
4403 return DRFLAC_FALSE;
4405 oggbs->currentBytePos += offset;
4407 return DRFLAC_TRUE;
4411 static drflac_bool32 drflac_oggbs__goto_next_page(drflac_oggbs* oggbs, drflac_ogg_crc_mismatch_recovery recoveryMethod)
4413 drflac_ogg_page_header header;
4414 for (;;) {
4415 drflac_uint32 crc32 = 0;
4416 drflac_uint32 bytesRead;
4417 if (drflac_ogg__read_page_header(oggbs->onRead, oggbs->pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
4418 return DRFLAC_FALSE;
4420 oggbs->currentBytePos += bytesRead;
4422 drflac_uint32 pageBodySize = drflac_ogg__get_page_body_size(&header);
4423 if (pageBodySize > DRFLAC_OGG_MAX_PAGE_SIZE) {
4424 continue; // Invalid page size. Assume it's corrupted and just move to the next page.
4427 if (header.serialNumber != oggbs->serialNumber) {
4428 // It's not a FLAC page. Skip it.
4429 if (pageBodySize > 0 && !drflac_oggbs__seek_physical(oggbs, pageBodySize, drflac_seek_origin_current)) {
4430 return DRFLAC_FALSE;
4432 continue;
4436 // We need to read the entire page and then do a CRC check on it. If there's a CRC mismatch we need to skip this page.
4437 if (drflac_oggbs__read_physical(oggbs, oggbs->pageData, pageBodySize) != pageBodySize) {
4438 return DRFLAC_FALSE;
4440 oggbs->pageDataSize = pageBodySize;
4442 #ifndef DR_FLAC_NO_CRC
4443 drflac_uint32 actualCRC32 = drflac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize);
4444 if (actualCRC32 != header.checksum) {
4445 if (recoveryMethod == drflac_ogg_recover_on_crc_mismatch) {
4446 continue; // CRC mismatch. Skip this page.
4447 } else {
4448 // Even though we are failing on a CRC mismatch, we still want our stream to be in a good state. Therefore we
4449 // go to the next valid page to ensure we're in a good state, but return false to let the caller know that the
4450 // seek did not fully complete.
4451 drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch);
4452 return DRFLAC_FALSE;
4455 #else
4456 (void)recoveryMethod; // <-- Silence a warning.
4457 #endif
4459 oggbs->currentPageHeader = header;
4460 oggbs->bytesRemainingInPage = pageBodySize;
4461 return DRFLAC_TRUE;
4465 // Function below is unused at the moment, but I might be re-adding it later.
4466 #if 0
4467 static drflac_uint8 drflac_oggbs__get_current_segment_index(drflac_oggbs* oggbs, drflac_uint8* pBytesRemainingInSeg)
4469 drflac_uint32 bytesConsumedInPage = drflac_ogg__get_page_body_size(&oggbs->currentPageHeader) - oggbs->bytesRemainingInPage;
4470 drflac_uint8 iSeg = 0;
4471 drflac_uint32 iByte = 0;
4472 while (iByte < bytesConsumedInPage) {
4473 drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
4474 if (iByte + segmentSize > bytesConsumedInPage) {
4475 break;
4476 } else {
4477 iSeg += 1;
4478 iByte += segmentSize;
4482 *pBytesRemainingInSeg = oggbs->currentPageHeader.segmentTable[iSeg] - (drflac_uint8)(bytesConsumedInPage - iByte);
4483 return iSeg;
4486 static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs)
4488 // The current packet ends when we get to the segment with a lacing value of < 255 which is not at the end of a page.
4489 for (;;) {
4490 drflac_bool32 atEndOfPage = DRFLAC_FALSE;
4492 drflac_uint8 bytesRemainingInSeg;
4493 drflac_uint8 iFirstSeg = drflac_oggbs__get_current_segment_index(oggbs, &bytesRemainingInSeg);
4495 drflac_uint32 bytesToEndOfPacketOrPage = bytesRemainingInSeg;
4496 for (drflac_uint8 iSeg = iFirstSeg; iSeg < oggbs->currentPageHeader.segmentCount; ++iSeg) {
4497 drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
4498 if (segmentSize < 255) {
4499 if (iSeg == oggbs->currentPageHeader.segmentCount-1) {
4500 atEndOfPage = DRFLAC_TRUE;
4503 break;
4506 bytesToEndOfPacketOrPage += segmentSize;
4509 // At this point we will have found either the packet or the end of the page. If were at the end of the page we'll
4510 // want to load the next page and keep searching for the end of the packet.
4511 drflac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, drflac_seek_origin_current);
4512 oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage;
4514 if (atEndOfPage) {
4515 // We're potentially at the next packet, but we need to check the next page first to be sure because the packet may
4516 // straddle pages.
4517 if (!drflac_oggbs__goto_next_page(oggbs)) {
4518 return DRFLAC_FALSE;
4521 // If it's a fresh packet it most likely means we're at the next packet.
4522 if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
4523 return DRFLAC_TRUE;
4525 } else {
4526 // We're at the next packet.
4527 return DRFLAC_TRUE;
4532 static drflac_bool32 drflac_oggbs__seek_to_next_frame(drflac_oggbs* oggbs)
4534 // The bitstream should be sitting on the first byte just after the header of the frame.
4536 // What we're actually doing here is seeking to the start of the next packet.
4537 return drflac_oggbs__seek_to_next_packet(oggbs);
4539 #endif
4541 static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead)
4543 drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
4544 drflac_assert(oggbs != NULL);
4546 drflac_uint8* pRunningBufferOut = (drflac_uint8*)bufferOut;
4548 // Reading is done page-by-page. If we've run out of bytes in the page we need to move to the next one.
4549 size_t bytesRead = 0;
4550 while (bytesRead < bytesToRead) {
4551 size_t bytesRemainingToRead = bytesToRead - bytesRead;
4553 if (oggbs->bytesRemainingInPage >= bytesRemainingToRead) {
4554 drflac_copy_memory(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), bytesRemainingToRead);
4555 bytesRead += bytesRemainingToRead;
4556 oggbs->bytesRemainingInPage -= (drflac_uint32)bytesRemainingToRead;
4557 break;
4560 // If we get here it means some of the requested data is contained in the next pages.
4561 if (oggbs->bytesRemainingInPage > 0) {
4562 drflac_copy_memory(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage);
4563 bytesRead += oggbs->bytesRemainingInPage;
4564 pRunningBufferOut += oggbs->bytesRemainingInPage;
4565 oggbs->bytesRemainingInPage = 0;
4568 drflac_assert(bytesRemainingToRead > 0);
4569 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
4570 break; // Failed to go to the next page. Might have simply hit the end of the stream.
4574 return bytesRead;
4577 static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_seek_origin origin)
4579 drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
4580 drflac_assert(oggbs != NULL);
4581 drflac_assert(offset >= 0); // <-- Never seek backwards.
4583 // Seeking is always forward which makes things a lot simpler.
4584 if (origin == drflac_seek_origin_start) {
4585 if (!drflac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, drflac_seek_origin_start)) {
4586 return DRFLAC_FALSE;
4589 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
4590 return DRFLAC_FALSE;
4593 return drflac__on_seek_ogg(pUserData, offset, drflac_seek_origin_current);
4597 drflac_assert(origin == drflac_seek_origin_current);
4599 int bytesSeeked = 0;
4600 while (bytesSeeked < offset) {
4601 int bytesRemainingToSeek = offset - bytesSeeked;
4602 drflac_assert(bytesRemainingToSeek >= 0);
4604 if (oggbs->bytesRemainingInPage >= (size_t)bytesRemainingToSeek) {
4605 bytesSeeked += bytesRemainingToSeek;
4606 oggbs->bytesRemainingInPage -= bytesRemainingToSeek;
4607 break;
4610 // If we get here it means some of the requested data is contained in the next pages.
4611 if (oggbs->bytesRemainingInPage > 0) {
4612 bytesSeeked += (int)oggbs->bytesRemainingInPage;
4613 oggbs->bytesRemainingInPage = 0;
4616 drflac_assert(bytesRemainingToSeek > 0);
4617 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
4618 // Failed to go to the next page. We either hit the end of the stream or had a CRC mismatch.
4619 return DRFLAC_FALSE;
4623 return DRFLAC_TRUE;
4626 drflac_bool32 drflac_ogg__seek_to_sample(drflac* pFlac, drflac_uint64 sampleIndex)
4628 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
4630 drflac_uint64 originalBytePos = oggbs->currentBytePos; // For recovery.
4632 // First seek to the first frame.
4633 if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFramePos)) {
4634 return DRFLAC_FALSE;
4636 oggbs->bytesRemainingInPage = 0;
4638 drflac_uint64 runningGranulePosition = 0;
4639 drflac_uint64 runningFrameBytePos = oggbs->currentBytePos; // <-- Points to the OggS identifier.
4640 for (;;) {
4641 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
4642 drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
4643 return DRFLAC_FALSE; // Never did find that sample...
4646 runningFrameBytePos = oggbs->currentBytePos - drflac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize;
4647 if (oggbs->currentPageHeader.granulePosition*pFlac->channels >= sampleIndex) {
4648 break; // The sample is somewhere in the previous page.
4652 // At this point we know the sample is not in the previous page. It could possibly be in this page. For simplicity we
4653 // disregard any pages that do not begin a fresh packet.
4654 if ((oggbs->currentPageHeader.headerType & 0x01) == 0) { // <-- Is it a fresh page?
4655 if (oggbs->currentPageHeader.segmentTable[0] >= 2) {
4656 drflac_uint8 firstBytesInPage[2];
4657 firstBytesInPage[0] = oggbs->pageData[0];
4658 firstBytesInPage[1] = oggbs->pageData[1];
4660 if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) { // <-- Does the page begin with a frame's sync code?
4661 runningGranulePosition = oggbs->currentPageHeader.granulePosition*pFlac->channels;
4664 continue;
4670 // We found the page that that is closest to the sample, so now we need to find it. The first thing to do is seek to the
4671 // start of that page. In the loop above we checked that it was a fresh page which means this page is also the start of
4672 // a new frame. This property means that after we've seeked to the page we can immediately start looping over frames until
4673 // we find the one containing the target sample.
4674 if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, drflac_seek_origin_start)) {
4675 return DRFLAC_FALSE;
4677 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
4678 return DRFLAC_FALSE;
4682 // At this point we'll be sitting on the first byte of the frame header of the first frame in the page. We just keep
4683 // looping over these frames until we find the one containing the sample we're after.
4684 drflac_uint64 runningSampleCount = runningGranulePosition;
4685 for (;;) {
4686 // There are two ways to find the sample and seek past irrelevant frames:
4687 // 1) Use the native FLAC decoder.
4688 // 2) Use Ogg's framing system.
4690 // Both of these options have their own pros and cons. Using the native FLAC decoder is slower because it needs to
4691 // do a full decode of the frame. Using Ogg's framing system is faster, but more complicated and involves some code
4692 // duplication for the decoding of frame headers.
4694 // Another thing to consider is that using the Ogg framing system will perform direct seeking of the physical Ogg
4695 // bitstream. This is important to consider because it means we cannot read data from the drflac_bs object using the
4696 // standard drflac__*() APIs because that will read in extra data for its own internal caching which in turn breaks
4697 // the positioning of the read pointer of the physical Ogg bitstream. Therefore, anything that would normally be read
4698 // using the native FLAC decoding APIs, such as drflac__read_next_frame_header(), need to be re-implemented so as to
4699 // avoid the use of the drflac_bs object.
4701 // Considering these issues, I have decided to use the slower native FLAC decoding method for the following reasons:
4702 // 1) Seeking is already partially accelerated using Ogg's paging system in the code block above.
4703 // 2) Seeking in an Ogg encapsulated FLAC stream is probably quite uncommon.
4704 // 3) Simplicity.
4705 if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) {
4706 return DRFLAC_FALSE;
4709 drflac_uint64 firstSampleInFrame = 0;
4710 drflac_uint64 lastSampleInFrame = 0;
4711 drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame);
4713 drflac_uint64 sampleCountInThisFrame = (lastSampleInFrame - firstSampleInFrame) + 1;
4714 if (sampleIndex < (runningSampleCount + sampleCountInThisFrame)) {
4715 // The sample should be in this frame. We need to fully decode it, however if it's an invalid frame (a CRC mismatch), we need to pretend
4716 // it never existed and keep iterating.
4717 drflac_result result = drflac__decode_frame(pFlac);
4718 if (result == DRFLAC_SUCCESS) {
4719 // The frame is valid. We just need to skip over some samples to ensure it's sample-exact.
4720 drflac_uint64 samplesToDecode = (size_t)(sampleIndex - runningSampleCount); // <-- Safe cast because the maximum number of samples in a frame is 65535.
4721 if (samplesToDecode == 0) {
4722 return DRFLAC_TRUE;
4724 return drflac_read_s32(pFlac, samplesToDecode, NULL) != 0; // <-- If this fails, something bad has happened (it should never fail).
4725 } else {
4726 if (result == DRFLAC_CRC_MISMATCH) {
4727 continue; // CRC mismatch. Pretend this frame never existed.
4728 } else {
4729 return DRFLAC_FALSE;
4732 } else {
4733 // It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this
4734 // frame never existed and leave the running sample count untouched.
4735 drflac_result result = drflac__seek_to_next_frame(pFlac);
4736 if (result == DRFLAC_SUCCESS) {
4737 runningSampleCount += sampleCountInThisFrame;
4738 } else {
4739 if (result == DRFLAC_CRC_MISMATCH) {
4740 continue; // CRC mismatch. Pretend this frame never existed.
4741 } else {
4742 return DRFLAC_FALSE;
4750 drflac_bool32 drflac__init_private__ogg(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed)
4752 // Pre: The bit stream should be sitting just past the 4-byte OggS capture pattern.
4753 (void)relaxed;
4755 pInit->container = drflac_container_ogg;
4756 pInit->oggFirstBytePos = 0;
4758 // We'll get here if the first 4 bytes of the stream were the OggS capture pattern, however it doesn't necessarily mean the
4759 // stream includes FLAC encoded audio. To check for this we need to scan the beginning-of-stream page markers and check if
4760 // any match the FLAC specification. Important to keep in mind that the stream may be multiplexed.
4761 drflac_ogg_page_header header;
4763 drflac_uint32 crc32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
4764 drflac_uint32 bytesRead = 0;
4765 if (drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
4766 return DRFLAC_FALSE;
4768 pInit->runningFilePos += bytesRead;
4770 for (;;) {
4771 // Break if we're past the beginning of stream page.
4772 if ((header.headerType & 0x02) == 0) {
4773 return DRFLAC_FALSE;
4777 // Check if it's a FLAC header.
4778 int pageBodySize = drflac_ogg__get_page_body_size(&header);
4779 if (pageBodySize == 51) { // 51 = the lacing value of the FLAC header packet.
4780 // It could be a FLAC page...
4781 drflac_uint32 bytesRemainingInPage = pageBodySize;
4783 drflac_uint8 packetType;
4784 if (onRead(pUserData, &packetType, 1) != 1) {
4785 return DRFLAC_FALSE;
4788 bytesRemainingInPage -= 1;
4789 if (packetType == 0x7F) {
4790 // Increasingly more likely to be a FLAC page...
4791 drflac_uint8 sig[4];
4792 if (onRead(pUserData, sig, 4) != 4) {
4793 return DRFLAC_FALSE;
4796 bytesRemainingInPage -= 4;
4797 if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') {
4798 // Almost certainly a FLAC page...
4799 drflac_uint8 mappingVersion[2];
4800 if (onRead(pUserData, mappingVersion, 2) != 2) {
4801 return DRFLAC_FALSE;
4804 if (mappingVersion[0] != 1) {
4805 return DRFLAC_FALSE; // Only supporting version 1.x of the Ogg mapping.
4808 // The next 2 bytes are the non-audio packets, not including this one. We don't care about this because we're going to
4809 // be handling it in a generic way based on the serial number and packet types.
4810 if (!onSeek(pUserData, 2, drflac_seek_origin_current)) {
4811 return DRFLAC_FALSE;
4814 // Expecting the native FLAC signature "fLaC".
4815 if (onRead(pUserData, sig, 4) != 4) {
4816 return DRFLAC_FALSE;
4819 if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C') {
4820 // The remaining data in the page should be the STREAMINFO block.
4821 drflac_uint8 isLastBlock;
4822 drflac_uint8 blockType;
4823 drflac_uint32 blockSize;
4824 if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
4825 return DRFLAC_FALSE;
4828 if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
4829 return DRFLAC_FALSE; // Invalid block type. First block must be the STREAMINFO block.
4832 drflac_streaminfo streaminfo;
4833 if (drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
4834 // Success!
4835 pInit->hasStreamInfoBlock = DRFLAC_TRUE;
4836 pInit->sampleRate = streaminfo.sampleRate;
4837 pInit->channels = streaminfo.channels;
4838 pInit->bitsPerSample = streaminfo.bitsPerSample;
4839 pInit->totalSampleCount = streaminfo.totalSampleCount;
4840 pInit->maxBlockSize = streaminfo.maxBlockSize;
4841 pInit->hasMetadataBlocks = !isLastBlock;
4843 if (onMeta) {
4844 drflac_metadata metadata;
4845 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
4846 metadata.pRawData = NULL;
4847 metadata.rawDataSize = 0;
4848 metadata.data.streaminfo = streaminfo;
4849 onMeta(pUserDataMD, &metadata);
4852 pInit->runningFilePos += pageBodySize;
4853 pInit->oggFirstBytePos = pInit->runningFilePos - 79; // Subtracting 79 will place us right on top of the "OggS" identifier of the FLAC bos page.
4854 pInit->oggSerial = header.serialNumber;
4855 pInit->oggBosHeader = header;
4856 break;
4857 } else {
4858 // Failed to read STREAMINFO block. Aww, so close...
4859 return DRFLAC_FALSE;
4861 } else {
4862 // Invalid file.
4863 return DRFLAC_FALSE;
4865 } else {
4866 // Not a FLAC header. Skip it.
4867 if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current)) {
4868 return DRFLAC_FALSE;
4871 } else {
4872 // Not a FLAC header. Seek past the entire page and move on to the next.
4873 if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current)) {
4874 return DRFLAC_FALSE;
4877 } else {
4878 if (!onSeek(pUserData, pageBodySize, drflac_seek_origin_current)) {
4879 return DRFLAC_FALSE;
4883 pInit->runningFilePos += pageBodySize;
4886 // Read the header of the next page.
4887 if (drflac_ogg__read_page_header(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
4888 return DRFLAC_FALSE;
4890 pInit->runningFilePos += bytesRead;
4894 // If we get here it means we found a FLAC audio stream. We should be sitting on the first byte of the header of the next page. The next
4895 // packets in the FLAC logical stream contain the metadata. The only thing left to do in the initialization phase for Ogg is to create the
4896 // Ogg bistream object.
4897 pInit->hasMetadataBlocks = DRFLAC_TRUE; // <-- Always have at least VORBIS_COMMENT metadata block.
4898 return DRFLAC_TRUE;
4900 #endif
4902 drflac_bool32 drflac__init_private(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD)
4904 if (pInit == NULL || onRead == NULL || onSeek == NULL) {
4905 return DRFLAC_FALSE;
4908 drflac_zero_memory(pInit, sizeof(*pInit));
4909 pInit->onRead = onRead;
4910 pInit->onSeek = onSeek;
4911 pInit->onMeta = onMeta;
4912 pInit->container = container;
4913 pInit->pUserData = pUserData;
4914 pInit->pUserDataMD = pUserDataMD;
4916 pInit->bs.onRead = onRead;
4917 pInit->bs.onSeek = onSeek;
4918 pInit->bs.pUserData = pUserData;
4919 drflac__reset_cache(&pInit->bs);
4922 // If the container is explicitly defined then we can try opening in relaxed mode.
4923 drflac_bool32 relaxed = container != drflac_container_unknown;
4925 drflac_uint8 id[4];
4927 // Skip over any ID3 tags.
4928 for (;;) {
4929 if (onRead(pUserData, id, 4) != 4) {
4930 return DRFLAC_FALSE; // Ran out of data.
4932 pInit->runningFilePos += 4;
4934 if (id[0] == 'I' && id[1] == 'D' && id[2] == '3') {
4935 drflac_uint8 header[6];
4936 if (onRead(pUserData, header, 6) != 6) {
4937 return DRFLAC_FALSE; // Ran out of data.
4939 pInit->runningFilePos += 6;
4941 drflac_uint8 flags = header[1];
4942 drflac_uint32 headerSize;
4943 drflac_copy_memory(&headerSize, header+2, 4);
4944 headerSize = drflac__unsynchsafe_32(drflac__be2host_32(headerSize));
4945 if (flags & 0x10) {
4946 headerSize += 10;
4949 if (!onSeek(pUserData, headerSize, drflac_seek_origin_current)) {
4950 return DRFLAC_FALSE; // Failed to seek past the tag.
4952 pInit->runningFilePos += headerSize;
4953 } else {
4954 break;
4958 if (id[0] == 'f' && id[1] == 'L' && id[2] == 'a' && id[3] == 'C') {
4959 return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
4961 #ifndef DR_FLAC_NO_OGG
4962 if (id[0] == 'O' && id[1] == 'g' && id[2] == 'g' && id[3] == 'S') {
4963 return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
4965 #endif
4967 // If we get here it means we likely don't have a header. Try opening in relaxed mode, if applicable.
4968 if (relaxed) {
4969 if (container == drflac_container_native) {
4970 return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
4972 #ifndef DR_FLAC_NO_OGG
4973 if (container == drflac_container_ogg) {
4974 return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
4976 #endif
4979 // Unsupported container.
4980 return DRFLAC_FALSE;
4983 void drflac__init_from_info(drflac* pFlac, drflac_init_info* pInit)
4985 drflac_assert(pFlac != NULL);
4986 drflac_assert(pInit != NULL);
4988 drflac_zero_memory(pFlac, sizeof(*pFlac));
4989 pFlac->bs = pInit->bs;
4990 pFlac->onMeta = pInit->onMeta;
4991 pFlac->pUserDataMD = pInit->pUserDataMD;
4992 pFlac->maxBlockSize = pInit->maxBlockSize;
4993 pFlac->sampleRate = pInit->sampleRate;
4994 pFlac->channels = (drflac_uint8)pInit->channels;
4995 pFlac->bitsPerSample = (drflac_uint8)pInit->bitsPerSample;
4996 pFlac->totalSampleCount = pInit->totalSampleCount;
4997 pFlac->container = pInit->container;
5000 drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD)
5002 #ifndef DRFLAC_NO_CPUID
5003 // CPU support first.
5004 drflac__init_cpu_caps();
5005 #endif
5007 drflac_init_info init;
5008 if (!drflac__init_private(&init, onRead, onSeek, onMeta, container, pUserData, pUserDataMD)) {
5009 return NULL;
5012 // The size of the allocation for the drflac object needs to be large enough to fit the following:
5013 // 1) The main members of the drflac structure
5014 // 2) A block of memory large enough to store the decoded samples of the largest frame in the stream
5015 // 3) If the container is Ogg, a drflac_oggbs object
5017 // The complicated part of the allocation is making sure there's enough room the decoded samples, taking into consideration
5018 // the different SIMD instruction sets.
5019 drflac_uint32 allocationSize = sizeof(drflac);
5021 // The allocation size for decoded frames depends on the number of 32-bit integers that fit inside the largest SIMD vector
5022 // we are supporting.
5023 drflac_uint32 wholeSIMDVectorCountPerChannel;
5024 if ((init.maxBlockSize % (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) == 0) {
5025 wholeSIMDVectorCountPerChannel = (init.maxBlockSize / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32)));
5026 } else {
5027 wholeSIMDVectorCountPerChannel = (init.maxBlockSize / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) + 1;
5030 drflac_uint32 decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * DRFLAC_MAX_SIMD_VECTOR_SIZE * init.channels;
5032 allocationSize += decodedSamplesAllocationSize;
5033 allocationSize += DRFLAC_MAX_SIMD_VECTOR_SIZE; // Allocate extra bytes to ensure we have enough for alignment.
5035 #ifndef DR_FLAC_NO_OGG
5036 // There's additional data required for Ogg streams.
5037 drflac_uint32 oggbsAllocationSize = 0;
5038 if (init.container == drflac_container_ogg) {
5039 oggbsAllocationSize = sizeof(drflac_oggbs);
5040 allocationSize += oggbsAllocationSize;
5043 drflac_oggbs oggbs;
5044 drflac_zero_memory(&oggbs, sizeof(oggbs));
5045 if (init.container == drflac_container_ogg) {
5046 oggbs.onRead = onRead;
5047 oggbs.onSeek = onSeek;
5048 oggbs.pUserData = pUserData;
5049 oggbs.currentBytePos = init.oggFirstBytePos;
5050 oggbs.firstBytePos = init.oggFirstBytePos;
5051 oggbs.serialNumber = init.oggSerial;
5052 oggbs.bosPageHeader = init.oggBosHeader;
5053 oggbs.bytesRemainingInPage = 0;
5055 #endif
5057 // This part is a bit awkward. We need to load the seektable so that it can be referenced in-memory, but I want the drflac object to
5058 // consist of only a single heap allocation. To this, the size of the seek table needs to be known, which we determine when reading
5059 // and decoding the metadata.
5060 drflac_uint64 firstFramePos = 42; // <-- We know we are at byte 42 at this point.
5061 drflac_uint64 seektablePos = 0;
5062 drflac_uint32 seektableSize = 0;
5063 if (init.hasMetadataBlocks) {
5064 drflac_read_proc onReadOverride = onRead;
5065 drflac_seek_proc onSeekOverride = onSeek;
5066 void* pUserDataOverride = pUserData;
5068 #ifndef DR_FLAC_NO_OGG
5069 if (init.container == drflac_container_ogg) {
5070 onReadOverride = drflac__on_read_ogg;
5071 onSeekOverride = drflac__on_seek_ogg;
5072 pUserDataOverride = (void*)&oggbs;
5074 #endif
5076 if (!drflac__read_and_decode_metadata(onReadOverride, onSeekOverride, onMeta, pUserDataOverride, pUserDataMD, &firstFramePos, &seektablePos, &seektableSize)) {
5077 return NULL;
5080 allocationSize += seektableSize;
5084 drflac* pFlac = (drflac*)DRFLAC_MALLOC(allocationSize);
5085 drflac__init_from_info(pFlac, &init);
5086 pFlac->pDecodedSamples = (drflac_int32*)drflac_align((size_t)pFlac->pExtraData, DRFLAC_MAX_SIMD_VECTOR_SIZE);
5088 #ifndef DR_FLAC_NO_OGG
5089 if (init.container == drflac_container_ogg) {
5090 drflac_oggbs* pInternalOggbs = (drflac_oggbs*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize + seektableSize);
5091 *pInternalOggbs = oggbs;
5093 // The Ogg bistream needs to be layered on top of the original bitstream.
5094 pFlac->bs.onRead = drflac__on_read_ogg;
5095 pFlac->bs.onSeek = drflac__on_seek_ogg;
5096 pFlac->bs.pUserData = (void*)pInternalOggbs;
5097 pFlac->_oggbs = (void*)pInternalOggbs;
5099 #endif
5101 pFlac->firstFramePos = firstFramePos;
5103 // NOTE: Seektables are not currently compatible with Ogg encapsulation (Ogg has its own accelerated seeking system). I may change this later, so I'm leaving this here for now.
5104 #ifndef DR_FLAC_NO_OGG
5105 if (init.container == drflac_container_ogg)
5107 pFlac->pSeekpoints = NULL;
5108 pFlac->seekpointCount = 0;
5110 else
5111 #endif
5113 // If we have a seektable we need to load it now, making sure we move back to where we were previously.
5114 if (seektablePos != 0) {
5115 pFlac->seekpointCount = seektableSize / sizeof(*pFlac->pSeekpoints);
5116 pFlac->pSeekpoints = (drflac_seekpoint*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize);
5118 // Seek to the seektable, then just read directly into our seektable buffer.
5119 if (pFlac->bs.onSeek(pFlac->bs.pUserData, (int)seektablePos, drflac_seek_origin_start)) {
5120 if (pFlac->bs.onRead(pFlac->bs.pUserData, pFlac->pSeekpoints, seektableSize) == seektableSize) {
5121 // Endian swap.
5122 for (drflac_uint32 iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
5123 pFlac->pSeekpoints[iSeekpoint].firstSample = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].firstSample);
5124 pFlac->pSeekpoints[iSeekpoint].frameOffset = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].frameOffset);
5125 pFlac->pSeekpoints[iSeekpoint].sampleCount = drflac__be2host_16(pFlac->pSeekpoints[iSeekpoint].sampleCount);
5127 } else {
5128 // Failed to read the seektable. Pretend we don't have one.
5129 pFlac->pSeekpoints = NULL;
5130 pFlac->seekpointCount = 0;
5133 // We need to seek back to where we were. If this fails it's a critical error.
5134 if (!pFlac->bs.onSeek(pFlac->bs.pUserData, (int)pFlac->firstFramePos, drflac_seek_origin_start)) {
5135 DRFLAC_FREE(pFlac);
5136 return NULL;
5138 } else {
5139 // Failed to seek to the seektable. Ominous sign, but for now we can just pretend we don't have one.
5140 pFlac->pSeekpoints = NULL;
5141 pFlac->seekpointCount = 0;
5148 // If we get here, but don't have a STREAMINFO block, it means we've opened the stream in relaxed mode and need to decode
5149 // the first frame.
5150 if (!init.hasStreamInfoBlock) {
5151 pFlac->currentFrame.header = init.firstFrameHeader;
5154 drflac_result result = drflac__decode_frame(pFlac);
5155 if (result == DRFLAC_SUCCESS) {
5156 break;
5157 } else {
5158 if (result == DRFLAC_CRC_MISMATCH) {
5159 if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header)) {
5160 DRFLAC_FREE(pFlac);
5161 return NULL;
5163 continue;
5164 } else {
5165 DRFLAC_FREE(pFlac);
5166 return NULL;
5169 } while (1);
5172 return pFlac;
5177 #ifndef DR_FLAC_NO_STDIO
5178 #include <stdio.h>
5180 static size_t drflac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead)
5182 return fread(bufferOut, 1, bytesToRead, (FILE*)pUserData);
5185 static drflac_bool32 drflac__on_seek_stdio(void* pUserData, int offset, drflac_seek_origin origin)
5187 drflac_assert(offset >= 0); // <-- Never seek backwards.
5189 return fseek((FILE*)pUserData, offset, (origin == drflac_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
5192 static FILE* drflac__fopen(const char* filename)
5194 FILE* pFile;
5195 #ifdef _MSC_VER
5196 if (fopen_s(&pFile, filename, "rb") != 0) {
5197 return NULL;
5199 #else
5200 pFile = fopen(filename, "rb");
5201 if (pFile == NULL) {
5202 return NULL;
5204 #endif
5206 return pFile;
5210 drflac* drflac_open_file(const char* filename)
5212 FILE* file = drflac__fopen(filename);
5213 if (file == NULL) {
5214 return NULL;
5217 drflac* pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, (void*)file);
5218 if (pFlac == NULL) {
5219 fclose(file);
5220 return NULL;
5223 return pFlac;
5226 drflac* drflac_open_file_with_metadata(const char* filename, drflac_meta_proc onMeta, void* pUserData)
5228 FILE* file = drflac__fopen(filename);
5229 if (file == NULL) {
5230 return NULL;
5233 drflac* pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, onMeta, drflac_container_unknown, (void*)file, pUserData);
5234 if (pFlac == NULL) {
5235 fclose(file);
5236 return pFlac;
5239 return pFlac;
5241 #endif //DR_FLAC_NO_STDIO
5243 static size_t drflac__on_read_memory(void* pUserData, void* bufferOut, size_t bytesToRead)
5245 drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
5246 drflac_assert(memoryStream != NULL);
5247 drflac_assert(memoryStream->dataSize >= memoryStream->currentReadPos);
5249 size_t bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos;
5250 if (bytesToRead > bytesRemaining) {
5251 bytesToRead = bytesRemaining;
5254 if (bytesToRead > 0) {
5255 drflac_copy_memory(bufferOut, memoryStream->data + memoryStream->currentReadPos, bytesToRead);
5256 memoryStream->currentReadPos += bytesToRead;
5259 return bytesToRead;
5262 static drflac_bool32 drflac__on_seek_memory(void* pUserData, int offset, drflac_seek_origin origin)
5264 drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
5265 drflac_assert(memoryStream != NULL);
5266 drflac_assert(offset >= 0); // <-- Never seek backwards.
5268 if (offset > (drflac_int64)memoryStream->dataSize) {
5269 return DRFLAC_FALSE;
5272 if (origin == drflac_seek_origin_current) {
5273 if (memoryStream->currentReadPos + offset <= memoryStream->dataSize) {
5274 memoryStream->currentReadPos += offset;
5275 } else {
5276 return DRFLAC_FALSE; // Trying to seek too far forward.
5278 } else {
5279 if ((drflac_uint32)offset <= memoryStream->dataSize) {
5280 memoryStream->currentReadPos = offset;
5281 } else {
5282 return DRFLAC_FALSE; // Trying to seek too far forward.
5286 return DRFLAC_TRUE;
5289 drflac* drflac_open_memory(const void* data, size_t dataSize)
5291 drflac__memory_stream memoryStream;
5292 memoryStream.data = (const unsigned char*)data;
5293 memoryStream.dataSize = dataSize;
5294 memoryStream.currentReadPos = 0;
5295 drflac* pFlac = drflac_open(drflac__on_read_memory, drflac__on_seek_memory, &memoryStream);
5296 if (pFlac == NULL) {
5297 return NULL;
5300 pFlac->memoryStream = memoryStream;
5302 // This is an awful hack...
5303 #ifndef DR_FLAC_NO_OGG
5304 if (pFlac->container == drflac_container_ogg)
5306 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
5307 oggbs->pUserData = &pFlac->memoryStream;
5309 else
5310 #endif
5312 pFlac->bs.pUserData = &pFlac->memoryStream;
5315 return pFlac;
5318 drflac* drflac_open_memory_with_metadata(const void* data, size_t dataSize, drflac_meta_proc onMeta, void* pUserData)
5320 drflac__memory_stream memoryStream;
5321 memoryStream.data = (const unsigned char*)data;
5322 memoryStream.dataSize = dataSize;
5323 memoryStream.currentReadPos = 0;
5324 drflac* pFlac = drflac_open_with_metadata_private(drflac__on_read_memory, drflac__on_seek_memory, onMeta, drflac_container_unknown, &memoryStream, pUserData);
5325 if (pFlac == NULL) {
5326 return NULL;
5329 pFlac->memoryStream = memoryStream;
5331 // This is an awful hack...
5332 #ifndef DR_FLAC_NO_OGG
5333 if (pFlac->container == drflac_container_ogg)
5335 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
5336 oggbs->pUserData = &pFlac->memoryStream;
5338 else
5339 #endif
5341 pFlac->bs.pUserData = &pFlac->memoryStream;
5344 return pFlac;
5349 drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData)
5351 return drflac_open_with_metadata_private(onRead, onSeek, NULL, drflac_container_unknown, pUserData, pUserData);
5353 drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData)
5355 return drflac_open_with_metadata_private(onRead, onSeek, NULL, container, pUserData, pUserData);
5358 drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData)
5360 return drflac_open_with_metadata_private(onRead, onSeek, onMeta, drflac_container_unknown, pUserData, pUserData);
5362 drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData)
5364 return drflac_open_with_metadata_private(onRead, onSeek, onMeta, container, pUserData, pUserData);
5367 void drflac_close(drflac* pFlac)
5369 if (pFlac == NULL) {
5370 return;
5373 #ifndef DR_FLAC_NO_STDIO
5374 // If we opened the file with drflac_open_file() we will want to close the file handle. We can know whether or not drflac_open_file()
5375 // was used by looking at the callbacks.
5376 if (pFlac->bs.onRead == drflac__on_read_stdio) {
5377 fclose((FILE*)pFlac->bs.pUserData);
5380 #ifndef DR_FLAC_NO_OGG
5381 // Need to clean up Ogg streams a bit differently due to the way the bit streaming is chained.
5382 if (pFlac->container == drflac_container_ogg) {
5383 drflac_assert(pFlac->bs.onRead == drflac__on_read_ogg);
5384 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
5385 if (oggbs->onRead == drflac__on_read_stdio) {
5386 fclose((FILE*)oggbs->pUserData);
5389 #endif
5390 #endif
5392 DRFLAC_FREE(pFlac);
5395 drflac_uint64 drflac__read_s32__misaligned(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int32* bufferOut)
5397 unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment);
5399 // We should never be calling this when the number of samples to read is >= the sample count.
5400 drflac_assert(samplesToRead < channelCount);
5401 drflac_assert(pFlac->currentFrame.samplesRemaining > 0 && samplesToRead <= pFlac->currentFrame.samplesRemaining);
5404 drflac_uint64 samplesRead = 0;
5405 while (samplesToRead > 0) {
5406 drflac_uint64 totalSamplesInFrame = pFlac->currentFrame.header.blockSize * channelCount;
5407 drflac_uint64 samplesReadFromFrameSoFar = totalSamplesInFrame - pFlac->currentFrame.samplesRemaining;
5408 drflac_uint64 channelIndex = samplesReadFromFrameSoFar % channelCount;
5410 drflac_uint64 nextSampleInFrame = samplesReadFromFrameSoFar / channelCount;
5412 int decodedSample = 0;
5413 switch (pFlac->currentFrame.header.channelAssignment)
5415 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
5417 if (channelIndex == 0) {
5418 decodedSample = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample;
5419 } else {
5420 int side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample;
5421 int left = pFlac->currentFrame.subframes[channelIndex - 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex - 1].wastedBitsPerSample;
5422 decodedSample = left - side;
5424 } break;
5426 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
5428 if (channelIndex == 0) {
5429 int side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample;
5430 int right = pFlac->currentFrame.subframes[channelIndex + 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 1].wastedBitsPerSample;
5431 decodedSample = side + right;
5432 } else {
5433 decodedSample = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample;
5435 } break;
5437 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
5439 int mid;
5440 int side;
5441 if (channelIndex == 0) {
5442 mid = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample;
5443 side = pFlac->currentFrame.subframes[channelIndex + 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 1].wastedBitsPerSample;
5445 mid = (((unsigned int)mid) << 1) | (side & 0x01);
5446 decodedSample = (mid + side) >> 1;
5447 } else {
5448 mid = pFlac->currentFrame.subframes[channelIndex - 1].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex - 1].wastedBitsPerSample;
5449 side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample;
5451 mid = (((unsigned int)mid) << 1) | (side & 0x01);
5452 decodedSample = (mid - side) >> 1;
5454 } break;
5456 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
5457 default:
5459 decodedSample = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame] << pFlac->currentFrame.subframes[channelIndex + 0].wastedBitsPerSample;
5460 } break;
5464 decodedSample <<= (32 - pFlac->bitsPerSample);
5466 if (bufferOut) {
5467 *bufferOut++ = decodedSample;
5470 samplesRead += 1;
5471 pFlac->currentFrame.samplesRemaining -= 1;
5472 samplesToRead -= 1;
5475 return samplesRead;
5478 drflac_uint64 drflac__seek_forward_by_samples(drflac* pFlac, drflac_uint64 samplesToRead)
5480 drflac_uint64 samplesRead = 0;
5481 while (samplesToRead > 0) {
5482 if (pFlac->currentFrame.samplesRemaining == 0) {
5483 if (!drflac__read_and_decode_next_frame(pFlac)) {
5484 break; // Couldn't read the next frame, so just break from the loop and return.
5486 } else {
5487 if (pFlac->currentFrame.samplesRemaining > samplesToRead) {
5488 samplesRead += samplesToRead;
5489 pFlac->currentFrame.samplesRemaining -= (drflac_uint32)samplesToRead; // <-- Safe cast. Will always be < currentFrame.samplesRemaining < 65536.
5490 samplesToRead = 0;
5491 } else {
5492 samplesRead += pFlac->currentFrame.samplesRemaining;
5493 samplesToRead -= pFlac->currentFrame.samplesRemaining;
5494 pFlac->currentFrame.samplesRemaining = 0;
5499 pFlac->currentSample += samplesRead;
5500 return samplesRead;
5503 drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int32* bufferOut)
5505 // Note that <bufferOut> is allowed to be null, in which case this will act like a seek.
5506 if (pFlac == NULL || samplesToRead == 0) {
5507 return 0;
5510 if (bufferOut == NULL) {
5511 return drflac__seek_forward_by_samples(pFlac, samplesToRead);
5515 drflac_uint64 samplesRead = 0;
5516 while (samplesToRead > 0) {
5517 // If we've run out of samples in this frame, go to the next.
5518 if (pFlac->currentFrame.samplesRemaining == 0) {
5519 if (!drflac__read_and_decode_next_frame(pFlac)) {
5520 break; // Couldn't read the next frame, so just break from the loop and return.
5522 } else {
5523 // Here is where we grab the samples and interleave them.
5525 unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment);
5526 drflac_uint64 totalSamplesInFrame = pFlac->currentFrame.header.blockSize * channelCount;
5527 drflac_uint64 samplesReadFromFrameSoFar = totalSamplesInFrame - pFlac->currentFrame.samplesRemaining;
5529 drflac_uint64 misalignedSampleCount = samplesReadFromFrameSoFar % channelCount;
5530 if (misalignedSampleCount > 0) {
5531 drflac_uint64 misalignedSamplesRead = drflac__read_s32__misaligned(pFlac, misalignedSampleCount, bufferOut);
5532 samplesRead += misalignedSamplesRead;
5533 samplesReadFromFrameSoFar += misalignedSamplesRead;
5534 bufferOut += misalignedSamplesRead;
5535 samplesToRead -= misalignedSamplesRead;
5536 pFlac->currentSample += misalignedSamplesRead;
5540 drflac_uint64 alignedSampleCountPerChannel = samplesToRead / channelCount;
5541 if (alignedSampleCountPerChannel > pFlac->currentFrame.samplesRemaining / channelCount) {
5542 alignedSampleCountPerChannel = pFlac->currentFrame.samplesRemaining / channelCount;
5545 drflac_uint64 firstAlignedSampleInFrame = samplesReadFromFrameSoFar / channelCount;
5546 unsigned int unusedBitsPerSample = 32 - pFlac->bitsPerSample;
5548 switch (pFlac->currentFrame.header.channelAssignment)
5550 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
5552 const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + firstAlignedSampleInFrame;
5553 const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame;
5555 for (drflac_uint64 i = 0; i < alignedSampleCountPerChannel; ++i) {
5556 int left = pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample);
5557 int side = pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample);
5558 int right = left - side;
5560 bufferOut[i*2+0] = left;
5561 bufferOut[i*2+1] = right;
5563 } break;
5565 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
5567 const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + firstAlignedSampleInFrame;
5568 const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame;
5570 for (drflac_uint64 i = 0; i < alignedSampleCountPerChannel; ++i) {
5571 int side = pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample);
5572 int right = pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample);
5573 int left = right + side;
5575 bufferOut[i*2+0] = left;
5576 bufferOut[i*2+1] = right;
5578 } break;
5580 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
5582 const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + firstAlignedSampleInFrame;
5583 const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame;
5585 for (drflac_uint64 i = 0; i < alignedSampleCountPerChannel; ++i) {
5586 int mid = pDecodedSamples0[i] << pFlac->currentFrame.subframes[0].wastedBitsPerSample;
5587 int side = pDecodedSamples1[i] << pFlac->currentFrame.subframes[1].wastedBitsPerSample;
5589 mid = (((drflac_uint32)mid) << 1) | (side & 0x01);
5591 bufferOut[i*2+0] = ((mid + side) >> 1) << (unusedBitsPerSample);
5592 bufferOut[i*2+1] = ((mid - side) >> 1) << (unusedBitsPerSample);
5594 } break;
5596 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
5597 default:
5599 if (pFlac->currentFrame.header.channelAssignment == 1) // 1 = Stereo
5601 // Stereo optimized inner loop unroll.
5602 const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + firstAlignedSampleInFrame;
5603 const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame;
5605 for (drflac_uint64 i = 0; i < alignedSampleCountPerChannel; ++i) {
5606 bufferOut[i*2+0] = pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample);
5607 bufferOut[i*2+1] = pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample);
5610 else
5612 // Generic interleaving.
5613 for (drflac_uint64 i = 0; i < alignedSampleCountPerChannel; ++i) {
5614 for (unsigned int j = 0; j < channelCount; ++j) {
5615 bufferOut[(i*channelCount)+j] = (pFlac->currentFrame.subframes[j].pDecodedSamples[firstAlignedSampleInFrame + i]) << (unusedBitsPerSample + pFlac->currentFrame.subframes[j].wastedBitsPerSample);
5619 } break;
5622 drflac_uint64 alignedSamplesRead = alignedSampleCountPerChannel * channelCount;
5623 samplesRead += alignedSamplesRead;
5624 samplesReadFromFrameSoFar += alignedSamplesRead;
5625 bufferOut += alignedSamplesRead;
5626 samplesToRead -= alignedSamplesRead;
5627 pFlac->currentSample += alignedSamplesRead;
5628 pFlac->currentFrame.samplesRemaining -= (unsigned int)alignedSamplesRead;
5631 // At this point we may still have some excess samples left to read.
5632 if (samplesToRead > 0 && pFlac->currentFrame.samplesRemaining > 0) {
5633 drflac_uint64 excessSamplesRead = 0;
5634 if (samplesToRead < pFlac->currentFrame.samplesRemaining) {
5635 excessSamplesRead = drflac__read_s32__misaligned(pFlac, samplesToRead, bufferOut);
5636 } else {
5637 excessSamplesRead = drflac__read_s32__misaligned(pFlac, pFlac->currentFrame.samplesRemaining, bufferOut);
5640 samplesRead += excessSamplesRead;
5641 samplesReadFromFrameSoFar += excessSamplesRead;
5642 bufferOut += excessSamplesRead;
5643 samplesToRead -= excessSamplesRead;
5644 pFlac->currentSample += excessSamplesRead;
5649 return samplesRead;
5652 drflac_uint64 drflac_read_s16(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int16* pBufferOut)
5654 // This reads samples in 2 passes and can probably be optimized.
5655 drflac_uint64 totalSamplesRead = 0;
5657 while (samplesToRead > 0) {
5658 drflac_int32 samples32[4096];
5659 drflac_uint64 samplesJustRead = drflac_read_s32(pFlac, (samplesToRead > 4096) ? 4096 : samplesToRead, samples32);
5660 if (samplesJustRead == 0) {
5661 break; // Reached the end.
5664 // s32 -> s16
5665 for (drflac_uint64 i = 0; i < samplesJustRead; ++i) {
5666 pBufferOut[i] = (drflac_int16)(samples32[i] >> 16);
5669 totalSamplesRead += samplesJustRead;
5670 samplesToRead -= samplesJustRead;
5671 pBufferOut += samplesJustRead;
5674 return totalSamplesRead;
5677 drflac_uint64 drflac_read_f32(drflac* pFlac, drflac_uint64 samplesToRead, float* pBufferOut)
5679 // This reads samples in 2 passes and can probably be optimized.
5680 drflac_uint64 totalSamplesRead = 0;
5682 while (samplesToRead > 0) {
5683 drflac_int32 samples32[4096];
5684 drflac_uint64 samplesJustRead = drflac_read_s32(pFlac, (samplesToRead > 4096) ? 4096 : samplesToRead, samples32);
5685 if (samplesJustRead == 0) {
5686 break; // Reached the end.
5689 // s32 -> f32
5690 for (drflac_uint64 i = 0; i < samplesJustRead; ++i) {
5691 pBufferOut[i] = (float)(samples32[i] / 2147483648.0);
5694 totalSamplesRead += samplesJustRead;
5695 samplesToRead -= samplesJustRead;
5696 pBufferOut += samplesJustRead;
5699 return totalSamplesRead;
5702 drflac_bool32 drflac_seek_to_sample(drflac* pFlac, drflac_uint64 sampleIndex)
5704 if (pFlac == NULL) {
5705 return DRFLAC_FALSE;
5708 // If we don't know where the first frame begins then we can't seek. This will happen when the STREAMINFO block was not present
5709 // when the decoder was opened.
5710 if (pFlac->firstFramePos == 0) {
5711 return DRFLAC_FALSE;
5714 if (sampleIndex == 0) {
5715 pFlac->currentSample = 0;
5716 return drflac__seek_to_first_frame(pFlac);
5717 } else {
5718 drflac_bool32 wasSuccessful = DRFLAC_FALSE;
5720 // Clamp the sample to the end.
5721 if (sampleIndex >= pFlac->totalSampleCount) {
5722 sampleIndex = pFlac->totalSampleCount - 1;
5725 // If the target sample and the current sample are in the same frame we just move the position forward.
5726 if (sampleIndex > pFlac->currentSample) {
5727 // Forward.
5728 drflac_uint32 offset = (drflac_uint32)(sampleIndex - pFlac->currentSample);
5729 if (pFlac->currentFrame.samplesRemaining > offset) {
5730 pFlac->currentFrame.samplesRemaining -= offset;
5731 pFlac->currentSample = sampleIndex;
5732 return DRFLAC_TRUE;
5734 } else {
5735 // Backward.
5736 drflac_uint32 offsetAbs = (drflac_uint32)(pFlac->currentSample - sampleIndex);
5737 drflac_uint32 currentFrameSampleCount = pFlac->currentFrame.header.blockSize * drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment);
5738 drflac_uint32 currentFrameSamplesConsumed = (drflac_uint32)(currentFrameSampleCount - pFlac->currentFrame.samplesRemaining);
5739 if (currentFrameSamplesConsumed > offsetAbs) {
5740 pFlac->currentFrame.samplesRemaining += offsetAbs;
5741 pFlac->currentSample = sampleIndex;
5742 return DRFLAC_TRUE;
5746 // Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so
5747 // we'll instead use Ogg's natural seeking facility.
5748 #ifndef DR_FLAC_NO_OGG
5749 if (pFlac->container == drflac_container_ogg)
5751 wasSuccessful = drflac_ogg__seek_to_sample(pFlac, sampleIndex);
5753 else
5754 #endif
5756 // First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower.
5757 wasSuccessful = drflac__seek_to_sample__seek_table(pFlac, sampleIndex);
5758 if (!wasSuccessful) {
5759 wasSuccessful = drflac__seek_to_sample__brute_force(pFlac, sampleIndex);
5763 pFlac->currentSample = sampleIndex;
5764 return wasSuccessful;
5770 //// High Level APIs ////
5772 #if defined(SIZE_MAX)
5773 #define DRFLAC_SIZE_MAX SIZE_MAX
5774 #else
5775 #if defined(DRFLAC_64BIT)
5776 #define DRFLAC_SIZE_MAX ((drflac_uint64)0xFFFFFFFFFFFFFFFF)
5777 #else
5778 #define DRFLAC_SIZE_MAX 0xFFFFFFFF
5779 #endif
5780 #endif
5783 // Using a macro as the definition of the drflac__full_decode_and_close_*() API family. Sue me.
5784 #define DRFLAC_DEFINE_FULL_DECODE_AND_CLOSE(extension, type) \
5785 static type* drflac__full_decode_and_close_ ## extension (drflac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalSampleCountOut)\
5787 drflac_assert(pFlac != NULL); \
5789 type* pSampleData = NULL; \
5790 drflac_uint64 totalSampleCount = pFlac->totalSampleCount; \
5792 if (totalSampleCount == 0) { \
5793 type buffer[4096]; \
5795 size_t sampleDataBufferSize = sizeof(buffer); \
5796 pSampleData = (type*)DRFLAC_MALLOC(sampleDataBufferSize); \
5797 if (pSampleData == NULL) { \
5798 goto on_error; \
5801 drflac_uint64 samplesRead; \
5802 while ((samplesRead = (drflac_uint64)drflac_read_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0]), buffer)) > 0) { \
5803 if (((totalSampleCount + samplesRead) * sizeof(type)) > sampleDataBufferSize) { \
5804 sampleDataBufferSize *= 2; \
5805 type* pNewSampleData = (type*)DRFLAC_REALLOC(pSampleData, sampleDataBufferSize); \
5806 if (pNewSampleData == NULL) { \
5807 DRFLAC_FREE(pSampleData); \
5808 goto on_error; \
5811 pSampleData = pNewSampleData; \
5814 drflac_copy_memory(pSampleData + totalSampleCount, buffer, (size_t)(samplesRead*sizeof(type))); \
5815 totalSampleCount += samplesRead; \
5818 /* At this point everything should be decoded, but we just want to fill the unused part buffer with silence - need to \
5819 protect those ears from random noise! */ \
5820 drflac_zero_memory(pSampleData + totalSampleCount, (size_t)(sampleDataBufferSize - totalSampleCount*sizeof(type))); \
5821 } else { \
5822 drflac_uint64 dataSize = totalSampleCount * sizeof(type); \
5823 if (dataSize > DRFLAC_SIZE_MAX) { \
5824 goto on_error; /* The decoded data is too big. */ \
5827 pSampleData = (type*)DRFLAC_MALLOC((size_t)dataSize); /* <-- Safe cast as per the check above. */ \
5828 if (pSampleData == NULL) { \
5829 goto on_error; \
5832 totalSampleCount = drflac_read_##extension(pFlac, pFlac->totalSampleCount, pSampleData); \
5835 if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \
5836 if (channelsOut) *channelsOut = pFlac->channels; \
5837 if (totalSampleCountOut) *totalSampleCountOut = totalSampleCount; \
5839 drflac_close(pFlac); \
5840 return pSampleData; \
5842 on_error: \
5843 drflac_close(pFlac); \
5844 return NULL; \
5847 DRFLAC_DEFINE_FULL_DECODE_AND_CLOSE(s32, drflac_int32)
5848 DRFLAC_DEFINE_FULL_DECODE_AND_CLOSE(s16, drflac_int16)
5849 DRFLAC_DEFINE_FULL_DECODE_AND_CLOSE(f32, float)
5851 drflac_int32* drflac_open_and_decode_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5853 // Safety.
5854 if (sampleRate) *sampleRate = 0;
5855 if (channels) *channels = 0;
5856 if (totalSampleCount) *totalSampleCount = 0;
5858 drflac* pFlac = drflac_open(onRead, onSeek, pUserData);
5859 if (pFlac == NULL) {
5860 return NULL;
5863 return drflac__full_decode_and_close_s32(pFlac, channels, sampleRate, totalSampleCount);
5866 drflac_int16* drflac_open_and_decode_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5868 // Safety.
5869 if (sampleRate) *sampleRate = 0;
5870 if (channels) *channels = 0;
5871 if (totalSampleCount) *totalSampleCount = 0;
5873 drflac* pFlac = drflac_open(onRead, onSeek, pUserData);
5874 if (pFlac == NULL) {
5875 return NULL;
5878 return drflac__full_decode_and_close_s16(pFlac, channels, sampleRate, totalSampleCount);
5881 float* drflac_open_and_decode_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5883 // Safety.
5884 if (sampleRate) *sampleRate = 0;
5885 if (channels) *channels = 0;
5886 if (totalSampleCount) *totalSampleCount = 0;
5888 drflac* pFlac = drflac_open(onRead, onSeek, pUserData);
5889 if (pFlac == NULL) {
5890 return NULL;
5893 return drflac__full_decode_and_close_f32(pFlac, channels, sampleRate, totalSampleCount);
5896 #ifndef DR_FLAC_NO_STDIO
5897 drflac_int32* drflac_open_and_decode_file_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5899 if (sampleRate) *sampleRate = 0;
5900 if (channels) *channels = 0;
5901 if (totalSampleCount) *totalSampleCount = 0;
5903 drflac* pFlac = drflac_open_file(filename);
5904 if (pFlac == NULL) {
5905 return NULL;
5908 return drflac__full_decode_and_close_s32(pFlac, channels, sampleRate, totalSampleCount);
5911 drflac_int16* drflac_open_and_decode_file_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5913 if (sampleRate) *sampleRate = 0;
5914 if (channels) *channels = 0;
5915 if (totalSampleCount) *totalSampleCount = 0;
5917 drflac* pFlac = drflac_open_file(filename);
5918 if (pFlac == NULL) {
5919 return NULL;
5922 return drflac__full_decode_and_close_s16(pFlac, channels, sampleRate, totalSampleCount);
5925 float* drflac_open_and_decode_file_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5927 if (sampleRate) *sampleRate = 0;
5928 if (channels) *channels = 0;
5929 if (totalSampleCount) *totalSampleCount = 0;
5931 drflac* pFlac = drflac_open_file(filename);
5932 if (pFlac == NULL) {
5933 return NULL;
5936 return drflac__full_decode_and_close_f32(pFlac, channels, sampleRate, totalSampleCount);
5938 #endif
5940 drflac_int32* drflac_open_and_decode_memory_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5942 if (sampleRate) *sampleRate = 0;
5943 if (channels) *channels = 0;
5944 if (totalSampleCount) *totalSampleCount = 0;
5946 drflac* pFlac = drflac_open_memory(data, dataSize);
5947 if (pFlac == NULL) {
5948 return NULL;
5951 return drflac__full_decode_and_close_s32(pFlac, channels, sampleRate, totalSampleCount);
5954 drflac_int16* drflac_open_and_decode_memory_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5956 if (sampleRate) *sampleRate = 0;
5957 if (channels) *channels = 0;
5958 if (totalSampleCount) *totalSampleCount = 0;
5960 drflac* pFlac = drflac_open_memory(data, dataSize);
5961 if (pFlac == NULL) {
5962 return NULL;
5965 return drflac__full_decode_and_close_s16(pFlac, channels, sampleRate, totalSampleCount);
5968 float* drflac_open_and_decode_memory_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5970 if (sampleRate) *sampleRate = 0;
5971 if (channels) *channels = 0;
5972 if (totalSampleCount) *totalSampleCount = 0;
5974 drflac* pFlac = drflac_open_memory(data, dataSize);
5975 if (pFlac == NULL) {
5976 return NULL;
5979 return drflac__full_decode_and_close_f32(pFlac, channels, sampleRate, totalSampleCount);
5982 void drflac_free(void* pSampleDataReturnedByOpenAndDecode)
5984 DRFLAC_FREE(pSampleDataReturnedByOpenAndDecode);
5990 void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments)
5992 if (pIter == NULL) {
5993 return;
5996 pIter->countRemaining = commentCount;
5997 pIter->pRunningData = (const char*)pComments;
6000 const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut)
6002 // Safety.
6003 if (pCommentLengthOut) *pCommentLengthOut = 0;
6005 if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
6006 return NULL;
6009 drflac_uint32 length = drflac__le2host_32(*(const drflac_uint32*)pIter->pRunningData);
6010 pIter->pRunningData += 4;
6012 const char* pComment = pIter->pRunningData;
6013 pIter->pRunningData += length;
6014 pIter->countRemaining -= 1;
6016 if (pCommentLengthOut) *pCommentLengthOut = length;
6017 return pComment;
6023 void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData)
6025 if (pIter == NULL) {
6026 return;
6029 pIter->countRemaining = trackCount;
6030 pIter->pRunningData = (const char*)pTrackData;
6033 drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack)
6035 if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
6036 return DRFLAC_FALSE;
6039 drflac_cuesheet_track cuesheetTrack;
6041 const char* pRunningData = pIter->pRunningData;
6043 drflac_uint64 offsetHi = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
6044 drflac_uint64 offsetLo = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
6045 cuesheetTrack.offset = offsetLo | (offsetHi << 32);
6046 cuesheetTrack.trackNumber = pRunningData[0]; pRunningData += 1;
6047 drflac_copy_memory(cuesheetTrack.ISRC, pRunningData, sizeof(cuesheetTrack.ISRC)); pRunningData += 12;
6048 cuesheetTrack.isAudio = (pRunningData[0] & 0x80) != 0;
6049 cuesheetTrack.preEmphasis = (pRunningData[0] & 0x40) != 0; pRunningData += 14;
6050 cuesheetTrack.indexCount = pRunningData[0]; pRunningData += 1;
6051 cuesheetTrack.pIndexPoints = (const drflac_cuesheet_track_index*)pRunningData; pRunningData += cuesheetTrack.indexCount * sizeof(drflac_cuesheet_track_index);
6053 pIter->pRunningData = pRunningData;
6054 pIter->countRemaining -= 1;
6056 if (pCuesheetTrack) *pCuesheetTrack = cuesheetTrack;
6057 return DRFLAC_TRUE;
6059 #endif //DR_FLAC_IMPLEMENTATION
6062 // REVISION HISTORY
6064 // v0.10.0 - 2018-09-11
6065 // - Remove the DR_FLAC_NO_WIN32_IO option and the Win32 file IO functionality. If you need to use Win32 file IO you
6066 // need to do it yourself via the callback API.
6067 // - Fix the clang build.
6068 // - Fix undefined behavior.
6069 // - Fix errors with CUESHEET metdata blocks.
6070 // - Add an API for iterating over each cuesheet track in the CUESHEET metadata block. This works the same way as the
6071 // Vorbis comment API.
6072 // - Other miscellaneous bug fixes, mostly relating to invalid FLAC streams.
6073 // - Minor optimizations.
6075 // v0.9.11 - 2018-08-29
6076 // - Fix a bug with sample reconstruction.
6078 // v0.9.10 - 2018-08-07
6079 // - Improve 64-bit detection.
6081 // v0.9.9 - 2018-08-05
6082 // - Fix C++ build on older versions of GCC.
6084 // v0.9.8 - 2018-07-24
6085 // - Fix compilation errors.
6087 // v0.9.7 - 2018-07-05
6088 // - Fix a warning.
6090 // v0.9.6 - 2018-06-29
6091 // - Fix some typos.
6093 // v0.9.5 - 2018-06-23
6094 // - Fix some warnings.
6096 // v0.9.4 - 2018-06-14
6097 // - Optimizations to seeking.
6098 // - Clean up.
6100 // v0.9.3 - 2018-05-22
6101 // - Bug fix.
6103 // v0.9.2 - 2018-05-12
6104 // - Fix a compilation error due to a missing break statement.
6106 // v0.9.1 - 2018-04-29
6107 // - Fix compilation error with Clang.
6109 // v0.9 - 2018-04-24
6110 // - Fix Clang build.
6111 // - Start using major.minor.revision versioning.
6113 // v0.8g - 2018-04-19
6114 // - Fix build on non-x86/x64 architectures.
6116 // v0.8f - 2018-02-02
6117 // - Stop pretending to support changing rate/channels mid stream.
6119 // v0.8e - 2018-02-01
6120 // - Fix a crash when the block size of a frame is larger than the maximum block size defined by the FLAC stream.
6121 // - Fix a crash the the Rice partition order is invalid.
6123 // v0.8d - 2017-09-22
6124 // - Add support for decoding streams with ID3 tags. ID3 tags are just skipped.
6126 // v0.8c - 2017-09-07
6127 // - Fix warning on non-x86/x64 architectures.
6129 // v0.8b - 2017-08-19
6130 // - Fix build on non-x86/x64 architectures.
6132 // v0.8a - 2017-08-13
6133 // - A small optimization for the Clang build.
6135 // v0.8 - 2017-08-12
6136 // - API CHANGE: Rename dr_* types to drflac_*.
6137 // - Optimizations. This brings dr_flac back to about the same class of efficiency as the reference implementation.
6138 // - Add support for custom implementations of malloc(), realloc(), etc.
6139 // - Add CRC checking to Ogg encapsulated streams.
6140 // - Fix VC++ 6 build. This is only for the C++ compiler. The C compiler is not currently supported.
6141 // - Bug fixes.
6143 // v0.7 - 2017-07-23
6144 // - Add support for opening a stream without a header block. To do this, use drflac_open_relaxed() / drflac_open_with_metadata_relaxed().
6146 // v0.6 - 2017-07-22
6147 // - Add support for recovering from invalid frames. With this change, dr_flac will simply skip over invalid frames as if they
6148 // never existed. Frames are checked against their sync code, the CRC-8 of the frame header and the CRC-16 of the whole frame.
6150 // v0.5 - 2017-07-16
6151 // - Fix typos.
6152 // - Change drflac_bool* types to unsigned.
6153 // - Add CRC checking. This makes dr_flac slower, but can be disabled with #define DR_FLAC_NO_CRC.
6155 // v0.4f - 2017-03-10
6156 // - Fix a couple of bugs with the bitstreaming code.
6158 // v0.4e - 2017-02-17
6159 // - Fix some warnings.
6161 // v0.4d - 2016-12-26
6162 // - Add support for 32-bit floating-point PCM decoding.
6163 // - Use drflac_int*/drflac_uint* sized types to improve compiler support.
6164 // - Minor improvements to documentation.
6166 // v0.4c - 2016-12-26
6167 // - Add support for signed 16-bit integer PCM decoding.
6169 // v0.4b - 2016-10-23
6170 // - A minor change to drflac_bool8 and drflac_bool32 types.
6172 // v0.4a - 2016-10-11
6173 // - Rename drBool32 to drflac_bool32 for styling consistency.
6175 // v0.4 - 2016-09-29
6176 // - API/ABI CHANGE: Use fixed size 32-bit booleans instead of the built-in bool type.
6177 // - API CHANGE: Rename drflac_open_and_decode*() to drflac_open_and_decode*_s32().
6178 // - API CHANGE: Swap the order of "channels" and "sampleRate" parameters in drflac_open_and_decode*(). Rationale for this is to
6179 // keep it consistent with drflac_audio.
6181 // v0.3f - 2016-09-21
6182 // - Fix a warning with GCC.
6184 // v0.3e - 2016-09-18
6185 // - Fixed a bug where GCC 4.3+ was not getting properly identified.
6186 // - Fixed a few typos.
6187 // - Changed date formats to ISO 8601 (YYYY-MM-DD).
6189 // v0.3d - 2016-06-11
6190 // - Minor clean up.
6192 // v0.3c - 2016-05-28
6193 // - Fixed compilation error.
6195 // v0.3b - 2016-05-16
6196 // - Fixed Linux/GCC build.
6197 // - Updated documentation.
6199 // v0.3a - 2016-05-15
6200 // - Minor fixes to documentation.
6202 // v0.3 - 2016-05-11
6203 // - Optimizations. Now at about parity with the reference implementation on 32-bit builds.
6204 // - Lots of clean up.
6206 // v0.2b - 2016-05-10
6207 // - Bug fixes.
6209 // v0.2a - 2016-05-10
6210 // - Made drflac_open_and_decode() more robust.
6211 // - Removed an unused debugging variable
6213 // v0.2 - 2016-05-09
6214 // - Added support for Ogg encapsulation.
6215 // - API CHANGE. Have the onSeek callback take a third argument which specifies whether or not the seek
6216 // should be relative to the start or the current position. Also changes the seeking rules such that
6217 // seeking offsets will never be negative.
6218 // - Have drflac_open_and_decode() fail gracefully if the stream has an unknown total sample count.
6220 // v0.1b - 2016-05-07
6221 // - Properly close the file handle in drflac_open_file() and family when the decoder fails to initialize.
6222 // - Removed a stale comment.
6224 // v0.1a - 2016-05-05
6225 // - Minor formatting changes.
6226 // - Fixed a warning on the GCC build.
6228 // v0.1 - 2016-05-03
6229 // - Initial versioned release.
6233 This is free and unencumbered software released into the public domain.
6235 Anyone is free to copy, modify, publish, use, compile, sell, or
6236 distribute this software, either in source code form or as a compiled
6237 binary, for any purpose, commercial or non-commercial, and by any
6238 means.
6240 In jurisdictions that recognize copyright laws, the author or authors
6241 of this software dedicate any and all copyright interest in the
6242 software to the public domain. We make this dedication for the benefit
6243 of the public at large and to the detriment of our heirs and
6244 successors. We intend this dedication to be an overt act of
6245 relinquishment in perpetuity of all present and future rights to this
6246 software under copyright law.
6248 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
6249 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
6250 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
6251 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
6252 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
6253 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
6254 OTHER DEALINGS IN THE SOFTWARE.
6256 For more information, please refer to <http://unlicense.org/>