1 // FLAC audio decoder. Public domain. See "unlicense" statement at the end of this file.
2 // dr_flac - v0.3d - 11/06/2016
3 // commit eebbf6ed17e9200a48c8f83a350a82722295558f
4 //
5 // David Reid - mackron@gmail.com
6 //
7 // some fixes from v0.4f - 2017-03-10
8 //   - Fix a couple of bugs with the bitstreaming code.
9 //
10 // fix from 767c3fbda48f54ce1050afa75110ae69cccdf0dd
11 //
12 // some fixes from v0.8d - 2017-09-22 (actually, one)
13 //   k8 SKIPPED: Add support for decoding streams with ID3 tags. ID3 tags are just skipped.
14 //   k8: i am absolutely not interested in such fucked flac files, and won't support that idiocy.
15 //
16 // D translation by Ketmar // Invisible Vector
17 module audioformats.drflac;
18 
19 nothrow @nogc:
20 version(decodeFLAC):
21 
22 
23 // USAGE
24 //
25 // dr_flac is a single-file library.
26 //
27 // To decode audio data, do something like the following:
28 //
29 //     drflac* pFlac = drflac_open_file("MySong.flac");
30 //     if (pFlac is null) {
31 //         // Failed to open FLAC file
32 //     }
33 //
34 //     int* pSamples = malloc(pFlac.totalSampleCount * (int)).sizeof;
35 //     ulong numberOfInterleavedSamplesActuallyRead = drflac_read_s32(pFlac, pFlac.totalSampleCount, pSamples);
36 //
37 // The drflac object represents the decoder. It is a transparent type so all the information you need, such as the number of
38 // channels and the bits per sample, should be directly accessible - just make sure you don't change their values. Samples are
39 // always output as interleaved signed 32-bit PCM. In the example above a native FLAC stream was opened, however dr_flac has
40 // seamless support for Ogg encapsulated FLAC streams as well.
41 //
42 // 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
43 // 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
44 // samples, just call it again. Example:
45 //
46 //     while (drflac_read_s32(pFlac, chunkSize, pChunkSamples) > 0) {
47 //         do_something();
48 //     }
49 //
50 // You can seek to a specific sample with drflac_seek_to_sample(). The given sample is based on interleaving. So for example,
51 // 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.
52 // 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
53 // left channel, etc.
54 //
55 //
56 // If you just want to quickly decode an entire FLAC file in one go you can do something like this:
57 //
58 //     uint sampleRate;
59 //     uint channels;
60 //     ulong totalSampleCount;
61 //     int* pSampleData = drflac_open_and_decode_file("MySong.flac", &sampleRate, &channels, &totalSampleCount);
62 //     if (pSampleData is null) {
63 //         // Failed to open and decode FLAC file.
64 //     }
65 //
66 //     ...
67 //
68 //     drflac_free(pSampleData);
69 //
70 //
71 // If you need access to metadata (album art, etc.), use drflac_open_with_metadata(), drflac_open_file_with_metdata() or
72 // drflac_open_memory_with_metadata(). The rationale for keeping these APIs separate is that they're slightly slower than the
73 // normal versions and also just a little bit harder to use.
74 //
75 // dr_flac reports metadata to the application through the use of a callback, and every metadata block is reported before
76 // drflac_open_with_metdata() returns. See https://github.com/mackron/dr_libs_tests/blob/master/dr_flac/dr_flac_test_2.c for
77 // an example on how to read metadata.
78 //
79 //
80 //
81 // OPTIONS
82 // #define these options before including this file.
83 //
84 // #define DR_FLAC_NO_STDIO
85 //   Disable drflac_open_file().
86 //
87 // #define DR_FLAC_NO_OGG
88 //   Disables support for Ogg/FLAC streams.
89 //
90 // #define DR_FLAC_NO_WIN32_IO
91 //   In the Win32 build, dr_flac uses the Win32 IO APIs for drflac_open_file() by default. This setting will make it use the
92 //   standard FILE APIs instead. Ignored when DR_FLAC_NO_STDIO is #defined. (The rationale for this configuration is that
93 //   there's a bug in one compiler's Win32 implementation of the FILE APIs which is not present in the Win32 IO APIs.)
94 //
95 // #define DR_FLAC_BUFFER_SIZE <number>
96 //   Defines the size of the internal buffer to store data from onRead(). This buffer is used to reduce the number of calls
97 //   back to the client for more data. Larger values means more memory, but better performance. My tests show diminishing
98 //   returns after about 4KB (which is the default). Consider reducing this if you have a very efficient implementation of
99 //   onRead(), or increase it if it's very inefficient. Must be a multiple of 8.
100 //
101 //
102 //
103 // QUICK NOTES
104 // - Based on my tests, the performance of the 32-bit build is at about parity with the reference implementation. The 64-bit build
105 //   is slightly faster.
106 // - dr_flac does not currently do any CRC checks.
107 // - dr_flac should work fine with valid native FLAC files, but for broadcast streams it won't work if the header and STREAMINFO
108 //   block is unavailable.
109 // - Audio data is output as signed 32-bit PCM, regardless of the bits per sample the FLAC stream is encoded as.
110 // - This has not been tested on big-endian architectures.
111 // - Rice codes in unencoded binary form (see https://xiph.org/flac/format.html#rice_partition) has not been tested. If anybody
112 //   knows where I can find some test files for this, let me know.
113 // - Perverse and erroneous files have not been tested. Again, if you know where I can get some test files let me know.
114 // - dr_flac is not thread-safe, but it's APIs can be called from any thread so long as you do your own synchronization.
115 
116 enum DrFlacHasVFS = false;
117 
118 
119 // As data is read from the client it is placed into an internal buffer for fast access. This controls the
120 // size of that buffer. Larger values means more speed, but also more memory. In my testing there is diminishing
121 // returns after about 4KB, but you can fiddle with this to suit your own needs. Must be a multiple of 8.
122 enum DR_FLAC_BUFFER_SIZE = 4096;
123 
124 // Check if we can enable 64-bit optimizations.
125 //version = DRFLAC_64BIT;
126 
127 version(DRFLAC_64BIT) alias drflac_cache_t = ulong; else alias drflac_cache_t = uint;
128 
129 // The various metadata block types.
130 enum DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO = 0;
131 enum DRFLAC_METADATA_BLOCK_TYPE_PADDING = 1;
132 enum DRFLAC_METADATA_BLOCK_TYPE_APPLICATION = 2;
133 enum DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE = 3;
134 enum DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT = 4;
135 enum DRFLAC_METADATA_BLOCK_TYPE_CUESHEET = 5;
136 enum DRFLAC_METADATA_BLOCK_TYPE_PICTURE = 6;
137 enum DRFLAC_METADATA_BLOCK_TYPE_INVALID = 127;
138 
139 // The various picture types specified in the PICTURE block.
140 enum DRFLAC_PICTURE_TYPE_OTHER = 0;
141 enum DRFLAC_PICTURE_TYPE_FILE_ICON = 1;
142 enum DRFLAC_PICTURE_TYPE_OTHER_FILE_ICON = 2;
143 enum DRFLAC_PICTURE_TYPE_COVER_FRONT = 3;
144 enum DRFLAC_PICTURE_TYPE_COVER_BACK = 4;
145 enum DRFLAC_PICTURE_TYPE_LEAFLET_PAGE = 5;
146 enum DRFLAC_PICTURE_TYPE_MEDIA = 6;
147 enum DRFLAC_PICTURE_TYPE_LEAD_ARTIST = 7;
148 enum DRFLAC_PICTURE_TYPE_ARTIST = 8;
149 enum DRFLAC_PICTURE_TYPE_CONDUCTOR = 9;
150 enum DRFLAC_PICTURE_TYPE_BAND = 10;
151 enum DRFLAC_PICTURE_TYPE_COMPOSER = 11;
152 enum DRFLAC_PICTURE_TYPE_LYRICIST = 12;
153 enum DRFLAC_PICTURE_TYPE_RECORDING_LOCATION = 13;
154 enum DRFLAC_PICTURE_TYPE_DURING_RECORDING = 14;
155 enum DRFLAC_PICTURE_TYPE_DURING_PERFORMANCE = 15;
156 enum DRFLAC_PICTURE_TYPE_SCREEN_CAPTURE = 16;
157 enum DRFLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH = 17;
158 enum DRFLAC_PICTURE_TYPE_ILLUSTRATION = 18;
159 enum DRFLAC_PICTURE_TYPE_BAND_LOGOTYPE = 19;
160 enum DRFLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20;
161 
162 alias drflac_container = int;
163 enum {
164   drflac_container_native,
165   drflac_container_ogg,
166 }
167 
168 alias drflac_seek_origin = int;
169 enum {
170   drflac_seek_origin_start,
171   drflac_seek_origin_current,
172 }
173 
174 // Packing is important on this structure because we map this directly to the raw data within the SEEKTABLE metadata block.
175 //#pragma pack(2)
176 align(2) struct drflac_seekpoint {
177 align(2):
178   ulong firstSample;
179   ulong frameOffset;   // The offset from the first byte of the header of the first frame.
180   ushort sampleCount;
181 }
182 //#pragma pack()
183 
184 struct drflac_streaminfo {
185   ushort minBlockSize;
186   ushort maxBlockSize;
187   uint minFrameSize;
188   uint maxFrameSize;
189   uint sampleRate;
190   ubyte channels;
191   ubyte bitsPerSample;
192   ulong totalSampleCount;
193   ubyte[16] md5;
194 }
195 
196 struct drflac_metadata {
197   // The metadata type. Use this to know how to interpret the data below.
198   uint type;
199 
200   // A pointer to the raw data. This points to a temporary buffer so don't hold on to it. It's best to
201   // not modify the contents of this buffer. Use the structures below for more meaningful and structured
202   // information about the metadata. It's possible for this to be null.
203   const(void)* pRawData;
204 
205   // The size in bytes of the block and the buffer pointed to by pRawData if it's non-null.
206   uint rawDataSize;
207 
208   static struct Padding {
209     int unused;
210   }
211 
212   static struct Application {
213     uint id;
214     const(void)* pData;
215     uint dataSize;
216   }
217 
218   static struct SeekTable {
219     uint seekpointCount;
220     const(drflac_seekpoint)* pSeekpoints;
221   }
222 
223   static struct VorbisComment {
224     uint vendorLength;
225     const(char)* vendor;
226     uint commentCount;
227     const(char)* comments;
228   }
229 
230   static struct CueSheet {
231     char[128] catalog;
232     ulong leadInSampleCount;
233     bool isCD;
234     ubyte trackCount;
235     const(ubyte)* pTrackData;
236   }
237 
238   static struct Picture {
239     uint type;
240     uint mimeLength;
241     const(char)* mime;
242     uint descriptionLength;
243     const(char)* description;
244     uint width;
245     uint height;
246     uint colorDepth;
247     uint indexColorCount;
248     uint pictureDataSize;
249     const(ubyte)* pPictureData;
250   }
251 
252   static union Data {
253     drflac_streaminfo streaminfo;
254     Padding padding;
255     Application application;
256     SeekTable seektable;
257     VorbisComment vorbis_comment;
258     CueSheet cuesheet;
259     Picture picture;
260   }
261 
262   Data data;
263 }
264 
265 
266 // Callback for when data needs to be read from the client.
267 //
268 // pUserData   [in]  The user data that was passed to drflac_open() and family.
269 // pBufferOut  [out] The output buffer.
270 // bytesToRead [in]  The number of bytes to read.
271 //
272 // Returns the number of bytes actually read.
273 alias drflac_read_proc = size_t function (void* pUserData, void* pBufferOut, size_t bytesToRead);
274 
275 // Callback for when data needs to be seeked.
276 //
277 // pUserData [in] The user data that was passed to drflac_open() and family.
278 // offset    [in] The number of bytes to move, relative to the origin. Will never be negative.
279 // origin    [in] The origin of the seek - the current position or the start of the stream.
280 //
281 // Returns whether or not the seek was successful.
282 //
283 // The offset will never be negative. Whether or not it is relative to the beginning or current position is determined
284 // by the "origin" parameter which will be either drflac_seek_origin_start or drflac_seek_origin_current.
285 alias drflac_seek_proc = bool function (void* pUserData, int offset, drflac_seek_origin origin);
286 
287 // Callback for when a metadata block is read.
288 //
289 // pUserData [in] The user data that was passed to drflac_open() and family.
290 // pMetadata [in] A pointer to a structure containing the data of the metadata block.
291 //
292 // Use pMetadata.type to determine which metadata block is being handled and how to read the data.
293 alias drflac_meta_proc = void delegate (void* pUserData, drflac_metadata* pMetadata);
294 
295 
296 // Structure for internal use. Only used for decoders opened with drflac_open_memory.
297 struct drflac__memory_stream {
298   const(ubyte)* data;
299   size_t dataSize;
300   size_t currentReadPos;
301 }
302 
303 // Structure for internal use. Used for bit streaming.
304 struct drflac_bs {
305   // The function to call when more data needs to be read.
306   //drflac_read_proc onRead;
307 
308   // The function to call when the current read position needs to be moved.
309   //drflac_seek_proc onSeek;
310 
311   // The user data to pass around to onRead and onSeek.
312   //void* pUserData;
313 
314   ReadStruct rs;
315 
316   // 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
317   // 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
318   // or not the bistreamer needs to run on a slower path to read those last bytes. This will never be more than (drflac_cache_t).sizeof.
319   size_t unalignedByteCount;
320 
321   // The content of the unaligned bytes.
322   drflac_cache_t unalignedCache;
323 
324   // The index of the next valid cache line in the "L2" cache.
325   size_t nextL2Line;
326 
327   // The number of bits that have been consumed by the cache. This is used to determine how many valid bits are remaining.
328   size_t consumedBits;
329 
330   // The cached data which was most recently read from the client. There are two levels of cache. Data flows as such:
331   // Client . L2 . L1. The L2 . L1 movement is aligned and runs on a fast path in just a few instructions.
332   drflac_cache_t[DR_FLAC_BUFFER_SIZE/(drflac_cache_t).sizeof] cacheL2;
333   drflac_cache_t cache;
334 }
335 
336 struct drflac_subframe {
337   // The type of the subframe: SUBFRAME_CONSTANT, SUBFRAME_VERBATIM, SUBFRAME_FIXED or SUBFRAME_LPC.
338   ubyte subframeType;
339 
340   // The number of wasted bits per sample as specified by the sub-frame header.
341   ubyte wastedBitsPerSample;
342 
343   // The order to use for the prediction stage for SUBFRAME_FIXED and SUBFRAME_LPC.
344   ubyte lpcOrder;
345 
346   // The number of bits per sample for this subframe. This is not always equal to the current frame's bit per sample because
347   // an extra bit is required for side channels when interchannel decorrelation is being used.
348   uint bitsPerSample;
349 
350   // A pointer to the buffer containing the decoded samples in the subframe. This pointer is an offset from drflac::pExtraData, or
351   // null if the heap is not being used. Note that it's a signed 32-bit integer for each value.
352   int* pDecodedSamples;
353 }
354 
355 struct drflac_frame_header {
356   // 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
357   // always be set to 0.
358   ulong sampleNumber;
359 
360   // 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.
361   uint frameNumber;
362 
363   // The sample rate of this frame.
364   uint sampleRate;
365 
366   // The number of samples in each sub-frame within this frame.
367   ushort blockSize;
368 
369   // The channel assignment of this frame. This is not always set to the channel count. If interchannel decorrelation is being used this
370   // will be set to DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE, DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE or DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE.
371   ubyte channelAssignment;
372 
373   // The number of bits per sample within this frame.
374   ubyte bitsPerSample;
375 
376   // The frame's CRC. This is set, but unused at the moment.
377   ubyte crc8;
378 }
379 
380 struct drflac_frame {
381   // The header.
382   drflac_frame_header header;
383 
384   // 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
385   // are read, this will be decremented. When it reaches 0, the decoder will see this frame as fully consumed and load the next frame.
386   uint samplesRemaining;
387 
388   // The list of sub-frames within the frame. There is one sub-frame for each channel, and there's a maximum of 8 channels.
389   drflac_subframe[8] subframes;
390 }
391 
392 struct drflac {
393   // The function to call when a metadata block is read.
394   //drflac_meta_proc onMeta;
395 
396   // The user data posted to the metadata callback function.
397   //void* pUserDataMD;
398 
399 
400   // The sample rate. Will be set to something like 44100.
401   uint sampleRate;
402 
403   // 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
404   // value specified in the STREAMINFO block.
405   ubyte channels;
406 
407   // The bits per sample. Will be set to somthing like 16, 24, etc.
408   ubyte bitsPerSample;
409 
410   // The maximum block size, in samples. This number represents the number of samples in each channel (not combined).
411   ushort maxBlockSize;
412 
413   // The total number of samples making up the stream. This includes every channel. For example, if the stream has 2 channels,
414   // 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
415   // valid stream, but just means the total sample count is unknown. Likely the case with streams like internet radio.
416   ulong totalSampleCount;
417 
418 
419   // The container type. This is set based on whether or not the decoder was opened from a native or Ogg stream.
420   drflac_container container;
421 
422 
423   // The position of the seektable in the file.
424   ulong seektablePos;
425 
426   // The size of the seektable.
427   uint seektableSize;
428 
429 
430   // Information about the frame the decoder is currently sitting on.
431   drflac_frame currentFrame;
432 
433   // The position of the first frame in the stream. This is only ever used for seeking.
434   ulong firstFramePos;
435 
436 
437   // A hack to avoid a malloc() when opening a decoder with drflac_open_memory().
438   drflac__memory_stream memoryStream;
439 
440 
441   // A pointer to the decoded sample data. This is an offset of pExtraData.
442   int* pDecodedSamples;
443 
444 
445   // The bit streamer. The raw FLAC data is fed through this object.
446   drflac_bs bs;
447 
448   // Variable length extra data. We attach this to the end of the object so we avoid unnecessary mallocs.
449   ubyte[1] pExtraData;
450 }
451 
452 
453 // Opens a FLAC decoder.
454 //
455 // onRead    [in]           The function to call when data needs to be read from the client.
456 // onSeek    [in]           The function to call when the read position of the client data needs to move.
457 // pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek.
458 //
459 // Returns a pointer to an object representing the decoder.
460 //
461 // Close the decoder with drflac_close().
462 //
463 // This function will automatically detect whether or not you are attempting to open a native or Ogg encapsulated
464 // FLAC, both of which should work seamlessly without any manual intervention. Ogg encapsulation also works with
465 // multiplexed streams which basically means it can play FLAC encoded audio tracks in videos.
466 //
467 // This is the lowest level function for opening a FLAC stream. You can also use drflac_open_file() and drflac_open_memory()
468 // to open the stream from a file or from a block of memory respectively.
469 //
470 // The STREAMINFO block must be present for this to succeed.
471 //
472 // See also: drflac_open_file(), drflac_open_memory(), drflac_open_with_metadata(), drflac_close()
473 //drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData);
474 
475 // Opens a FLAC decoder and notifies the caller of the metadata chunks (album art, etc.).
476 //
477 // onRead    [in]           The function to call when data needs to be read from the client.
478 // onSeek    [in]           The function to call when the read position of the client data needs to move.
479 // onMeta    [in]           The function to call for every metadata block.
480 // pUserData [in, optional] A pointer to application defined data that will be passed to onRead, onSeek and onMeta.
481 //
482 // Returns a pointer to an object representing the decoder.
483 //
484 // Close the decoder with drflac_close().
485 //
486 // This is slower that drflac_open(), so avoid this one if you don't need metadata. Internally, this will do a malloc()
487 // and free() for every metadata block except for STREAMINFO and PADDING blocks.
488 //
489 // The caller is notified of the metadata via the onMeta callback. All metadata blocks withh be handled before the function
490 // returns.
491 //
492 // See also: drflac_open_file_with_metadata(), drflac_open_memory_with_metadata(), drflac_open(), drflac_close()
493 //drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData);
494 
495 // Closes the given FLAC decoder.
496 //
497 // pFlac [in] The decoder to close.
498 //
499 // This will destroy the decoder object.
500 //void drflac_close(drflac* pFlac);
501 
502 
503 // Reads sample data from the given FLAC decoder, output as interleaved signed 32-bit PCM.
504 //
505 // pFlac         [in]            The decoder.
506 // samplesToRead [in]            The number of samples to read.
507 // pBufferOut    [out, optional] A pointer to the buffer that will receive the decoded samples.
508 //
509 // Returns the number of samples actually read.
510 //
511 // pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of samples
512 // seeked.
513 //ulong drflac_read_s32(drflac* pFlac, ulong samplesToRead, int* pBufferOut);
514 
515 // Seeks to the sample at the given index.
516 //
517 // pFlac       [in] The decoder.
518 // sampleIndex [in] The index of the sample to seek to. See notes below.
519 //
520 // Returns true if successful; false otherwise.
521 //
522 // The sample index is based on interleaving. In a stereo stream, for example, the sample at index 0 is the first sample
523 // in the left channel; the sample at index 1 is the first sample on the right channel, and so on.
524 //
525 // When seeking, you will likely want to ensure it's rounded to a multiple of the channel count. You can do this with
526 // something like drflac_seek_to_sample(pFlac, (mySampleIndex + (mySampleIndex % pFlac.channels)))
527 //bool drflac_seek_to_sample(drflac* pFlac, ulong sampleIndex);
528 
529 
530 // Opens a FLAC decoder from the file at the given path.
531 //
532 // filename [in] The path of the file to open, either absolute or relative to the current directory.
533 //
534 // Returns a pointer to an object representing the decoder.
535 //
536 // Close the decoder with drflac_close().
537 //
538 // This will hold a handle to the file until the decoder is closed with drflac_close(). Some platforms will restrict the
539 // number of files a process can have open at any given time, so keep this mind if you have many decoders open at the
540 // same time.
541 //
542 // See also: drflac_open(), drflac_open_file_with_metadata(), drflac_close()
543 //drflac* drflac_open_file(const(char)[] filename);
544 
545 // Opens a FLAC decoder from the file at the given path and notifies the caller of the metadata chunks (album art, etc.)
546 //
547 // Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
548 //drflac* drflac_open_file_with_metadata(const(char)[] filename, drflac_meta_proc onMeta, void* pUserData);
549 
550 // Opens a FLAC decoder from a pre-allocated block of memory
551 //
552 // This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for
553 // the lifetime of the decoder.
554 //drflac* drflac_open_memory(const void* data, size_t dataSize);
555 
556 // Opens a FLAC decoder from a pre-allocated block of memory and notifies the caller of the metadata chunks (album art, etc.)
557 //
558 // Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
559 //drflac* drflac_open_memory_with_metadata(const void* data, size_t dataSize, drflac_meta_proc onMeta, void* pUserData);
560 
561 
562 
563 //// High Level APIs ////
564 
565 // Opens a FLAC stream from the given callbacks and fully decodes it in a single operation. The return value is a
566 // pointer to the sample data as interleaved signed 32-bit PCM. The returned data must be freed with drflac_free().
567 //
568 // Sometimes a FLAC file won't keep track of the total sample count. In this situation the function will continuously
569 // read samples into a dynamically sized buffer on the heap until no samples are left.
570 //
571 // Do not call this function on a broadcast type of stream (like internet radio streams and whatnot).
572 //int* drflac_open_and_decode(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, uint* sampleRate, uint* channels, ulong* totalSampleCount);
573 
574 //#ifndef DR_FLAC_NO_STDIO
575 // Same as drflac_open_and_decode() except opens the decoder from a file.
576 //int* drflac_open_and_decode_file(const(char)[] filename, uint* sampleRate, uint* channels, ulong* totalSampleCount);
577 //#endif
578 
579 // Same as drflac_open_and_decode() except opens the decoder from a block of memory.
580 //int* drflac_open_and_decode_memory(const void* data, size_t dataSize, uint* sampleRate, uint* channels, ulong* totalSampleCount);
581 
582 // Frees data returned by drflac_open_and_decode_*().
583 //void drflac_free(void* pSampleDataReturnedByOpenAndDecode);
584 
585 
586 // Structure representing an iterator for vorbis comments in a VORBIS_COMMENT metadata block.
587 struct drflac_vorbis_comment_iterator {
588   uint countRemaining;
589   const(char)* pRunningData;
590 }
591 
592 // Initializes a vorbis comment iterator. This can be used for iterating over the vorbis comments in a VORBIS_COMMENT
593 // metadata block.
594 //void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, uint commentCount, const(char)* pComments);
595 
596 // Goes to the next vorbis comment in the given iterator. If null is returned it means there are no more comments. The
597 // returned string is NOT null terminated.
598 //const(char)* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, uint* pCommentLengthOut);
599 
600 
601 ///////////////////////////////////////////////////////////////////////////////
602 //
603 // IMPLEMENTATION
604 //
605 ///////////////////////////////////////////////////////////////////////////////
606 private: nothrow {
607 enum DRFLAC_SUBFRAME_CONSTANT = 0;
608 enum DRFLAC_SUBFRAME_VERBATIM = 1;
609 enum DRFLAC_SUBFRAME_FIXED = 8;
610 enum DRFLAC_SUBFRAME_LPC = 32;
611 enum DRFLAC_SUBFRAME_RESERVED = 255;
612 
613 enum DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE = 0;
614 enum DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 = 1;
615 
616 enum DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT = 0;
617 enum DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE = 8;
618 enum DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE = 9;
619 enum DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE = 10;
620 
621 
622 //// Endian Management ////
623 version(LittleEndian) enum drflac__is_little_endian = true; else enum drflac__is_little_endian = false;
624 
625 ushort drflac__be2host_16 (ushort n) pure nothrow @safe @nogc {
626   static if (__VERSION__ > 2067) pragma(inline, true);
627   version(LittleEndian) {
628     return cast(ushort)((n>>8)|((n&0xff)<<8));
629   } else {
630     return n;
631   }
632 }
633 
634 uint drflac__be2host_32 (uint n) pure nothrow @safe @nogc {
635   static if (__VERSION__ > 2067) pragma(inline, true);
636   version(LittleEndian) {
637     import core.bitop : bswap;
638     return bswap(n);
639   } else {
640     return n;
641   }
642 }
643 
644 ulong drflac__be2host_64 (ulong n) pure nothrow @safe @nogc {
645   static if (__VERSION__ > 2067) pragma(inline, true);
646   version(LittleEndian) {
647     import core.bitop : bswap;
648     version(GNU) {
649       auto n0 = cast(ulong)bswap(cast(uint)n);
650       auto n1 = cast(ulong)bswap(cast(uint)(n>>32));
651       return (n0<<32)|n1;
652     } else {
653       return bswap(n);
654     }
655   } else {
656     return n;
657   }
658 }
659 
660 
661 uint drflac__le2host_32 (uint n) pure nothrow @safe @nogc {
662   static if (__VERSION__ > 2067) pragma(inline, true);
663   version(LittleEndian) {
664     return n;
665   } else {
666     import core.bitop : bswap;
667     return bswap(n);
668   }
669 }
670 
671 
672 version(DRFLAC_64BIT) {
673   alias drflac__be2host__cache_line = drflac__be2host_64;
674 } else {
675   alias drflac__be2host__cache_line = drflac__be2host_32;
676 }
677 
678 // BIT READING ATTEMPT #2
679 //
680 // 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
681 // on the most significant bit. It uses the notion of an L1 and L2 cache (borrowed from CPU architecture), where the L1 cache
682 // 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
683 // 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
684 // from onRead() is read into.
685 enum DRFLAC_CACHE_L1_SIZE_BYTES(string bs) = "((("~bs~").cache).sizeof)";
686 enum DRFLAC_CACHE_L1_SIZE_BITS(string bs) = "((("~bs~").cache).sizeof*8)";
687 enum DRFLAC_CACHE_L1_BITS_REMAINING(string bs) = "("~DRFLAC_CACHE_L1_SIZE_BITS!(bs)~"-(("~bs~").consumedBits))";
688 version(DRFLAC_64BIT) {
689   enum DRFLAC_CACHE_L1_SELECTION_MASK(string _bitCount) = "(~((cast(ulong)-1L)>>("~_bitCount~")))";
690 } else {
691   enum DRFLAC_CACHE_L1_SELECTION_MASK(string _bitCount) = "(~((cast(uint)-1)>>("~_bitCount~")))";
692 }
693 enum DRFLAC_CACHE_L1_SELECTION_SHIFT(string bs, string _bitCount) = "("~DRFLAC_CACHE_L1_SIZE_BITS!bs~"-("~_bitCount~"))";
694 enum DRFLAC_CACHE_L1_SELECT(string bs, string _bitCount) = "((("~bs~").cache)&"~DRFLAC_CACHE_L1_SELECTION_MASK!_bitCount~")";
695 enum DRFLAC_CACHE_L1_SELECT_AND_SHIFT(string bs, string _bitCount) = "("~DRFLAC_CACHE_L1_SELECT!(bs, _bitCount)~">>"~DRFLAC_CACHE_L1_SELECTION_SHIFT!(bs, _bitCount)~")";
696 enum DRFLAC_CACHE_L2_SIZE_BYTES(string bs) = "((("~bs~").cacheL2).sizeof)";
697 enum DRFLAC_CACHE_L2_LINE_COUNT(string bs) = "("~DRFLAC_CACHE_L2_SIZE_BYTES!bs~"/(("~bs~").cacheL2[0]).sizeof)";
698 enum DRFLAC_CACHE_L2_LINES_REMAINING(string bs) = "("~DRFLAC_CACHE_L2_LINE_COUNT!bs~"-("~bs~").nextL2Line)";
699 
700 bool drflac__reload_l1_cache_from_l2 (drflac_bs* bs) {
701   // Fast path. Try loading straight from L2.
702   if (bs.nextL2Line < mixin(DRFLAC_CACHE_L2_LINE_COUNT!"bs")) {
703     bs.cache = bs.cacheL2.ptr[bs.nextL2Line++];
704     return true;
705   }
706 
707   // 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 any left.
708   if (bs.unalignedByteCount > 0) return false; // If we have any unaligned bytes it means there's no more aligned bytes left in the client.
709 
710   size_t bytesRead = bs.rs.read(bs.cacheL2.ptr, mixin(DRFLAC_CACHE_L2_SIZE_BYTES!"bs"));
711 
712   bs.nextL2Line = 0;
713   if (bytesRead == mixin(DRFLAC_CACHE_L2_SIZE_BYTES!"bs")) {
714     bs.cache = bs.cacheL2.ptr[bs.nextL2Line++];
715     return true;
716   }
717 
718   // If we get here it means we were unable to retrieve enough data to fill the entire L2 cache. It probably
719   // means we've just reached the end of the file. We need to move the valid data down to the end of the buffer
720   // and adjust the index of the next line accordingly. Also keep in mind that the L2 cache must be aligned to
721   // the size of the L1 so we'll need to seek backwards by any misaligned bytes.
722   size_t alignedL1LineCount = bytesRead/mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs");
723 
724   // We need to keep track of any unaligned bytes for later use.
725   bs.unalignedByteCount = bytesRead-(alignedL1LineCount*mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs"));
726   if (bs.unalignedByteCount > 0) {
727       bs.unalignedCache = bs.cacheL2.ptr[alignedL1LineCount];
728   }
729 
730   if (alignedL1LineCount > 0) {
731     size_t offset = mixin(DRFLAC_CACHE_L2_LINE_COUNT!"bs")-alignedL1LineCount;
732     for (size_t i = alignedL1LineCount; i > 0; --i) bs.cacheL2.ptr[i-1+offset] = bs.cacheL2.ptr[i-1];
733     bs.nextL2Line = offset;
734     bs.cache = bs.cacheL2.ptr[bs.nextL2Line++];
735     return true;
736   } else {
737     // If we get into this branch it means we weren't able to load any L1-aligned data.
738     bs.nextL2Line = mixin(DRFLAC_CACHE_L2_LINE_COUNT!"bs");
739     return false;
740   }
741 }
742 
743 bool drflac__reload_cache (drflac_bs* bs) {
744   // Fast path. Try just moving the next value in the L2 cache to the L1 cache.
745   if (drflac__reload_l1_cache_from_l2(bs)) {
746     bs.cache = drflac__be2host__cache_line(bs.cache);
747     bs.consumedBits = 0;
748     return true;
749   }
750 
751   // Slow path.
752 
753   // 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
754   // 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
755   // data from the unaligned cache.
756   size_t bytesRead = bs.unalignedByteCount;
757   if (bytesRead == 0) return false;
758 
759   assert(bytesRead < mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs"));
760   bs.consumedBits = (mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs")-bytesRead)*8;
761 
762   bs.cache = drflac__be2host__cache_line(bs.unalignedCache);
763   //bs.cache &= DRFLAC_CACHE_L1_SELECTION_MASK(DRFLAC_CACHE_L1_SIZE_BITS(bs)-bs.consumedBits);
764   bs.cache &= mixin(DRFLAC_CACHE_L1_SELECTION_MASK!(DRFLAC_CACHE_L1_SIZE_BITS!"bs"~"-bs.consumedBits"));
765     // <-- Make sure the consumed bits are always set to zero. Other parts of the library depend on this property.
766   bs.unalignedByteCount = 0; // <-- At this point the unaligned bytes have been moved into the cache and we thus have no more unaligned bytes.
767   return true;
768 }
769 
770 void drflac__reset_cache (drflac_bs* bs) {
771   bs.nextL2Line   = mixin(DRFLAC_CACHE_L2_LINE_COUNT!"bs");  // <-- This clears the L2 cache.
772   bs.consumedBits = mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs");   // <-- This clears the L1 cache.
773   bs.cache = 0;
774   bs.unalignedByteCount = 0; // <-- This clears the trailing unaligned bytes.
775   bs.unalignedCache = 0;
776 }
777 
778 bool drflac__seek_bits (drflac_bs* bs, size_t bitsToSeek) {
779   if (bitsToSeek <= mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"bs")) {
780     bs.consumedBits += bitsToSeek;
781     bs.cache <<= bitsToSeek;
782     return true;
783   } else {
784     // It straddles the cached data. This function isn't called too frequently so I'm favouring simplicity here.
785     bitsToSeek -= mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"bs");
786     bs.consumedBits += mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"bs");
787     bs.cache = 0;
788 
789     size_t wholeBytesRemainingToSeek = bitsToSeek/8;
790     if (wholeBytesRemainingToSeek > 0) {
791       // The next bytes to seek will be located in the L2 cache. The problem is that the L2 cache is not byte aligned,
792       // but rather DRFLAC_CACHE_L1_SIZE_BYTES aligned (usually 4 or 8). If, for example, the number of bytes to seek is
793       // 3, we'll need to handle it in a special way.
794       size_t wholeCacheLinesRemaining = wholeBytesRemainingToSeek/mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs");
795       if (wholeCacheLinesRemaining < mixin(DRFLAC_CACHE_L2_LINES_REMAINING!"bs")) {
796         wholeBytesRemainingToSeek -= wholeCacheLinesRemaining*mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs");
797         bitsToSeek -= wholeCacheLinesRemaining*mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs");
798         bs.nextL2Line += wholeCacheLinesRemaining;
799       } else {
800         wholeBytesRemainingToSeek -= mixin(DRFLAC_CACHE_L2_LINES_REMAINING!"bs")*mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs");
801         bitsToSeek -= mixin(DRFLAC_CACHE_L2_LINES_REMAINING!"bs")*mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs");
802         bs.nextL2Line += mixin(DRFLAC_CACHE_L2_LINES_REMAINING!"bs");
803         // Note that we only seek on the client side if it's got any data left to seek. We can know this by checking
804         // if we have any unaligned data which can be determined with bs->unalignedByteCount.
805         if (wholeBytesRemainingToSeek > 0 && bs.unalignedByteCount == 0) {
806           if (!bs.rs.seek(cast(int)wholeBytesRemainingToSeek, drflac_seek_origin_current)) return false;
807           bitsToSeek -= wholeBytesRemainingToSeek*8;
808         }
809       }
810     }
811     if (bitsToSeek > 0) {
812       if (!drflac__reload_cache(bs)) return false;
813       return drflac__seek_bits(bs, bitsToSeek);
814     }
815     return true;
816   }
817 }
818 
819 bool drflac__read_uint32 (drflac_bs* bs, uint bitCount, uint* pResultOut) {
820   assert(bs !is null);
821   assert(pResultOut !is null);
822   assert(bitCount > 0);
823   assert(bitCount <= 32);
824 
825   if (bs.consumedBits == mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs")) {
826     if (!drflac__reload_cache(bs)) return false;
827   }
828 
829   if (bitCount <= mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"bs")) {
830     if (bitCount < mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs")) {
831       *pResultOut = cast(uint)mixin(DRFLAC_CACHE_L1_SELECT_AND_SHIFT!("bs", "bitCount")); //k8
832       bs.consumedBits += bitCount;
833       bs.cache <<= bitCount;
834     } else {
835       *pResultOut = cast(uint)bs.cache;
836       bs.consumedBits = mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs");
837       bs.cache = 0;
838     }
839     return true;
840   } else {
841     // 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.
842     size_t bitCountHi = mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"bs");
843     size_t bitCountLo = bitCount-bitCountHi;
844     uint resultHi = cast(uint)mixin(DRFLAC_CACHE_L1_SELECT_AND_SHIFT!("bs", "bitCountHi")); //k8
845     if (!drflac__reload_cache(bs)) return false;
846     *pResultOut = cast(uint)((resultHi<<bitCountLo)|mixin(DRFLAC_CACHE_L1_SELECT_AND_SHIFT!("bs", "bitCountLo"))); //k8
847     bs.consumedBits += bitCountLo;
848     bs.cache <<= bitCountLo;
849     return true;
850   }
851 }
852 
853 bool drflac__read_int32 (drflac_bs* bs, uint bitCount, int* pResult) {
854   assert(bs !is null);
855   assert(pResult !is null);
856   assert(bitCount > 0);
857   assert(bitCount <= 32);
858 
859   uint result;
860   if (!drflac__read_uint32(bs, bitCount, &result)) return false;
861 
862   uint signbit = ((result>>(bitCount-1))&0x01);
863   result |= (~signbit+1)<<bitCount;
864 
865   *pResult = cast(int)result;
866   return true;
867 }
868 
869 bool drflac__read_uint64 (drflac_bs* bs, uint bitCount, ulong* pResultOut) {
870   assert(bitCount <= 64);
871   assert(bitCount >  32);
872 
873   uint resultHi;
874   if (!drflac__read_uint32(bs, bitCount-32, &resultHi)) return false;
875 
876   uint resultLo;
877   if (!drflac__read_uint32(bs, 32, &resultLo)) return false;
878 
879   *pResultOut = ((cast(ulong)resultHi)<<32)|(cast(ulong)resultLo);
880   return true;
881 }
882 
883 bool drflac__read_uint16 (drflac_bs* bs, uint bitCount, ushort* pResult) {
884   assert(bs !is null);
885   assert(pResult !is null);
886   assert(bitCount > 0);
887   assert(bitCount <= 16);
888 
889   uint result;
890   if (!drflac__read_uint32(bs, bitCount, &result)) return false;
891 
892   *pResult = cast(ushort)result;
893   return true;
894 }
895 
896 bool drflac__read_int16 (drflac_bs* bs, uint bitCount, short* pResult) {
897   assert(bs !is null);
898   assert(pResult !is null);
899   assert(bitCount > 0);
900   assert(bitCount <= 16);
901 
902   int result;
903   if (!drflac__read_int32(bs, bitCount, &result)) return false;
904 
905   *pResult = cast(short)result;
906   return true;
907 }
908 
909 bool drflac__read_uint8 (drflac_bs* bs, uint bitCount, ubyte* pResult) {
910   assert(bs !is null);
911   assert(pResult !is null);
912   assert(bitCount > 0);
913   assert(bitCount <= 8);
914 
915   uint result;
916   if (!drflac__read_uint32(bs, bitCount, &result)) return false;
917 
918   *pResult = cast(ubyte)result;
919   return true;
920 }
921 
922 bool drflac__read_int8 (drflac_bs* bs, uint bitCount, byte* pResult) {
923   assert(bs !is null);
924   assert(pResult !is null);
925   assert(bitCount > 0);
926   assert(bitCount <= 8);
927 
928   int result;
929   if (!drflac__read_int32(bs, bitCount, &result)) return false;
930 
931   *pResult = cast(byte)result;
932   return true;
933 }
934 
935 
936 bool drflac__seek_past_next_set_bit (drflac_bs* bs, uint* pOffsetOut) {
937   uint zeroCounter = 0;
938   while (bs.cache == 0) {
939     zeroCounter += cast(uint)mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"bs");
940     if (!drflac__reload_cache(bs)) return false;
941   }
942 
943   // At this point the cache should not be zero, in which case we know the first set bit should be somewhere in here. There is
944   // no need for us to perform any cache reloading logic here which should make things much faster.
945   assert(bs.cache != 0);
946 
947   static immutable uint[16] bitOffsetTable = [
948     0,
949     4,
950     3, 3,
951     2, 2, 2, 2,
952     1, 1, 1, 1, 1, 1, 1, 1
953   ];
954 
955   uint setBitOffsetPlus1 = bitOffsetTable.ptr[mixin(DRFLAC_CACHE_L1_SELECT_AND_SHIFT!("bs", "4"))];
956   if (setBitOffsetPlus1 == 0) {
957     if (bs.cache == 1) {
958       setBitOffsetPlus1 = mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs");
959     } else {
960       setBitOffsetPlus1 = 5;
961       for (;;) {
962         if ((bs.cache&mixin(DRFLAC_CACHE_L1_SELECT!("bs", "setBitOffsetPlus1")))) break;
963         setBitOffsetPlus1 += 1;
964       }
965     }
966   }
967 
968   bs.consumedBits += setBitOffsetPlus1;
969   bs.cache <<= setBitOffsetPlus1;
970 
971   *pOffsetOut = zeroCounter+setBitOffsetPlus1-1;
972   return true;
973 }
974 
975 
976 bool drflac__seek_to_byte (drflac_bs* bs, ulong offsetFromStart) {
977   assert(bs !is null);
978   assert(offsetFromStart > 0);
979 
980   // Seeking from the start is not quite as trivial as it sounds because the onSeek callback takes a signed 32-bit integer (which
981   // is intentional because it simplifies the implementation of the onSeek callbacks), however offsetFromStart is unsigned 64-bit.
982   // 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.
983   if (offsetFromStart > 0x7FFFFFFF) {
984     ulong bytesRemaining = offsetFromStart;
985     if (!bs.rs.seek(0x7FFFFFFF, drflac_seek_origin_start)) return false;
986     bytesRemaining -= 0x7FFFFFFF;
987     while (bytesRemaining > 0x7FFFFFFF) {
988       if (!bs.rs.seek(0x7FFFFFFF, drflac_seek_origin_current)) return false;
989       bytesRemaining -= 0x7FFFFFFF;
990     }
991     if (bytesRemaining > 0) {
992       if (!bs.rs.seek(cast(int)bytesRemaining, drflac_seek_origin_current)) return false;
993     }
994   } else {
995     if (!bs.rs.seek(cast(int)offsetFromStart, drflac_seek_origin_start)) return false;
996   }
997   // The cache should be reset to force a reload of fresh data from the client.
998   drflac__reset_cache(bs);
999   return true;
1000 }
1001 
1002 
1003 bool drflac__read_utf8_coded_number (drflac_bs* bs, ulong* pNumberOut) {
1004   assert(bs !is null);
1005   assert(pNumberOut !is null);
1006 
1007   ubyte[7] utf8 = 0;
1008   if (!drflac__read_uint8(bs, 8, utf8.ptr)) {
1009     *pNumberOut = 0;
1010     return false;
1011   }
1012 
1013   if ((utf8.ptr[0]&0x80) == 0) {
1014     *pNumberOut = utf8.ptr[0];
1015     return true;
1016   }
1017 
1018   int byteCount = 1;
1019        if ((utf8.ptr[0]&0xE0) == 0xC0) byteCount = 2;
1020   else if ((utf8.ptr[0]&0xF0) == 0xE0) byteCount = 3;
1021   else if ((utf8.ptr[0]&0xF8) == 0xF0) byteCount = 4;
1022   else if ((utf8.ptr[0]&0xFC) == 0xF8) byteCount = 5;
1023   else if ((utf8.ptr[0]&0xFE) == 0xFC) byteCount = 6;
1024   else if ((utf8.ptr[0]&0xFF) == 0xFE) byteCount = 7;
1025   else { *pNumberOut = 0; return false; } // Bad UTF-8 encoding.
1026 
1027   // Read extra bytes.
1028   assert(byteCount > 1);
1029 
1030   ulong result = cast(ulong)(utf8.ptr[0]&(0xFF>>(byteCount+1)));
1031   for (int i = 1; i < byteCount; ++i) {
1032     if (!drflac__read_uint8(bs, 8, utf8.ptr+i)) {
1033       *pNumberOut = 0;
1034       return false;
1035     }
1036     result = (result<<6)|(utf8.ptr[i]&0x3F);
1037   }
1038 
1039   *pNumberOut = result;
1040   return true;
1041 }
1042 
1043 
1044 bool drflac__read_and_seek_rice (drflac_bs* bs, ubyte m) {
1045   uint unused;
1046   if (!drflac__seek_past_next_set_bit(bs, &unused)) return false;
1047   if (m > 0) {
1048     if (!drflac__seek_bits(bs, m)) return false;
1049   }
1050   return true;
1051 }
1052 
1053 
1054 // The next two functions are responsible for calculating the prediction.
1055 //
1056 // 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
1057 // 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.
1058 int drflac__calculate_prediction_32 (uint order, int shift, const(short)* coefficients, int* pDecodedSamples) {
1059   assert(order <= 32);
1060   int prediction = 0;
1061   switch (order) {
1062     case 32: prediction += coefficients[31]*pDecodedSamples[-32]; goto case;
1063     case 31: prediction += coefficients[30]*pDecodedSamples[-31]; goto case;
1064     case 30: prediction += coefficients[29]*pDecodedSamples[-30]; goto case;
1065     case 29: prediction += coefficients[28]*pDecodedSamples[-29]; goto case;
1066     case 28: prediction += coefficients[27]*pDecodedSamples[-28]; goto case;
1067     case 27: prediction += coefficients[26]*pDecodedSamples[-27]; goto case;
1068     case 26: prediction += coefficients[25]*pDecodedSamples[-26]; goto case;
1069     case 25: prediction += coefficients[24]*pDecodedSamples[-25]; goto case;
1070     case 24: prediction += coefficients[23]*pDecodedSamples[-24]; goto case;
1071     case 23: prediction += coefficients[22]*pDecodedSamples[-23]; goto case;
1072     case 22: prediction += coefficients[21]*pDecodedSamples[-22]; goto case;
1073     case 21: prediction += coefficients[20]*pDecodedSamples[-21]; goto case;
1074     case 20: prediction += coefficients[19]*pDecodedSamples[-20]; goto case;
1075     case 19: prediction += coefficients[18]*pDecodedSamples[-19]; goto case;
1076     case 18: prediction += coefficients[17]*pDecodedSamples[-18]; goto case;
1077     case 17: prediction += coefficients[16]*pDecodedSamples[-17]; goto case;
1078     case 16: prediction += coefficients[15]*pDecodedSamples[-16]; goto case;
1079     case 15: prediction += coefficients[14]*pDecodedSamples[-15]; goto case;
1080     case 14: prediction += coefficients[13]*pDecodedSamples[-14]; goto case;
1081     case 13: prediction += coefficients[12]*pDecodedSamples[-13]; goto case;
1082     case 12: prediction += coefficients[11]*pDecodedSamples[-12]; goto case;
1083     case 11: prediction += coefficients[10]*pDecodedSamples[-11]; goto case;
1084     case 10: prediction += coefficients[ 9]*pDecodedSamples[-10]; goto case;
1085     case  9: prediction += coefficients[ 8]*pDecodedSamples[- 9]; goto case;
1086     case  8: prediction += coefficients[ 7]*pDecodedSamples[- 8]; goto case;
1087     case  7: prediction += coefficients[ 6]*pDecodedSamples[- 7]; goto case;
1088     case  6: prediction += coefficients[ 5]*pDecodedSamples[- 6]; goto case;
1089     case  5: prediction += coefficients[ 4]*pDecodedSamples[- 5]; goto case;
1090     case  4: prediction += coefficients[ 3]*pDecodedSamples[- 4]; goto case;
1091     case  3: prediction += coefficients[ 2]*pDecodedSamples[- 3]; goto case;
1092     case  2: prediction += coefficients[ 1]*pDecodedSamples[- 2]; goto case;
1093     case  1: prediction += coefficients[ 0]*pDecodedSamples[- 1]; goto default;
1094     default:
1095   }
1096   return cast(int)(prediction>>shift);
1097 }
1098 
1099 int drflac__calculate_prediction_64 (uint order, int shift, const(short)* coefficients, int* pDecodedSamples) {
1100   assert(order <= 32);
1101   long prediction = 0;
1102   switch (order) {
1103     case 32: prediction += coefficients[31]*cast(long)pDecodedSamples[-32]; goto case;
1104     case 31: prediction += coefficients[30]*cast(long)pDecodedSamples[-31]; goto case;
1105     case 30: prediction += coefficients[29]*cast(long)pDecodedSamples[-30]; goto case;
1106     case 29: prediction += coefficients[28]*cast(long)pDecodedSamples[-29]; goto case;
1107     case 28: prediction += coefficients[27]*cast(long)pDecodedSamples[-28]; goto case;
1108     case 27: prediction += coefficients[26]*cast(long)pDecodedSamples[-27]; goto case;
1109     case 26: prediction += coefficients[25]*cast(long)pDecodedSamples[-26]; goto case;
1110     case 25: prediction += coefficients[24]*cast(long)pDecodedSamples[-25]; goto case;
1111     case 24: prediction += coefficients[23]*cast(long)pDecodedSamples[-24]; goto case;
1112     case 23: prediction += coefficients[22]*cast(long)pDecodedSamples[-23]; goto case;
1113     case 22: prediction += coefficients[21]*cast(long)pDecodedSamples[-22]; goto case;
1114     case 21: prediction += coefficients[20]*cast(long)pDecodedSamples[-21]; goto case;
1115     case 20: prediction += coefficients[19]*cast(long)pDecodedSamples[-20]; goto case;
1116     case 19: prediction += coefficients[18]*cast(long)pDecodedSamples[-19]; goto case;
1117     case 18: prediction += coefficients[17]*cast(long)pDecodedSamples[-18]; goto case;
1118     case 17: prediction += coefficients[16]*cast(long)pDecodedSamples[-17]; goto case;
1119     case 16: prediction += coefficients[15]*cast(long)pDecodedSamples[-16]; goto case;
1120     case 15: prediction += coefficients[14]*cast(long)pDecodedSamples[-15]; goto case;
1121     case 14: prediction += coefficients[13]*cast(long)pDecodedSamples[-14]; goto case;
1122     case 13: prediction += coefficients[12]*cast(long)pDecodedSamples[-13]; goto case;
1123     case 12: prediction += coefficients[11]*cast(long)pDecodedSamples[-12]; goto case;
1124     case 11: prediction += coefficients[10]*cast(long)pDecodedSamples[-11]; goto case;
1125     case 10: prediction += coefficients[ 9]*cast(long)pDecodedSamples[-10]; goto case;
1126     case  9: prediction += coefficients[ 8]*cast(long)pDecodedSamples[- 9]; goto case;
1127     case  8: prediction += coefficients[ 7]*cast(long)pDecodedSamples[- 8]; goto case;
1128     case  7: prediction += coefficients[ 6]*cast(long)pDecodedSamples[- 7]; goto case;
1129     case  6: prediction += coefficients[ 5]*cast(long)pDecodedSamples[- 6]; goto case;
1130     case  5: prediction += coefficients[ 4]*cast(long)pDecodedSamples[- 5]; goto case;
1131     case  4: prediction += coefficients[ 3]*cast(long)pDecodedSamples[- 4]; goto case;
1132     case  3: prediction += coefficients[ 2]*cast(long)pDecodedSamples[- 3]; goto case;
1133     case  2: prediction += coefficients[ 1]*cast(long)pDecodedSamples[- 2]; goto case;
1134     case  1: prediction += coefficients[ 0]*cast(long)pDecodedSamples[- 1]; goto default;
1135     default:
1136   }
1137   return cast(int)(prediction>>shift);
1138 }
1139 
1140 
1141 // Reads and decodes a string of residual values as Rice codes. The decoder should be sitting on the first bit of the Rice codes.
1142 //
1143 // This is the most frequently called function in the library. It does both the Rice decoding and the prediction in a single loop
1144 // iteration. The prediction is done at the end, and there's an annoying branch I'd like to avoid so the main function is defined
1145 // as a #define - sue me!
1146 //#define DRFLAC__DECODE_SAMPLES_WITH_RESIDULE__RICE__PROC(funcName, predictionFunc)
1147 enum DRFLAC__DECODE_SAMPLES_WITH_RESIDULE__RICE__PROC(string funcName, string predictionFunc) =
1148 "static bool "~funcName~" (drflac_bs* bs, uint count, ubyte riceParam, uint order, int shift, const(short)* coefficients, int* pSamplesOut) {\n"~
1149 "  assert(bs !is null);\n"~
1150 "  assert(count > 0);\n"~
1151 "  assert(pSamplesOut !is null);\n"~
1152 "\n"~
1153 "  static immutable uint[16] bitOffsetTable = [\n"~
1154 "    0,\n"~
1155 "    4,\n"~
1156 "    3, 3,\n"~
1157 "    2, 2, 2, 2,\n"~
1158 "    1, 1, 1, 1, 1, 1, 1, 1\n"~
1159 "  ];\n"~
1160 "\n"~
1161 "  drflac_cache_t riceParamMask = cast(drflac_cache_t)("~DRFLAC_CACHE_L1_SELECTION_MASK!"riceParam"~");\n"~
1162 "  drflac_cache_t resultHiShift = cast(drflac_cache_t)("~DRFLAC_CACHE_L1_SIZE_BITS!"bs"~"-riceParam);\n"~
1163 "\n"~
1164 "  for (int i = 0; i < cast(int)count; ++i) {\n"~
1165 "    uint zeroCounter = 0;\n"~
1166 "    while (bs.cache == 0) {\n"~
1167 "      zeroCounter += cast(uint)"~DRFLAC_CACHE_L1_BITS_REMAINING!"bs"~";\n"~
1168 "      if (!drflac__reload_cache(bs)) return false;\n"~
1169 "    }\n"~
1170 "\n"~
1171 "    /* At this point the cache should not be zero, in which case we know the first set bit should be somewhere in here. There is\n"~
1172 "       no need for us to perform any cache reloading logic here which should make things much faster. */\n"~
1173 "    assert(bs.cache != 0);\n"~
1174 "    uint decodedRice;\n"~
1175 "\n"~
1176 "    uint setBitOffsetPlus1 = bitOffsetTable.ptr["~DRFLAC_CACHE_L1_SELECT_AND_SHIFT!("bs", "4")~"];\n"~
1177 "    if (setBitOffsetPlus1 > 0) {\n"~
1178 "      decodedRice = (zeroCounter+(setBitOffsetPlus1-1))<<riceParam;\n"~
1179 "    } else {\n"~
1180 "      if (bs.cache == 1) {\n"~
1181 "        setBitOffsetPlus1 = cast(uint)("~DRFLAC_CACHE_L1_SIZE_BITS!"bs"~");\n"~
1182 "        decodedRice = cast(uint)((zeroCounter+("~DRFLAC_CACHE_L1_SIZE_BITS!"bs"~"-1))<<riceParam);\n"~
1183 "      } else {\n"~
1184 "        setBitOffsetPlus1 = 5;\n"~
1185 "        for (;;) {\n"~
1186 "          if ((bs.cache&"~DRFLAC_CACHE_L1_SELECT!("bs", "setBitOffsetPlus1")~")) {\n"~
1187 "            decodedRice = (zeroCounter+(setBitOffsetPlus1-1))<<riceParam;\n"~
1188 "            break;\n"~
1189 "          }\n"~
1190 "          setBitOffsetPlus1 += 1;\n"~
1191 "        }\n"~
1192 "      }\n"~
1193 "    }\n"~
1194 "\n"~
1195 "    uint bitsLo = 0;\n"~
1196 "    uint riceLength = setBitOffsetPlus1+riceParam;\n"~
1197 "    if (riceLength < "~DRFLAC_CACHE_L1_BITS_REMAINING!"bs"~") {\n"~
1198 "      bitsLo = cast(uint)((bs.cache&(riceParamMask>>setBitOffsetPlus1))>>("~DRFLAC_CACHE_L1_SIZE_BITS!"bs"~"-riceLength));\n"~
1199 "      bs.consumedBits += riceLength;\n"~
1200 "      bs.cache <<= riceLength;\n"~
1201 "    } else {\n"~
1202 "      bs.consumedBits += riceLength;\n"~
1203 "      bs.cache <<= setBitOffsetPlus1;\n"~
1204 "\n"~
1205 "      /* 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. */\n"~
1206 "      size_t bitCountLo = bs.consumedBits-"~DRFLAC_CACHE_L1_SIZE_BITS!"bs"~";\n"~
1207 "      drflac_cache_t resultHi = bs.cache&riceParamMask;    /* <-- This mask is OK because all bits after the first bits are always zero. */\n"~
1208 "\n"~
1209 "      if (bs.nextL2Line < "~DRFLAC_CACHE_L2_LINE_COUNT!"bs"~") {\n"~
1210 "        bs.cache = drflac__be2host__cache_line(bs.cacheL2.ptr[bs.nextL2Line++]);\n"~
1211 "      } else {\n"~
1212 "        /* Slow path. We need to fetch more data from the client. */\n"~
1213 "        if (!drflac__reload_cache(bs)) return false;\n"~
1214 "      }\n"~
1215 "\n"~
1216 "      bitsLo = cast(uint)((resultHi>>resultHiShift)|"~DRFLAC_CACHE_L1_SELECT_AND_SHIFT!("bs", "bitCountLo")~");\n"~
1217 "      bs.consumedBits = bitCountLo;\n"~
1218 "      bs.cache <<= bitCountLo;\n"~
1219 "    }\n"~
1220 "\n"~
1221 "    decodedRice |= bitsLo;\n"~
1222 "    decodedRice = (decodedRice>>1)^(~(decodedRice&0x01)+1);   /* <-- Ah, much faster! :) */\n"~
1223 "    /*\n"~
1224 "    if ((decodedRice&0x01)) {\n"~
1225 "      decodedRice = ~(decodedRice>>1);\n"~
1226 "    } else {\n"~
1227 "      decodedRice = (decodedRice>>1);\n"~
1228 "    }\n"~
1229 "    */\n"~
1230 "\n"~
1231 "    /* In order to properly calculate the prediction when the bits per sample is >16 we need to do it using 64-bit arithmetic. We can assume this\n"~
1232 "       is probably going to be slower on 32-bit systems so we'll do a more optimized 32-bit version when the bits per sample is low enough.*/\n"~
1233 "    pSamplesOut[i] = (cast(int)decodedRice+"~predictionFunc~"(order, shift, coefficients, pSamplesOut+i));\n"~
1234 "  }\n"~
1235 "\n"~
1236 "  return true;\n"~
1237 "}\n";
1238 
1239 mixin(DRFLAC__DECODE_SAMPLES_WITH_RESIDULE__RICE__PROC!("drflac__decode_samples_with_residual__rice_64", "drflac__calculate_prediction_64"));
1240 mixin(DRFLAC__DECODE_SAMPLES_WITH_RESIDULE__RICE__PROC!("drflac__decode_samples_with_residual__rice_32", "drflac__calculate_prediction_32"));
1241 
1242 
1243 // 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.
1244 bool drflac__read_and_seek_residual__rice (drflac_bs* bs, uint count, ubyte riceParam) {
1245   assert(bs !is null);
1246   assert(count > 0);
1247 
1248   for (uint i = 0; i < count; ++i) {
1249     if (!drflac__read_and_seek_rice(bs, riceParam)) return false;
1250   }
1251 
1252   return true;
1253 }
1254 
1255 bool drflac__decode_samples_with_residual__unencoded (drflac_bs* bs, uint bitsPerSample, uint count, ubyte unencodedBitsPerSample, uint order, int shift, const short* coefficients, int* pSamplesOut) {
1256   assert(bs !is null);
1257   assert(count > 0);
1258   assert(unencodedBitsPerSample > 0 && unencodedBitsPerSample <= 32);
1259   assert(pSamplesOut !is null);
1260 
1261   for (uint i = 0; i < count; ++i) {
1262     if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut+i)) return false;
1263     if (bitsPerSample > 16) {
1264       pSamplesOut[i] += drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut+i);
1265     } else {
1266       pSamplesOut[i] += drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut+i);
1267     }
1268   }
1269 
1270   return true;
1271 }
1272 
1273 
1274 // Reads and decodes the residual for the sub-frame the decoder is currently sitting on. This function should be called
1275 // when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be ignored. The
1276 // <blockSize> and <order> parameters are used to determine how many residual values need to be decoded.
1277 bool drflac__decode_samples_with_residual (drflac_bs* bs, uint bitsPerSample, uint blockSize, uint order, int shift, const short* coefficients, int* pDecodedSamples) {
1278   assert(bs !is null);
1279   assert(blockSize != 0);
1280   assert(pDecodedSamples !is null);       // <-- Should we allow null, in which case we just seek past the residual rather than do a full decode?
1281 
1282   ubyte residualMethod;
1283   if (!drflac__read_uint8(bs, 2, &residualMethod)) return false;
1284 
1285   if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) return false; // Unknown or unsupported residual coding method.
1286 
1287   // Ignore the first <order> values.
1288   pDecodedSamples += order;
1289 
1290   ubyte partitionOrder;
1291   if (!drflac__read_uint8(bs, 4, &partitionOrder)) return false;
1292 
1293   uint samplesInPartition = (blockSize/(1<<partitionOrder))-order;
1294   uint partitionsRemaining = (1<<partitionOrder);
1295   for (;;) {
1296     ubyte riceParam = 0;
1297     if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
1298       if (!drflac__read_uint8(bs, 4, &riceParam)) return false;
1299       if (riceParam == 16) riceParam = 0xFF;
1300     } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
1301       if (!drflac__read_uint8(bs, 5, &riceParam)) return false;
1302       if (riceParam == 32) riceParam = 0xFF;
1303     }
1304 
1305     if (riceParam != 0xFF) {
1306       if (bitsPerSample > 16) {
1307         if (!drflac__decode_samples_with_residual__rice_64(bs, samplesInPartition, riceParam, order, shift, coefficients, pDecodedSamples)) return false;
1308       } else {
1309         if (!drflac__decode_samples_with_residual__rice_32(bs, samplesInPartition, riceParam, order, shift, coefficients, pDecodedSamples)) return false;
1310       }
1311     } else {
1312       ubyte unencodedBitsPerSample = 0;
1313       if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) return false;
1314       if (!drflac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, order, shift, coefficients, pDecodedSamples)) return false;
1315     }
1316 
1317     pDecodedSamples += samplesInPartition;
1318 
1319     if (partitionsRemaining == 1) break;
1320 
1321     partitionsRemaining -= 1;
1322     samplesInPartition = blockSize/(1<<partitionOrder);
1323   }
1324 
1325   return true;
1326 }
1327 
1328 // Reads and seeks past the residual for the sub-frame the decoder is currently sitting on. This function should be called
1329 // when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be set to 0. The
1330 // <blockSize> and <order> parameters are used to determine how many residual values need to be decoded.
1331 bool drflac__read_and_seek_residual (drflac_bs* bs, uint blockSize, uint order) {
1332   assert(bs !is null);
1333   assert(blockSize != 0);
1334 
1335   ubyte residualMethod;
1336   if (!drflac__read_uint8(bs, 2, &residualMethod)) return false;
1337 
1338   if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) return false; // Unknown or unsupported residual coding method.
1339 
1340   ubyte partitionOrder;
1341   if (!drflac__read_uint8(bs, 4, &partitionOrder)) return false;
1342 
1343   uint samplesInPartition = (blockSize/(1<<partitionOrder))-order;
1344   uint partitionsRemaining = (1<<partitionOrder);
1345   for (;;) {
1346     ubyte riceParam = 0;
1347     if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
1348       if (!drflac__read_uint8(bs, 4, &riceParam)) return false;
1349       if (riceParam == 16) riceParam = 0xFF;
1350     } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
1351       if (!drflac__read_uint8(bs, 5, &riceParam)) return false;
1352       if (riceParam == 32) riceParam = 0xFF;
1353     }
1354 
1355     if (riceParam != 0xFF) {
1356       if (!drflac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) return false;
1357     } else {
1358       ubyte unencodedBitsPerSample = 0;
1359       if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) return false;
1360       if (!drflac__seek_bits(bs, unencodedBitsPerSample*samplesInPartition)) return false;
1361     }
1362 
1363     if (partitionsRemaining == 1) break;
1364 
1365     partitionsRemaining -= 1;
1366     samplesInPartition = blockSize/(1<<partitionOrder);
1367   }
1368 
1369   return true;
1370 }
1371 
1372 
1373 bool drflac__decode_samples__constant (drflac_bs* bs, uint blockSize, uint bitsPerSample, int* pDecodedSamples) {
1374   // Only a single sample needs to be decoded here.
1375   int sample;
1376   if (!drflac__read_int32(bs, bitsPerSample, &sample)) return false;
1377 
1378   // We don't really need to expand this, but it does simplify the process of reading samples. If this becomes a performance issue (unlikely)
1379   // we'll want to look at a more efficient way.
1380   for (uint i = 0; i < blockSize; ++i) pDecodedSamples[i] = sample;
1381 
1382   return true;
1383 }
1384 
1385 bool drflac__decode_samples__verbatim (drflac_bs* bs, uint blockSize, uint bitsPerSample, int* pDecodedSamples) {
1386   for (uint i = 0; i < blockSize; ++i) {
1387     int sample;
1388     if (!drflac__read_int32(bs, bitsPerSample, &sample)) return false;
1389     pDecodedSamples[i] = sample;
1390   }
1391   return true;
1392 }
1393 
1394 bool drflac__decode_samples__fixed (drflac_bs* bs, uint blockSize, uint bitsPerSample, ubyte lpcOrder, int* pDecodedSamples) {
1395   static immutable short[4][5] lpcCoefficientsTable = [
1396       [0,  0, 0,  0],
1397       [1,  0, 0,  0],
1398       [2, -1, 0,  0],
1399       [3, -3, 1,  0],
1400       [4, -6, 4, -1]
1401   ];
1402 
1403   // Warm up samples and coefficients.
1404   for (uint i = 0; i < lpcOrder; ++i) {
1405     int sample;
1406     if (!drflac__read_int32(bs, bitsPerSample, &sample)) return false;
1407     pDecodedSamples[i] = sample;
1408   }
1409 
1410   if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, 0, lpcCoefficientsTable.ptr[lpcOrder].ptr, pDecodedSamples)) return false;
1411 
1412   return true;
1413 }
1414 
1415 bool drflac__decode_samples__lpc (drflac_bs* bs, uint blockSize, uint bitsPerSample, ubyte lpcOrder, int* pDecodedSamples) {
1416   // Warm up samples.
1417   for (ubyte i = 0; i < lpcOrder; ++i) {
1418     int sample;
1419     if (!drflac__read_int32(bs, bitsPerSample, &sample)) return false;
1420     pDecodedSamples[i] = sample;
1421   }
1422 
1423   ubyte lpcPrecision;
1424   if (!drflac__read_uint8(bs, 4, &lpcPrecision)) return false;
1425   if (lpcPrecision == 15) return false;    // Invalid.
1426   lpcPrecision += 1;
1427 
1428   byte lpcShift;
1429   if (!drflac__read_int8(bs, 5, &lpcShift)) return false;
1430 
1431   short[32] coefficients;
1432   for (ubyte i = 0; i < lpcOrder; ++i) {
1433     if (!drflac__read_int16(bs, lpcPrecision, coefficients.ptr+i)) return false;
1434   }
1435 
1436   if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, coefficients.ptr, pDecodedSamples)) return false;
1437 
1438   return true;
1439 }
1440 
1441 
1442 bool drflac__read_next_frame_header (drflac_bs* bs, ubyte streaminfoBitsPerSample, drflac_frame_header* header) {
1443   assert(bs !is null);
1444   assert(header !is null);
1445 
1446   // At the moment the sync code is as a form of basic validation. The CRC is stored, but is unused at the moment. This
1447   // should probably be handled better in the future.
1448 
1449   static immutable uint[12] sampleRateTable  = [0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000];
1450   static immutable ubyte[8] bitsPerSampleTable = [0, 8, 12, cast(ubyte)-1, 16, 20, 24, cast(ubyte)-1];   // -1 = reserved.
1451 
1452   ushort syncCode = 0;
1453   if (!drflac__read_uint16(bs, 14, &syncCode)) return false;
1454 
1455   if (syncCode != 0x3FFE) return false; // TODO: Try and recover by attempting to seek to and read the next frame?
1456 
1457   ubyte reserved;
1458   if (!drflac__read_uint8(bs, 1, &reserved)) return false;
1459 
1460   ubyte blockingStrategy = 0;
1461   if (!drflac__read_uint8(bs, 1, &blockingStrategy)) return false;
1462 
1463   ubyte blockSize = 0;
1464   if (!drflac__read_uint8(bs, 4, &blockSize)) return false;
1465 
1466   ubyte sampleRate = 0;
1467   if (!drflac__read_uint8(bs, 4, &sampleRate)) return false;
1468 
1469   ubyte channelAssignment = 0;
1470   if (!drflac__read_uint8(bs, 4, &channelAssignment)) return false;
1471 
1472   ubyte bitsPerSample = 0;
1473   if (!drflac__read_uint8(bs, 3, &bitsPerSample)) return false;
1474 
1475   if (!drflac__read_uint8(bs, 1, &reserved)) return false;
1476 
1477   bool isVariableBlockSize = blockingStrategy == 1;
1478   if (isVariableBlockSize) {
1479     ulong sampleNumber;
1480     if (!drflac__read_utf8_coded_number(bs, &sampleNumber)) return false;
1481     header.frameNumber  = 0;
1482     header.sampleNumber = sampleNumber;
1483   } else {
1484     ulong frameNumber = 0;
1485     if (!drflac__read_utf8_coded_number(bs, &frameNumber)) return false;
1486     header.frameNumber  = cast(uint)frameNumber;   // <-- Safe cast.
1487     header.sampleNumber = 0;
1488   }
1489 
1490   if (blockSize == 1) {
1491     header.blockSize = 192;
1492   } else if (blockSize >= 2 && blockSize <= 5) {
1493     header.blockSize = cast(ushort)(576*(1<<(blockSize-2))); //k8
1494   } else if (blockSize == 6) {
1495     if (!drflac__read_uint16(bs, 8, &header.blockSize)) return false;
1496     header.blockSize += 1;
1497   } else if (blockSize == 7) {
1498     if (!drflac__read_uint16(bs, 16, &header.blockSize)) return false;
1499     header.blockSize += 1;
1500   } else {
1501     header.blockSize = cast(ushort)(256*(1<<(blockSize-8))); //k8
1502   }
1503 
1504   if (sampleRate <= 11) {
1505     header.sampleRate = sampleRateTable.ptr[sampleRate];
1506   } else if (sampleRate == 12) {
1507     if (!drflac__read_uint32(bs, 8, &header.sampleRate)) return false;
1508     header.sampleRate *= 1000;
1509   } else if (sampleRate == 13) {
1510     if (!drflac__read_uint32(bs, 16, &header.sampleRate)) return false;
1511   } else if (sampleRate == 14) {
1512     if (!drflac__read_uint32(bs, 16, &header.sampleRate)) return false;
1513     header.sampleRate *= 10;
1514   } else {
1515     return false;  // Invalid.
1516   }
1517 
1518   header.channelAssignment = channelAssignment;
1519 
1520   header.bitsPerSample = bitsPerSampleTable.ptr[bitsPerSample];
1521   if (header.bitsPerSample == 0) header.bitsPerSample = streaminfoBitsPerSample;
1522 
1523   if (drflac__read_uint8(bs, 8, &header.crc8) != 1) return false;
1524 
1525   return true;
1526 }
1527 
1528 bool drflac__read_subframe_header (drflac_bs* bs, drflac_subframe* pSubframe) {
1529   ubyte header;
1530   if (!drflac__read_uint8(bs, 8, &header)) return false;
1531 
1532   // First bit should always be 0.
1533   if ((header&0x80) != 0) return false;
1534 
1535   int type = (header&0x7E)>>1;
1536   if (type == 0) {
1537     pSubframe.subframeType = DRFLAC_SUBFRAME_CONSTANT;
1538   } else if (type == 1) {
1539     pSubframe.subframeType = DRFLAC_SUBFRAME_VERBATIM;
1540   } else {
1541     if ((type&0x20) != 0) {
1542       pSubframe.subframeType = DRFLAC_SUBFRAME_LPC;
1543       pSubframe.lpcOrder = (type&0x1F)+1;
1544     } else if ((type&0x08) != 0) {
1545       pSubframe.subframeType = DRFLAC_SUBFRAME_FIXED;
1546       pSubframe.lpcOrder = (type&0x07);
1547       if (pSubframe.lpcOrder > 4) {
1548         pSubframe.subframeType = DRFLAC_SUBFRAME_RESERVED;
1549         pSubframe.lpcOrder = 0;
1550       }
1551     } else {
1552       pSubframe.subframeType = DRFLAC_SUBFRAME_RESERVED;
1553     }
1554   }
1555 
1556   if (pSubframe.subframeType == DRFLAC_SUBFRAME_RESERVED) return false;
1557 
1558   // Wasted bits per sample.
1559   pSubframe.wastedBitsPerSample = 0;
1560   if ((header&0x01) == 1) {
1561     uint wastedBitsPerSample;
1562     if (!drflac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) return false;
1563     pSubframe.wastedBitsPerSample = cast(ubyte)(cast(ubyte)wastedBitsPerSample+1); // k8
1564   }
1565 
1566   return true;
1567 }
1568 
1569 bool drflac__decode_subframe (drflac_bs* bs, drflac_frame* frame, int subframeIndex, int* pDecodedSamplesOut) {
1570   assert(bs !is null);
1571   assert(frame !is null);
1572 
1573   drflac_subframe* pSubframe = frame.subframes.ptr+subframeIndex;
1574   if (!drflac__read_subframe_header(bs, pSubframe)) return false;
1575 
1576   // Side channels require an extra bit per sample. Took a while to figure that one out...
1577   pSubframe.bitsPerSample = frame.header.bitsPerSample;
1578   if ((frame.header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame.header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
1579     pSubframe.bitsPerSample += 1;
1580   } else if (frame.header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
1581     pSubframe.bitsPerSample += 1;
1582   }
1583 
1584   // Need to handle wasted bits per sample.
1585   pSubframe.bitsPerSample -= pSubframe.wastedBitsPerSample;
1586   pSubframe.pDecodedSamples = pDecodedSamplesOut;
1587 
1588   switch (pSubframe.subframeType) {
1589     case DRFLAC_SUBFRAME_CONSTANT: drflac__decode_samples__constant(bs, frame.header.blockSize, pSubframe.bitsPerSample, pSubframe.pDecodedSamples); break;
1590     case DRFLAC_SUBFRAME_VERBATIM: drflac__decode_samples__verbatim(bs, frame.header.blockSize, pSubframe.bitsPerSample, pSubframe.pDecodedSamples); break;
1591     case DRFLAC_SUBFRAME_FIXED: drflac__decode_samples__fixed(bs, frame.header.blockSize, pSubframe.bitsPerSample, pSubframe.lpcOrder, pSubframe.pDecodedSamples); break;
1592     case DRFLAC_SUBFRAME_LPC: drflac__decode_samples__lpc(bs, frame.header.blockSize, pSubframe.bitsPerSample, pSubframe.lpcOrder, pSubframe.pDecodedSamples); break;
1593     default: return false;
1594   }
1595 
1596   return true;
1597 }
1598 
1599 bool drflac__seek_subframe (drflac_bs* bs, drflac_frame* frame, int subframeIndex) {
1600   assert(bs !is null);
1601   assert(frame !is null);
1602 
1603   drflac_subframe* pSubframe = frame.subframes.ptr+subframeIndex;
1604   if (!drflac__read_subframe_header(bs, pSubframe)) return false;
1605 
1606   // Side channels require an extra bit per sample. Took a while to figure that one out...
1607   pSubframe.bitsPerSample = frame.header.bitsPerSample;
1608   if ((frame.header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame.header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
1609     pSubframe.bitsPerSample += 1;
1610   } else if (frame.header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
1611     pSubframe.bitsPerSample += 1;
1612   }
1613 
1614   // Need to handle wasted bits per sample.
1615   pSubframe.bitsPerSample -= pSubframe.wastedBitsPerSample;
1616   pSubframe.pDecodedSamples = null;
1617   //pSubframe.pDecodedSamples = pFlac.pDecodedSamples+(pFlac.currentFrame.header.blockSize*subframeIndex);
1618 
1619   switch (pSubframe.subframeType) {
1620     case DRFLAC_SUBFRAME_CONSTANT:
1621       if (!drflac__seek_bits(bs, pSubframe.bitsPerSample)) return false;
1622       break;
1623 
1624     case DRFLAC_SUBFRAME_VERBATIM:
1625       uint bitsToSeek = frame.header.blockSize*pSubframe.bitsPerSample;
1626       if (!drflac__seek_bits(bs, bitsToSeek)) return false;
1627       break;
1628 
1629     case DRFLAC_SUBFRAME_FIXED:
1630       uint bitsToSeek = pSubframe.lpcOrder*pSubframe.bitsPerSample;
1631       if (!drflac__seek_bits(bs, bitsToSeek)) return false;
1632       if (!drflac__read_and_seek_residual(bs, frame.header.blockSize, pSubframe.lpcOrder)) return false;
1633       break;
1634 
1635     case DRFLAC_SUBFRAME_LPC:
1636       uint bitsToSeek = pSubframe.lpcOrder*pSubframe.bitsPerSample;
1637       if (!drflac__seek_bits(bs, bitsToSeek)) return false;
1638       ubyte lpcPrecision;
1639       if (!drflac__read_uint8(bs, 4, &lpcPrecision)) return false;
1640       if (lpcPrecision == 15) return false;    // Invalid.
1641       lpcPrecision += 1;
1642       bitsToSeek = (pSubframe.lpcOrder*lpcPrecision)+5;    // +5 for shift.
1643       if (!drflac__seek_bits(bs, bitsToSeek)) return false;
1644       if (!drflac__read_and_seek_residual(bs, frame.header.blockSize, pSubframe.lpcOrder)) return false;
1645       break;
1646 
1647     default: return false;
1648   }
1649 
1650   return true;
1651 }
1652 
1653 
1654 ubyte drflac__get_channel_count_from_channel_assignment (byte channelAssignment) {
1655   assert(channelAssignment <= 10);
1656   static immutable ubyte[11] lookup = [1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2];
1657   return lookup.ptr[channelAssignment];
1658 }
1659 
1660 bool drflac__decode_frame (drflac* pFlac) {
1661   import core.stdc.string : memset;
1662   // This function should be called while the stream is sitting on the first byte after the frame header.
1663   memset(pFlac.currentFrame.subframes.ptr, 0, (pFlac.currentFrame.subframes).sizeof);
1664 
1665   int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment);
1666   for (int i = 0; i < channelCount; ++i) {
1667     if (!drflac__decode_subframe(&pFlac.bs, &pFlac.currentFrame, i, pFlac.pDecodedSamples+(pFlac.currentFrame.header.blockSize*i))) return false;
1668   }
1669 
1670   // At the end of the frame sits the padding and CRC. We don't use these so we can just seek past.
1671   if (!drflac__seek_bits(&pFlac.bs, (mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"(&pFlac.bs)")&7)+16)) return false;
1672 
1673   pFlac.currentFrame.samplesRemaining = pFlac.currentFrame.header.blockSize*channelCount;
1674 
1675   return true;
1676 }
1677 
1678 bool drflac__seek_frame (drflac* pFlac) {
1679   int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment);
1680   for (int i = 0; i < channelCount; ++i) {
1681     if (!drflac__seek_subframe(&pFlac.bs, &pFlac.currentFrame, i)) return false;
1682   }
1683   // Padding and CRC.
1684   return drflac__seek_bits(&pFlac.bs, (mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"(&pFlac.bs)")&7)+16);
1685 }
1686 
1687 bool drflac__read_and_decode_next_frame (drflac* pFlac) {
1688   assert(pFlac !is null);
1689 
1690   if (!drflac__read_next_frame_header(&pFlac.bs, pFlac.bitsPerSample, &pFlac.currentFrame.header)) return false;
1691 
1692   return drflac__decode_frame(pFlac);
1693 }
1694 
1695 
1696 void drflac__get_current_frame_sample_range (drflac* pFlac, ulong* pFirstSampleInFrameOut, ulong* pLastSampleInFrameOut) {
1697   assert(pFlac !is null);
1698 
1699   uint channelCount = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment);
1700 
1701   ulong firstSampleInFrame = pFlac.currentFrame.header.sampleNumber;
1702   if (firstSampleInFrame == 0) firstSampleInFrame = pFlac.currentFrame.header.frameNumber*pFlac.maxBlockSize*channelCount;
1703 
1704   ulong lastSampleInFrame = firstSampleInFrame+(pFlac.currentFrame.header.blockSize*channelCount);
1705   if (lastSampleInFrame > 0) lastSampleInFrame -= 1; // Needs to be zero based.
1706 
1707   if (pFirstSampleInFrameOut) *pFirstSampleInFrameOut = firstSampleInFrame;
1708   if (pLastSampleInFrameOut) *pLastSampleInFrameOut = lastSampleInFrame;
1709 }
1710 
1711 bool drflac__seek_to_first_frame (drflac* pFlac) {
1712   import core.stdc.string : memset;
1713   assert(pFlac !is null);
1714 
1715   bool result = drflac__seek_to_byte(&pFlac.bs, pFlac.firstFramePos);
1716 
1717   memset(&pFlac.currentFrame, 0, (pFlac.currentFrame).sizeof);
1718   return result;
1719 }
1720 
1721 bool drflac__seek_to_next_frame (drflac* pFlac) {
1722   // This function should only ever be called while the decoder is sitting on the first byte past the FRAME_HEADER section.
1723   assert(pFlac !is null);
1724   return drflac__seek_frame(pFlac);
1725 }
1726 
1727 bool drflac__seek_to_frame_containing_sample (drflac* pFlac, ulong sampleIndex) {
1728   assert(pFlac !is null);
1729 
1730   if (!drflac__seek_to_first_frame(pFlac)) return false;
1731 
1732   ulong firstSampleInFrame = 0;
1733   ulong lastSampleInFrame = 0;
1734   for (;;) {
1735     // We need to read the frame's header in order to determine the range of samples it contains.
1736     if (!drflac__read_next_frame_header(&pFlac.bs, pFlac.bitsPerSample, &pFlac.currentFrame.header)) return false;
1737     drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame);
1738     if (sampleIndex >= firstSampleInFrame && sampleIndex <= lastSampleInFrame) break;  // The sample is in this frame.
1739     if (!drflac__seek_to_next_frame(pFlac)) return false;
1740   }
1741 
1742   // If we get here we should be right at the start of the frame containing the sample.
1743   return true;
1744 }
1745 
1746 public bool drflac__seek_to_sample__brute_force (drflac* pFlac, ulong sampleIndex) {
1747   if (!drflac__seek_to_frame_containing_sample(pFlac, sampleIndex)) return false;
1748 
1749   // At this point we should be sitting on the first byte of the frame containing the sample. We need to decode every sample up to (but
1750   // not including) the sample we're seeking to.
1751   ulong firstSampleInFrame = 0;
1752   drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, null);
1753 
1754   assert(firstSampleInFrame <= sampleIndex);
1755   size_t samplesToDecode = cast(size_t)(sampleIndex-firstSampleInFrame);    // <-- Safe cast because the maximum number of samples in a frame is 65535.
1756   if (samplesToDecode == 0) return true;
1757 
1758   // At this point we are just sitting on the byte after the frame header. We need to decode the frame before reading anything from it.
1759   if (!drflac__decode_frame(pFlac)) return false;
1760 
1761   return drflac_read_s32(pFlac, samplesToDecode, null) != 0;
1762 }
1763 
1764 
1765 bool drflac__seek_to_sample__seek_table (drflac* pFlac, ulong sampleIndex) {
1766   assert(pFlac !is null);
1767 
1768   if (pFlac.seektablePos == 0) return false;
1769 
1770   if (!drflac__seek_to_byte(&pFlac.bs, pFlac.seektablePos)) return false;
1771 
1772   // The number of seek points is derived from the size of the SEEKTABLE block.
1773   uint seekpointCount = pFlac.seektableSize/18;   // 18 = the size of each seek point.
1774   if (seekpointCount == 0) return false;   // Would this ever happen?
1775 
1776   drflac_seekpoint closestSeekpoint = {0};
1777 
1778   uint seekpointsRemaining = seekpointCount;
1779   while (seekpointsRemaining > 0) {
1780     drflac_seekpoint seekpoint;
1781     if (!drflac__read_uint64(&pFlac.bs, 64, &seekpoint.firstSample)) break;
1782     if (!drflac__read_uint64(&pFlac.bs, 64, &seekpoint.frameOffset)) break;
1783     if (!drflac__read_uint16(&pFlac.bs, 16, &seekpoint.sampleCount)) break;
1784     if (seekpoint.firstSample*pFlac.channels > sampleIndex) break;
1785     closestSeekpoint = seekpoint;
1786     seekpointsRemaining -= 1;
1787   }
1788 
1789   // At this point we should have found the seekpoint closest to our sample. We need to seek to it using basically the same
1790   // technique as we use with the brute force method.
1791   if (!drflac__seek_to_byte(&pFlac.bs, pFlac.firstFramePos+closestSeekpoint.frameOffset)) return false;
1792 
1793   ulong firstSampleInFrame = 0;
1794   ulong lastSampleInFrame = 0;
1795   for (;;) {
1796     // We need to read the frame's header in order to determine the range of samples it contains.
1797     if (!drflac__read_next_frame_header(&pFlac.bs, pFlac.bitsPerSample, &pFlac.currentFrame.header)) return false;
1798     drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame);
1799     if (sampleIndex >= firstSampleInFrame && sampleIndex <= lastSampleInFrame) break;  // The sample is in this frame.
1800     if (!drflac__seek_to_next_frame(pFlac)) return false;
1801   }
1802 
1803   assert(firstSampleInFrame <= sampleIndex);
1804 
1805   // At this point we are just sitting on the byte after the frame header. We need to decode the frame before reading anything from it.
1806   if (!drflac__decode_frame(pFlac)) return false;
1807 
1808   size_t samplesToDecode = cast(size_t)(sampleIndex-firstSampleInFrame);    // <-- Safe cast because the maximum number of samples in a frame is 65535.
1809   return drflac_read_s32(pFlac, samplesToDecode, null) == samplesToDecode;
1810 }
1811 
1812 
1813 //#ifndef DR_FLAC_NO_OGG
1814 struct drflac_ogg_page_header {
1815   ubyte[4] capturePattern;  // Should be "OggS"
1816   ubyte structureVersion;   // Always 0.
1817   ubyte headerType;
1818   ulong granulePosition;
1819   uint serialNumber;
1820   uint sequenceNumber;
1821   uint checksum;
1822   ubyte segmentCount;
1823   ubyte[255] segmentTable;
1824 }
1825 //#endif
1826 
1827 struct drflac_init_info {
1828   //drflac_read_proc onRead;
1829   //drflac_seek_proc onSeek;
1830   //void* pUserData;
1831   ReadStruct rs;
1832   //drflac_meta_proc onMeta;
1833   //void* pUserDataMD;
1834   drflac_container container;
1835   uint sampleRate;
1836   ubyte  channels;
1837   ubyte  bitsPerSample;
1838   ulong totalSampleCount;
1839   ushort maxBlockSize;
1840   ulong runningFilePos;
1841   bool hasMetadataBlocks;
1842 
1843 //#ifndef DR_FLAC_NO_OGG
1844   uint oggSerial;
1845   ulong oggFirstBytePos;
1846   drflac_ogg_page_header oggBosHeader;
1847 //#endif
1848 }
1849 
1850 private struct ReadStruct {
1851 @nogc:	
1852   drflac_read_proc onReadCB;
1853   drflac_seek_proc onSeekCB;
1854   void* pUserData;
1855 
1856   size_t read (void* pBufferOut, size_t bytesToRead) nothrow {
1857     auto b = cast(ubyte*)pBufferOut;
1858     auto res = 0;
1859     try {
1860       while (bytesToRead > 0) {
1861         size_t rd = 0;
1862         if (onReadCB !is null) {
1863           rd = onReadCB(pUserData, b, bytesToRead);
1864         } else {
1865          }
1866         if (rd == 0) break;
1867         b += rd;
1868         res += rd;
1869         bytesToRead -= rd;
1870       }
1871       return res;
1872     } catch (Exception e) {
1873       return 0;
1874     }
1875   }
1876 
1877   bool seek (int offset, drflac_seek_origin origin) nothrow {
1878     try {
1879       if (onSeekCB !is null) {
1880         return onSeekCB(pUserData, offset, origin);
1881       } else {
1882       }
1883       return false;
1884     } catch (Exception e) {
1885       return 0;
1886     }
1887   }
1888 }
1889 
1890 
1891 void drflac__decode_block_header (uint blockHeader, ubyte* isLastBlock, ubyte* blockType, uint* blockSize) {
1892   blockHeader = drflac__be2host_32(blockHeader);
1893   *isLastBlock = (blockHeader&(0x01<<31))>>31;
1894   *blockType   = (blockHeader&(0x7F<<24))>>24;
1895   *blockSize   = (blockHeader&0xFFFFFF);
1896 }
1897 
1898 bool drflac__read_and_decode_block_header (ref ReadStruct rs, ubyte* isLastBlock, ubyte* blockType, uint* blockSize) {
1899   uint blockHeader;
1900   if (rs.read(&blockHeader, 4) != 4) return false;
1901   drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize);
1902   return true;
1903 }
1904 
1905 bool drflac__read_streaminfo (ref ReadStruct rs, drflac_streaminfo* pStreamInfo) {
1906   import core.stdc.string : memcpy;
1907   // min/max block size.
1908   uint blockSizes;
1909   if (rs.read(&blockSizes, 4) != 4) return false;
1910   // min/max frame size.
1911   ulong frameSizes = 0;
1912   if (rs.read(&frameSizes, 6) != 6) return false;
1913   // Sample rate, channels, bits per sample and total sample count.
1914   ulong importantProps;
1915   if (rs.read(&importantProps, 8) != 8) return false;
1916   // MD5
1917   ubyte[16] md5;
1918   if (rs.read(md5.ptr, md5.sizeof) != md5.sizeof) return false;
1919 
1920   blockSizes     = drflac__be2host_32(blockSizes);
1921   frameSizes     = drflac__be2host_64(frameSizes);
1922   importantProps = drflac__be2host_64(importantProps);
1923 
1924   pStreamInfo.minBlockSize     = (blockSizes&0xFFFF0000)>>16;
1925   pStreamInfo.maxBlockSize     = blockSizes&0x0000FFFF;
1926   pStreamInfo.minFrameSize     = cast(uint)((frameSizes&0xFFFFFF0000000000UL)>>40);
1927   pStreamInfo.maxFrameSize     = cast(uint)((frameSizes&0x000000FFFFFF0000UL)>>16);
1928   pStreamInfo.sampleRate       = cast(uint)((importantProps&0xFFFFF00000000000UL)>>44);
1929   pStreamInfo.channels         = cast(ubyte )((importantProps&0x00000E0000000000UL)>>41)+1;
1930   pStreamInfo.bitsPerSample    = cast(ubyte )((importantProps&0x000001F000000000UL)>>36)+1;
1931   pStreamInfo.totalSampleCount = (importantProps&0x0000000FFFFFFFFFUL)*pStreamInfo.channels;
1932   memcpy(pStreamInfo.md5.ptr, md5.ptr, md5.sizeof);
1933 
1934   return true;
1935 }
1936 
1937 bool drflac__read_and_decode_metadata (drflac* pFlac, scope drflac_meta_proc onMeta, void* pUserDataMD) {
1938   import core.stdc.stdlib : malloc, free;
1939   assert(pFlac !is null);
1940 
1941   // 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
1942   // we'll be sitting on byte 42.
1943   ulong runningFilePos = 42;
1944   ulong seektablePos  = 0;
1945   uint seektableSize = 0;
1946 
1947   for (;;) {
1948     ubyte isLastBlock = 0;
1949     ubyte blockType;
1950     uint blockSize;
1951     if (!drflac__read_and_decode_block_header(pFlac.bs.rs, &isLastBlock, &blockType, &blockSize)) return false;
1952     runningFilePos += 4;
1953 
1954     drflac_metadata metadata;
1955     metadata.type = blockType;
1956     metadata.pRawData = null;
1957     metadata.rawDataSize = 0;
1958 
1959     switch (blockType) {
1960       case DRFLAC_METADATA_BLOCK_TYPE_APPLICATION:
1961         if (onMeta) {
1962             void* pRawData = malloc(blockSize);
1963             if (pRawData is null) return false;
1964             scope(exit) free(pRawData);
1965 
1966             if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false;
1967 
1968             metadata.pRawData = pRawData;
1969             metadata.rawDataSize = blockSize;
1970             metadata.data.application.id       = drflac__be2host_32(*cast(uint*)pRawData);
1971             metadata.data.application.pData    = cast(const(void)*)(cast(ubyte*)pRawData+uint.sizeof);
1972             metadata.data.application.dataSize = blockSize-cast(uint)uint.sizeof;
1973             try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; }
1974         }
1975         break;
1976 
1977       case DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE:
1978         seektablePos  = runningFilePos;
1979         seektableSize = blockSize;
1980 
1981         if (onMeta) {
1982           void* pRawData = malloc(blockSize);
1983           if (pRawData is null) return false;
1984           scope(exit) free(pRawData);
1985 
1986           if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false;
1987 
1988           metadata.pRawData = pRawData;
1989           metadata.rawDataSize = blockSize;
1990           metadata.data.seektable.seekpointCount = blockSize/(drflac_seekpoint).sizeof;
1991           metadata.data.seektable.pSeekpoints = cast(const(drflac_seekpoint)*)pRawData;
1992 
1993           // Endian swap.
1994           for (uint iSeekpoint = 0; iSeekpoint < metadata.data.seektable.seekpointCount; ++iSeekpoint) {
1995             drflac_seekpoint* pSeekpoint = cast(drflac_seekpoint*)pRawData+iSeekpoint;
1996             pSeekpoint.firstSample = drflac__be2host_64(pSeekpoint.firstSample);
1997             pSeekpoint.frameOffset = drflac__be2host_64(pSeekpoint.frameOffset);
1998             pSeekpoint.sampleCount = drflac__be2host_16(pSeekpoint.sampleCount);
1999           }
2000 
2001           try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; }
2002         }
2003         break;
2004 
2005       case DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT:
2006         if (onMeta) {
2007           void* pRawData = malloc(blockSize);
2008           if (pRawData is null) return false;
2009           scope(exit) free(pRawData);
2010 
2011           if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false;
2012 
2013           metadata.pRawData = pRawData;
2014           metadata.rawDataSize = blockSize;
2015 
2016           const(char)* pRunningData = cast(const(char)*)pRawData;
2017           metadata.data.vorbis_comment.vendorLength = drflac__le2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2018           metadata.data.vorbis_comment.vendor       = pRunningData;                                 pRunningData += metadata.data.vorbis_comment.vendorLength;
2019           metadata.data.vorbis_comment.commentCount = drflac__le2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2020           metadata.data.vorbis_comment.comments     = pRunningData;
2021           try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; }
2022         }
2023         break;
2024 
2025       case DRFLAC_METADATA_BLOCK_TYPE_CUESHEET:
2026         if (onMeta) {
2027           import core.stdc.string : memcpy;
2028           void* pRawData = malloc(blockSize);
2029           if (pRawData is null) return false;
2030           scope(exit) free(pRawData);
2031 
2032           if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false;
2033 
2034           metadata.pRawData = pRawData;
2035           metadata.rawDataSize = blockSize;
2036 
2037           const(char)* pRunningData = cast(const(char)*)pRawData;
2038           memcpy(metadata.data.cuesheet.catalog.ptr, pRunningData, 128);                           pRunningData += 128;
2039           metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*cast(ulong*)pRunningData);pRunningData += 4;
2040           metadata.data.cuesheet.isCD              = ((pRunningData[0]&0x80)>>7) != 0;         pRunningData += 259;
2041           metadata.data.cuesheet.trackCount        = pRunningData[0];                              pRunningData += 1;
2042           metadata.data.cuesheet.pTrackData        = cast(const(ubyte)*)pRunningData;
2043           try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; }
2044         }
2045         break;
2046 
2047       case DRFLAC_METADATA_BLOCK_TYPE_PICTURE:
2048         if (onMeta) {
2049           void* pRawData = malloc(blockSize);
2050           if (pRawData is null) return false;
2051           scope(exit) free(pRawData);
2052 
2053           if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false;
2054 
2055           metadata.pRawData = pRawData;
2056           metadata.rawDataSize = blockSize;
2057 
2058           const(char)* pRunningData = cast(const(char)*)pRawData;
2059           metadata.data.picture.type              = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2060           metadata.data.picture.mimeLength        = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2061           metadata.data.picture.mime              = pRunningData;                                 pRunningData += metadata.data.picture.mimeLength;
2062           metadata.data.picture.descriptionLength = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2063           metadata.data.picture.description       = pRunningData;
2064           metadata.data.picture.width             = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2065           metadata.data.picture.height            = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2066           metadata.data.picture.colorDepth        = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2067           metadata.data.picture.indexColorCount   = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2068           metadata.data.picture.pictureDataSize   = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2069           metadata.data.picture.pPictureData      = cast(const(ubyte)*)pRunningData;
2070           try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; }
2071         }
2072         break;
2073 
2074       case DRFLAC_METADATA_BLOCK_TYPE_PADDING:
2075         if (onMeta) {
2076           metadata.data.padding.unused = 0;
2077           // Padding doesn't have anything meaningful in it, so just skip over it.
2078           if (!pFlac.bs.rs.seek(blockSize, drflac_seek_origin_current)) return false;
2079           //onMeta(pUserDataMD, &metadata);
2080         }
2081         break;
2082 
2083       case DRFLAC_METADATA_BLOCK_TYPE_INVALID:
2084         // Invalid chunk. Just skip over this one.
2085         if (onMeta) {
2086           if (!pFlac.bs.rs.seek(blockSize, drflac_seek_origin_current)) return false;
2087         }
2088         goto default;
2089 
2090       default:
2091         // It's an unknown chunk, but not necessarily invalid. There's a chance more metadata blocks might be defined later on, so we
2092         // can at the very least report the chunk to the application and let it look at the raw data.
2093         if (onMeta) {
2094           void* pRawData = malloc(blockSize);
2095           if (pRawData is null) return false;
2096           scope(exit) free(pRawData);
2097 
2098           if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false;
2099 
2100           metadata.pRawData = pRawData;
2101           metadata.rawDataSize = blockSize;
2102           try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; }
2103         }
2104         break;
2105     }
2106 
2107     // 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.
2108     if (onMeta is null) {
2109       if (!pFlac.bs.rs.seek(blockSize, drflac_seek_origin_current)) return false;
2110     }
2111 
2112     runningFilePos += blockSize;
2113     if (isLastBlock) break;
2114   }
2115 
2116   pFlac.seektablePos = seektablePos;
2117   pFlac.seektableSize = seektableSize;
2118   pFlac.firstFramePos = runningFilePos;
2119 
2120   return true;
2121 }
2122 
2123 bool drflac__init_private__native (drflac_init_info* pInit, ref ReadStruct rs, scope drflac_meta_proc onMeta, void* pUserDataMD) {
2124   // Pre: The bit stream should be sitting just past the 4-byte id header.
2125 
2126   pInit.container = drflac_container_native;
2127 
2128   // The first metadata block should be the STREAMINFO block.
2129   ubyte isLastBlock;
2130   ubyte blockType;
2131   uint blockSize;
2132   if (!drflac__read_and_decode_block_header(rs, &isLastBlock, &blockType, &blockSize)) return false;
2133 
2134   if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) return false;    // Invalid block type. First block must be the STREAMINFO block.
2135 
2136   drflac_streaminfo streaminfo;
2137   if (!drflac__read_streaminfo(rs, &streaminfo)) return false;
2138 
2139   pInit.sampleRate       = streaminfo.sampleRate;
2140   pInit.channels         = streaminfo.channels;
2141   pInit.bitsPerSample    = streaminfo.bitsPerSample;
2142   pInit.totalSampleCount = streaminfo.totalSampleCount;
2143   pInit.maxBlockSize     = streaminfo.maxBlockSize;    // Don't care about the min block size - only the max (used for determining the size of the memory allocation).
2144 
2145   if (onMeta !is null) {
2146     drflac_metadata metadata;
2147     metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
2148     metadata.pRawData = null;
2149     metadata.rawDataSize = 0;
2150     metadata.data.streaminfo = streaminfo;
2151     try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; }
2152   }
2153 
2154   pInit.hasMetadataBlocks = !isLastBlock;
2155   return true;
2156 }
2157 
2158 //#ifndef DR_FLAC_NO_OGG
2159 bool drflac_ogg__is_capture_pattern (const(ubyte)* pattern/*[4]*/) {
2160   return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S';
2161 }
2162 
2163 uint drflac_ogg__get_page_header_size (drflac_ogg_page_header* pHeader) {
2164   return 27+pHeader.segmentCount;
2165 }
2166 
2167 uint drflac_ogg__get_page_body_size (drflac_ogg_page_header* pHeader) {
2168   uint pageBodySize = 0;
2169   for (int i = 0; i < pHeader.segmentCount; ++i) pageBodySize += pHeader.segmentTable.ptr[i];
2170   return pageBodySize;
2171 }
2172 
2173 bool drflac_ogg__read_page_header_after_capture_pattern (ref ReadStruct rs, drflac_ogg_page_header* pHeader, uint* pHeaderSize) {
2174   if (rs.read(&pHeader.structureVersion, 1) != 1 || pHeader.structureVersion != 0) return false;   // Unknown structure version. Possibly corrupt stream.
2175   if (rs.read(&pHeader.headerType, 1) != 1) return false;
2176   if (rs.read(&pHeader.granulePosition, 8) != 8) return false;
2177   if (rs.read(&pHeader.serialNumber, 4) != 4) return false;
2178   if (rs.read(&pHeader.sequenceNumber, 4) != 4) return false;
2179   if (rs.read(&pHeader.checksum, 4) != 4) return false;
2180   if (rs.read(&pHeader.segmentCount, 1) != 1 || pHeader.segmentCount == 0) return false;   // Should not have a segment count of 0.
2181   if (rs.read(&pHeader.segmentTable, pHeader.segmentCount) != pHeader.segmentCount) return false;
2182   if (pHeaderSize) *pHeaderSize = (27+pHeader.segmentCount);
2183   return true;
2184 }
2185 
2186 bool drflac_ogg__read_page_header (ref ReadStruct rs, drflac_ogg_page_header* pHeader, uint* pHeaderSize) {
2187   ubyte[4] id;
2188   if (rs.read(id.ptr, 4) != 4) return false;
2189   if (id.ptr[0] != 'O' || id.ptr[1] != 'g' || id.ptr[2] != 'g' || id.ptr[3] != 'S') return false;
2190   return drflac_ogg__read_page_header_after_capture_pattern(rs, pHeader, pHeaderSize);
2191 }
2192 
2193 
2194 // The main part of the Ogg encapsulation is the conversion from the physical Ogg bitstream to the native FLAC bitstream. It works
2195 // in three general stages: Ogg Physical Bitstream . Ogg/FLAC Logical Bitstream . FLAC Native Bitstream. dr_flac is architecured
2196 // in such a way that the core sections assume everything is delivered in native format. Therefore, for each encapsulation type
2197 // 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
2198 // the physical Ogg bitstream are converted and delivered in native FLAC format.
2199 struct drflac_oggbs {
2200   //drflac_read_proc onRead;    // The original onRead callback from drflac_open() and family.
2201   //drflac_seek_proc onSeek;    // The original onSeek callback from drflac_open() and family.
2202   //void* pUserData;            // The user data passed on onRead and onSeek. This is the user data that was passed on drflac_open() and family.
2203   ReadStruct rs;
2204   ulong currentBytePos;    // The position of the byte we are sitting on in the physical byte stream. Used for efficient seeking.
2205   ulong firstBytePos;      // The position of the first byte in the physical bitstream. Points to the start of the "OggS" identifier of the FLAC bos page.
2206   uint serialNumber;      // The serial number of the FLAC audio pages. This is determined by the initial header page that was read during initialization.
2207   drflac_ogg_page_header bosPageHeader;   // Used for seeking.
2208   drflac_ogg_page_header currentPageHeader;
2209   uint bytesRemainingInPage;
2210   bool stdio; //k8: it is drflac's stdio shit
2211 } // oggbs = Ogg Bitstream
2212 
2213 size_t drflac_oggbs__read_physical (drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead) {
2214   size_t bytesActuallyRead = oggbs.rs.read(bufferOut, bytesToRead);
2215   oggbs.currentBytePos += bytesActuallyRead;
2216   return bytesActuallyRead;
2217 }
2218 
2219 bool drflac_oggbs__seek_physical (drflac_oggbs* oggbs, ulong offset, drflac_seek_origin origin) {
2220   if (origin == drflac_seek_origin_start) {
2221     if (offset <= 0x7FFFFFFF) {
2222       if (!oggbs.rs.seek(cast(int)offset, drflac_seek_origin_start)) return false;
2223       oggbs.currentBytePos = offset;
2224       return true;
2225     } else {
2226       if (!oggbs.rs.seek(0x7FFFFFFF, drflac_seek_origin_start)) return false;
2227       oggbs.currentBytePos = offset;
2228       return drflac_oggbs__seek_physical(oggbs, offset-0x7FFFFFFF, drflac_seek_origin_current);
2229     }
2230   } else {
2231     while (offset > 0x7FFFFFFF) {
2232       if (!oggbs.rs.seek(0x7FFFFFFF, drflac_seek_origin_current)) return false;
2233       oggbs.currentBytePos += 0x7FFFFFFF;
2234       offset -= 0x7FFFFFFF;
2235     }
2236     if (!oggbs.rs.seek(cast(int)offset, drflac_seek_origin_current)) return false; // <-- Safe cast thanks to the loop above.
2237     oggbs.currentBytePos += offset;
2238     return true;
2239   }
2240 }
2241 
2242 bool drflac_oggbs__goto_next_page (drflac_oggbs* oggbs) {
2243   drflac_ogg_page_header header;
2244   for (;;) {
2245     uint headerSize;
2246     if (!drflac_ogg__read_page_header(oggbs.rs, &header, &headerSize)) return false;
2247     oggbs.currentBytePos += headerSize;
2248     uint pageBodySize = drflac_ogg__get_page_body_size(&header);
2249     if (header.serialNumber == oggbs.serialNumber) {
2250       oggbs.currentPageHeader = header;
2251       oggbs.bytesRemainingInPage = pageBodySize;
2252       return true;
2253     }
2254     // If we get here it means the page is not a FLAC page - skip it.
2255     if (pageBodySize > 0 && !drflac_oggbs__seek_physical(oggbs, pageBodySize, drflac_seek_origin_current)) return false; // <-- Safe cast - maximum size of a page is way below that of an int.
2256   }
2257 }
2258 
2259 size_t drflac__on_read_ogg (void* pUserData, void* bufferOut, size_t bytesToRead) {
2260   drflac_oggbs* oggbs = cast(drflac_oggbs*)pUserData;
2261   assert(oggbs !is null);
2262 
2263   ubyte* pRunningBufferOut = cast(ubyte*)bufferOut;
2264 
2265   // Reading is done page-by-page. If we've run out of bytes in the page we need to move to the next one.
2266   size_t bytesRead = 0;
2267   while (bytesRead < bytesToRead) {
2268     size_t bytesRemainingToRead = bytesToRead-bytesRead;
2269 
2270     if (oggbs.bytesRemainingInPage >= bytesRemainingToRead) {
2271       bytesRead += oggbs.rs.read(pRunningBufferOut, bytesRemainingToRead);
2272       oggbs.bytesRemainingInPage -= cast(uint)bytesRemainingToRead;
2273       break;
2274     }
2275 
2276     // If we get here it means some of the requested data is contained in the next pages.
2277     if (oggbs.bytesRemainingInPage > 0) {
2278       size_t bytesJustRead = oggbs.rs.read(pRunningBufferOut, oggbs.bytesRemainingInPage);
2279       bytesRead += bytesJustRead;
2280       pRunningBufferOut += bytesJustRead;
2281       if (bytesJustRead != oggbs.bytesRemainingInPage) break;  // Ran out of data.
2282     }
2283 
2284     assert(bytesRemainingToRead > 0);
2285     if (!drflac_oggbs__goto_next_page(oggbs)) break;  // Failed to go to the next chunk. Might have simply hit the end of the stream.
2286   }
2287 
2288   oggbs.currentBytePos += bytesRead;
2289   return bytesRead;
2290 }
2291 
2292 bool drflac__on_seek_ogg (void* pUserData, int offset, drflac_seek_origin origin) {
2293   drflac_oggbs* oggbs = cast(drflac_oggbs*)pUserData;
2294   assert(oggbs !is null);
2295   assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start));
2296 
2297   // Seeking is always forward which makes things a lot simpler.
2298   if (origin == drflac_seek_origin_start) {
2299     int startBytePos = cast(int)oggbs.firstBytePos+(79-42);  // 79 = size of bos page; 42 = size of FLAC header data. Seek up to the first byte of the native FLAC data.
2300     if (!drflac_oggbs__seek_physical(oggbs, startBytePos, drflac_seek_origin_start)) return false;
2301     oggbs.currentPageHeader = oggbs.bosPageHeader;
2302     oggbs.bytesRemainingInPage = 42;   // 42 = size of the native FLAC header data. That's our start point for seeking.
2303     return drflac__on_seek_ogg(pUserData, offset, drflac_seek_origin_current);
2304   }
2305 
2306   assert(origin == drflac_seek_origin_current);
2307 
2308   int bytesSeeked = 0;
2309   while (bytesSeeked < offset) {
2310     int bytesRemainingToSeek = offset-bytesSeeked;
2311     assert(bytesRemainingToSeek >= 0);
2312 
2313     if (oggbs.bytesRemainingInPage >= cast(size_t)bytesRemainingToSeek) {
2314       if (!drflac_oggbs__seek_physical(oggbs, bytesRemainingToSeek, drflac_seek_origin_current)) return false;
2315       bytesSeeked += bytesRemainingToSeek;
2316       oggbs.bytesRemainingInPage -= bytesRemainingToSeek;
2317       break;
2318     }
2319 
2320     // If we get here it means some of the requested data is contained in the next pages.
2321     if (oggbs.bytesRemainingInPage > 0) {
2322       if (!drflac_oggbs__seek_physical(oggbs, oggbs.bytesRemainingInPage, drflac_seek_origin_current)) return false;
2323       bytesSeeked += cast(int)oggbs.bytesRemainingInPage;
2324     }
2325 
2326     assert(bytesRemainingToSeek > 0);
2327     if (!drflac_oggbs__goto_next_page(oggbs)) break;  // Failed to go to the next chunk. Might have simply hit the end of the stream.
2328   }
2329 
2330   return true;
2331 }
2332 
2333 bool drflac_ogg__seek_to_sample (drflac* pFlac, ulong sample) {
2334   drflac_oggbs* oggbs = cast(drflac_oggbs*)((cast(int*)pFlac.pExtraData)+pFlac.maxBlockSize*pFlac.channels);
2335 
2336   ulong originalBytePos = oggbs.currentBytePos;   // For recovery.
2337 
2338   // First seek to the first frame.
2339   if (!drflac__seek_to_byte(&pFlac.bs, pFlac.firstFramePos)) return false;
2340   oggbs.bytesRemainingInPage = 0;
2341 
2342   ulong runningGranulePosition = 0;
2343   ulong runningFrameBytePos = oggbs.currentBytePos;   // <-- Points to the OggS identifier.
2344   for (;;) {
2345     if (!drflac_oggbs__goto_next_page(oggbs)) {
2346       drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
2347       return false;   // Never did find that sample...
2348     }
2349 
2350     runningFrameBytePos = oggbs.currentBytePos-drflac_ogg__get_page_header_size(&oggbs.currentPageHeader);
2351     if (oggbs.currentPageHeader.granulePosition*pFlac.channels >= sample) break; // The sample is somewhere in the previous page.
2352 
2353     // At this point we know the sample is not in the previous page. It could possibly be in this page. For simplicity we
2354     // disregard any pages that do not begin a fresh packet.
2355     if ((oggbs.currentPageHeader.headerType&0x01) == 0) {    // <-- Is it a fresh page?
2356       if (oggbs.currentPageHeader.segmentTable.ptr[0] >= 2) {
2357         ubyte[2] firstBytesInPage;
2358         if (drflac_oggbs__read_physical(oggbs, firstBytesInPage.ptr, 2) != 2) {
2359           drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
2360           return false;
2361         }
2362         if ((firstBytesInPage.ptr[0] == 0xFF) && (firstBytesInPage.ptr[1]&0xFC) == 0xF8) {    // <-- Does the page begin with a frame's sync code?
2363           runningGranulePosition = oggbs.currentPageHeader.granulePosition*pFlac.channels;
2364         }
2365 
2366         if (!drflac_oggbs__seek_physical(oggbs, cast(int)oggbs.bytesRemainingInPage-2, drflac_seek_origin_current)) {
2367           drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
2368           return false;
2369         }
2370 
2371         continue;
2372       }
2373     }
2374 
2375     if (!drflac_oggbs__seek_physical(oggbs, cast(int)oggbs.bytesRemainingInPage, drflac_seek_origin_current)) {
2376       drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
2377       return false;
2378     }
2379   }
2380 
2381   // 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
2382   // 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
2383   // a new frame. This property means that after we've seeked to the page we can immediately start looping over frames until
2384   // we find the one containing the target sample.
2385   if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, drflac_seek_origin_start)) return false;
2386   if (!drflac_oggbs__goto_next_page(oggbs)) return false;
2387 
2388   // 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
2389   // looping over these frames until we find the one containing the sample we're after.
2390   ulong firstSampleInFrame = runningGranulePosition;
2391   for (;;) {
2392     // NOTE for later: When using Ogg's page/segment based seeking later on we can't use this function (or any drflac__*
2393     // reading functions) because otherwise it will pull extra data for use in it's own internal caches which will then
2394     // break the positioning of the read pointer for the Ogg bitstream.
2395     if (!drflac__read_next_frame_header(&pFlac.bs, pFlac.bitsPerSample, &pFlac.currentFrame.header)) return false;
2396 
2397     int channels = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment);
2398     ulong lastSampleInFrame = firstSampleInFrame+(pFlac.currentFrame.header.blockSize*channels);
2399     lastSampleInFrame -= 1; // <-- Zero based.
2400 
2401     if (sample >= firstSampleInFrame && sample <= lastSampleInFrame) break;  // The sample is in this frame.
2402 
2403     // If we get here it means the sample is not in this frame so we need to move to the next one. Now the cool thing
2404     // with Ogg is that we can efficiently seek past the frame by looking at the lacing values of each segment in
2405     // the page.
2406     firstSampleInFrame = lastSampleInFrame+1;
2407 
2408     version(all) {
2409       // Slow way. This uses the native FLAC decoder to seek past the frame. This is slow because it needs to do a partial
2410       // decode of the frame. Although this is how the native version works, we can use Ogg's framing system to make it
2411       // more efficient. Leaving this here for reference and to use as a basis for debugging purposes.
2412       if (!drflac__seek_to_next_frame(pFlac)) return false;
2413     } else {
2414       // TODO: This is not yet complete. See note at the top of this loop body.
2415 
2416       // Fast(er) way. This uses Ogg's framing system to seek past the frame. This should be much more efficient than the
2417       // native FLAC seeking.
2418       if (!drflac_oggbs__seek_to_next_frame(oggbs)) return false;
2419     }
2420   }
2421 
2422   assert(firstSampleInFrame <= sample);
2423 
2424   if (!drflac__decode_frame(pFlac)) return false;
2425 
2426   size_t samplesToDecode = cast(size_t)(sample-firstSampleInFrame);    // <-- Safe cast because the maximum number of samples in a frame is 65535.
2427   return drflac_read_s32(pFlac, samplesToDecode, null) == samplesToDecode;
2428 }
2429 
2430 
2431 bool drflac__init_private__ogg (drflac_init_info* pInit, ref ReadStruct rs, scope drflac_meta_proc onMeta, void* pUserDataMD) {
2432   // Pre: The bit stream should be sitting just past the 4-byte OggS capture pattern.
2433 
2434   pInit.container = drflac_container_ogg;
2435   pInit.oggFirstBytePos = 0;
2436 
2437   // We'll get here if the first 4 bytes of the stream were the OggS capture pattern, however it doesn't necessarily mean the
2438   // stream includes FLAC encoded audio. To check for this we need to scan the beginning-of-stream page markers and check if
2439   // any match the FLAC specification. Important to keep in mind that the stream may be multiplexed.
2440   drflac_ogg_page_header header;
2441 
2442   uint headerSize = 0;
2443   if (!drflac_ogg__read_page_header_after_capture_pattern(rs, &header, &headerSize)) return false;
2444   pInit.runningFilePos += headerSize;
2445 
2446   for (;;) {
2447     // Break if we're past the beginning of stream page.
2448     if ((header.headerType&0x02) == 0) return false;
2449 
2450     // Check if it's a FLAC header.
2451     int pageBodySize = drflac_ogg__get_page_body_size(&header);
2452     if (pageBodySize == 51) { // 51 = the lacing value of the FLAC header packet.
2453       // It could be a FLAC page...
2454       uint bytesRemainingInPage = pageBodySize;
2455 
2456       ubyte packetType;
2457       if (rs.read(&packetType, 1) != 1) return false;
2458 
2459       bytesRemainingInPage -= 1;
2460       if (packetType == 0x7F) {
2461         // Increasingly more likely to be a FLAC page...
2462         ubyte[4] sig;
2463         if (rs.read(sig.ptr, 4) != 4) return false;
2464 
2465         bytesRemainingInPage -= 4;
2466         if (sig.ptr[0] == 'F' && sig.ptr[1] == 'L' && sig.ptr[2] == 'A' && sig.ptr[3] == 'C') {
2467           // Almost certainly a FLAC page...
2468           ubyte[2] mappingVersion;
2469           if (rs.read(mappingVersion.ptr, 2) != 2) return false;
2470 
2471           if (mappingVersion.ptr[0] != 1) return false;   // Only supporting version 1.x of the Ogg mapping.
2472 
2473           // The next 2 bytes are the non-audio packets, not including this one. We don't care about this because we're going to
2474           // be handling it in a generic way based on the serial number and packet types.
2475           if (!rs.seek(2, drflac_seek_origin_current)) return false;
2476 
2477           // Expecting the native FLAC signature "fLaC".
2478           if (rs.read(sig.ptr, 4) != 4) return false;
2479 
2480           if (sig.ptr[0] == 'f' && sig.ptr[1] == 'L' && sig.ptr[2] == 'a' && sig.ptr[3] == 'C') {
2481             // The remaining data in the page should be the STREAMINFO block.
2482             ubyte isLastBlock;
2483             ubyte blockType;
2484             uint blockSize;
2485             if (!drflac__read_and_decode_block_header(rs, &isLastBlock, &blockType, &blockSize)) return false;
2486 
2487             if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) return false;    // Invalid block type. First block must be the STREAMINFO block.
2488 
2489             drflac_streaminfo streaminfo;
2490             if (drflac__read_streaminfo(rs, &streaminfo)) {
2491               // Success!
2492               pInit.sampleRate       = streaminfo.sampleRate;
2493               pInit.channels         = streaminfo.channels;
2494               pInit.bitsPerSample    = streaminfo.bitsPerSample;
2495               pInit.totalSampleCount = streaminfo.totalSampleCount;
2496               pInit.maxBlockSize     = streaminfo.maxBlockSize;
2497 
2498               if (onMeta !is null) {
2499                 drflac_metadata metadata;
2500                 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
2501                 metadata.pRawData = null;
2502                 metadata.rawDataSize = 0;
2503                 metadata.data.streaminfo = streaminfo;
2504                 try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; }
2505               }
2506 
2507               pInit.runningFilePos  += pageBodySize;
2508               pInit.oggFirstBytePos  = pInit.runningFilePos-79;   // Subtracting 79 will place us right on top of the "OggS" identifier of the FLAC bos page.
2509               pInit.oggSerial        = header.serialNumber;
2510               pInit.oggBosHeader     = header;
2511               break;
2512             } else {
2513               // Failed to read STREAMINFO block. Aww, so close...
2514               return false;
2515             }
2516           } else {
2517             // Invalid file.
2518             return false;
2519           }
2520         } else {
2521           // Not a FLAC header. Skip it.
2522           if (!rs.seek(bytesRemainingInPage, drflac_seek_origin_current)) return false;
2523         }
2524       } else {
2525         // Not a FLAC header. Seek past the entire page and move on to the next.
2526         if (!rs.seek(bytesRemainingInPage, drflac_seek_origin_current)) return false;
2527       }
2528     } else {
2529       if (!rs.seek(pageBodySize, drflac_seek_origin_current)) return false;
2530     }
2531 
2532     pInit.runningFilePos += pageBodySize;
2533 
2534     // Read the header of the next page.
2535     if (!drflac_ogg__read_page_header(rs, &header, &headerSize)) return false;
2536     pInit.runningFilePos += headerSize;
2537   }
2538 
2539 
2540   // 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
2541   // packets in the FLAC logical stream contain the metadata. The only thing left to do in the initialiation phase for Ogg is to create the
2542   // Ogg bistream object.
2543   pInit.hasMetadataBlocks = true;    // <-- Always have at least VORBIS_COMMENT metadata block.
2544   return true;
2545 }
2546 //#endif
2547 
2548 bool drflac__check_init_private (drflac_init_info* pInit, scope drflac_meta_proc onMeta, void* pUserDataMD) {
2549   ubyte[4] id;
2550   if (pInit.rs.read(id.ptr, 4) != 4) return false;
2551   if (id.ptr[0] == 'f' && id.ptr[1] == 'L' && id.ptr[2] == 'a' && id.ptr[3] == 'C') return drflac__init_private__native(pInit, pInit.rs, onMeta, pUserDataMD);
2552 //#ifndef DR_FLAC_NO_OGG
2553   if (id.ptr[0] == 'O' && id.ptr[1] == 'g' && id.ptr[2] == 'g' && id.ptr[3] == 'S') return drflac__init_private__ogg(pInit, pInit.rs, onMeta, pUserDataMD);
2554 //#endif
2555   // unsupported container
2556   return false;
2557 }
2558 
2559 bool drflac__init_private (drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, scope drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD) {
2560   if (pInit is null || onRead is null || onSeek is null) return false;
2561 
2562   pInit.rs.onReadCB  = onRead;
2563   pInit.rs.onSeekCB  = onSeek;
2564   pInit.rs.pUserData = pUserData;
2565   //pInit.onMeta       = onMeta;
2566   //pInit.pUserDataMD  = pUserDataMD;
2567 
2568   return drflac__check_init_private(pInit, onMeta, pUserDataMD);
2569 }
2570 
2571 } //nothrow
2572 
2573 nothrow {
2574 void drflac__init_from_info (drflac* pFlac, drflac_init_info* pInit) {
2575   import core.stdc.string : memcpy, memset;
2576   assert(pFlac !is null);
2577   assert(pInit !is null);
2578 
2579   memset(pFlac, 0, (*pFlac).sizeof);
2580   pFlac.bs.rs            = pInit.rs;
2581   pFlac.bs.nextL2Line    = (pFlac.bs.cacheL2).sizeof/(pFlac.bs.cacheL2.ptr[0]).sizeof; // <-- Initialize to this to force a client-side data retrieval right from the start.
2582   pFlac.bs.consumedBits  = (pFlac.bs.cache).sizeof*8;
2583 
2584   //pFlac.onMeta           = pInit.onMeta;
2585   //pFlac.pUserDataMD      = pInit.pUserDataMD;
2586   pFlac.maxBlockSize     = pInit.maxBlockSize;
2587   pFlac.sampleRate       = pInit.sampleRate;
2588   pFlac.channels         = cast(ubyte)pInit.channels;
2589   pFlac.bitsPerSample    = cast(ubyte)pInit.bitsPerSample;
2590   pFlac.totalSampleCount = pInit.totalSampleCount;
2591   pFlac.container        = pInit.container;
2592 }
2593 
2594 drflac* drflac_open_with_metadata_private_xx (drflac_init_info* init, scope drflac_meta_proc onMeta, void* pUserDataMD, bool stdio) {
2595   import core.stdc.stdlib : malloc, free;
2596   import core.stdc.string : memset;
2597 
2598   size_t allocationSize = (drflac).sizeof;
2599   allocationSize += init.maxBlockSize*init.channels*(int).sizeof;
2600   //allocationSize += init.seektableSize;
2601 
2602 //#ifndef DR_FLAC_NO_OGG
2603   // There's additional data required for Ogg streams.
2604   if (init.container == drflac_container_ogg) allocationSize += (drflac_oggbs).sizeof;
2605 //#endif
2606 
2607   drflac* pFlac = cast(drflac*)malloc(allocationSize);
2608   memset(pFlac, 0, (*pFlac).sizeof);
2609   drflac__init_from_info(pFlac, init);
2610   pFlac.pDecodedSamples = cast(int*)pFlac.pExtraData;
2611 
2612 //#ifndef DR_FLAC_NO_OGG
2613   if (init.container == drflac_container_ogg) {
2614     drflac_oggbs* oggbs = cast(drflac_oggbs*)((cast(int*)pFlac.pExtraData)+init.maxBlockSize*init.channels);
2615     oggbs.stdio = stdio;
2616     oggbs.rs = init.rs;
2617     oggbs.currentBytePos = init.oggFirstBytePos;
2618     oggbs.firstBytePos = init.oggFirstBytePos;
2619     oggbs.serialNumber = init.oggSerial;
2620     oggbs.bosPageHeader = init.oggBosHeader;
2621     oggbs.bytesRemainingInPage = 0;
2622 
2623     // The Ogg bistream needs to be layered on top of the original bitstream.
2624     pFlac.bs.rs.onReadCB = &drflac__on_read_ogg;
2625     pFlac.bs.rs.onSeekCB = &drflac__on_seek_ogg;
2626     pFlac.bs.rs.pUserData = cast(void*)oggbs;
2627   }
2628 //#endif
2629 
2630   // Decode metadata before returning.
2631   if (init.hasMetadataBlocks) {
2632     if (!drflac__read_and_decode_metadata(pFlac, onMeta, pUserDataMD)) {
2633       free(pFlac);
2634       return null;
2635     }
2636   }
2637 
2638   return pFlac;
2639 }
2640 
2641 
2642 drflac* drflac_open_with_metadata_private (drflac_read_proc onRead, drflac_seek_proc onSeek, scope drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, bool stdio) {
2643   drflac_init_info init;
2644   if (!drflac__init_private(&init, onRead, onSeek, onMeta, pUserData, pUserDataMD)) return null;
2645   return drflac_open_with_metadata_private_xx(&init, onMeta, pUserDataMD, stdio);
2646 }
2647 
2648 } //nothrow
2649 
2650 nothrow {
2651 
2652 size_t drflac__on_read_memory (void* pUserData, void* bufferOut, size_t bytesToRead) {
2653   drflac__memory_stream* memoryStream = cast(drflac__memory_stream*)pUserData;
2654   assert(memoryStream !is null);
2655   assert(memoryStream.dataSize >= memoryStream.currentReadPos);
2656 
2657   size_t bytesRemaining = memoryStream.dataSize-memoryStream.currentReadPos;
2658   if (bytesToRead > bytesRemaining) bytesToRead = bytesRemaining;
2659 
2660   if (bytesToRead > 0) {
2661     import core.stdc.string : memcpy;
2662     memcpy(bufferOut, memoryStream.data+memoryStream.currentReadPos, bytesToRead);
2663     memoryStream.currentReadPos += bytesToRead;
2664   }
2665 
2666   return bytesToRead;
2667 }
2668 
2669 bool drflac__on_seek_memory (void* pUserData, int offset, drflac_seek_origin origin) {
2670   drflac__memory_stream* memoryStream = cast(drflac__memory_stream*)pUserData;
2671   assert(memoryStream !is null);
2672   assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start));
2673 
2674   if (origin == drflac_seek_origin_current) {
2675     if (memoryStream.currentReadPos+offset <= memoryStream.dataSize) {
2676       memoryStream.currentReadPos += offset;
2677     } else {
2678       memoryStream.currentReadPos = memoryStream.dataSize;  // Trying to seek too far forward.
2679     }
2680   } else {
2681     if (cast(uint)offset <= memoryStream.dataSize) {
2682       memoryStream.currentReadPos = offset;
2683     } else {
2684       memoryStream.currentReadPos = memoryStream.dataSize;  // Trying to seek too far forward.
2685     }
2686   }
2687 
2688   return true;
2689 }
2690 
2691 public drflac* drflac_open_memory (const(void)* data, size_t dataSize) {
2692 
2693   drflac__memory_stream memoryStream;
2694   memoryStream.data = cast(const(ubyte)*)data;
2695   memoryStream.dataSize = dataSize;
2696   memoryStream.currentReadPos = 0;
2697 
2698   drflac* pFlac = drflac_open(&drflac__on_read_memory, &drflac__on_seek_memory, &memoryStream);
2699   if (pFlac is null) return null;
2700 
2701   pFlac.memoryStream = memoryStream;
2702 
2703   // This is an awful hack...
2704 //#ifndef DR_FLAC_NO_OGG
2705   if (pFlac.container == drflac_container_ogg) {
2706     drflac_oggbs* oggbs = cast(drflac_oggbs*)((cast(int*)pFlac.pExtraData)+pFlac.maxBlockSize*pFlac.channels);
2707     oggbs.rs.pUserData = &pFlac.memoryStream;
2708   }
2709   else
2710 //#endif
2711   {
2712     pFlac.bs.rs.pUserData = &pFlac.memoryStream;
2713   }
2714 
2715   return pFlac;
2716 }
2717 
2718 public drflac* drflac_open_memory_with_metadata (const(void)* data, size_t dataSize, scope drflac_meta_proc onMeta, void* pUserData) {
2719 
2720   drflac__memory_stream memoryStream;
2721   memoryStream.data = cast(const(ubyte)*)data;
2722   memoryStream.dataSize = dataSize;
2723   memoryStream.currentReadPos = 0;
2724 
2725   drflac* pFlac = drflac_open_with_metadata_private(&drflac__on_read_memory, &drflac__on_seek_memory, onMeta, &memoryStream, pUserData, false);
2726   if (pFlac is null) return null;
2727 
2728   pFlac.memoryStream = memoryStream;
2729 
2730   // This is an awful hack...
2731 //#ifndef DR_FLAC_NO_OGG
2732   if (pFlac.container == drflac_container_ogg) {
2733     drflac_oggbs* oggbs = cast(drflac_oggbs*)((cast(int*)pFlac.pExtraData)+pFlac.maxBlockSize*pFlac.channels);
2734     oggbs.rs.pUserData = &pFlac.memoryStream;
2735   } else
2736 //#endif
2737   {
2738     pFlac.bs.rs.pUserData = &pFlac.memoryStream;
2739   }
2740 
2741   return pFlac;
2742 }
2743 
2744 public drflac* drflac_open (drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData) {
2745   return drflac_open_with_metadata_private(onRead, onSeek, null, pUserData, pUserData, false);
2746 }
2747 
2748 } //nothrow
2749 
2750 
2751 nothrow {
2752 
2753 public drflac* drflac_open_with_metadata (drflac_read_proc onRead, drflac_seek_proc onSeek, scope drflac_meta_proc onMeta, void* pUserData) {
2754   return drflac_open_with_metadata_private(onRead, onSeek, onMeta, pUserData, pUserData, false);
2755 }
2756 
2757 public void drflac_close (drflac* pFlac) 
2758 {
2759     import core.stdc.stdlib : free;
2760     free(pFlac);
2761 }
2762 
2763 
2764 ulong drflac__read_s32__misaligned (drflac* pFlac, ulong samplesToRead, int* bufferOut) {
2765   uint channelCount = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment);
2766 
2767   // We should never be calling this when the number of samples to read is >= the sample count.
2768   assert(samplesToRead < channelCount);
2769   assert(pFlac.currentFrame.samplesRemaining > 0 && samplesToRead <= pFlac.currentFrame.samplesRemaining);
2770 
2771   ulong samplesRead = 0;
2772   while (samplesToRead > 0) {
2773     ulong totalSamplesInFrame = pFlac.currentFrame.header.blockSize*channelCount;
2774     ulong samplesReadFromFrameSoFar = totalSamplesInFrame-pFlac.currentFrame.samplesRemaining;
2775     uint channelIndex = samplesReadFromFrameSoFar%channelCount;
2776 
2777     ulong nextSampleInFrame = samplesReadFromFrameSoFar/channelCount;
2778 
2779     int decodedSample = 0;
2780     switch (pFlac.currentFrame.header.channelAssignment) {
2781       case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
2782         if (channelIndex == 0) {
2783           decodedSample = pFlac.currentFrame.subframes.ptr[channelIndex].pDecodedSamples[cast(uint)nextSampleInFrame];
2784         } else {
2785           int side = pFlac.currentFrame.subframes.ptr[channelIndex+0].pDecodedSamples[cast(uint)nextSampleInFrame];
2786           int left = pFlac.currentFrame.subframes.ptr[channelIndex-1].pDecodedSamples[cast(uint)nextSampleInFrame];
2787           decodedSample = left-side;
2788         }
2789         break;
2790 
2791       case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2792         if (channelIndex == 0) {
2793           int side  = pFlac.currentFrame.subframes.ptr[channelIndex+0].pDecodedSamples[cast(uint)nextSampleInFrame];
2794           int right = pFlac.currentFrame.subframes.ptr[channelIndex+1].pDecodedSamples[cast(uint)nextSampleInFrame];
2795           decodedSample = side+right;
2796         } else {
2797           decodedSample = pFlac.currentFrame.subframes.ptr[channelIndex].pDecodedSamples[cast(uint)nextSampleInFrame];
2798         }
2799         break;
2800 
2801       case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
2802         int mid;
2803         int side;
2804         if (channelIndex == 0) {
2805           mid  = pFlac.currentFrame.subframes.ptr[channelIndex+0].pDecodedSamples[cast(uint)nextSampleInFrame];
2806           side = pFlac.currentFrame.subframes.ptr[channelIndex+1].pDecodedSamples[cast(uint)nextSampleInFrame];
2807           mid = ((cast(uint)mid)<<1)|(side&0x01);
2808           decodedSample = (mid+side)>>1;
2809         } else {
2810           mid  = pFlac.currentFrame.subframes.ptr[channelIndex-1].pDecodedSamples[cast(uint)nextSampleInFrame];
2811           side = pFlac.currentFrame.subframes.ptr[channelIndex+0].pDecodedSamples[cast(uint)nextSampleInFrame];
2812           mid = ((cast(uint)mid)<<1)|(side&0x01);
2813           decodedSample = (mid-side)>>1;
2814         }
2815         break;
2816 
2817       case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: goto default;
2818       default:
2819         decodedSample = pFlac.currentFrame.subframes.ptr[channelIndex].pDecodedSamples[cast(uint)nextSampleInFrame];
2820         break;
2821     }
2822 
2823     decodedSample <<= ((32-pFlac.bitsPerSample)+pFlac.currentFrame.subframes.ptr[channelIndex].wastedBitsPerSample);
2824 
2825     if (bufferOut) *bufferOut++ = decodedSample;
2826 
2827     samplesRead += 1;
2828     pFlac.currentFrame.samplesRemaining -= 1;
2829     samplesToRead -= 1;
2830   }
2831 
2832   return samplesRead;
2833 }
2834 
2835 ulong drflac__seek_forward_by_samples (drflac* pFlac, ulong samplesToRead) {
2836   ulong samplesRead = 0;
2837   while (samplesToRead > 0) {
2838     if (pFlac.currentFrame.samplesRemaining == 0) {
2839       if (!drflac__read_and_decode_next_frame(pFlac)) break;  // Couldn't read the next frame, so just break from the loop and return.
2840     } else {
2841       samplesRead += 1;
2842       pFlac.currentFrame.samplesRemaining -= 1;
2843       samplesToRead -= 1;
2844     }
2845   }
2846   return samplesRead;
2847 }
2848 
2849 public ulong drflac_read_s32 (drflac* pFlac, ulong samplesToRead, int* bufferOut) {
2850   // Note that <bufferOut> is allowed to be null, in which case this will be treated as something like a seek.
2851   if (pFlac is null || samplesToRead == 0) return 0;
2852 
2853   if (bufferOut is null) 
2854   {
2855      // wtf
2856      return drflac__seek_forward_by_samples(pFlac, samplesToRead);
2857   }
2858 
2859   ulong samplesRead = 0;
2860   while (samplesToRead > 0) {
2861     // If we've run out of samples in this frame, go to the next.
2862     if (pFlac.currentFrame.samplesRemaining == 0) {
2863       if (!drflac__read_and_decode_next_frame(pFlac)) break;  // Couldn't read the next frame, so just break from the loop and return.
2864     } else {
2865       // Here is where we grab the samples and interleave them.
2866 
2867       uint channelCount = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment);
2868       ulong totalSamplesInFrame = pFlac.currentFrame.header.blockSize*channelCount;
2869       ulong samplesReadFromFrameSoFar = totalSamplesInFrame-pFlac.currentFrame.samplesRemaining;
2870 
2871       int misalignedSampleCount = cast(int)(samplesReadFromFrameSoFar%channelCount);
2872       if (misalignedSampleCount > 0) {
2873         ulong misalignedSamplesRead = drflac__read_s32__misaligned(pFlac, misalignedSampleCount, bufferOut);
2874         samplesRead   += misalignedSamplesRead;
2875         samplesReadFromFrameSoFar += misalignedSamplesRead;
2876         bufferOut     += misalignedSamplesRead;
2877         samplesToRead -= misalignedSamplesRead;
2878       }
2879 
2880       ulong alignedSampleCountPerChannel = samplesToRead/channelCount;
2881       if (alignedSampleCountPerChannel > pFlac.currentFrame.samplesRemaining/channelCount) {
2882         alignedSampleCountPerChannel = pFlac.currentFrame.samplesRemaining/channelCount;
2883       }
2884 
2885       ulong firstAlignedSampleInFrame = samplesReadFromFrameSoFar/channelCount;
2886       uint unusedBitsPerSample = 32-pFlac.bitsPerSample;
2887 
2888       switch (pFlac.currentFrame.header.channelAssignment) {
2889         case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
2890           const int* pDecodedSamples0 = pFlac.currentFrame.subframes.ptr[0].pDecodedSamples+firstAlignedSampleInFrame;
2891           const int* pDecodedSamples1 = pFlac.currentFrame.subframes.ptr[1].pDecodedSamples+firstAlignedSampleInFrame;
2892 
2893           for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) {
2894             int left  = pDecodedSamples0[i];
2895             int side  = pDecodedSamples1[i];
2896             int right = left-side;
2897             bufferOut[i*2+0] = left<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[0].wastedBitsPerSample);
2898             bufferOut[i*2+1] = right<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[1].wastedBitsPerSample);
2899           }
2900           break;
2901 
2902         case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2903           const int* pDecodedSamples0 = pFlac.currentFrame.subframes.ptr[0].pDecodedSamples+firstAlignedSampleInFrame;
2904           const int* pDecodedSamples1 = pFlac.currentFrame.subframes.ptr[1].pDecodedSamples+firstAlignedSampleInFrame;
2905           for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) {
2906             int side  = pDecodedSamples0[i];
2907             int right = pDecodedSamples1[i];
2908             int left  = right+side;
2909             bufferOut[i*2+0] = left<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[0].wastedBitsPerSample);
2910             bufferOut[i*2+1] = right<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[1].wastedBitsPerSample);
2911           }
2912           break;
2913 
2914         case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
2915           const int* pDecodedSamples0 = pFlac.currentFrame.subframes.ptr[0].pDecodedSamples+firstAlignedSampleInFrame;
2916           const int* pDecodedSamples1 = pFlac.currentFrame.subframes.ptr[1].pDecodedSamples+firstAlignedSampleInFrame;
2917           for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) {
2918             int side = pDecodedSamples1[i];
2919             int mid  = ((cast(uint)pDecodedSamples0[i])<<1)|(side&0x01);
2920             bufferOut[i*2+0] = ((mid+side)>>1)<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[0].wastedBitsPerSample);
2921             bufferOut[i*2+1] = ((mid-side)>>1)<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[1].wastedBitsPerSample);
2922           }
2923           break;
2924 
2925         case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: goto default;
2926         default:
2927           if (pFlac.currentFrame.header.channelAssignment == 1) { // 1 = Stereo
2928             // Stereo optimized inner loop unroll.
2929             const int* pDecodedSamples0 = pFlac.currentFrame.subframes.ptr[0].pDecodedSamples+firstAlignedSampleInFrame;
2930             const int* pDecodedSamples1 = pFlac.currentFrame.subframes.ptr[1].pDecodedSamples+firstAlignedSampleInFrame;
2931             for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) {
2932               bufferOut[i*2+0] = pDecodedSamples0[i]<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[0].wastedBitsPerSample);
2933               bufferOut[i*2+1] = pDecodedSamples1[i]<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[1].wastedBitsPerSample);
2934             }
2935           } else {
2936             // Generic interleaving.
2937             for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) {
2938               for (uint j = 0; j < channelCount; ++j) {
2939                 bufferOut[(i*channelCount)+j] = (pFlac.currentFrame.subframes.ptr[j].pDecodedSamples[cast(uint)firstAlignedSampleInFrame+i])<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[j].wastedBitsPerSample);
2940               }
2941             }
2942           }
2943           break;
2944       }
2945 
2946       ulong alignedSamplesRead = alignedSampleCountPerChannel*channelCount;
2947       samplesRead   += alignedSamplesRead;
2948       samplesReadFromFrameSoFar += alignedSamplesRead;
2949       bufferOut     += alignedSamplesRead;
2950       samplesToRead -= alignedSamplesRead;
2951       pFlac.currentFrame.samplesRemaining -= cast(uint)alignedSamplesRead;
2952 
2953       // At this point we may still have some excess samples left to read.
2954       if (samplesToRead > 0 && pFlac.currentFrame.samplesRemaining > 0) {
2955         ulong excessSamplesRead = 0;
2956         if (samplesToRead < pFlac.currentFrame.samplesRemaining) {
2957           excessSamplesRead = drflac__read_s32__misaligned(pFlac, samplesToRead, bufferOut);
2958         } else {
2959           excessSamplesRead = drflac__read_s32__misaligned(pFlac, pFlac.currentFrame.samplesRemaining, bufferOut);
2960         }
2961 
2962         samplesRead   += excessSamplesRead;
2963         samplesReadFromFrameSoFar += excessSamplesRead;
2964         bufferOut     += excessSamplesRead;
2965         samplesToRead -= excessSamplesRead;
2966       }
2967     }
2968   }
2969 
2970   return samplesRead;
2971 }
2972 
2973 public bool drflac_seek_to_sample (drflac* pFlac, ulong sampleIndex) {
2974   if (pFlac is null) return false;
2975 
2976   // 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
2977   // when the decoder was opened.
2978   if (pFlac.firstFramePos == 0) return false;
2979 
2980   if (sampleIndex == 0) return drflac__seek_to_first_frame(pFlac);
2981 
2982   // Clamp the sample to the end.
2983   if (sampleIndex >= pFlac.totalSampleCount) sampleIndex  = pFlac.totalSampleCount-1;
2984 
2985   // Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so
2986   // we'll instead use Ogg's natural seeking facility.
2987 //#ifndef DR_FLAC_NO_OGG
2988   if (pFlac.container == drflac_container_ogg) {
2989     return drflac_ogg__seek_to_sample(pFlac, sampleIndex);
2990   }
2991   else
2992 //#endif
2993   {
2994     // First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower.
2995     if (!drflac__seek_to_sample__seek_table(pFlac, sampleIndex)) return drflac__seek_to_sample__brute_force(pFlac, sampleIndex);
2996   }
2997 
2998   return true;
2999 }
3000 
3001 public void drflac_free (void* pSampleDataReturnedByOpenAndDecode) {
3002   import core.stdc.stdlib : free;
3003   free(pSampleDataReturnedByOpenAndDecode);
3004 }
3005 
3006 
3007 public void drflac_init_vorbis_comment_iterator (drflac_vorbis_comment_iterator* pIter, uint commentCount, const(char)* pComments) {
3008   if (pIter is null) return;
3009   pIter.countRemaining = commentCount;
3010   pIter.pRunningData   = pComments;
3011 }
3012 
3013 public const(char)* drflac_next_vorbis_comment (drflac_vorbis_comment_iterator* pIter, uint* pCommentLengthOut) {
3014   // Safety.
3015   if (pCommentLengthOut) *pCommentLengthOut = 0;
3016 
3017   if (pIter is null || pIter.countRemaining == 0 || pIter.pRunningData is null) return null;
3018 
3019   uint length = drflac__le2host_32(*cast(uint*)pIter.pRunningData);
3020   pIter.pRunningData += 4;
3021 
3022   const(char)* pComment = pIter.pRunningData;
3023   pIter.pRunningData += length;
3024   pIter.countRemaining -= 1;
3025 
3026   if (pCommentLengthOut) *pCommentLengthOut = length;
3027   return pComment;
3028 }
3029 
3030 
3031 public long drflac_vorbis_comment_size (uint commentCount, const(char)* pComments) {
3032   uint res = 0;
3033   while (commentCount-- > 0) {
3034     uint length = drflac__le2host_32(*cast(uint*)pComments);
3035     pComments += 4;
3036     pComments += length;
3037     res += length+4;
3038   }
3039   return res;
3040 }
3041 
3042 }
3043 
3044 // REVISION HISTORY
3045 //
3046 // v0.3d - 11/06/2016
3047 //   - Minor clean up.
3048 //
3049 // v0.3c - 28/05/2016
3050 //   - Fixed compilation error.
3051 //
3052 // v0.3b - 16/05/2016
3053 //   - Fixed Linux/GCC build.
3054 //   - Updated documentation.
3055 //
3056 // v0.3a - 15/05/2016
3057 //   - Minor fixes to documentation.
3058 //
3059 // v0.3 - 11/05/2016
3060 //   - Optimizations. Now at about parity with the reference implementation on 32-bit builds.
3061 //   - Lots of clean up.
3062 //
3063 // v0.2b - 10/05/2016
3064 //   - Bug fixes.
3065 //
3066 // v0.2a - 10/05/2016
3067 //   - Made drflac_open_and_decode() more robust.
3068 //   - Removed an unused debugging variable
3069 //
3070 // v0.2 - 09/05/2016
3071 //   - Added support for Ogg encapsulation.
3072 //   - API CHANGE. Have the onSeek callback take a third argument which specifies whether or not the seek
3073 //     should be relative to the start or the current position. Also changes the seeking rules such that
3074 //     seeking offsets will never be negative.
3075 //   - Have drflac_open_and_decode() fail gracefully if the stream has an unknown total sample count.
3076 //
3077 // v0.1b - 07/05/2016
3078 //   - Properly close the file handle in drflac_open_file() and family when the decoder fails to initialize.
3079 //   - Removed a stale comment.
3080 //
3081 // v0.1a - 05/05/2016
3082 //   - Minor formatting changes.
3083 //   - Fixed a warning on the GCC build.
3084 //
3085 // v0.1 - 03/05/2016
3086 //   - Initial versioned release.
3087 
3088 // TODO
3089 // - Add support for initializing the decoder without a header STREAMINFO block.
3090 // - Test CUESHEET metadata blocks.
3091 
3092 
3093 /*
3094 This is free and unencumbered software released into the public domain.
3095 
3096 Anyone is free to copy, modify, publish, use, compile, sell, or
3097 distribute this software, either in source code form or as a compiled
3098 binary, for any purpose, commercial or non-commercial, and by any
3099 means.
3100 
3101 In jurisdictions that recognize copyright laws, the author or authors
3102 of this software dedicate any and all copyright interest in the
3103 software to the public domain. We make this dedication for the benefit
3104 of the public at large and to the detriment of our heirs and
3105 successors. We intend this dedication to be an overt act of
3106 relinquishment in perpetuity of all present and future rights to this
3107 software under copyright law.
3108 
3109 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
3110 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3111 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
3112 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
3113 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
3114 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
3115 OTHER DEALINGS IN THE SOFTWARE.
3116 
3117 For more information, please refer to <http://unlicense.org/>
3118 */