The OpenD Programming Language

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   {
1860     auto b = cast(ubyte*)pBufferOut;
1861     auto res = 0;
1862     while (bytesToRead > 0) 
1863     {
1864         size_t rd = 0;
1865         if (onReadCB !is null) 
1866         {
1867             rd = onReadCB(pUserData, b, bytesToRead);
1868         }
1869         if (rd == 0) 
1870             break;
1871         b += rd;
1872         res += rd;
1873         bytesToRead -= rd;
1874     }
1875     return res;
1876   }
1877 
1878   bool seek (int offset, drflac_seek_origin origin) nothrow {
1879       if (onSeekCB !is null) {
1880         return onSeekCB(pUserData, offset, origin);
1881       }
1882       return false;
1883   }
1884 }
1885 
1886 
1887 void drflac__decode_block_header (uint blockHeader, ubyte* isLastBlock, ubyte* blockType, uint* blockSize) {
1888   blockHeader = drflac__be2host_32(blockHeader);
1889   *isLastBlock = (blockHeader&(0x01<<31))>>31;
1890   *blockType   = (blockHeader&(0x7F<<24))>>24;
1891   *blockSize   = (blockHeader&0xFFFFFF);
1892 }
1893 
1894 bool drflac__read_and_decode_block_header (ref ReadStruct rs, ubyte* isLastBlock, ubyte* blockType, uint* blockSize) {
1895   uint blockHeader;
1896   if (rs.read(&blockHeader, 4) != 4) return false;
1897   drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize);
1898   return true;
1899 }
1900 
1901 bool drflac__read_streaminfo (ref ReadStruct rs, drflac_streaminfo* pStreamInfo) {
1902   import core.stdc.string : memcpy;
1903   // min/max block size.
1904   uint blockSizes;
1905   if (rs.read(&blockSizes, 4) != 4) return false;
1906   // min/max frame size.
1907   ulong frameSizes = 0;
1908   if (rs.read(&frameSizes, 6) != 6) return false;
1909   // Sample rate, channels, bits per sample and total sample count.
1910   ulong importantProps;
1911   if (rs.read(&importantProps, 8) != 8) return false;
1912   // MD5
1913   ubyte[16] md5;
1914   if (rs.read(md5.ptr, md5.sizeof) != md5.sizeof) return false;
1915 
1916   blockSizes     = drflac__be2host_32(blockSizes);
1917   frameSizes     = drflac__be2host_64(frameSizes);
1918   importantProps = drflac__be2host_64(importantProps);
1919 
1920   pStreamInfo.minBlockSize     = (blockSizes&0xFFFF0000)>>16;
1921   pStreamInfo.maxBlockSize     = blockSizes&0x0000FFFF;
1922   pStreamInfo.minFrameSize     = cast(uint)((frameSizes&0xFFFFFF0000000000UL)>>40);
1923   pStreamInfo.maxFrameSize     = cast(uint)((frameSizes&0x000000FFFFFF0000UL)>>16);
1924   pStreamInfo.sampleRate       = cast(uint)((importantProps&0xFFFFF00000000000UL)>>44);
1925   pStreamInfo.channels         = cast(ubyte )((importantProps&0x00000E0000000000UL)>>41)+1;
1926   pStreamInfo.bitsPerSample    = cast(ubyte )((importantProps&0x000001F000000000UL)>>36)+1;
1927   pStreamInfo.totalSampleCount = (importantProps&0x0000000FFFFFFFFFUL)*pStreamInfo.channels;
1928   memcpy(pStreamInfo.md5.ptr, md5.ptr, md5.sizeof);
1929 
1930   return true;
1931 }
1932 
1933 bool drflac__read_and_decode_metadata (drflac* pFlac, scope drflac_meta_proc onMeta, void* pUserDataMD) nothrow
1934 {
1935   import core.stdc.stdlib : malloc, free;
1936   assert(pFlac !is null);
1937 
1938   // 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
1939   // we'll be sitting on byte 42.
1940   ulong runningFilePos = 42;
1941   ulong seektablePos  = 0;
1942   uint seektableSize = 0;
1943 
1944   for (;;) {
1945     ubyte isLastBlock = 0;
1946     ubyte blockType;
1947     uint blockSize;
1948     if (!drflac__read_and_decode_block_header(pFlac.bs.rs, &isLastBlock, &blockType, &blockSize)) return false;
1949     runningFilePos += 4;
1950 
1951     drflac_metadata metadata;
1952     metadata.type = blockType;
1953     metadata.pRawData = null;
1954     metadata.rawDataSize = 0;
1955 
1956     switch (blockType) {
1957       case DRFLAC_METADATA_BLOCK_TYPE_APPLICATION:
1958         if (onMeta) {
1959             void* pRawData = malloc(blockSize);
1960             if (pRawData is null) return false;
1961             scope(exit) free(pRawData);
1962 
1963             if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false;
1964 
1965             metadata.pRawData = pRawData;
1966             metadata.rawDataSize = blockSize;
1967             metadata.data.application.id       = drflac__be2host_32(*cast(uint*)pRawData);
1968             metadata.data.application.pData    = cast(const(void)*)(cast(ubyte*)pRawData+uint.sizeof);
1969             metadata.data.application.dataSize = blockSize-cast(uint)uint.sizeof;
1970             onMeta(pUserDataMD, &metadata);
1971         }
1972         break;
1973 
1974       case DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE:
1975         seektablePos  = runningFilePos;
1976         seektableSize = blockSize;
1977 
1978         if (onMeta) {
1979           void* pRawData = malloc(blockSize);
1980           if (pRawData is null) return false;
1981           scope(exit) free(pRawData);
1982 
1983           if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false;
1984 
1985           metadata.pRawData = pRawData;
1986           metadata.rawDataSize = blockSize;
1987           metadata.data.seektable.seekpointCount = blockSize/(drflac_seekpoint).sizeof;
1988           metadata.data.seektable.pSeekpoints = cast(const(drflac_seekpoint)*)pRawData;
1989 
1990           // Endian swap.
1991           for (uint iSeekpoint = 0; iSeekpoint < metadata.data.seektable.seekpointCount; ++iSeekpoint) {
1992             drflac_seekpoint* pSeekpoint = cast(drflac_seekpoint*)pRawData+iSeekpoint;
1993             pSeekpoint.firstSample = drflac__be2host_64(pSeekpoint.firstSample);
1994             pSeekpoint.frameOffset = drflac__be2host_64(pSeekpoint.frameOffset);
1995             pSeekpoint.sampleCount = drflac__be2host_16(pSeekpoint.sampleCount);
1996           }
1997 
1998           onMeta(pUserDataMD, &metadata);
1999         }
2000         break;
2001 
2002       case DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT:
2003         if (onMeta) {
2004           void* pRawData = malloc(blockSize);
2005           if (pRawData is null) return false;
2006           scope(exit) free(pRawData);
2007 
2008           if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false;
2009 
2010           metadata.pRawData = pRawData;
2011           metadata.rawDataSize = blockSize;
2012 
2013           const(char)* pRunningData = cast(const(char)*)pRawData;
2014           metadata.data.vorbis_comment.vendorLength = drflac__le2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2015           metadata.data.vorbis_comment.vendor       = pRunningData;                                 pRunningData += metadata.data.vorbis_comment.vendorLength;
2016           metadata.data.vorbis_comment.commentCount = drflac__le2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2017           metadata.data.vorbis_comment.comments     = pRunningData;
2018           onMeta(pUserDataMD, &metadata);
2019         }
2020         break;
2021 
2022       case DRFLAC_METADATA_BLOCK_TYPE_CUESHEET:
2023         if (onMeta) {
2024           import core.stdc.string : memcpy;
2025           void* pRawData = malloc(blockSize);
2026           if (pRawData is null) return false;
2027           scope(exit) free(pRawData);
2028 
2029           if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false;
2030 
2031           metadata.pRawData = pRawData;
2032           metadata.rawDataSize = blockSize;
2033 
2034           const(char)* pRunningData = cast(const(char)*)pRawData;
2035           memcpy(metadata.data.cuesheet.catalog.ptr, pRunningData, 128);                           pRunningData += 128;
2036           metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*cast(ulong*)pRunningData);pRunningData += 4;
2037           metadata.data.cuesheet.isCD              = ((pRunningData[0]&0x80)>>7) != 0;         pRunningData += 259;
2038           metadata.data.cuesheet.trackCount        = pRunningData[0];                              pRunningData += 1;
2039           metadata.data.cuesheet.pTrackData        = cast(const(ubyte)*)pRunningData;
2040           onMeta(pUserDataMD, &metadata);
2041         }
2042         break;
2043 
2044       case DRFLAC_METADATA_BLOCK_TYPE_PICTURE:
2045         if (onMeta) {
2046           void* pRawData = malloc(blockSize);
2047           if (pRawData is null) return false;
2048           scope(exit) free(pRawData);
2049 
2050           if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false;
2051 
2052           metadata.pRawData = pRawData;
2053           metadata.rawDataSize = blockSize;
2054 
2055           const(char)* pRunningData = cast(const(char)*)pRawData;
2056           metadata.data.picture.type              = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2057           metadata.data.picture.mimeLength        = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2058           metadata.data.picture.mime              = pRunningData;                                 pRunningData += metadata.data.picture.mimeLength;
2059           metadata.data.picture.descriptionLength = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2060           metadata.data.picture.description       = pRunningData;
2061           metadata.data.picture.width             = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2062           metadata.data.picture.height            = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2063           metadata.data.picture.colorDepth        = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2064           metadata.data.picture.indexColorCount   = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2065           metadata.data.picture.pictureDataSize   = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4;
2066           metadata.data.picture.pPictureData      = cast(const(ubyte)*)pRunningData;
2067           onMeta(pUserDataMD, &metadata);
2068         }
2069         break;
2070 
2071       case DRFLAC_METADATA_BLOCK_TYPE_PADDING:
2072         if (onMeta) {
2073           metadata.data.padding.unused = 0;
2074           // Padding doesn't have anything meaningful in it, so just skip over it.
2075           if (!pFlac.bs.rs.seek(blockSize, drflac_seek_origin_current)) return false;
2076           //onMeta(pUserDataMD, &metadata);
2077         }
2078         break;
2079 
2080       case DRFLAC_METADATA_BLOCK_TYPE_INVALID:
2081         // Invalid chunk. Just skip over this one.
2082         if (onMeta) {
2083           if (!pFlac.bs.rs.seek(blockSize, drflac_seek_origin_current)) return false;
2084         }
2085         goto default;
2086 
2087       default:
2088         // It's an unknown chunk, but not necessarily invalid. There's a chance more metadata blocks might be defined later on, so we
2089         // can at the very least report the chunk to the application and let it look at the raw data.
2090         if (onMeta) {
2091           void* pRawData = malloc(blockSize);
2092           if (pRawData is null) return false;
2093           scope(exit) free(pRawData);
2094 
2095           if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false;
2096 
2097           metadata.pRawData = pRawData;
2098           metadata.rawDataSize = blockSize;
2099           onMeta(pUserDataMD, &metadata);
2100         }
2101         break;
2102     }
2103 
2104     // 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.
2105     if (onMeta is null) {
2106       if (!pFlac.bs.rs.seek(blockSize, drflac_seek_origin_current)) return false;
2107     }
2108 
2109     runningFilePos += blockSize;
2110     if (isLastBlock) break;
2111   }
2112 
2113   pFlac.seektablePos = seektablePos;
2114   pFlac.seektableSize = seektableSize;
2115   pFlac.firstFramePos = runningFilePos;
2116 
2117   return true;
2118 }
2119 
2120 bool drflac__init_private__native (drflac_init_info* pInit, ref ReadStruct rs, scope drflac_meta_proc onMeta, void* pUserDataMD) {
2121   // Pre: The bit stream should be sitting just past the 4-byte id header.
2122 
2123   pInit.container = drflac_container_native;
2124 
2125   // The first metadata block should be the STREAMINFO block.
2126   ubyte isLastBlock;
2127   ubyte blockType;
2128   uint blockSize;
2129   if (!drflac__read_and_decode_block_header(rs, &isLastBlock, &blockType, &blockSize)) return false;
2130 
2131   if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) return false;    // Invalid block type. First block must be the STREAMINFO block.
2132 
2133   drflac_streaminfo streaminfo;
2134   if (!drflac__read_streaminfo(rs, &streaminfo)) return false;
2135 
2136   pInit.sampleRate       = streaminfo.sampleRate;
2137   pInit.channels         = streaminfo.channels;
2138   pInit.bitsPerSample    = streaminfo.bitsPerSample;
2139   pInit.totalSampleCount = streaminfo.totalSampleCount;
2140   pInit.maxBlockSize     = streaminfo.maxBlockSize;    // Don't care about the min block size - only the max (used for determining the size of the memory allocation).
2141 
2142   if (onMeta !is null) {
2143     drflac_metadata metadata;
2144     metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
2145     metadata.pRawData = null;
2146     metadata.rawDataSize = 0;
2147     metadata.data.streaminfo = streaminfo;
2148     onMeta(pUserDataMD, &metadata);
2149   }
2150 
2151   pInit.hasMetadataBlocks = !isLastBlock;
2152   return true;
2153 }
2154 
2155 //#ifndef DR_FLAC_NO_OGG
2156 bool drflac_ogg__is_capture_pattern (const(ubyte)* pattern/*[4]*/) {
2157   return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S';
2158 }
2159 
2160 uint drflac_ogg__get_page_header_size (drflac_ogg_page_header* pHeader) {
2161   return 27+pHeader.segmentCount;
2162 }
2163 
2164 uint drflac_ogg__get_page_body_size (drflac_ogg_page_header* pHeader) {
2165   uint pageBodySize = 0;
2166   for (int i = 0; i < pHeader.segmentCount; ++i) pageBodySize += pHeader.segmentTable.ptr[i];
2167   return pageBodySize;
2168 }
2169 
2170 bool drflac_ogg__read_page_header_after_capture_pattern (ref ReadStruct rs, drflac_ogg_page_header* pHeader, uint* pHeaderSize) {
2171   if (rs.read(&pHeader.structureVersion, 1) != 1 || pHeader.structureVersion != 0) return false;   // Unknown structure version. Possibly corrupt stream.
2172   if (rs.read(&pHeader.headerType, 1) != 1) return false;
2173   if (rs.read(&pHeader.granulePosition, 8) != 8) return false;
2174   if (rs.read(&pHeader.serialNumber, 4) != 4) return false;
2175   if (rs.read(&pHeader.sequenceNumber, 4) != 4) return false;
2176   if (rs.read(&pHeader.checksum, 4) != 4) return false;
2177   if (rs.read(&pHeader.segmentCount, 1) != 1 || pHeader.segmentCount == 0) return false;   // Should not have a segment count of 0.
2178   if (rs.read(&pHeader.segmentTable, pHeader.segmentCount) != pHeader.segmentCount) return false;
2179   if (pHeaderSize) *pHeaderSize = (27+pHeader.segmentCount);
2180   return true;
2181 }
2182 
2183 bool drflac_ogg__read_page_header (ref ReadStruct rs, drflac_ogg_page_header* pHeader, uint* pHeaderSize) {
2184   ubyte[4] id;
2185   if (rs.read(id.ptr, 4) != 4) return false;
2186   if (id.ptr[0] != 'O' || id.ptr[1] != 'g' || id.ptr[2] != 'g' || id.ptr[3] != 'S') return false;
2187   return drflac_ogg__read_page_header_after_capture_pattern(rs, pHeader, pHeaderSize);
2188 }
2189 
2190 
2191 // The main part of the Ogg encapsulation is the conversion from the physical Ogg bitstream to the native FLAC bitstream. It works
2192 // in three general stages: Ogg Physical Bitstream . Ogg/FLAC Logical Bitstream . FLAC Native Bitstream. dr_flac is architecured
2193 // in such a way that the core sections assume everything is delivered in native format. Therefore, for each encapsulation type
2194 // 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
2195 // the physical Ogg bitstream are converted and delivered in native FLAC format.
2196 struct drflac_oggbs {
2197   //drflac_read_proc onRead;    // The original onRead callback from drflac_open() and family.
2198   //drflac_seek_proc onSeek;    // The original onSeek callback from drflac_open() and family.
2199   //void* pUserData;            // The user data passed on onRead and onSeek. This is the user data that was passed on drflac_open() and family.
2200   ReadStruct rs;
2201   ulong currentBytePos;    // The position of the byte we are sitting on in the physical byte stream. Used for efficient seeking.
2202   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.
2203   uint serialNumber;      // The serial number of the FLAC audio pages. This is determined by the initial header page that was read during initialization.
2204   drflac_ogg_page_header bosPageHeader;   // Used for seeking.
2205   drflac_ogg_page_header currentPageHeader;
2206   uint bytesRemainingInPage;
2207   bool stdio; //k8: it is drflac's stdio shit
2208 } // oggbs = Ogg Bitstream
2209 
2210 size_t drflac_oggbs__read_physical (drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead) {
2211   size_t bytesActuallyRead = oggbs.rs.read(bufferOut, bytesToRead);
2212   oggbs.currentBytePos += bytesActuallyRead;
2213   return bytesActuallyRead;
2214 }
2215 
2216 bool drflac_oggbs__seek_physical (drflac_oggbs* oggbs, ulong offset, drflac_seek_origin origin) {
2217   if (origin == drflac_seek_origin_start) {
2218     if (offset <= 0x7FFFFFFF) {
2219       if (!oggbs.rs.seek(cast(int)offset, drflac_seek_origin_start)) return false;
2220       oggbs.currentBytePos = offset;
2221       return true;
2222     } else {
2223       if (!oggbs.rs.seek(0x7FFFFFFF, drflac_seek_origin_start)) return false;
2224       oggbs.currentBytePos = offset;
2225       return drflac_oggbs__seek_physical(oggbs, offset-0x7FFFFFFF, drflac_seek_origin_current);
2226     }
2227   } else {
2228     while (offset > 0x7FFFFFFF) {
2229       if (!oggbs.rs.seek(0x7FFFFFFF, drflac_seek_origin_current)) return false;
2230       oggbs.currentBytePos += 0x7FFFFFFF;
2231       offset -= 0x7FFFFFFF;
2232     }
2233     if (!oggbs.rs.seek(cast(int)offset, drflac_seek_origin_current)) return false; // <-- Safe cast thanks to the loop above.
2234     oggbs.currentBytePos += offset;
2235     return true;
2236   }
2237 }
2238 
2239 bool drflac_oggbs__goto_next_page (drflac_oggbs* oggbs) {
2240   drflac_ogg_page_header header;
2241   for (;;) {
2242     uint headerSize;
2243     if (!drflac_ogg__read_page_header(oggbs.rs, &header, &headerSize)) return false;
2244     oggbs.currentBytePos += headerSize;
2245     uint pageBodySize = drflac_ogg__get_page_body_size(&header);
2246     if (header.serialNumber == oggbs.serialNumber) {
2247       oggbs.currentPageHeader = header;
2248       oggbs.bytesRemainingInPage = pageBodySize;
2249       return true;
2250     }
2251     // If we get here it means the page is not a FLAC page - skip it.
2252     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.
2253   }
2254 }
2255 
2256 size_t drflac__on_read_ogg (void* pUserData, void* bufferOut, size_t bytesToRead) {
2257   drflac_oggbs* oggbs = cast(drflac_oggbs*)pUserData;
2258   assert(oggbs !is null);
2259 
2260   ubyte* pRunningBufferOut = cast(ubyte*)bufferOut;
2261 
2262   // Reading is done page-by-page. If we've run out of bytes in the page we need to move to the next one.
2263   size_t bytesRead = 0;
2264   while (bytesRead < bytesToRead) {
2265     size_t bytesRemainingToRead = bytesToRead-bytesRead;
2266 
2267     if (oggbs.bytesRemainingInPage >= bytesRemainingToRead) {
2268       bytesRead += oggbs.rs.read(pRunningBufferOut, bytesRemainingToRead);
2269       oggbs.bytesRemainingInPage -= cast(uint)bytesRemainingToRead;
2270       break;
2271     }
2272 
2273     // If we get here it means some of the requested data is contained in the next pages.
2274     if (oggbs.bytesRemainingInPage > 0) {
2275       size_t bytesJustRead = oggbs.rs.read(pRunningBufferOut, oggbs.bytesRemainingInPage);
2276       bytesRead += bytesJustRead;
2277       pRunningBufferOut += bytesJustRead;
2278       if (bytesJustRead != oggbs.bytesRemainingInPage) break;  // Ran out of data.
2279     }
2280 
2281     assert(bytesRemainingToRead > 0);
2282     if (!drflac_oggbs__goto_next_page(oggbs)) break;  // Failed to go to the next chunk. Might have simply hit the end of the stream.
2283   }
2284 
2285   oggbs.currentBytePos += bytesRead;
2286   return bytesRead;
2287 }
2288 
2289 bool drflac__on_seek_ogg (void* pUserData, int offset, drflac_seek_origin origin) {
2290   drflac_oggbs* oggbs = cast(drflac_oggbs*)pUserData;
2291   assert(oggbs !is null);
2292   assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start));
2293 
2294   // Seeking is always forward which makes things a lot simpler.
2295   if (origin == drflac_seek_origin_start) {
2296     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.
2297     if (!drflac_oggbs__seek_physical(oggbs, startBytePos, drflac_seek_origin_start)) return false;
2298     oggbs.currentPageHeader = oggbs.bosPageHeader;
2299     oggbs.bytesRemainingInPage = 42;   // 42 = size of the native FLAC header data. That's our start point for seeking.
2300     return drflac__on_seek_ogg(pUserData, offset, drflac_seek_origin_current);
2301   }
2302 
2303   assert(origin == drflac_seek_origin_current);
2304 
2305   int bytesSeeked = 0;
2306   while (bytesSeeked < offset) {
2307     int bytesRemainingToSeek = offset-bytesSeeked;
2308     assert(bytesRemainingToSeek >= 0);
2309 
2310     if (oggbs.bytesRemainingInPage >= cast(size_t)bytesRemainingToSeek) {
2311       if (!drflac_oggbs__seek_physical(oggbs, bytesRemainingToSeek, drflac_seek_origin_current)) return false;
2312       bytesSeeked += bytesRemainingToSeek;
2313       oggbs.bytesRemainingInPage -= bytesRemainingToSeek;
2314       break;
2315     }
2316 
2317     // If we get here it means some of the requested data is contained in the next pages.
2318     if (oggbs.bytesRemainingInPage > 0) {
2319       if (!drflac_oggbs__seek_physical(oggbs, oggbs.bytesRemainingInPage, drflac_seek_origin_current)) return false;
2320       bytesSeeked += cast(int)oggbs.bytesRemainingInPage;
2321     }
2322 
2323     assert(bytesRemainingToSeek > 0);
2324     if (!drflac_oggbs__goto_next_page(oggbs)) break;  // Failed to go to the next chunk. Might have simply hit the end of the stream.
2325   }
2326 
2327   return true;
2328 }
2329 
2330 bool drflac_ogg__seek_to_sample (drflac* pFlac, ulong sample) {
2331   drflac_oggbs* oggbs = cast(drflac_oggbs*)((cast(int*)pFlac.pExtraData)+pFlac.maxBlockSize*pFlac.channels);
2332 
2333   ulong originalBytePos = oggbs.currentBytePos;   // For recovery.
2334 
2335   // First seek to the first frame.
2336   if (!drflac__seek_to_byte(&pFlac.bs, pFlac.firstFramePos)) return false;
2337   oggbs.bytesRemainingInPage = 0;
2338 
2339   ulong runningGranulePosition = 0;
2340   ulong runningFrameBytePos = oggbs.currentBytePos;   // <-- Points to the OggS identifier.
2341   for (;;) {
2342     if (!drflac_oggbs__goto_next_page(oggbs)) {
2343       drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
2344       return false;   // Never did find that sample...
2345     }
2346 
2347     runningFrameBytePos = oggbs.currentBytePos-drflac_ogg__get_page_header_size(&oggbs.currentPageHeader);
2348     if (oggbs.currentPageHeader.granulePosition*pFlac.channels >= sample) break; // The sample is somewhere in the previous page.
2349 
2350     // At this point we know the sample is not in the previous page. It could possibly be in this page. For simplicity we
2351     // disregard any pages that do not begin a fresh packet.
2352     if ((oggbs.currentPageHeader.headerType&0x01) == 0) {    // <-- Is it a fresh page?
2353       if (oggbs.currentPageHeader.segmentTable.ptr[0] >= 2) {
2354         ubyte[2] firstBytesInPage;
2355         if (drflac_oggbs__read_physical(oggbs, firstBytesInPage.ptr, 2) != 2) {
2356           drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
2357           return false;
2358         }
2359         if ((firstBytesInPage.ptr[0] == 0xFF) && (firstBytesInPage.ptr[1]&0xFC) == 0xF8) {    // <-- Does the page begin with a frame's sync code?
2360           runningGranulePosition = oggbs.currentPageHeader.granulePosition*pFlac.channels;
2361         }
2362 
2363         if (!drflac_oggbs__seek_physical(oggbs, cast(int)oggbs.bytesRemainingInPage-2, drflac_seek_origin_current)) {
2364           drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
2365           return false;
2366         }
2367 
2368         continue;
2369       }
2370     }
2371 
2372     if (!drflac_oggbs__seek_physical(oggbs, cast(int)oggbs.bytesRemainingInPage, drflac_seek_origin_current)) {
2373       drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
2374       return false;
2375     }
2376   }
2377 
2378   // 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
2379   // 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
2380   // a new frame. This property means that after we've seeked to the page we can immediately start looping over frames until
2381   // we find the one containing the target sample.
2382   if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, drflac_seek_origin_start)) return false;
2383   if (!drflac_oggbs__goto_next_page(oggbs)) return false;
2384 
2385   // 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
2386   // looping over these frames until we find the one containing the sample we're after.
2387   ulong firstSampleInFrame = runningGranulePosition;
2388   for (;;) {
2389     // NOTE for later: When using Ogg's page/segment based seeking later on we can't use this function (or any drflac__*
2390     // reading functions) because otherwise it will pull extra data for use in it's own internal caches which will then
2391     // break the positioning of the read pointer for the Ogg bitstream.
2392     if (!drflac__read_next_frame_header(&pFlac.bs, pFlac.bitsPerSample, &pFlac.currentFrame.header)) return false;
2393 
2394     int channels = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment);
2395     ulong lastSampleInFrame = firstSampleInFrame+(pFlac.currentFrame.header.blockSize*channels);
2396     lastSampleInFrame -= 1; // <-- Zero based.
2397 
2398     if (sample >= firstSampleInFrame && sample <= lastSampleInFrame) break;  // The sample is in this frame.
2399 
2400     // 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
2401     // with Ogg is that we can efficiently seek past the frame by looking at the lacing values of each segment in
2402     // the page.
2403     firstSampleInFrame = lastSampleInFrame+1;
2404 
2405     version(all) {
2406       // Slow way. This uses the native FLAC decoder to seek past the frame. This is slow because it needs to do a partial
2407       // decode of the frame. Although this is how the native version works, we can use Ogg's framing system to make it
2408       // more efficient. Leaving this here for reference and to use as a basis for debugging purposes.
2409       if (!drflac__seek_to_next_frame(pFlac)) return false;
2410     } else {
2411       // TODO: This is not yet complete. See note at the top of this loop body.
2412 
2413       // Fast(er) way. This uses Ogg's framing system to seek past the frame. This should be much more efficient than the
2414       // native FLAC seeking.
2415       if (!drflac_oggbs__seek_to_next_frame(oggbs)) return false;
2416     }
2417   }
2418 
2419   assert(firstSampleInFrame <= sample);
2420 
2421   if (!drflac__decode_frame(pFlac)) return false;
2422 
2423   size_t samplesToDecode = cast(size_t)(sample-firstSampleInFrame);    // <-- Safe cast because the maximum number of samples in a frame is 65535.
2424   return drflac_read_s32(pFlac, samplesToDecode, null) == samplesToDecode;
2425 }
2426 
2427 
2428 bool drflac__init_private__ogg (drflac_init_info* pInit, ref ReadStruct rs, scope drflac_meta_proc onMeta, void* pUserDataMD) {
2429   // Pre: The bit stream should be sitting just past the 4-byte OggS capture pattern.
2430 
2431   pInit.container = drflac_container_ogg;
2432   pInit.oggFirstBytePos = 0;
2433 
2434   // We'll get here if the first 4 bytes of the stream were the OggS capture pattern, however it doesn't necessarily mean the
2435   // stream includes FLAC encoded audio. To check for this we need to scan the beginning-of-stream page markers and check if
2436   // any match the FLAC specification. Important to keep in mind that the stream may be multiplexed.
2437   drflac_ogg_page_header header;
2438 
2439   uint headerSize = 0;
2440   if (!drflac_ogg__read_page_header_after_capture_pattern(rs, &header, &headerSize)) return false;
2441   pInit.runningFilePos += headerSize;
2442 
2443   for (;;) {
2444     // Break if we're past the beginning of stream page.
2445     if ((header.headerType&0x02) == 0) return false;
2446 
2447     // Check if it's a FLAC header.
2448     int pageBodySize = drflac_ogg__get_page_body_size(&header);
2449     if (pageBodySize == 51) { // 51 = the lacing value of the FLAC header packet.
2450       // It could be a FLAC page...
2451       uint bytesRemainingInPage = pageBodySize;
2452 
2453       ubyte packetType;
2454       if (rs.read(&packetType, 1) != 1) return false;
2455 
2456       bytesRemainingInPage -= 1;
2457       if (packetType == 0x7F) {
2458         // Increasingly more likely to be a FLAC page...
2459         ubyte[4] sig;
2460         if (rs.read(sig.ptr, 4) != 4) return false;
2461 
2462         bytesRemainingInPage -= 4;
2463         if (sig.ptr[0] == 'F' && sig.ptr[1] == 'L' && sig.ptr[2] == 'A' && sig.ptr[3] == 'C') {
2464           // Almost certainly a FLAC page...
2465           ubyte[2] mappingVersion;
2466           if (rs.read(mappingVersion.ptr, 2) != 2) return false;
2467 
2468           if (mappingVersion.ptr[0] != 1) return false;   // Only supporting version 1.x of the Ogg mapping.
2469 
2470           // The next 2 bytes are the non-audio packets, not including this one. We don't care about this because we're going to
2471           // be handling it in a generic way based on the serial number and packet types.
2472           if (!rs.seek(2, drflac_seek_origin_current)) return false;
2473 
2474           // Expecting the native FLAC signature "fLaC".
2475           if (rs.read(sig.ptr, 4) != 4) return false;
2476 
2477           if (sig.ptr[0] == 'f' && sig.ptr[1] == 'L' && sig.ptr[2] == 'a' && sig.ptr[3] == 'C') {
2478             // The remaining data in the page should be the STREAMINFO block.
2479             ubyte isLastBlock;
2480             ubyte blockType;
2481             uint blockSize;
2482             if (!drflac__read_and_decode_block_header(rs, &isLastBlock, &blockType, &blockSize)) return false;
2483 
2484             if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) return false;    // Invalid block type. First block must be the STREAMINFO block.
2485 
2486             drflac_streaminfo streaminfo;
2487             if (drflac__read_streaminfo(rs, &streaminfo)) {
2488               // Success!
2489               pInit.sampleRate       = streaminfo.sampleRate;
2490               pInit.channels         = streaminfo.channels;
2491               pInit.bitsPerSample    = streaminfo.bitsPerSample;
2492               pInit.totalSampleCount = streaminfo.totalSampleCount;
2493               pInit.maxBlockSize     = streaminfo.maxBlockSize;
2494 
2495               if (onMeta !is null) {
2496                 drflac_metadata metadata;
2497                 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
2498                 metadata.pRawData = null;
2499                 metadata.rawDataSize = 0;
2500                 metadata.data.streaminfo = streaminfo;
2501                 onMeta(pUserDataMD, &metadata);
2502               }
2503 
2504               pInit.runningFilePos  += pageBodySize;
2505               pInit.oggFirstBytePos  = pInit.runningFilePos-79;   // Subtracting 79 will place us right on top of the "OggS" identifier of the FLAC bos page.
2506               pInit.oggSerial        = header.serialNumber;
2507               pInit.oggBosHeader     = header;
2508               break;
2509             } else {
2510               // Failed to read STREAMINFO block. Aww, so close...
2511               return false;
2512             }
2513           } else {
2514             // Invalid file.
2515             return false;
2516           }
2517         } else {
2518           // Not a FLAC header. Skip it.
2519           if (!rs.seek(bytesRemainingInPage, drflac_seek_origin_current)) return false;
2520         }
2521       } else {
2522         // Not a FLAC header. Seek past the entire page and move on to the next.
2523         if (!rs.seek(bytesRemainingInPage, drflac_seek_origin_current)) return false;
2524       }
2525     } else {
2526       if (!rs.seek(pageBodySize, drflac_seek_origin_current)) return false;
2527     }
2528 
2529     pInit.runningFilePos += pageBodySize;
2530 
2531     // Read the header of the next page.
2532     if (!drflac_ogg__read_page_header(rs, &header, &headerSize)) return false;
2533     pInit.runningFilePos += headerSize;
2534   }
2535 
2536 
2537   // 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
2538   // 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
2539   // Ogg bistream object.
2540   pInit.hasMetadataBlocks = true;    // <-- Always have at least VORBIS_COMMENT metadata block.
2541   return true;
2542 }
2543 //#endif
2544 
2545 bool drflac__check_init_private (drflac_init_info* pInit, scope drflac_meta_proc onMeta, void* pUserDataMD) {
2546   ubyte[4] id;
2547   if (pInit.rs.read(id.ptr, 4) != 4) return false;
2548   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);
2549 //#ifndef DR_FLAC_NO_OGG
2550   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);
2551 //#endif
2552   // unsupported container
2553   return false;
2554 }
2555 
2556 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) {
2557   if (pInit is null || onRead is null || onSeek is null) return false;
2558 
2559   pInit.rs.onReadCB  = onRead;
2560   pInit.rs.onSeekCB  = onSeek;
2561   pInit.rs.pUserData = pUserData;
2562   //pInit.onMeta       = onMeta;
2563   //pInit.pUserDataMD  = pUserDataMD;
2564 
2565   return drflac__check_init_private(pInit, onMeta, pUserDataMD);
2566 }
2567 
2568 } //nothrow
2569 
2570 nothrow {
2571 void drflac__init_from_info (drflac* pFlac, drflac_init_info* pInit) {
2572   import core.stdc.string : memcpy, memset;
2573   assert(pFlac !is null);
2574   assert(pInit !is null);
2575 
2576   memset(pFlac, 0, (*pFlac).sizeof);
2577   pFlac.bs.rs            = pInit.rs;
2578   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.
2579   pFlac.bs.consumedBits  = (pFlac.bs.cache).sizeof*8;
2580 
2581   //pFlac.onMeta           = pInit.onMeta;
2582   //pFlac.pUserDataMD      = pInit.pUserDataMD;
2583   pFlac.maxBlockSize     = pInit.maxBlockSize;
2584   pFlac.sampleRate       = pInit.sampleRate;
2585   pFlac.channels         = cast(ubyte)pInit.channels;
2586   pFlac.bitsPerSample    = cast(ubyte)pInit.bitsPerSample;
2587   pFlac.totalSampleCount = pInit.totalSampleCount;
2588   pFlac.container        = pInit.container;
2589 }
2590 
2591 drflac* drflac_open_with_metadata_private_xx (drflac_init_info* init, scope drflac_meta_proc onMeta, void* pUserDataMD, bool stdio) {
2592   import core.stdc.stdlib : malloc, free;
2593   import core.stdc.string : memset;
2594 
2595   size_t allocationSize = (drflac).sizeof;
2596   allocationSize += init.maxBlockSize*init.channels*(int).sizeof;
2597   //allocationSize += init.seektableSize;
2598 
2599 //#ifndef DR_FLAC_NO_OGG
2600   // There's additional data required for Ogg streams.
2601   if (init.container == drflac_container_ogg) allocationSize += (drflac_oggbs).sizeof;
2602 //#endif
2603 
2604   drflac* pFlac = cast(drflac*)malloc(allocationSize);
2605   memset(pFlac, 0, (*pFlac).sizeof);
2606   drflac__init_from_info(pFlac, init);
2607   pFlac.pDecodedSamples = cast(int*)pFlac.pExtraData;
2608 
2609 //#ifndef DR_FLAC_NO_OGG
2610   if (init.container == drflac_container_ogg) {
2611     drflac_oggbs* oggbs = cast(drflac_oggbs*)((cast(int*)pFlac.pExtraData)+init.maxBlockSize*init.channels);
2612     oggbs.stdio = stdio;
2613     oggbs.rs = init.rs;
2614     oggbs.currentBytePos = init.oggFirstBytePos;
2615     oggbs.firstBytePos = init.oggFirstBytePos;
2616     oggbs.serialNumber = init.oggSerial;
2617     oggbs.bosPageHeader = init.oggBosHeader;
2618     oggbs.bytesRemainingInPage = 0;
2619 
2620     // The Ogg bistream needs to be layered on top of the original bitstream.
2621     pFlac.bs.rs.onReadCB = &drflac__on_read_ogg;
2622     pFlac.bs.rs.onSeekCB = &drflac__on_seek_ogg;
2623     pFlac.bs.rs.pUserData = cast(void*)oggbs;
2624   }
2625 //#endif
2626 
2627   // Decode metadata before returning.
2628   if (init.hasMetadataBlocks) {
2629     if (!drflac__read_and_decode_metadata(pFlac, onMeta, pUserDataMD)) {
2630       free(pFlac);
2631       return null;
2632     }
2633   }
2634 
2635   return pFlac;
2636 }
2637 
2638 
2639 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) {
2640   drflac_init_info init;
2641   if (!drflac__init_private(&init, onRead, onSeek, onMeta, pUserData, pUserDataMD)) return null;
2642   return drflac_open_with_metadata_private_xx(&init, onMeta, pUserDataMD, stdio);
2643 }
2644 
2645 } //nothrow
2646 
2647 nothrow {
2648 
2649 size_t drflac__on_read_memory (void* pUserData, void* bufferOut, size_t bytesToRead) {
2650   drflac__memory_stream* memoryStream = cast(drflac__memory_stream*)pUserData;
2651   assert(memoryStream !is null);
2652   assert(memoryStream.dataSize >= memoryStream.currentReadPos);
2653 
2654   size_t bytesRemaining = memoryStream.dataSize-memoryStream.currentReadPos;
2655   if (bytesToRead > bytesRemaining) bytesToRead = bytesRemaining;
2656 
2657   if (bytesToRead > 0) {
2658     import core.stdc.string : memcpy;
2659     memcpy(bufferOut, memoryStream.data+memoryStream.currentReadPos, bytesToRead);
2660     memoryStream.currentReadPos += bytesToRead;
2661   }
2662 
2663   return bytesToRead;
2664 }
2665 
2666 bool drflac__on_seek_memory (void* pUserData, int offset, drflac_seek_origin origin) {
2667   drflac__memory_stream* memoryStream = cast(drflac__memory_stream*)pUserData;
2668   assert(memoryStream !is null);
2669   assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start));
2670 
2671   if (origin == drflac_seek_origin_current) {
2672     if (memoryStream.currentReadPos+offset <= memoryStream.dataSize) {
2673       memoryStream.currentReadPos += offset;
2674     } else {
2675       memoryStream.currentReadPos = memoryStream.dataSize;  // Trying to seek too far forward.
2676     }
2677   } else {
2678     if (cast(uint)offset <= memoryStream.dataSize) {
2679       memoryStream.currentReadPos = offset;
2680     } else {
2681       memoryStream.currentReadPos = memoryStream.dataSize;  // Trying to seek too far forward.
2682     }
2683   }
2684 
2685   return true;
2686 }
2687 
2688 public drflac* drflac_open_memory (const(void)* data, size_t dataSize) {
2689 
2690   drflac__memory_stream memoryStream;
2691   memoryStream.data = cast(const(ubyte)*)data;
2692   memoryStream.dataSize = dataSize;
2693   memoryStream.currentReadPos = 0;
2694 
2695   drflac* pFlac = drflac_open(&drflac__on_read_memory, &drflac__on_seek_memory, &memoryStream);
2696   if (pFlac is null) return null;
2697 
2698   pFlac.memoryStream = memoryStream;
2699 
2700   // This is an awful hack...
2701 //#ifndef DR_FLAC_NO_OGG
2702   if (pFlac.container == drflac_container_ogg) {
2703     drflac_oggbs* oggbs = cast(drflac_oggbs*)((cast(int*)pFlac.pExtraData)+pFlac.maxBlockSize*pFlac.channels);
2704     oggbs.rs.pUserData = &pFlac.memoryStream;
2705   }
2706   else
2707 //#endif
2708   {
2709     pFlac.bs.rs.pUserData = &pFlac.memoryStream;
2710   }
2711 
2712   return pFlac;
2713 }
2714 
2715 public drflac* drflac_open_memory_with_metadata (const(void)* data, size_t dataSize, scope drflac_meta_proc onMeta, void* pUserData) {
2716 
2717   drflac__memory_stream memoryStream;
2718   memoryStream.data = cast(const(ubyte)*)data;
2719   memoryStream.dataSize = dataSize;
2720   memoryStream.currentReadPos = 0;
2721 
2722   drflac* pFlac = drflac_open_with_metadata_private(&drflac__on_read_memory, &drflac__on_seek_memory, onMeta, &memoryStream, pUserData, false);
2723   if (pFlac is null) return null;
2724 
2725   pFlac.memoryStream = memoryStream;
2726 
2727   // This is an awful hack...
2728 //#ifndef DR_FLAC_NO_OGG
2729   if (pFlac.container == drflac_container_ogg) {
2730     drflac_oggbs* oggbs = cast(drflac_oggbs*)((cast(int*)pFlac.pExtraData)+pFlac.maxBlockSize*pFlac.channels);
2731     oggbs.rs.pUserData = &pFlac.memoryStream;
2732   } else
2733 //#endif
2734   {
2735     pFlac.bs.rs.pUserData = &pFlac.memoryStream;
2736   }
2737 
2738   return pFlac;
2739 }
2740 
2741 public drflac* drflac_open (drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData) {
2742   return drflac_open_with_metadata_private(onRead, onSeek, null, pUserData, pUserData, false);
2743 }
2744 
2745 } //nothrow
2746 
2747 
2748 nothrow {
2749 
2750 public drflac* drflac_open_with_metadata (drflac_read_proc onRead, drflac_seek_proc onSeek, scope drflac_meta_proc onMeta, void* pUserData) {
2751   return drflac_open_with_metadata_private(onRead, onSeek, onMeta, pUserData, pUserData, false);
2752 }
2753 
2754 public void drflac_close (drflac* pFlac) 
2755 {
2756     import core.stdc.stdlib : free;
2757     free(pFlac);
2758 }
2759 
2760 
2761 ulong drflac__read_s32__misaligned (drflac* pFlac, ulong samplesToRead, int* bufferOut) {
2762   uint channelCount = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment);
2763 
2764   // We should never be calling this when the number of samples to read is >= the sample count.
2765   assert(samplesToRead < channelCount);
2766   assert(pFlac.currentFrame.samplesRemaining > 0 && samplesToRead <= pFlac.currentFrame.samplesRemaining);
2767 
2768   ulong samplesRead = 0;
2769   while (samplesToRead > 0) {
2770     ulong totalSamplesInFrame = pFlac.currentFrame.header.blockSize*channelCount;
2771     ulong samplesReadFromFrameSoFar = totalSamplesInFrame-pFlac.currentFrame.samplesRemaining;
2772     uint channelIndex = samplesReadFromFrameSoFar%channelCount;
2773 
2774     ulong nextSampleInFrame = samplesReadFromFrameSoFar/channelCount;
2775 
2776     int decodedSample = 0;
2777     switch (pFlac.currentFrame.header.channelAssignment) {
2778       case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
2779         if (channelIndex == 0) {
2780           decodedSample = pFlac.currentFrame.subframes.ptr[channelIndex].pDecodedSamples[cast(uint)nextSampleInFrame];
2781         } else {
2782           int side = pFlac.currentFrame.subframes.ptr[channelIndex+0].pDecodedSamples[cast(uint)nextSampleInFrame];
2783           int left = pFlac.currentFrame.subframes.ptr[channelIndex-1].pDecodedSamples[cast(uint)nextSampleInFrame];
2784           decodedSample = left-side;
2785         }
2786         break;
2787 
2788       case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2789         if (channelIndex == 0) {
2790           int side  = pFlac.currentFrame.subframes.ptr[channelIndex+0].pDecodedSamples[cast(uint)nextSampleInFrame];
2791           int right = pFlac.currentFrame.subframes.ptr[channelIndex+1].pDecodedSamples[cast(uint)nextSampleInFrame];
2792           decodedSample = side+right;
2793         } else {
2794           decodedSample = pFlac.currentFrame.subframes.ptr[channelIndex].pDecodedSamples[cast(uint)nextSampleInFrame];
2795         }
2796         break;
2797 
2798       case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
2799         int mid;
2800         int side;
2801         if (channelIndex == 0) {
2802           mid  = pFlac.currentFrame.subframes.ptr[channelIndex+0].pDecodedSamples[cast(uint)nextSampleInFrame];
2803           side = pFlac.currentFrame.subframes.ptr[channelIndex+1].pDecodedSamples[cast(uint)nextSampleInFrame];
2804           mid = ((cast(uint)mid)<<1)|(side&0x01);
2805           decodedSample = (mid+side)>>1;
2806         } else {
2807           mid  = pFlac.currentFrame.subframes.ptr[channelIndex-1].pDecodedSamples[cast(uint)nextSampleInFrame];
2808           side = pFlac.currentFrame.subframes.ptr[channelIndex+0].pDecodedSamples[cast(uint)nextSampleInFrame];
2809           mid = ((cast(uint)mid)<<1)|(side&0x01);
2810           decodedSample = (mid-side)>>1;
2811         }
2812         break;
2813 
2814       case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: goto default;
2815       default:
2816         decodedSample = pFlac.currentFrame.subframes.ptr[channelIndex].pDecodedSamples[cast(uint)nextSampleInFrame];
2817         break;
2818     }
2819 
2820     decodedSample <<= ((32-pFlac.bitsPerSample)+pFlac.currentFrame.subframes.ptr[channelIndex].wastedBitsPerSample);
2821 
2822     if (bufferOut) *bufferOut++ = decodedSample;
2823 
2824     samplesRead += 1;
2825     pFlac.currentFrame.samplesRemaining -= 1;
2826     samplesToRead -= 1;
2827   }
2828 
2829   return samplesRead;
2830 }
2831 
2832 ulong drflac__seek_forward_by_samples (drflac* pFlac, ulong samplesToRead) {
2833   ulong samplesRead = 0;
2834   while (samplesToRead > 0) {
2835     if (pFlac.currentFrame.samplesRemaining == 0) {
2836       if (!drflac__read_and_decode_next_frame(pFlac)) break;  // Couldn't read the next frame, so just break from the loop and return.
2837     } else {
2838       samplesRead += 1;
2839       pFlac.currentFrame.samplesRemaining -= 1;
2840       samplesToRead -= 1;
2841     }
2842   }
2843   return samplesRead;
2844 }
2845 
2846 public ulong drflac_read_s32 (drflac* pFlac, ulong samplesToRead, int* bufferOut) {
2847   // Note that <bufferOut> is allowed to be null, in which case this will be treated as something like a seek.
2848   if (pFlac is null || samplesToRead == 0) return 0;
2849 
2850   if (bufferOut is null) 
2851   {
2852      // wtf
2853      return drflac__seek_forward_by_samples(pFlac, samplesToRead);
2854   }
2855 
2856   ulong samplesRead = 0;
2857   while (samplesToRead > 0) {
2858     // If we've run out of samples in this frame, go to the next.
2859     if (pFlac.currentFrame.samplesRemaining == 0) {
2860       if (!drflac__read_and_decode_next_frame(pFlac)) break;  // Couldn't read the next frame, so just break from the loop and return.
2861     } else {
2862       // Here is where we grab the samples and interleave them.
2863 
2864       uint channelCount = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment);
2865       ulong totalSamplesInFrame = pFlac.currentFrame.header.blockSize*channelCount;
2866       ulong samplesReadFromFrameSoFar = totalSamplesInFrame-pFlac.currentFrame.samplesRemaining;
2867 
2868       int misalignedSampleCount = cast(int)(samplesReadFromFrameSoFar%channelCount);
2869       if (misalignedSampleCount > 0) {
2870         ulong misalignedSamplesRead = drflac__read_s32__misaligned(pFlac, misalignedSampleCount, bufferOut);
2871         samplesRead   += misalignedSamplesRead;
2872         samplesReadFromFrameSoFar += misalignedSamplesRead;
2873         bufferOut     += misalignedSamplesRead;
2874         samplesToRead -= misalignedSamplesRead;
2875       }
2876 
2877       ulong alignedSampleCountPerChannel = samplesToRead/channelCount;
2878       if (alignedSampleCountPerChannel > pFlac.currentFrame.samplesRemaining/channelCount) {
2879         alignedSampleCountPerChannel = pFlac.currentFrame.samplesRemaining/channelCount;
2880       }
2881 
2882       ulong firstAlignedSampleInFrame = samplesReadFromFrameSoFar/channelCount;
2883       uint unusedBitsPerSample = 32-pFlac.bitsPerSample;
2884 
2885       switch (pFlac.currentFrame.header.channelAssignment) {
2886         case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
2887           const int* pDecodedSamples0 = pFlac.currentFrame.subframes.ptr[0].pDecodedSamples+firstAlignedSampleInFrame;
2888           const int* pDecodedSamples1 = pFlac.currentFrame.subframes.ptr[1].pDecodedSamples+firstAlignedSampleInFrame;
2889 
2890           for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) {
2891             int left  = pDecodedSamples0[i];
2892             int side  = pDecodedSamples1[i];
2893             int right = left-side;
2894             bufferOut[i*2+0] = left<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[0].wastedBitsPerSample);
2895             bufferOut[i*2+1] = right<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[1].wastedBitsPerSample);
2896           }
2897           break;
2898 
2899         case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
2900           const int* pDecodedSamples0 = pFlac.currentFrame.subframes.ptr[0].pDecodedSamples+firstAlignedSampleInFrame;
2901           const int* pDecodedSamples1 = pFlac.currentFrame.subframes.ptr[1].pDecodedSamples+firstAlignedSampleInFrame;
2902           for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) {
2903             int side  = pDecodedSamples0[i];
2904             int right = pDecodedSamples1[i];
2905             int left  = right+side;
2906             bufferOut[i*2+0] = left<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[0].wastedBitsPerSample);
2907             bufferOut[i*2+1] = right<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[1].wastedBitsPerSample);
2908           }
2909           break;
2910 
2911         case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
2912           const int* pDecodedSamples0 = pFlac.currentFrame.subframes.ptr[0].pDecodedSamples+firstAlignedSampleInFrame;
2913           const int* pDecodedSamples1 = pFlac.currentFrame.subframes.ptr[1].pDecodedSamples+firstAlignedSampleInFrame;
2914           for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) {
2915             int side = pDecodedSamples1[i];
2916             int mid  = ((cast(uint)pDecodedSamples0[i])<<1)|(side&0x01);
2917             bufferOut[i*2+0] = ((mid+side)>>1)<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[0].wastedBitsPerSample);
2918             bufferOut[i*2+1] = ((mid-side)>>1)<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[1].wastedBitsPerSample);
2919           }
2920           break;
2921 
2922         case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: goto default;
2923         default:
2924           if (pFlac.currentFrame.header.channelAssignment == 1) { // 1 = Stereo
2925             // Stereo optimized inner loop unroll.
2926             const int* pDecodedSamples0 = pFlac.currentFrame.subframes.ptr[0].pDecodedSamples+firstAlignedSampleInFrame;
2927             const int* pDecodedSamples1 = pFlac.currentFrame.subframes.ptr[1].pDecodedSamples+firstAlignedSampleInFrame;
2928             for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) {
2929               bufferOut[i*2+0] = pDecodedSamples0[i]<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[0].wastedBitsPerSample);
2930               bufferOut[i*2+1] = pDecodedSamples1[i]<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[1].wastedBitsPerSample);
2931             }
2932           } else {
2933             // Generic interleaving.
2934             for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) {
2935               for (uint j = 0; j < channelCount; ++j) {
2936                 bufferOut[(i*channelCount)+j] = (pFlac.currentFrame.subframes.ptr[j].pDecodedSamples[cast(uint)firstAlignedSampleInFrame+i])<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[j].wastedBitsPerSample);
2937               }
2938             }
2939           }
2940           break;
2941       }
2942 
2943       ulong alignedSamplesRead = alignedSampleCountPerChannel*channelCount;
2944       samplesRead   += alignedSamplesRead;
2945       samplesReadFromFrameSoFar += alignedSamplesRead;
2946       bufferOut     += alignedSamplesRead;
2947       samplesToRead -= alignedSamplesRead;
2948       pFlac.currentFrame.samplesRemaining -= cast(uint)alignedSamplesRead;
2949 
2950       // At this point we may still have some excess samples left to read.
2951       if (samplesToRead > 0 && pFlac.currentFrame.samplesRemaining > 0) {
2952         ulong excessSamplesRead = 0;
2953         if (samplesToRead < pFlac.currentFrame.samplesRemaining) {
2954           excessSamplesRead = drflac__read_s32__misaligned(pFlac, samplesToRead, bufferOut);
2955         } else {
2956           excessSamplesRead = drflac__read_s32__misaligned(pFlac, pFlac.currentFrame.samplesRemaining, bufferOut);
2957         }
2958 
2959         samplesRead   += excessSamplesRead;
2960         samplesReadFromFrameSoFar += excessSamplesRead;
2961         bufferOut     += excessSamplesRead;
2962         samplesToRead -= excessSamplesRead;
2963       }
2964     }
2965   }
2966 
2967   return samplesRead;
2968 }
2969 
2970 public bool drflac_seek_to_sample (drflac* pFlac, ulong sampleIndex) {
2971   if (pFlac is null) return false;
2972 
2973   // 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
2974   // when the decoder was opened.
2975   if (pFlac.firstFramePos == 0) return false;
2976 
2977   if (sampleIndex == 0) return drflac__seek_to_first_frame(pFlac);
2978 
2979   // Clamp the sample to the end.
2980   if (sampleIndex >= pFlac.totalSampleCount) sampleIndex  = pFlac.totalSampleCount-1;
2981 
2982   // Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so
2983   // we'll instead use Ogg's natural seeking facility.
2984 //#ifndef DR_FLAC_NO_OGG
2985   if (pFlac.container == drflac_container_ogg) {
2986     return drflac_ogg__seek_to_sample(pFlac, sampleIndex);
2987   }
2988   else
2989 //#endif
2990   {
2991     // First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower.
2992     if (!drflac__seek_to_sample__seek_table(pFlac, sampleIndex)) return drflac__seek_to_sample__brute_force(pFlac, sampleIndex);
2993   }
2994 
2995   return true;
2996 }
2997 
2998 public void drflac_free (void* pSampleDataReturnedByOpenAndDecode) {
2999   import core.stdc.stdlib : free;
3000   free(pSampleDataReturnedByOpenAndDecode);
3001 }
3002 
3003 
3004 public void drflac_init_vorbis_comment_iterator (drflac_vorbis_comment_iterator* pIter, uint commentCount, const(char)* pComments) {
3005   if (pIter is null) return;
3006   pIter.countRemaining = commentCount;
3007   pIter.pRunningData   = pComments;
3008 }
3009 
3010 public const(char)* drflac_next_vorbis_comment (drflac_vorbis_comment_iterator* pIter, uint* pCommentLengthOut) {
3011   // Safety.
3012   if (pCommentLengthOut) *pCommentLengthOut = 0;
3013 
3014   if (pIter is null || pIter.countRemaining == 0 || pIter.pRunningData is null) return null;
3015 
3016   uint length = drflac__le2host_32(*cast(uint*)pIter.pRunningData);
3017   pIter.pRunningData += 4;
3018 
3019   const(char)* pComment = pIter.pRunningData;
3020   pIter.pRunningData += length;
3021   pIter.countRemaining -= 1;
3022 
3023   if (pCommentLengthOut) *pCommentLengthOut = length;
3024   return pComment;
3025 }
3026 
3027 
3028 public long drflac_vorbis_comment_size (uint commentCount, const(char)* pComments) {
3029   uint res = 0;
3030   while (commentCount-- > 0) {
3031     uint length = drflac__le2host_32(*cast(uint*)pComments);
3032     pComments += 4;
3033     pComments += length;
3034     res += length+4;
3035   }
3036   return res;
3037 }
3038 
3039 }
3040 
3041 // REVISION HISTORY
3042 //
3043 // v0.3d - 11/06/2016
3044 //   - Minor clean up.
3045 //
3046 // v0.3c - 28/05/2016
3047 //   - Fixed compilation error.
3048 //
3049 // v0.3b - 16/05/2016
3050 //   - Fixed Linux/GCC build.
3051 //   - Updated documentation.
3052 //
3053 // v0.3a - 15/05/2016
3054 //   - Minor fixes to documentation.
3055 //
3056 // v0.3 - 11/05/2016
3057 //   - Optimizations. Now at about parity with the reference implementation on 32-bit builds.
3058 //   - Lots of clean up.
3059 //
3060 // v0.2b - 10/05/2016
3061 //   - Bug fixes.
3062 //
3063 // v0.2a - 10/05/2016
3064 //   - Made drflac_open_and_decode() more robust.
3065 //   - Removed an unused debugging variable
3066 //
3067 // v0.2 - 09/05/2016
3068 //   - Added support for Ogg encapsulation.
3069 //   - API CHANGE. Have the onSeek callback take a third argument which specifies whether or not the seek
3070 //     should be relative to the start or the current position. Also changes the seeking rules such that
3071 //     seeking offsets will never be negative.
3072 //   - Have drflac_open_and_decode() fail gracefully if the stream has an unknown total sample count.
3073 //
3074 // v0.1b - 07/05/2016
3075 //   - Properly close the file handle in drflac_open_file() and family when the decoder fails to initialize.
3076 //   - Removed a stale comment.
3077 //
3078 // v0.1a - 05/05/2016
3079 //   - Minor formatting changes.
3080 //   - Fixed a warning on the GCC build.
3081 //
3082 // v0.1 - 03/05/2016
3083 //   - Initial versioned release.
3084 
3085 // TODO
3086 // - Add support for initializing the decoder without a header STREAMINFO block.
3087 // - Test CUESHEET metadata blocks.
3088 
3089 
3090 /*
3091 This is free and unencumbered software released into the public domain.
3092 
3093 Anyone is free to copy, modify, publish, use, compile, sell, or
3094 distribute this software, either in source code form or as a compiled
3095 binary, for any purpose, commercial or non-commercial, and by any
3096 means.
3097 
3098 In jurisdictions that recognize copyright laws, the author or authors
3099 of this software dedicate any and all copyright interest in the
3100 software to the public domain. We make this dedication for the benefit
3101 of the public at large and to the detriment of our heirs and
3102 successors. We intend this dedication to be an overt act of
3103 relinquishment in perpetuity of all present and future rights to this
3104 software under copyright law.
3105 
3106 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
3107 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
3108 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
3109 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
3110 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
3111 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
3112 OTHER DEALINGS IN THE SOFTWARE.
3113 
3114 For more information, please refer to <http://unlicense.org/>
3115 */