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