RetroArch
dr_flac.h
Go to the documentation of this file.
1 #ifndef dr_flac_h
2 #define dr_flac_h
3 
4 #define DR_FLAC_NO_STDIO
5 
6 #include <stdint.h>
7 #include <stddef.h>
8 #include <retro_inline.h>
9 
20 #define DRFLAC_TRUE 1
21 #define DRFLAC_FALSE 0
22 
23 /* As data is read from the client it is placed into an internal buffer for fast access. This controls the
24  * size of that buffer. Larger values means more speed, but also more memory. In my testing there is diminishing
25  * returns after about 4KB, but you can fiddle with this to suit your own needs. Must be a multiple of 8.
26  */
27 #ifndef DR_FLAC_BUFFER_SIZE
28 #define DR_FLAC_BUFFER_SIZE 4096
29 #endif
30 
31 #ifdef __cplusplus
32 extern "C" {
33 #endif
34 
35 /* Check if we can enable 64-bit optimizations. */
36 #if defined(_WIN64)
37 #define DRFLAC_64BIT
38 #endif
39 
40 #if defined(__GNUC__)
41 #if defined(__x86_64__) || defined(__ppc64__)
42 #define DRFLAC_64BIT
43 #endif
44 #endif
45 
46 #ifdef DRFLAC_64BIT
48 #else
50 #endif
51 
52 /* The various metadata block types. */
53 #define DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO 0
54 #define DRFLAC_METADATA_BLOCK_TYPE_PADDING 1
55 #define DRFLAC_METADATA_BLOCK_TYPE_APPLICATION 2
56 #define DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE 3
57 #define DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT 4
58 #define DRFLAC_METADATA_BLOCK_TYPE_CUESHEET 5
59 #define DRFLAC_METADATA_BLOCK_TYPE_PICTURE 6
60 #define DRFLAC_METADATA_BLOCK_TYPE_INVALID 127
61 
62 /* The various picture types specified in the PICTURE block. */
63 #define DRFLAC_PICTURE_TYPE_OTHER 0
64 #define DRFLAC_PICTURE_TYPE_FILE_ICON 1
65 #define DRFLAC_PICTURE_TYPE_OTHER_FILE_ICON 2
66 #define DRFLAC_PICTURE_TYPE_COVER_FRONT 3
67 #define DRFLAC_PICTURE_TYPE_COVER_BACK 4
68 #define DRFLAC_PICTURE_TYPE_LEAFLET_PAGE 5
69 #define DRFLAC_PICTURE_TYPE_MEDIA 6
70 #define DRFLAC_PICTURE_TYPE_LEAD_ARTIST 7
71 #define DRFLAC_PICTURE_TYPE_ARTIST 8
72 #define DRFLAC_PICTURE_TYPE_CONDUCTOR 9
73 #define DRFLAC_PICTURE_TYPE_BAND 10
74 #define DRFLAC_PICTURE_TYPE_COMPOSER 11
75 #define DRFLAC_PICTURE_TYPE_LYRICIST 12
76 #define DRFLAC_PICTURE_TYPE_RECORDING_LOCATION 13
77 #define DRFLAC_PICTURE_TYPE_DURING_RECORDING 14
78 #define DRFLAC_PICTURE_TYPE_DURING_PERFORMANCE 15
79 #define DRFLAC_PICTURE_TYPE_SCREEN_CAPTURE 16
80 #define DRFLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH 17
81 #define DRFLAC_PICTURE_TYPE_ILLUSTRATION 18
82 #define DRFLAC_PICTURE_TYPE_BAND_LOGOTYPE 19
83 #define DRFLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE 20
84 
85 typedef enum
86 {
91 
92 typedef enum
93 {
97 
98 /* Packing is important on this structure because we map this directly to the raw data within the SEEKTABLE metadata block. */
99 #pragma pack(2)
100 typedef struct
101 {
103  drflac_uint64 frameOffset; /* The offset from the first byte of the header of the first frame. */
106 #pragma pack()
107 
108 typedef struct
109 {
120 
121 typedef struct
122 {
123  /* The metadata type. Use this to know how to interpret the data below. */
125 
126  /* A pointer to the raw data. This points to a temporary buffer so don't hold on to it. It's best to
127  * not modify the contents of this buffer. Use the structures below for more meaningful and structured
128  * information about the metadata. It's possible for this to be null.
129  */
130  const void* pRawData;
131 
132  /* The size in bytes of the block and the buffer pointed to by pRawData if it's non-NULL. */
134 
135  union
136  {
138 
139  struct
140  {
141  int unused;
142  } padding;
143 
144  struct
145  {
147  const void* pData;
149  } application;
150 
151  struct
152  {
155  } seektable;
156 
157  struct
158  {
160  const char* vendor;
162  const char* comments;
163  } vorbis_comment;
164 
165  struct
166  {
167  char catalog[128];
172  } cuesheet;
173 
174  struct
175  {
178  const char* mime;
180  const char* description;
187  } picture;
188  } data;
190 
191 
192 /* Callback for when data needs to be read from the client.
193  *
194  * pUserData [in] The user data that was passed to drflac_open() and family.
195  * pBufferOut [out] The output buffer.
196  * bytesToRead [in] The number of bytes to read.
197  *
198  * Returns the number of bytes actually read.
199  *
200  * A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until
201  * either the entire bytesToRead is filled or you have reached the end of the stream.
202  */
203 typedef size_t (* drflac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
204 
205 /* Callback for when data needs to be seeked.
206  *
207  * pUserData [in] The user data that was passed to drflac_open() and family.
208  * offset [in] The number of bytes to move, relative to the origin. Will never be negative.
209  * origin [in] The origin of the seek - the current position or the start of the stream.
210  *
211  * Returns whether or not the seek was successful.
212  *
213  * The offset will never be negative. Whether or not it is relative to the beginning or current position is determined
214  * by the "origin" parameter which will be either drflac_seek_origin_start or drflac_seek_origin_current.
215  */
216 typedef drflac_bool32 (* drflac_seek_proc)(void* pUserData, int offset, drflac_seek_origin origin);
217 
218 /* Callback for when a metadata block is read.
219  *
220  * pUserData [in] The user data that was passed to drflac_open() and family.
221  * pMetadata [in] A pointer to a structure containing the data of the metadata block.
222  *
223  * Use pMetadata->type to determine which metadata block is being handled and how to read the data.
224  */
225 typedef void (* drflac_meta_proc)(void* pUserData, drflac_metadata* pMetadata);
226 
227 
228 /* Structure for internal use. Only used for decoders opened with drflac_open_memory. */
229 typedef struct
230 {
232  size_t dataSize;
235 
236 /* Structure for internal use. Used for bit streaming. */
237 typedef struct
238 {
239  /* The function to call when more data needs to be read. */
241 
242  /* The function to call when the current read position needs to be moved. */
244 
245  /* The user data to pass around to onRead and onSeek. */
246  void* pUserData;
247 
248 
249  /* 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
250  * 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
251  * or not the bistreamer needs to run on a slower path to read those last bytes. This will never be more than sizeof(drflac_cache_t).
252  */
254 
255  /* The content of the unaligned bytes. */
257 
258  /* The index of the next valid cache line in the "L2" cache. */
260 
261  /* The number of bits that have been consumed by the cache. This is used to determine how many valid bits are remaining. */
263 
264  /* The cached data which was most recently read from the client. There are two levels of cache. Data flows as such:
265  * Client -> L2 -> L1. The L2 -> L1 movement is aligned and runs on a fast path in just a few instructions. */
268 
269  /* CRC-16. This is updated whenever bits are read from the bit stream. Manually set this to 0 to reset the CRC. For FLAC, this
270  * is reset to 0 at the beginning of each frame. */
272  drflac_cache_t crc16Cache; /* A cache for optimizing CRC calculations. This is filled when when the L1 cache is reloaded. */
273  drflac_uint32 crc16CacheIgnoredBytes; /* The number of bytes to ignore when updating the CRC-16 from the CRC-16 cache. */
274 } drflac_bs;
275 
276 typedef struct
277 {
278  /* The type of the subframe: SUBFRAME_CONSTANT, SUBFRAME_VERBATIM, SUBFRAME_FIXED or SUBFRAME_LPC. */
280 
281  /* The number of wasted bits per sample as specified by the sub-frame header. */
283 
284  /* The order to use for the prediction stage for SUBFRAME_FIXED and SUBFRAME_LPC. */
286 
287  /* The number of bits per sample for this subframe. This is not always equal to the current frame's bit per sample because
288  * an extra bit is required for side channels when interchannel decorrelation is being used. */
290 
291  /* A pointer to the buffer containing the decoded samples in the subframe. This pointer is an offset from drflac::pExtraData. Note that
292  * it's a signed 32-bit integer for each value. */
295 
296 typedef struct
297 {
298  /* 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
299  * always be set to 0. */
301 
302  /* 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. */
304 
305  /* The sample rate of this frame. */
307 
308  /* The number of samples in each sub-frame within this frame. */
310 
311  /* The channel assignment of this frame. This is not always set to the channel count. If interchannel decorrelation is being used this
312  * will be set to DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE, DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE or DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE. */
314 
315  /* The number of bits per sample within this frame. */
317 
318  /* The frame's CRC. */
321 
322 typedef struct
323 {
324  /* The header. */
326 
327  /* 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
328  * are read, this will be decremented. When it reaches 0, the decoder will see this frame as fully consumed and load the next frame.
329  */
331 
332  /* The list of sub-frames within the frame. There is one sub-frame for each channel, and there's a maximum of 8 channels. */
333  drflac_subframe subframes[8];
334 } drflac_frame;
335 
336 typedef struct
337 {
338  /* The function to call when a metadata block is read. */
340 
341  /* The user data posted to the metadata callback function. */
342  void* pUserDataMD;
343 
344 
345  /* The sample rate. Will be set to something like 44100. */
347 
348  /* 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
349  * value specified in the STREAMINFO block. */
351 
352  /* The bits per sample. Will be set to somthing like 16, 24, etc. */
354 
355  /* The maximum block size, in samples. This number represents the number of samples in each channel (not combined). */
357 
358  /* The total number of samples making up the stream. This includes every channel. For example, if the stream has 2 channels,
359  * 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
360  * valid stream, but just means the total sample count is unknown. Likely the case with streams like internet radio. */
362 
363 
364  /* The container type. This is set based on whether or not the decoder was opened from a native or Ogg stream. */
366 
367  /* The position of the seektable in the file. */
369 
370  /* The size of the seektable. */
372 
373 
374  /* Information about the frame the decoder is currently sitting on. */
376 
377  /* The position of the first frame in the stream. This is only ever used for seeking. */
379 
380 
381  /* A hack to avoid a malloc() when opening a decoder with drflac_open_memory(). */
383 
384 
385  /* A pointer to the decoded sample data. This is an offset of pExtraData. */
387 
388  /* Internal use only. Only used with Ogg containers. Points to a drflac_oggbs object. This is an offset of pExtraData. */
389  void* _oggbs;
390 
391  /* The bit streamer. The raw FLAC data is fed through this object. */
393 
394  /* Variable length extra data. We attach this to the end of the object so we can avoid unnecessary mallocs. */
395  drflac_uint8 pExtraData[1];
396 } drflac;
397 
398 
399 /* Opens a FLAC decoder.
400  *
401  * onRead [in] The function to call when data needs to be read from the client.
402  * onSeek [in] The function to call when the read position of the client data needs to move.
403  * pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek.
404  *
405  * Returns a pointer to an object representing the decoder.
406  *
407  * Close the decoder with drflac_close().
408  *
409  * This function will automatically detect whether or not you are attempting to open a native or Ogg encapsulated
410  * FLAC, both of which should work seamlessly without any manual intervention. Ogg encapsulation also works with
411  * multiplexed streams which basically means it can play FLAC encoded audio tracks in videos.
412  *
413  * This is the lowest level function for opening a FLAC stream. You can also use drflac_open_file() and drflac_open_memory()
414  * to open the stream from a file or from a block of memory respectively.
415  *
416  * The STREAMINFO block must be present for this to succeed. Use drflac_open_relaxed() to open a FLAC stream where
417  * the header may not be present.
418  *
419  * See also: drflac_open_file(), drflac_open_memory(), drflac_open_with_metadata(), drflac_close()
420  */
421 drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData);
422 
423 /* The same as drflac_open(), except attempts to open the stream even when a header block is not present.
424  *
425  * Because the header is not necessarily available, the caller must explicitly define the container (Native or Ogg). Do
426  * not set this to drflac_container_unknown - that is for internal use only.
427  *
428  * Opening in relaxed mode will continue reading data from onRead until it finds a valid frame. If a frame is never
429  * found it will continue forever. To abort, force your onRead callback to return 0, which dr_flac will use as an
430  * indicator that the end of the stream was found. */
431 drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData);
432 
433 /* Opens a FLAC decoder and notifies the caller of the metadata chunks (album art, etc.).
434  *
435  * onRead [in] The function to call when data needs to be read from the client.
436  * onSeek [in] The function to call when the read position of the client data needs to move.
437  * onMeta [in] The function to call for every metadata block.
438  * pUserData [in, optional] A pointer to application defined data that will be passed to onRead, onSeek and onMeta.
439  *
440  * Returns a pointer to an object representing the decoder.
441  *
442  * Close the decoder with drflac_close().
443  *
444  * This is slower than drflac_open(), so avoid this one if you don't need metadata. Internally, this will do a DRFLAC_MALLOC()
445  * and DRFLAC_FREE() for every metadata block except for STREAMINFO and PADDING blocks.
446  *
447  * The caller is notified of the metadata via the onMeta callback. All metadata blocks will be handled before the function
448  * returns.
449  *
450  * The STREAMINFO block must be present for this to succeed. Use drflac_open_with_metadata_relaxed() to open a FLAC
451  * stream where the header may not be present.
452  *
453  * Note that this will behave inconsistently with drflac_open() if the stream is an Ogg encapsulated stream and a metadata
454  * block is corrupted. This is due to the way the Ogg stream recovers from corrupted pages. When drflac_open_with_metadata()
455  * is being used, the open routine will try to read the contents of the metadata block, whereas drflac_open() will simply
456  * seek past it (for the sake of efficiency). This inconsistency can result in different samples being returned depending on
457  * whether or not the stream is being opened with metadata.
458  *
459  * See also: drflac_open_file_with_metadata(), drflac_open_memory_with_metadata(), drflac_open(), drflac_close()
460  */
461 drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData);
462 
463 /* The same as drflac_open_with_metadata(), except attemps to open the stream even when a header block is not present.
464  *
465  * See also: drflac_open_with_metadata(), drflac_open_relaxed()
466  */
468 
469 /* Closes the given FLAC decoder.
470  *
471  * pFlac [in] The decoder to close.
472  *
473  * This will destroy the decoder object. */
474 void drflac_close(drflac* pFlac);
475 
476 
477 /* Reads sample data from the given FLAC decoder, output as interleaved signed 32-bit PCM.
478  *
479  * pFlac [in] The decoder.
480  * samplesToRead [in] The number of samples to read.
481  * pBufferOut [out, optional] A pointer to the buffer that will receive the decoded samples.
482  *
483  * Returns the number of samples actually read.
484  *
485  * pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of samples
486  * seeked. */
487 drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int32* pBufferOut);
488 
489 /* Same as drflac_read_s32(), except outputs samples as 16-bit integer PCM rather than 32-bit.
490  *
491  * pFlac [in] The decoder.
492  * samplesToRead [in] The number of samples to read.
493  * pBufferOut [out, optional] A pointer to the buffer that will receive the decoded samples.
494  *
495  * Returns the number of samples actually read.
496  *
497  * pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of samples
498  * seeked.
499  *
500  * Note that this is lossy for streams where the bits per sample is larger than 16.
501  */
502 drflac_uint64 drflac_read_s16(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int16* pBufferOut);
503 
504 /* Same as drflac_read_s32(), except outputs samples as 32-bit floating-point PCM.
505  *
506  * pFlac [in] The decoder.
507  * samplesToRead [in] The number of samples to read.
508  * pBufferOut [out, optional] A pointer to the buffer that will receive the decoded samples.
509  *
510  * Returns the number of samples actually read.
511  *
512  * pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of samples
513  * seeked.
514  *
515  * Note that this should be considered lossy due to the nature of floating point numbers not being able to exactly
516  * represent every possible number.
517  */
518 drflac_uint64 drflac_read_f32(drflac* pFlac, drflac_uint64 samplesToRead, float* pBufferOut);
519 
520 /* Seeks to the sample at the given index.
521  *
522  * pFlac [in] The decoder.
523  * sampleIndex [in] The index of the sample to seek to. See notes below.
524  *
525  * Returns DRFLAC_TRUE if successful; DRFLAC_FALSE otherwise.
526  *
527  * The sample index is based on interleaving. In a stereo stream, for example, the sample at index 0 is the first sample
528  * in the left channel; the sample at index 1 is the first sample on the right channel, and so on.
529  *
530  * When seeking, you will likely want to ensure it's rounded to a multiple of the channel count. You can do this with
531  * something like drflac_seek_to_sample(pFlac, (mySampleIndex + (mySampleIndex % pFlac->channels)))
532  */
534 
535 
536 
537 #ifndef DR_FLAC_NO_STDIO
538 /* Opens a FLAC decoder from the file at the given path.
539  *
540  * filename [in] The path of the file to open, either absolute or relative to the current directory.
541  *
542  * Returns a pointer to an object representing the decoder.
543  *
544  * Close the decoder with drflac_close().
545  *
546  * This will hold a handle to the file until the decoder is closed with drflac_close(). Some platforms will restrict the
547  * number of files a process can have open at any given time, so keep this mind if you have many decoders open at the
548  * same time.
549  *
550  * See also: drflac_open(), drflac_open_file_with_metadata(), drflac_close()
551  */
552 drflac* drflac_open_file(const char* filename);
553 
554 /* Opens a FLAC decoder from the file at the given path and notifies the caller of the metadata chunks (album art, etc.)
555  *
556  * Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
557  */
558 drflac* drflac_open_file_with_metadata(const char* filename, drflac_meta_proc onMeta, void* pUserData);
559 #endif
560 
561 /* Opens a FLAC decoder from a pre-allocated block of memory
562  *
563  * This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for
564  * the lifetime of the decoder.
565  */
566 drflac* drflac_open_memory(const void* data, size_t dataSize);
567 
568 /* Opens a FLAC decoder from a pre-allocated block of memory and notifies the caller of the metadata chunks (album art, etc.)
569  *
570  * Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
571  */
572 drflac* drflac_open_memory_with_metadata(const void* data, size_t dataSize, drflac_meta_proc onMeta, void* pUserData);
573 
574 /* High Level APIs */
575 
576 /* Opens a FLAC stream from the given callbacks and fully decodes it in a single operation. The return value is a
577  * pointer to the sample data as interleaved signed 32-bit PCM. The returned data must be freed with DRFLAC_FREE().
578  *
579  * Sometimes a FLAC file won't keep track of the total sample count. In this situation the function will continuously
580  * read samples into a dynamically sized buffer on the heap until no samples are left.
581  *
582  * Do not call this function on a broadcast type of stream (like internet radio streams and whatnot).
583  */
584 drflac_int32* drflac_open_and_decode_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
585 
586 /* Same as drflac_open_and_decode_s32(), except returns signed 16-bit integer samples. */
587 drflac_int16* drflac_open_and_decode_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
588 
589 /* Same as drflac_open_and_decode_s32(), except returns 32-bit floating-point samples. */
590 float* drflac_open_and_decode_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
591 
592 #ifndef DR_FLAC_NO_STDIO
593 /* Same as drflac_open_and_decode_s32() except opens the decoder from a file. */
594 drflac_int32* drflac_open_and_decode_file_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
595 
596 /* Same as drflac_open_and_decode_file_s32(), except returns signed 16-bit integer samples. */
597 drflac_int16* drflac_open_and_decode_file_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
598 
599 /* Same as drflac_open_and_decode_file_f32(), except returns 32-bit floating-point samples. */
600 float* drflac_open_and_decode_file_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
601 #endif
602 
603 /* Same as drflac_open_and_decode_s32() except opens the decoder from a block of memory. */
604 drflac_int32* drflac_open_and_decode_memory_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
605 
606 /* Same as drflac_open_and_decode_memory_s32(), except returns signed 16-bit integer samples. */
607 drflac_int16* drflac_open_and_decode_memory_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
608 
609 /* Same as drflac_open_and_decode_memory_s32(), except returns 32-bit floating-point samples. */
610 float* drflac_open_and_decode_memory_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount);
611 
612 /* Frees memory that was allocated internally by dr_flac. */
613 void drflac_free(void* p);
614 
615 
616 /* Structure representing an iterator for vorbis comments in a VORBIS_COMMENT metadata block. */
617 typedef struct
618 {
620  const char* pRunningData;
622 
623 /* Initializes a vorbis comment iterator. This can be used for iterating over the vorbis comments in a VORBIS_COMMENT
624  * metadata block. */
625 void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const char* pComments);
626 
627 /* Goes to the next vorbis comment in the given iterator. If null is returned it means there are no more comments. The
628  * returned string is NOT null terminated. */
629 const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut);
630 
631 
632 
633 #ifdef __cplusplus
634 }
635 #endif
636 #endif /* dr_flac_h */
637 
638 
639 /*
640  *
641  * IMPLEMENTATION
642  *
643  */
644 #ifdef DR_FLAC_IMPLEMENTATION
645 #include <stdlib.h>
646 #include <string.h>
647 
648 /* CPU architecture. */
649 #if defined(__x86_64__) || defined(_M_X64)
650 #define DRFLAC_X64
651 #elif defined(__i386) || defined(_M_IX86)
652 #define DRFLAC_X86
653 #elif defined(__arm__) || defined(_M_ARM)
654 #define DRFLAC_ARM
655 #endif
656 
657 /* Compile-time CPU feature support. */
658 #if !defined(DR_FLAC_NO_SIMD) && (defined(DRFLAC_X86) || defined(DRFLAC_X64))
659  #if defined(_MSC_VER) && !defined(__clang__)
660  #if _MSC_VER >= 1400
661  #include <intrin.h>
662  static void drflac__cpuid(int info[4], int fid)
663  {
664  __cpuid(info, fid);
665  }
666  #else
667  #define DRFLAC_NO_CPUID
668  #endif
669  #else
670  #if defined(__GNUC__) || defined(__clang__)
671  static void drflac__cpuid(int info[4], int fid)
672  {
673  __asm__ __volatile__ (
674  "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
675  );
676  }
677  #else
678  #define DRFLAC_NO_CPUID
679  #endif
680  #endif
681 #else
682 #define DRFLAC_NO_CPUID
683 #endif
684 
685 
686 #ifdef __linux__
687 #define _BSD_SOURCE
688 #include <endian.h>
689 #endif
690 
691 #if defined(_MSC_VER) && _MSC_VER >= 1500 && (defined(DRFLAC_X86) || defined(DRFLAC_X64))
692 #define DRFLAC_HAS_LZCNT_INTRINSIC
693 #elif (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
694 #define DRFLAC_HAS_LZCNT_INTRINSIC
695 #elif defined(__clang__)
696  #if __has_builtin(__builtin_clzll) || __has_builtin(__builtin_clzl)
697  #define DRFLAC_HAS_LZCNT_INTRINSIC
698  #endif
699 #endif
700 
701 #if defined(_MSC_VER) && _MSC_VER >= 1300
702 #define DRFLAC_HAS_BYTESWAP_INTRINSIC
703 #elif defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
704 #define DRFLAC_HAS_BYTESWAP_INTRINSIC
705 #elif defined(__clang__)
706  #if __has_builtin(__builtin_bswap16) && __has_builtin(__builtin_bswap32) && __has_builtin(__builtin_bswap64)
707  #define DRFLAC_HAS_BYTESWAP_INTRINSIC
708  #endif
709 #endif
710 
711 /* Standard library stuff. */
712 #ifndef DRFLAC_ASSERT
713 #include <assert.h>
714 #define DRFLAC_ASSERT(expression) assert(expression)
715 #endif
716 #ifndef DRFLAC_MALLOC
717 #define DRFLAC_MALLOC(sz) malloc((sz))
718 #endif
719 #ifndef DRFLAC_REALLOC
720 #define DRFLAC_REALLOC(p, sz) realloc((p), (sz))
721 #endif
722 #ifndef DRFLAC_FREE
723 #define DRFLAC_FREE(p) free((p))
724 #endif
725 #ifndef DRFLAC_COPY_MEMORY
726 #define DRFLAC_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
727 #endif
728 #ifndef DRFLAC_ZERO_MEMORY
729 #define DRFLAC_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
730 #endif
731 
732 #define DRFLAC_MAX_SIMD_VECTOR_SIZE 64 /* 64 for AVX-512 in the future. */
733 
734 #ifdef _MSC_VER
735 #define DRFLAC_INLINE __forceinline
736 #else
737 #ifdef __GNUC__
738 #define DRFLAC_INLINE INLINE __attribute__((always_inline))
739 #else
740 #define DRFLAC_INLINE INLINE
741 #endif
742 #endif
743 
744 typedef drflac_int32 drflac_result;
745 #define DRFLAC_SUCCESS 0
746 #define DRFLAC_ERROR -1 /* A generic error. */
747 #define DRFLAC_INVALID_ARGS -2
748 #define DRFLAC_END_OF_STREAM -128
749 #define DRFLAC_CRC_MISMATCH -129
750 
751 #define DRFLAC_SUBFRAME_CONSTANT 0
752 #define DRFLAC_SUBFRAME_VERBATIM 1
753 #define DRFLAC_SUBFRAME_FIXED 8
754 #define DRFLAC_SUBFRAME_LPC 32
755 #define DRFLAC_SUBFRAME_RESERVED 255
756 
757 #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE 0
758 #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 1
759 
760 #define DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT 0
761 #define DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE 8
762 #define DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE 9
763 #define DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE 10
764 
765 
766 #define drflac_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
767 #define drflac_assert DRFLAC_ASSERT
768 #define drflac_copy_memory DRFLAC_COPY_MEMORY
769 #define drflac_zero_memory DRFLAC_ZERO_MEMORY
770 
771 /* CPU caps. */
772 static drflac_bool32 drflac__gIsLZCNTSupported = DRFLAC_FALSE;
773 #ifndef DRFLAC_NO_CPUID
774 static drflac_bool32 drflac__gIsSSE42Supported = DRFLAC_FALSE;
775 static void drflac__init_cpu_caps()
776 {
777  int info[4] = {0};
778 
779  /* LZCNT */
780  drflac__cpuid(info, 0x80000001);
781  drflac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0;
782 
783  /* SSE4.2 */
784  drflac__cpuid(info, 1);
785  drflac__gIsSSE42Supported = (info[2] & (1 << 19)) != 0;
786 }
787 #endif
788 
789 
790 /* Endian Management */
791 static DRFLAC_INLINE drflac_bool32 drflac__is_little_endian()
792 {
793 #if defined(DRFLAC_X86) || defined(DRFLAC_X64)
794  return DRFLAC_TRUE;
795 #else
796  int n = 1;
797  return (*(char*)&n) == 1;
798 #endif
799 }
800 
801 static DRFLAC_INLINE drflac_uint16 drflac__swap_endian_uint16(drflac_uint16 n)
802 {
803 #ifdef DRFLAC_HAS_BYTESWAP_INTRINSIC
804  #if defined(_MSC_VER)
805  return _byteswap_ushort(n);
806  #elif defined(__GNUC__) || defined(__clang__)
807  return __builtin_bswap16(n);
808  #else
809  #error "This compiler does not support the byte swap intrinsic."
810  #endif
811 #else
812  return ((n & 0xFF00) >> 8) |
813  ((n & 0x00FF) << 8);
814 #endif
815 }
816 
817 static DRFLAC_INLINE drflac_uint32 drflac__swap_endian_uint32(drflac_uint32 n)
818 {
819 #ifdef DRFLAC_HAS_BYTESWAP_INTRINSIC
820  #if defined(_MSC_VER)
821  return _byteswap_ulong(n);
822  #elif defined(__GNUC__) || defined(__clang__)
823  return __builtin_bswap32(n);
824  #else
825  #error "This compiler does not support the byte swap intrinsic."
826  #endif
827 #else
828  return ((n & 0xFF000000) >> 24) |
829  ((n & 0x00FF0000) >> 8) |
830  ((n & 0x0000FF00) << 8) |
831  ((n & 0x000000FF) << 24);
832 #endif
833 }
834 
835 static DRFLAC_INLINE drflac_uint64 drflac__swap_endian_uint64(drflac_uint64 n)
836 {
837 #ifdef DRFLAC_HAS_BYTESWAP_INTRINSIC
838  #if defined(_MSC_VER)
839  return _byteswap_uint64(n);
840  #elif defined(__GNUC__) || defined(__clang__)
841  return __builtin_bswap64(n);
842  #else
843  #error "This compiler does not support the byte swap intrinsic."
844  #endif
845 #else
846  return ((n & (drflac_uint64)0xFF00000000000000) >> 56) |
847  ((n & (drflac_uint64)0x00FF000000000000) >> 40) |
848  ((n & (drflac_uint64)0x0000FF0000000000) >> 24) |
849  ((n & (drflac_uint64)0x000000FF00000000) >> 8) |
850  ((n & (drflac_uint64)0x00000000FF000000) << 8) |
851  ((n & (drflac_uint64)0x0000000000FF0000) << 24) |
852  ((n & (drflac_uint64)0x000000000000FF00) << 40) |
853  ((n & (drflac_uint64)0x00000000000000FF) << 56);
854 #endif
855 }
856 
857 
858 static DRFLAC_INLINE drflac_uint16 drflac__be2host_16(drflac_uint16 n)
859 {
860 #ifdef __linux__
861  return be16toh(n);
862 #else
863  if (drflac__is_little_endian())
864  return drflac__swap_endian_uint16(n);
865 
866  return n;
867 #endif
868 }
869 
870 static DRFLAC_INLINE drflac_uint32 drflac__be2host_32(drflac_uint32 n)
871 {
872 #ifdef __linux__
873  return be32toh(n);
874 #else
875  if (drflac__is_little_endian())
876  return drflac__swap_endian_uint32(n);
877 
878  return n;
879 #endif
880 }
881 
882 static DRFLAC_INLINE drflac_uint64 drflac__be2host_64(drflac_uint64 n)
883 {
884 #ifdef __linux__
885  return be64toh(n);
886 #else
887  if (drflac__is_little_endian())
888  return drflac__swap_endian_uint64(n);
889 
890  return n;
891 #endif
892 }
893 
894 
895 static DRFLAC_INLINE drflac_uint32 drflac__le2host_32(drflac_uint32 n)
896 {
897 #ifdef __linux__
898  return le32toh(n);
899 #else
900  if (!drflac__is_little_endian())
901  return drflac__swap_endian_uint32(n);
902 
903  return n;
904 #endif
905 }
906 
907 
908 static DRFLAC_INLINE drflac_uint32 drflac__unsynchsafe_32(drflac_uint32 n)
909 {
910  drflac_uint32 result = 0;
911  result |= (n & 0x7F000000) >> 3;
912  result |= (n & 0x007F0000) >> 2;
913  result |= (n & 0x00007F00) >> 1;
914  result |= (n & 0x0000007F) >> 0;
915 
916  return result;
917 }
918 
919 /* The CRC code below is based on this document: http://zlib.net/crc_v3.txt */
920 static drflac_uint8 drflac__crc8_table[] = {
921  0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
922  0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
923  0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
924  0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
925  0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
926  0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
927  0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
928  0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
929  0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
930  0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
931  0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
932  0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
933  0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
934  0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
935  0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
936  0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
937 };
938 
939 static drflac_uint16 drflac__crc16_table[] = {
940  0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
941  0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022,
942  0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072,
943  0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041,
944  0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2,
945  0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1,
946  0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1,
947  0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
948  0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192,
949  0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1,
950  0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1,
951  0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2,
952  0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151,
953  0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162,
954  0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132,
955  0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101,
956  0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312,
957  0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
958  0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371,
959  0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342,
960  0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1,
961  0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
962  0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2,
963  0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381,
964  0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291,
965  0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2,
966  0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2,
967  0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1,
968  0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252,
969  0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261,
970  0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231,
971  0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202
972 };
973 
974 static DRFLAC_INLINE drflac_uint8 drflac_crc8_byte(drflac_uint8 crc, drflac_uint8 data)
975 {
976  return drflac__crc8_table[crc ^ data];
977 }
978 
979 static DRFLAC_INLINE drflac_uint8 drflac_crc8(drflac_uint8 crc, drflac_uint32 data, drflac_uint32 count)
980 {
981 
982 #ifdef DR_FLAC_NO_CRC
983  (void)crc;
984  (void)data;
985  (void)count;
986  drflac_assert(count <= 32);
987  return 0;
988 #else
989 #if 0
990  /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc8(crc, 0, 8);") */
991  drflac_uint8 p = 0x07;
992  for (int i = count-1; i >= 0; --i)
993  {
994  drflac_uint8 bit = (data & (1 << i)) >> i;
995  if (crc & 0x80)
996  crc = ((crc << 1) | bit) ^ p;
997  else
998  crc = ((crc << 1) | bit);
999  }
1000  return crc;
1001 #else
1002  static drflac_uint64 leftoverDataMaskTable[8] = {
1003  0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
1004  };
1005  drflac_uint32 wholeBytes = count >> 3;
1006  drflac_uint32 leftoverBits = count - (wholeBytes*8);
1007  drflac_uint64 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
1008  drflac_assert(count <= 32);
1009 
1010  switch (wholeBytes)
1011  {
1012  case 4: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
1013  case 3: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
1014  case 2: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
1015  case 1: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
1016  case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc8_table[(crc >> (8 - leftoverBits)) ^ (data & leftoverDataMask)];
1017  }
1018  return crc;
1019 #endif
1020 #endif
1021 }
1022 
1023 static DRFLAC_INLINE drflac_uint16 drflac_crc16_byte(drflac_uint16 crc, drflac_uint8 data)
1024 {
1025  return (crc << 8) ^ drflac__crc16_table[(drflac_uint8)(crc >> 8) ^ data];
1026 }
1027 
1028 static DRFLAC_INLINE drflac_uint16 drflac_crc16_bytes(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 byteCount)
1029 {
1030  switch (byteCount)
1031  {
1032 #ifdef DRFLAC_64BIT
1033  case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
1034  case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
1035  case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
1036  case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
1037 #endif
1038  case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
1039  case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
1040  case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF));
1041  case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF));
1042  }
1043 
1044  return crc;
1045 }
1046 
1047 static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac_uint32 data, drflac_uint32 count)
1048 {
1049 
1050 #ifdef DR_FLAC_NO_CRC
1051  (void)crc;
1052  (void)data;
1053  (void)count;
1054  drflac_assert(count <= 64);
1055  return 0;
1056 #else
1057 #if 0
1058  /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc16(crc, 0, 16);") */
1059  drflac_uint16 p = 0x8005;
1060  for (int i = count-1; i >= 0; --i)
1061  {
1062  drflac_uint16 bit = (data & (1ULL << i)) >> i;
1063  if (r & 0x8000)
1064  r = ((r << 1) | bit) ^ p;
1065  else
1066  r = ((r << 1) | bit);
1067  }
1068 
1069  return crc;
1070 #else
1071  drflac_uint32 wholeBytes = count >> 3;
1072  drflac_uint32 leftoverBits = count - (wholeBytes*8);
1073 
1074  static drflac_uint64 leftoverDataMaskTable[8] = {
1075  0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
1076  };
1077  drflac_uint64 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
1078 
1079  drflac_assert(count <= 64);
1080 
1081  switch (wholeBytes)
1082  {
1083  default:
1084  case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
1085  case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
1086  case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
1087  case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
1088  case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
1089  }
1090  return crc;
1091 #endif
1092 #endif
1093 }
1094 
1095 static DRFLAC_INLINE drflac_uint16 drflac_crc16__64bit(drflac_uint16 crc, drflac_uint64 data, drflac_uint32 count)
1096 {
1097 
1098 #ifdef DR_FLAC_NO_CRC
1099  (void)crc;
1100  (void)data;
1101  (void)count;
1102  drflac_assert(count <= 64);
1103  return 0;
1104 #else
1105  drflac_uint32 wholeBytes = count >> 3;
1106  drflac_uint32 leftoverBits = count - (wholeBytes*8);
1107 
1108  static drflac_uint64 leftoverDataMaskTable[8] = {
1109  0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
1110  };
1111  drflac_uint64 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
1112 
1113  drflac_assert(count <= 64);
1114 
1115  switch (wholeBytes)
1116  {
1117  default:
1118  case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0xFF00000000000000 << leftoverBits)) >> (56 + leftoverBits)));
1119  case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x00FF000000000000 << leftoverBits)) >> (48 + leftoverBits)));
1120  case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x0000FF0000000000 << leftoverBits)) >> (40 + leftoverBits)));
1121  case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x000000FF00000000 << leftoverBits)) >> (32 + leftoverBits)));
1122  case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x00000000FF000000 << leftoverBits)) >> (24 + leftoverBits)));
1123  case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x0000000000FF0000 << leftoverBits)) >> (16 + leftoverBits)));
1124  case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x000000000000FF00 << leftoverBits)) >> ( 8 + leftoverBits)));
1125  case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & ((drflac_uint64)0x00000000000000FF << leftoverBits)) >> ( 0 + leftoverBits)));
1126  case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
1127  }
1128  return crc;
1129 #endif
1130 }
1131 
1132 
1133 static DRFLAC_INLINE drflac_uint16 drflac_crc16(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 count)
1134 {
1135 #ifdef DRFLAC_64BIT
1136  return drflac_crc16__64bit(crc, data, count);
1137 #else
1138  return drflac_crc16__32bit(crc, data, count);
1139 #endif
1140 }
1141 
1142 
1143 #ifdef DRFLAC_64BIT
1144 #define drflac__be2host__cache_line drflac__be2host_64
1145 #else
1146 #define drflac__be2host__cache_line drflac__be2host_32
1147 #endif
1148 
1149 /* BIT READING ATTEMPT #2
1150  *
1151  * 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
1152  * on the most significant bit. It uses the notion of an L1 and L2 cache (borrowed from CPU architecture), where the L1 cache
1153  * 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
1154  * 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
1155  * from onRead() is read into.
1156  */
1157 #define DRFLAC_CACHE_L1_SIZE_BYTES(bs) (sizeof((bs)->cache))
1158 #define DRFLAC_CACHE_L1_SIZE_BITS(bs) (sizeof((bs)->cache)*8)
1159 #define DRFLAC_CACHE_L1_BITS_REMAINING(bs) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - ((bs)->consumedBits))
1160 #ifdef DRFLAC_64BIT
1161 #define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~(((drflac_uint64)-1LL) >> (_bitCount)))
1162 #else
1163 #define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~(((drflac_uint32)-1) >> (_bitCount)))
1164 #endif
1165 #define DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount))
1166 #define DRFLAC_CACHE_L1_SELECT(bs, _bitCount) (((bs)->cache) & DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount))
1167 #define DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SELECT((bs), _bitCount) >> DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), _bitCount))
1168 #define DRFLAC_CACHE_L2_SIZE_BYTES(bs) (sizeof((bs)->cacheL2))
1169 #define DRFLAC_CACHE_L2_LINE_COUNT(bs) (DRFLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0]))
1170 #define DRFLAC_CACHE_L2_LINES_REMAINING(bs) (DRFLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line)
1171 
1172 
1173 #ifndef DR_FLAC_NO_CRC
1174 static DRFLAC_INLINE void drflac__reset_crc16(drflac_bs* bs)
1175 {
1176  bs->crc16 = 0;
1177  bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
1178 }
1179 
1180 static DRFLAC_INLINE void drflac__update_crc16(drflac_bs* bs)
1181 {
1182  bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache, DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bs->crc16CacheIgnoredBytes);
1183  bs->crc16CacheIgnoredBytes = 0;
1184 }
1185 
1186 static DRFLAC_INLINE drflac_uint16 drflac__flush_crc16(drflac_bs* bs)
1187 {
1188  /* We should never be flushing in a situation where we are not aligned on a byte boundary. */
1189  drflac_assert((DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7) == 0);
1190 
1191  /* The bits that were read from the L1 cache need to be accumulated. The number of bytes needing to be accumulated is determined
1192  * by the number of bits that have been consumed. */
1193  if (DRFLAC_CACHE_L1_BITS_REMAINING(bs) == 0)
1194  drflac__update_crc16(bs);
1195  else
1196  {
1197  /* We only accumulate the consumed bits. */
1198  bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache >> DRFLAC_CACHE_L1_BITS_REMAINING(bs), (bs->consumedBits >> 3) - bs->crc16CacheIgnoredBytes);
1199 
1200  /* The bits that we just accumulated should never be accumulated again. We need to keep track of how many bytes were accumulated
1201  * so we can handle that later. */
1202  bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
1203  }
1204 
1205  return bs->crc16;
1206 }
1207 #endif
1208 
1209 static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs)
1210 {
1211  size_t alignedL1LineCount;
1212  size_t bytesRead;
1213  /* Fast path. Try loading straight from L2. */
1214  if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs))
1215  {
1216  bs->cache = bs->cacheL2[bs->nextL2Line++];
1217  return DRFLAC_TRUE;
1218  }
1219 
1220  /* 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
1221  * any left. */
1222  if (bs->unalignedByteCount > 0)
1223  return DRFLAC_FALSE; /* If we have any unaligned bytes it means there's no more aligned bytes left in the client. */
1224 
1225  bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, DRFLAC_CACHE_L2_SIZE_BYTES(bs));
1226 
1227  bs->nextL2Line = 0;
1228  if (bytesRead == DRFLAC_CACHE_L2_SIZE_BYTES(bs))
1229  {
1230  bs->cache = bs->cacheL2[bs->nextL2Line++];
1231  return DRFLAC_TRUE;
1232  }
1233 
1234 
1235  /* If we get here it means we were unable to retrieve enough data to fill the entire L2 cache. It probably
1236  * means we've just reached the end of the file. We need to move the valid data down to the end of the buffer
1237  * and adjust the index of the next line accordingly. Also keep in mind that the L2 cache must be aligned to
1238  * the size of the L1 so we'll need to seek backwards by any misaligned bytes.
1239  */
1240  alignedL1LineCount = bytesRead / DRFLAC_CACHE_L1_SIZE_BYTES(bs);
1241 
1242  /* We need to keep track of any unaligned bytes for later use. */
1243  bs->unalignedByteCount = bytesRead - (alignedL1LineCount * DRFLAC_CACHE_L1_SIZE_BYTES(bs));
1244  if (bs->unalignedByteCount > 0)
1245  bs->unalignedCache = bs->cacheL2[alignedL1LineCount];
1246 
1247  if (alignedL1LineCount > 0)
1248  {
1249  size_t i;
1250  size_t offset = DRFLAC_CACHE_L2_LINE_COUNT(bs) - alignedL1LineCount;
1251  for (i = alignedL1LineCount; i > 0; --i)
1252  bs->cacheL2[i-1 + offset] = bs->cacheL2[i-1];
1253 
1255  bs->cache = bs->cacheL2[bs->nextL2Line++];
1256  return DRFLAC_TRUE;
1257  }
1258 
1259  /* If we get into this branch it means we weren't able to load any L1-aligned data. */
1260  bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs);
1261  return DRFLAC_FALSE;
1262 }
1263 
1264 static drflac_bool32 drflac__reload_cache(drflac_bs* bs)
1265 {
1266  size_t bytesRead;
1267 
1268 #ifndef DR_FLAC_NO_CRC
1269  drflac__update_crc16(bs);
1270 #endif
1271 
1272  /* Fast path. Try just moving the next value in the L2 cache to the L1 cache. */
1273  if (drflac__reload_l1_cache_from_l2(bs))
1274  {
1275  bs->cache = drflac__be2host__cache_line(bs->cache);
1276  bs->consumedBits = 0;
1277 #ifndef DR_FLAC_NO_CRC
1278  bs->crc16Cache = bs->cache;
1279 #endif
1280  return DRFLAC_TRUE;
1281  }
1282 
1283  /* Slow path. */
1284 
1285  /* 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
1286  * 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
1287  * data from the unaligned cache. */
1288  bytesRead = bs->unalignedByteCount;
1289  if (bytesRead == 0)
1290  return DRFLAC_FALSE;
1291 
1292  drflac_assert(bytesRead < DRFLAC_CACHE_L1_SIZE_BYTES(bs));
1293  bs->consumedBits = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bytesRead) * 8;
1294 
1295  bs->cache = drflac__be2host__cache_line(bs->unalignedCache);
1296  bs->cache &= DRFLAC_CACHE_L1_SELECTION_MASK(DRFLAC_CACHE_L1_SIZE_BITS(bs) - bs->consumedBits); /* <-- Make sure the consumed bits are always set to zero. Other parts of the library depend on this property. */
1297  bs->unalignedByteCount = 0; /* <-- At this point the unaligned bytes have been moved into the cache and we thus have no more unaligned bytes. */
1298 
1299 #ifndef DR_FLAC_NO_CRC
1300  bs->crc16Cache = bs->cache >> bs->consumedBits;
1301  bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
1302 #endif
1303  return DRFLAC_TRUE;
1304 }
1305 
1306 static void drflac__reset_cache(drflac_bs* bs)
1307 {
1308  bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs); /* <-- This clears the L2 cache. */
1309  bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); /* <-- This clears the L1 cache. */
1310  bs->cache = 0;
1311  bs->unalignedByteCount = 0; /* <-- This clears the trailing unaligned bytes. */
1312  bs->unalignedCache = 0;
1313 
1314 #ifndef DR_FLAC_NO_CRC
1315  bs->crc16Cache = 0;
1316  bs->crc16CacheIgnoredBytes = 0;
1317 #endif
1318 }
1319 
1320 
1321 static DRFLAC_INLINE drflac_bool32 drflac__read_uint32(drflac_bs* bs, unsigned int bitCount, drflac_uint32* pResultOut)
1322 {
1323  drflac_assert(bs != NULL);
1324  drflac_assert(pResultOut != NULL);
1325  drflac_assert(bitCount > 0);
1326  drflac_assert(bitCount <= 32);
1327 
1328  if (bs->consumedBits == DRFLAC_CACHE_L1_SIZE_BITS(bs))
1329  {
1330  if (!drflac__reload_cache(bs))
1331  return DRFLAC_FALSE;
1332  }
1333 
1334  if (bitCount <= DRFLAC_CACHE_L1_BITS_REMAINING(bs))
1335  {
1336  if (bitCount < DRFLAC_CACHE_L1_SIZE_BITS(bs))
1337  {
1338  *pResultOut = DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
1339  bs->consumedBits += bitCount;
1340  bs->cache <<= bitCount;
1341  } else {
1342  *pResultOut = (drflac_uint32)bs->cache;
1343  bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);
1344  bs->cache = 0;
1345  }
1346  return DRFLAC_TRUE;
1347  } else {
1348  /* 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. */
1349  drflac_uint32 bitCountHi = DRFLAC_CACHE_L1_BITS_REMAINING(bs);
1350  drflac_uint32 bitCountLo = bitCount - bitCountHi;
1351  drflac_uint32 resultHi = DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountHi);
1352 
1353  if (!drflac__reload_cache(bs))
1354  return DRFLAC_FALSE;
1355 
1356  *pResultOut = (resultHi << bitCountLo) | DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo);
1357  bs->consumedBits += bitCountLo;
1358  bs->cache <<= bitCountLo;
1359  return DRFLAC_TRUE;
1360  }
1361 }
1362 
1363 static drflac_bool32 drflac__read_int32(drflac_bs* bs, unsigned int bitCount, drflac_int32* pResult)
1364 {
1366  drflac_uint32 signbit;
1367 
1368  drflac_assert(bs != NULL);
1369  drflac_assert(pResult != NULL);
1370  drflac_assert(bitCount > 0);
1371  drflac_assert(bitCount <= 32);
1372 
1373  if (!drflac__read_uint32(bs, bitCount, &result))
1374  return DRFLAC_FALSE;
1375 
1376  signbit = ((result >> (bitCount-1)) & 0x01);
1377  result |= (~signbit + 1) << bitCount;
1378 
1379  *pResult = (drflac_int32)result;
1380  return DRFLAC_TRUE;
1381 }
1382 
1383 static drflac_bool32 drflac__read_uint64(drflac_bs* bs, unsigned int bitCount, drflac_uint64* pResultOut)
1384 {
1385  drflac_uint32 resultHi;
1386  drflac_uint32 resultLo;
1387 
1388  drflac_assert(bitCount <= 64);
1389  drflac_assert(bitCount > 32);
1390 
1391  if (!drflac__read_uint32(bs, bitCount - 32, &resultHi))
1392  return DRFLAC_FALSE;
1393 
1394  if (!drflac__read_uint32(bs, 32, &resultLo))
1395  return DRFLAC_FALSE;
1396 
1397  *pResultOut = (((drflac_uint64)resultHi) << 32) | ((drflac_uint64)resultLo);
1398  return DRFLAC_TRUE;
1399 }
1400 
1401 /* Function below is unused, but leaving it here in case I need to quickly add it again. */
1402 #if 0
1403 static drflac_bool32 drflac__read_int64(drflac_bs* bs, unsigned int bitCount, drflac_int64* pResultOut)
1404 {
1405  drflac_assert(bitCount <= 64);
1406 
1408  if (!drflac__read_uint64(bs, bitCount, &result))
1409  return DRFLAC_FALSE;
1410 
1411  drflac_uint64 signbit = ((result >> (bitCount-1)) & 0x01);
1412  result |= (~signbit + 1) << bitCount;
1413 
1414  *pResultOut = (drflac_int64)result;
1415  return DRFLAC_TRUE;
1416 }
1417 #endif
1418 
1419 static drflac_bool32 drflac__read_uint16(drflac_bs* bs, unsigned int bitCount, drflac_uint16* pResult)
1420 {
1422 
1423  drflac_assert(bs != NULL);
1424  drflac_assert(pResult != NULL);
1425  drflac_assert(bitCount > 0);
1426  drflac_assert(bitCount <= 16);
1427 
1428  if (!drflac__read_uint32(bs, bitCount, &result))
1429  return DRFLAC_FALSE;
1430 
1431  *pResult = (drflac_uint16)result;
1432  return DRFLAC_TRUE;
1433 }
1434 
1435 #if 0
1436 static drflac_bool32 drflac__read_int16(drflac_bs* bs, unsigned int bitCount, drflac_int16* pResult)
1437 {
1439 
1440  drflac_assert(bs != NULL);
1441  drflac_assert(pResult != NULL);
1442  drflac_assert(bitCount > 0);
1443  drflac_assert(bitCount <= 16);
1444 
1445  if (!drflac__read_int32(bs, bitCount, &result))
1446  return DRFLAC_FALSE;
1447 
1448  *pResult = (drflac_int16)result;
1449  return DRFLAC_TRUE;
1450 }
1451 #endif
1452 
1453 static drflac_bool32 drflac__read_uint8(drflac_bs* bs, unsigned int bitCount, drflac_uint8* pResult)
1454 {
1456 
1457  drflac_assert(bs != NULL);
1458  drflac_assert(pResult != NULL);
1459  drflac_assert(bitCount > 0);
1460  drflac_assert(bitCount <= 8);
1461 
1462  if (!drflac__read_uint32(bs, bitCount, &result))
1463  return DRFLAC_FALSE;
1464 
1465  *pResult = (drflac_uint8)result;
1466  return DRFLAC_TRUE;
1467 }
1468 
1469 static drflac_bool32 drflac__read_int8(drflac_bs* bs, unsigned int bitCount, drflac_int8* pResult)
1470 {
1472 
1473  drflac_assert(bs != NULL);
1474  drflac_assert(pResult != NULL);
1475  drflac_assert(bitCount > 0);
1476  drflac_assert(bitCount <= 8);
1477 
1478  if (!drflac__read_int32(bs, bitCount, &result))
1479  return DRFLAC_FALSE;
1480 
1481  *pResult = (drflac_int8)result;
1482  return DRFLAC_TRUE;
1483 }
1484 
1485 
1486 static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek)
1487 {
1488  if (bitsToSeek <= DRFLAC_CACHE_L1_BITS_REMAINING(bs))
1489  {
1490  bs->consumedBits += (drflac_uint32)bitsToSeek;
1491  bs->cache <<= bitsToSeek;
1492  return DRFLAC_TRUE;
1493  }
1494 
1495  /* It straddles the cached data. This function isn't called too frequently so I'm favouring simplicity here. */
1496  bitsToSeek -= DRFLAC_CACHE_L1_BITS_REMAINING(bs);
1497  bs->consumedBits += DRFLAC_CACHE_L1_BITS_REMAINING(bs);
1498  bs->cache = 0;
1499 
1500  /* Simple case. Seek in groups of the same number as bits that fit within a cache line. */
1501 #ifdef DRFLAC_64BIT
1502  while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs))
1503  {
1504  drflac_uint64 bin;
1505  if (!drflac__read_uint64(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin))
1506  return DRFLAC_FALSE;
1507  bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
1508  }
1509 #else
1510  while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs))
1511  {
1512  drflac_uint32 bin;
1513  if (!drflac__read_uint32(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin))
1514  return DRFLAC_FALSE;
1515  bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
1516  }
1517 #endif
1518 
1519  /* Whole leftover bytes. */
1520  while (bitsToSeek >= 8)
1521  {
1522  drflac_uint8 bin;
1523  if (!drflac__read_uint8(bs, 8, &bin))
1524  return DRFLAC_FALSE;
1525  bitsToSeek -= 8;
1526  }
1527 
1528  /* Leftover bits. */
1529  if (bitsToSeek > 0)
1530  {
1531  drflac_uint8 bin;
1532  if (!drflac__read_uint8(bs, (drflac_uint32)bitsToSeek, &bin))
1533  return DRFLAC_FALSE;
1534  bitsToSeek = 0; /* <-- Necessary for the assert below. */
1535  }
1536 
1537  drflac_assert(bitsToSeek == 0);
1538  return DRFLAC_TRUE;
1539 }
1540 
1541 
1542 /* This function moves the bit streamer to the first bit after the sync code (bit 15 of the of the frame header). It will also update the CRC-16. */
1543 static drflac_bool32 drflac__find_and_seek_to_next_sync_code(drflac_bs* bs)
1544 {
1545  drflac_assert(bs != NULL);
1546 
1547  /* The sync code is always aligned to 8 bits. This is convenient for us because it means we can do byte-aligned movements. The first
1548  * thing to do is align to the next byte. */
1549  if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7))
1550  return DRFLAC_FALSE;
1551 
1552  for (;;)
1553  {
1554  drflac_uint8 hi;
1555 
1556 #ifndef DR_FLAC_NO_CRC
1557  drflac__reset_crc16(bs);
1558 #endif
1559 
1560  if (!drflac__read_uint8(bs, 8, &hi))
1561  return DRFLAC_FALSE;
1562 
1563  if (hi == 0xFF)
1564  {
1565  drflac_uint8 lo;
1566  if (!drflac__read_uint8(bs, 6, &lo))
1567  return DRFLAC_FALSE;
1568 
1569  if (lo == 0x3E)
1570  return DRFLAC_TRUE;
1571 
1572  if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7))
1573  return DRFLAC_FALSE;
1574  }
1575  }
1576 
1577 #if 0
1578  /* Should never get here. */
1579  return DRFLAC_FALSE;
1580 #endif
1581 }
1582 
1583 
1584 #if !defined(DR_FLAC_NO_SIMD) && defined(DRFLAC_HAS_LZCNT_INTRINSIC)
1585 #define DRFLAC_IMPLEMENT_CLZ_LZCNT
1586 #endif
1587 #if defined(_MSC_VER) && _MSC_VER >= 1400 && (defined(DRFLAC_X64) || defined(DRFLAC_X86))
1588 #define DRFLAC_IMPLEMENT_CLZ_MSVC
1589 #endif
1590 
1591 static DRFLAC_INLINE drflac_uint32 drflac__clz_software(drflac_cache_t x)
1592 {
1593  static drflac_uint32 clz_table_4[] = {
1594  0,
1595  4,
1596  3, 3,
1597  2, 2, 2, 2,
1598  1, 1, 1, 1, 1, 1, 1, 1
1599  };
1600  drflac_uint32 n = clz_table_4[x >> (sizeof(x)*8 - 4)];
1601 
1602  if (n == 0)
1603  {
1604 #ifdef DRFLAC_64BIT
1605  if ((x & 0xFFFFFFFF00000000ULL) == 0) { n = 32; x <<= 32; }
1606  if ((x & 0xFFFF000000000000ULL) == 0) { n += 16; x <<= 16; }
1607  if ((x & 0xFF00000000000000ULL) == 0) { n += 8; x <<= 8; }
1608  if ((x & 0xF000000000000000ULL) == 0) { n += 4; x <<= 4; }
1609 #else
1610  if ((x & 0xFFFF0000) == 0) { n = 16; x <<= 16; }
1611  if ((x & 0xFF000000) == 0) { n += 8; x <<= 8; }
1612  if ((x & 0xF0000000) == 0) { n += 4; x <<= 4; }
1613 #endif
1614  n += clz_table_4[x >> (sizeof(x)*8 - 4)];
1615  }
1616 
1617  return n - 1;
1618 }
1619 
1620 #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
1621 static DRFLAC_INLINE drflac_bool32 drflac__is_lzcnt_supported()
1622 {
1623  /* If the compiler itself does not support the intrinsic then we'll need to return false. */
1624 #ifdef DRFLAC_HAS_LZCNT_INTRINSIC
1625  return drflac__gIsLZCNTSupported;
1626 #else
1627  return DRFLAC_FALSE;
1628 #endif
1629 }
1630 
1631 static DRFLAC_INLINE drflac_uint32 drflac__clz_lzcnt(drflac_cache_t x)
1632 {
1633 #if defined(_MSC_VER) && !defined(__clang__)
1634 #ifdef DRFLAC_64BIT
1635  return (drflac_uint32)__lzcnt64(x);
1636 #else
1637  return (drflac_uint32)__lzcnt(x);
1638 #endif
1639 #else
1640 #if defined(__GNUC__) || defined(__clang__)
1641 #ifdef DRFLAC_64BIT
1642  return (drflac_uint32)__builtin_clzll((unsigned long long)x);
1643 #else
1644  return (drflac_uint32)__builtin_clzl((unsigned long)x);
1645 #endif
1646 #else
1647  /* Unsupported compiler. */
1648 #error "This compiler does not support the lzcnt intrinsic."
1649 #endif
1650 #endif
1651 }
1652 #endif
1653 
1654 #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
1655 static DRFLAC_INLINE drflac_uint32 drflac__clz_msvc(drflac_cache_t x)
1656 {
1657  drflac_uint32 n;
1658 #ifdef DRFLAC_64BIT
1659  _BitScanReverse64((unsigned long*)&n, x);
1660 #else
1661  _BitScanReverse((unsigned long*)&n, x);
1662 #endif
1663  return sizeof(x)*8 - n - 1;
1664 }
1665 #endif
1666 
1667 static DRFLAC_INLINE drflac_uint32 drflac__clz(drflac_cache_t x)
1668 {
1669  /* This function assumes at least one bit is set. Checking for 0 needs to be done at a higher level, outside this function. */
1670 #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
1671  if (drflac__is_lzcnt_supported())
1672  return drflac__clz_lzcnt(x);
1673 #endif
1674 
1675 #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
1676  return drflac__clz_msvc(x);
1677 #else
1678  return drflac__clz_software(x);
1679 #endif
1680 }
1681 
1682 static INLINE drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsigned int* pOffsetOut)
1683 {
1684  drflac_uint32 setBitOffsetPlus1;
1685  drflac_uint32 zeroCounter = 0;
1686  while (bs->cache == 0)
1687  {
1688  zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
1689  if (!drflac__reload_cache(bs))
1690  return DRFLAC_FALSE;
1691  }
1692 
1693  setBitOffsetPlus1 = drflac__clz(bs->cache);
1694  zeroCounter += setBitOffsetPlus1;
1695  setBitOffsetPlus1 += 1;
1696 
1697  bs->consumedBits += setBitOffsetPlus1;
1698  bs->cache <<= setBitOffsetPlus1;
1699 
1700  *pOffsetOut = zeroCounter + setBitOffsetPlus1 - 1;
1701  return DRFLAC_TRUE;
1702 }
1703 
1704 
1705 
1706 static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFromStart)
1707 {
1708  drflac_assert(bs != NULL);
1709  drflac_assert(offsetFromStart > 0);
1710 
1711  /* Seeking from the start is not quite as trivial as it sounds because the onSeek callback takes a signed 32-bit integer (which
1712  * is intentional because it simplifies the implementation of the onSeek callbacks), however offsetFromStart is unsigned 64-bit.
1713  * 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. */
1714  if (offsetFromStart > 0x7FFFFFFF)
1715  {
1716  drflac_uint64 bytesRemaining = offsetFromStart;
1717  if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start))
1718  return DRFLAC_FALSE;
1719  bytesRemaining -= 0x7FFFFFFF;
1720 
1721  while (bytesRemaining > 0x7FFFFFFF)
1722  {
1723  if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current))
1724  return DRFLAC_FALSE;
1725  bytesRemaining -= 0x7FFFFFFF;
1726  }
1727 
1728  if (bytesRemaining > 0)
1729  {
1730  if (!bs->onSeek(bs->pUserData, (int)bytesRemaining, drflac_seek_origin_current))
1731  return DRFLAC_FALSE;
1732  }
1733  }
1734  else
1735  {
1736  if (!bs->onSeek(bs->pUserData, (int)offsetFromStart, drflac_seek_origin_start))
1737  return DRFLAC_FALSE;
1738  }
1739 
1740  /* The cache should be reset to force a reload of fresh data from the client. */
1741  drflac__reset_cache(bs);
1742  return DRFLAC_TRUE;
1743 }
1744 
1745 
1746 static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64* pNumberOut, drflac_uint8* pCRCOut)
1747 {
1749  int i;
1750  int byteCount = 1;
1751  unsigned char utf8[7] = {0};
1752  drflac_uint8 crc;
1753 
1754  drflac_assert(bs != NULL);
1755  drflac_assert(pNumberOut != NULL);
1756 
1757  crc = *pCRCOut;
1758 
1759  if (!drflac__read_uint8(bs, 8, utf8))
1760  {
1761  *pNumberOut = 0;
1762  return DRFLAC_END_OF_STREAM;
1763  }
1764  crc = drflac_crc8(crc, utf8[0], 8);
1765 
1766  if ((utf8[0] & 0x80) == 0)
1767  {
1768  *pNumberOut = utf8[0];
1769  *pCRCOut = crc;
1770  return DRFLAC_SUCCESS;
1771  }
1772 
1773  if ((utf8[0] & 0xE0) == 0xC0)
1774  byteCount = 2;
1775  else if ((utf8[0] & 0xF0) == 0xE0)
1776  byteCount = 3;
1777  else if ((utf8[0] & 0xF8) == 0xF0)
1778  byteCount = 4;
1779  else if ((utf8[0] & 0xFC) == 0xF8)
1780  byteCount = 5;
1781  else if ((utf8[0] & 0xFE) == 0xFC)
1782  byteCount = 6;
1783  else if ((utf8[0] & 0xFF) == 0xFE)
1784  byteCount = 7;
1785  else
1786  {
1787  *pNumberOut = 0;
1788  return DRFLAC_CRC_MISMATCH; /* Bad UTF-8 encoding. */
1789  }
1790 
1791  /* Read extra bytes. */
1792  drflac_assert(byteCount > 1);
1793 
1794  result = (drflac_uint64)(utf8[0] & (0xFF >> (byteCount + 1)));
1795  for (i = 1; i < byteCount; ++i)
1796  {
1797  if (!drflac__read_uint8(bs, 8, utf8 + i))
1798  {
1799  *pNumberOut = 0;
1800  return DRFLAC_END_OF_STREAM;
1801  }
1802  crc = drflac_crc8(crc, utf8[i], 8);
1803 
1804  result = (result << 6) | (utf8[i] & 0x3F);
1805  }
1806 
1807  *pNumberOut = result;
1808  *pCRCOut = crc;
1809  return DRFLAC_SUCCESS;
1810 }
1811 
1812 
1813 
1814 
1815 /* The next two functions are responsible for calculating the prediction.
1816  *
1817  * 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
1818  * 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.
1819  */
1820 static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_32(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
1821 {
1822  drflac_int32 prediction = 0;
1823 
1824  drflac_assert(order <= 32);
1825 
1826  /* 32-bit version.
1827 
1828  * VC++ optimizes this to a single jmp. I've not yet verified this for other compilers. */
1829 
1830  switch (order)
1831  {
1832  case 32: prediction += coefficients[31] * pDecodedSamples[-32];
1833  case 31: prediction += coefficients[30] * pDecodedSamples[-31];
1834  case 30: prediction += coefficients[29] * pDecodedSamples[-30];
1835  case 29: prediction += coefficients[28] * pDecodedSamples[-29];
1836  case 28: prediction += coefficients[27] * pDecodedSamples[-28];
1837  case 27: prediction += coefficients[26] * pDecodedSamples[-27];
1838  case 26: prediction += coefficients[25] * pDecodedSamples[-26];
1839  case 25: prediction += coefficients[24] * pDecodedSamples[-25];
1840  case 24: prediction += coefficients[23] * pDecodedSamples[-24];
1841  case 23: prediction += coefficients[22] * pDecodedSamples[-23];
1842  case 22: prediction += coefficients[21] * pDecodedSamples[-22];
1843  case 21: prediction += coefficients[20] * pDecodedSamples[-21];
1844  case 20: prediction += coefficients[19] * pDecodedSamples[-20];
1845  case 19: prediction += coefficients[18] * pDecodedSamples[-19];
1846  case 18: prediction += coefficients[17] * pDecodedSamples[-18];
1847  case 17: prediction += coefficients[16] * pDecodedSamples[-17];
1848  case 16: prediction += coefficients[15] * pDecodedSamples[-16];
1849  case 15: prediction += coefficients[14] * pDecodedSamples[-15];
1850  case 14: prediction += coefficients[13] * pDecodedSamples[-14];
1851  case 13: prediction += coefficients[12] * pDecodedSamples[-13];
1852  case 12: prediction += coefficients[11] * pDecodedSamples[-12];
1853  case 11: prediction += coefficients[10] * pDecodedSamples[-11];
1854  case 10: prediction += coefficients[ 9] * pDecodedSamples[-10];
1855  case 9: prediction += coefficients[ 8] * pDecodedSamples[- 9];
1856  case 8: prediction += coefficients[ 7] * pDecodedSamples[- 8];
1857  case 7: prediction += coefficients[ 6] * pDecodedSamples[- 7];
1858  case 6: prediction += coefficients[ 5] * pDecodedSamples[- 6];
1859  case 5: prediction += coefficients[ 4] * pDecodedSamples[- 5];
1860  case 4: prediction += coefficients[ 3] * pDecodedSamples[- 4];
1861  case 3: prediction += coefficients[ 2] * pDecodedSamples[- 3];
1862  case 2: prediction += coefficients[ 1] * pDecodedSamples[- 2];
1863  case 1: prediction += coefficients[ 0] * pDecodedSamples[- 1];
1864  }
1865 
1866  return (drflac_int32)(prediction >> shift);
1867 }
1868 
1869 static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
1870 {
1871  drflac_int64 prediction;
1872  drflac_assert(order <= 32);
1873 
1874  /* 64-bit version.
1875 
1876  * This method is faster on the 32-bit build when compiling with VC++. See note below.
1877  */
1878 
1879 #ifndef DRFLAC_64BIT
1880  if (order == 8)
1881  {
1882  prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
1883  prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
1884  prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
1885  prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
1886  prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
1887  prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
1888  prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
1889  prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
1890  }
1891  else if (order == 7)
1892  {
1893  prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
1894  prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
1895  prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
1896  prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
1897  prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
1898  prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
1899  prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
1900  }
1901  else if (order == 3)
1902  {
1903  prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
1904  prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
1905  prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
1906  }
1907  else if (order == 6)
1908  {
1909  prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
1910  prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
1911  prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
1912  prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
1913  prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
1914  prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
1915  }
1916  else if (order == 5)
1917  {
1918  prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
1919  prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
1920  prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
1921  prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
1922  prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
1923  }
1924  else if (order == 4)
1925  {
1926  prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
1927  prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
1928  prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
1929  prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
1930  }
1931  else if (order == 12)
1932  {
1933  prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
1934  prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
1935  prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
1936  prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
1937  prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
1938  prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
1939  prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
1940  prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
1941  prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
1942  prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
1943  prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
1944  prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
1945  }
1946  else if (order == 2)
1947  {
1948  prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
1949  prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
1950  }
1951  else if (order == 1)
1952  {
1953  prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
1954  }
1955  else if (order == 10)
1956  {
1957  prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
1958  prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
1959  prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
1960  prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
1961  prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
1962  prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
1963  prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
1964  prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
1965  prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
1966  prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
1967  }
1968  else if (order == 9)
1969  {
1970  prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
1971  prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
1972  prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
1973  prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
1974  prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
1975  prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
1976  prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
1977  prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
1978  prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
1979  }
1980  else if (order == 11)
1981  {
1982  prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
1983  prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
1984  prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
1985  prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
1986  prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
1987  prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
1988  prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
1989  prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
1990  prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
1991  prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
1992  prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
1993  }
1994  else
1995  {
1996  int j;
1997  prediction = 0;
1998  for (j = 0; j < (int)order; ++j)
1999  prediction += coefficients[j] * (drflac_int64)pDecodedSamples[-j-1];
2000  }
2001 #endif
2002 
2003  /* VC++ optimizes this to a single jmp instruction, but only the 64-bit build. The 32-bit build generates less efficient code for some
2004  * reason. The ugly version above is faster so we'll just switch between the two depending on the target platform. */
2005 #ifdef DRFLAC_64BIT
2006  prediction = 0;
2007 
2008  switch (order)
2009  {
2010  case 32: prediction += coefficients[31] * (drflac_int64)pDecodedSamples[-32];
2011  case 31: prediction += coefficients[30] * (drflac_int64)pDecodedSamples[-31];
2012  case 30: prediction += coefficients[29] * (drflac_int64)pDecodedSamples[-30];
2013  case 29: prediction += coefficients[28] * (drflac_int64)pDecodedSamples[-29];
2014  case 28: prediction += coefficients[27] * (drflac_int64)pDecodedSamples[-28];
2015  case 27: prediction += coefficients[26] * (drflac_int64)pDecodedSamples[-27];
2016  case 26: prediction += coefficients[25] * (drflac_int64)pDecodedSamples[-26];
2017  case 25: prediction += coefficients[24] * (drflac_int64)pDecodedSamples[-25];
2018  case 24: prediction += coefficients[23] * (drflac_int64)pDecodedSamples[-24];
2019  case 23: prediction += coefficients[22] * (drflac_int64)pDecodedSamples[-23];
2020  case 22: prediction += coefficients[21] * (drflac_int64)pDecodedSamples[-22];
2021  case 21: prediction += coefficients[20] * (drflac_int64)pDecodedSamples[-21];
2022  case 20: prediction += coefficients[19] * (drflac_int64)pDecodedSamples[-20];
2023  case 19: prediction += coefficients[18] * (drflac_int64)pDecodedSamples[-19];
2024  case 18: prediction += coefficients[17] * (drflac_int64)pDecodedSamples[-18];
2025  case 17: prediction += coefficients[16] * (drflac_int64)pDecodedSamples[-17];
2026  case 16: prediction += coefficients[15] * (drflac_int64)pDecodedSamples[-16];
2027  case 15: prediction += coefficients[14] * (drflac_int64)pDecodedSamples[-15];
2028  case 14: prediction += coefficients[13] * (drflac_int64)pDecodedSamples[-14];
2029  case 13: prediction += coefficients[12] * (drflac_int64)pDecodedSamples[-13];
2030  case 12: prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
2031  case 11: prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
2032  case 10: prediction += coefficients[ 9] * (drflac_int64)pDecodedSamples[-10];
2033  case 9: prediction += coefficients[ 8] * (drflac_int64)pDecodedSamples[- 9];
2034  case 8: prediction += coefficients[ 7] * (drflac_int64)pDecodedSamples[- 8];
2035  case 7: prediction += coefficients[ 6] * (drflac_int64)pDecodedSamples[- 7];
2036  case 6: prediction += coefficients[ 5] * (drflac_int64)pDecodedSamples[- 6];
2037  case 5: prediction += coefficients[ 4] * (drflac_int64)pDecodedSamples[- 5];
2038  case 4: prediction += coefficients[ 3] * (drflac_int64)pDecodedSamples[- 4];
2039  case 3: prediction += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 3];
2040  case 2: prediction += coefficients[ 1] * (drflac_int64)pDecodedSamples[- 2];
2041  case 1: prediction += coefficients[ 0] * (drflac_int64)pDecodedSamples[- 1];
2042  }
2043 #endif
2044 
2045  return (drflac_int32)(prediction >> shift);
2046 }
2047 
2048 #if 0
2049 /* Reference implementation for reading and decoding samples with residual. This is intentionally left unoptimized for the
2050  * sake of readability and should only be used as a reference. */
2051 static drflac_bool32 drflac__decode_samples_with_residual__rice__reference(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
2052 {
2053  drflac_assert(bs != NULL);
2054  drflac_assert(count > 0);
2055  drflac_assert(pSamplesOut != NULL);
2056 
2057  for (drflac_uint32 i = 0; i < count; ++i)
2058  {
2059  drflac_uint32 zeroCounter = 0;
2060  for (;;)
2061  {
2062  drflac_uint8 bit;
2063  if (!drflac__read_uint8(bs, 1, &bit))
2064  return DRFLAC_FALSE;
2065 
2066  if (bit == 0)
2067  zeroCounter += 1;
2068  else
2069  break;
2070  }
2071 
2072  drflac_uint32 decodedRice;
2073  if (riceParam > 0)
2074  {
2075  if (!drflac__read_uint32(bs, riceParam, &decodedRice))
2076  return DRFLAC_FALSE;
2077  }
2078  else
2079  decodedRice = 0;
2080 
2081  decodedRice |= (zeroCounter << riceParam);
2082  if ((decodedRice & 0x01))
2083  decodedRice = ~(decodedRice >> 1);
2084  else
2085  decodedRice = (decodedRice >> 1);
2086 
2087 
2088  if (bitsPerSample > 16)
2089  pSamplesOut[i] = decodedRice + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + i);
2090  else
2091  pSamplesOut[i] = decodedRice + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + i);
2092  }
2093 
2094  return DRFLAC_TRUE;
2095 }
2096 #endif
2097 
2098 #if 0
2099 static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
2100 {
2101  drflac_uint32 zeroCounter = 0;
2102  for (;;) {
2103  drflac_uint8 bit;
2104  if (!drflac__read_uint8(bs, 1, &bit))
2105  return DRFLAC_FALSE;
2106 
2107  if (bit == 0)
2108  zeroCounter += 1;
2109  else
2110  break;
2111  }
2112 
2113  drflac_uint32 decodedRice;
2114  if (riceParam > 0)
2115  {
2116  if (!drflac__read_uint32(bs, riceParam, &decodedRice))
2117  return DRFLAC_FALSE;
2118  }
2119  else
2120  decodedRice = 0;
2121 
2122  *pZeroCounterOut = zeroCounter;
2123  *pRiceParamPartOut = decodedRice;
2124  return DRFLAC_TRUE;
2125 }
2126 #endif
2127 
2128 static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
2129 {
2130  drflac_uint32 riceLength;
2131  drflac_uint32 riceParamPart = 0;
2132  drflac_uint32 setBitOffsetPlus1;
2133  drflac_cache_t riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParam);
2134  drflac_cache_t resultHiShift = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParam;
2135  drflac_uint32 zeroCounter = 0;
2136  while (bs->cache == 0) {
2137  zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2138  if (!drflac__reload_cache(bs))
2139  return DRFLAC_FALSE;
2140  }
2141 
2142  setBitOffsetPlus1 = drflac__clz(bs->cache);
2143  zeroCounter += setBitOffsetPlus1;
2144  setBitOffsetPlus1 += 1;
2145 
2146  riceLength = setBitOffsetPlus1 + riceParam;
2147 
2148  if (riceLength < DRFLAC_CACHE_L1_BITS_REMAINING(bs))
2149  {
2150  riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> (DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceLength));
2151 
2152  bs->consumedBits += riceLength;
2153  bs->cache <<= riceLength;
2154  }
2155  else
2156  {
2157  drflac_uint32 bitCountLo;
2158  drflac_cache_t resultHi;
2159 
2160  bs->consumedBits += riceLength;
2161  if (setBitOffsetPlus1 < DRFLAC_CACHE_L1_SIZE_BITS(bs))
2162  bs->cache <<= setBitOffsetPlus1;
2163 
2164  /* 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. */
2165  bitCountLo = bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs);
2166  resultHi = bs->cache & riceParamMask; /* <-- This mask is OK because all bits after the first bits are always zero. */
2167 
2168  if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
2169 #ifndef DR_FLAC_NO_CRC
2170  drflac__update_crc16(bs);
2171 #endif
2172  bs->cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
2173  bs->consumedBits = 0;
2174 #ifndef DR_FLAC_NO_CRC
2175  bs->crc16Cache = bs->cache;
2176 #endif
2177  } else {
2178  /* Slow path. We need to fetch more data from the client. */
2179  if (!drflac__reload_cache(bs)) {
2180  return DRFLAC_FALSE;
2181  }
2182  }
2183 
2184  riceParamPart = (drflac_uint32)((resultHi >> resultHiShift) | DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo));
2185 
2186  bs->consumedBits += bitCountLo;
2187  bs->cache <<= bitCountLo;
2188  }
2189 
2190  *pZeroCounterOut = zeroCounter;
2191  *pRiceParamPartOut = riceParamPart;
2192  return DRFLAC_TRUE;
2193 }
2194 
2195 
2196 static drflac_bool32 drflac__decode_samples_with_residual__rice__simple(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
2197 {
2198  drflac_uint32 zeroCountPart = 0;
2199  drflac_uint32 riceParamPart = 0;
2200  drflac_uint32 i = 0;
2201 
2202  drflac_assert(bs != NULL);
2203  drflac_assert(count > 0);
2204  drflac_assert(pSamplesOut != NULL);
2205 
2206  while (i < count)
2207  {
2208  static drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
2209  /* Rice extraction. */
2210  if (!drflac__read_rice_parts(bs, riceParam, &zeroCountPart, &riceParamPart))
2211  return DRFLAC_FALSE;
2212 
2213  /* Rice reconstruction. */
2214 
2215  riceParamPart |= (zeroCountPart << riceParam);
2216  riceParamPart = (riceParamPart >> 1) ^ t[riceParamPart & 0x01];
2217 #if 0
2218  riceParamPart = (riceParamPart >> 1) ^ (~(riceParamPart & 0x01) + 1);
2219 #endif
2220 
2221  /* Sample reconstruction. */
2222  if (bitsPerSample > 16)
2223  {
2224  pSamplesOut[i] = riceParamPart + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + i);
2225  }
2226  else
2227  {
2228  pSamplesOut[i] = riceParamPart + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + i);
2229  }
2230 
2231  i += 1;
2232  }
2233 
2234  return DRFLAC_TRUE;
2235 }
2236 
2237 static drflac_bool32 drflac__decode_samples_with_residual__rice(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
2238 {
2239 #if 0
2240  return drflac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut);
2241 #else
2242  return drflac__decode_samples_with_residual__rice__simple(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut);
2243 #endif
2244 }
2245 
2246 /* 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. */
2247 static drflac_bool32 drflac__read_and_seek_residual__rice(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam)
2248 {
2249  drflac_uint32 i;
2250  drflac_assert(bs != NULL);
2251  drflac_assert(count > 0);
2252 
2253  for (i = 0; i < count; ++i)
2254  {
2255  drflac_uint32 zeroCountPart;
2256  drflac_uint32 riceParamPart;
2257  if (!drflac__read_rice_parts(bs, riceParam, &zeroCountPart, &riceParamPart))
2258  return DRFLAC_FALSE;
2259  }
2260 
2261  return DRFLAC_TRUE;
2262 }
2263 
2264 static drflac_bool32 drflac__decode_samples_with_residual__unencoded(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 unencodedBitsPerSample, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
2265 {
2266  unsigned int i;
2267  drflac_assert(bs != NULL);
2268  drflac_assert(count > 0);
2269  drflac_assert(unencodedBitsPerSample > 0 && unencodedBitsPerSample <= 32);
2270  drflac_assert(pSamplesOut != NULL);
2271 
2272  for (i = 0; i < count; ++i)
2273  {
2274  if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i))
2275  return DRFLAC_FALSE;
2276 
2277  if (bitsPerSample > 16)
2278  {
2279  pSamplesOut[i] += drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + i);
2280  }
2281  else
2282  {
2283  pSamplesOut[i] += drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + i);
2284  }
2285  }
2286 
2287  return DRFLAC_TRUE;
2288 }
2289 
2290 
2291 /* Reads and decodes the residual for the sub-frame the decoder is currently sitting on. This function should be called
2292  * when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be ignored. The
2293  * <blockSize> and <order> parameters are used to determine how many residual values need to be decoded. */
2294 static drflac_bool32 drflac__decode_samples_with_residual(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 blockSize, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
2295 {
2296  drflac_uint8 partitionOrder;
2297  drflac_uint8 residualMethod;
2298  drflac_uint32 samplesInPartition;
2299  drflac_uint32 partitionsRemaining;
2300 
2301  drflac_assert(bs != NULL);
2302  drflac_assert(blockSize != 0);
2303  drflac_assert(pDecodedSamples != NULL); /* <-- Should we allow NULL, in which case we just seek past the residual rather than do a full decode? */
2304 
2305  if (!drflac__read_uint8(bs, 2, &residualMethod))
2306  return DRFLAC_FALSE;
2307 
2308  if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2)
2309  return DRFLAC_FALSE; /* Unknown or unsupported residual coding method. */
2310 
2311  /* Ignore the first <order> values. */
2312  pDecodedSamples += order;
2313 
2314 
2315  if (!drflac__read_uint8(bs, 4, &partitionOrder))
2316  return DRFLAC_FALSE;
2317 
2318  /* From the FLAC spec:
2319  * The Rice partition order in a Rice-coded residual section must be less than or equal to 8. */
2320  if (partitionOrder > 8)
2321  return DRFLAC_FALSE;
2322 
2323  /* Validation check. */
2324  if ((blockSize / (1 << partitionOrder)) <= order)
2325  return DRFLAC_FALSE;
2326 
2327  samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
2328  partitionsRemaining = (1 << partitionOrder);
2329 
2330  for (;;)
2331  {
2332  drflac_uint8 riceParam = 0;
2333  if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE)
2334  {
2335  if (!drflac__read_uint8(bs, 4, &riceParam))
2336  return DRFLAC_FALSE;
2337  if (riceParam == 16)
2338  riceParam = 0xFF;
2339  }
2340  else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2)
2341  {
2342  if (!drflac__read_uint8(bs, 5, &riceParam))
2343  return DRFLAC_FALSE;
2344  if (riceParam == 32)
2345  riceParam = 0xFF;
2346  }
2347 
2348  if (riceParam != 0xFF)
2349  {
2350  if (!drflac__decode_samples_with_residual__rice(bs, bitsPerSample, samplesInPartition, riceParam, order, shift, coefficients, pDecodedSamples))
2351  return DRFLAC_FALSE;
2352  }
2353  else
2354  {
2355  unsigned char unencodedBitsPerSample = 0;
2356  if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample))
2357  return DRFLAC_FALSE;
2358 
2359  if (!drflac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, order, shift, coefficients, pDecodedSamples))
2360  return DRFLAC_FALSE;
2361  }
2362 
2363  pDecodedSamples += samplesInPartition;
2364 
2365 
2366  if (partitionsRemaining == 1)
2367  break;
2368 
2369  partitionsRemaining -= 1;
2370 
2371  if (partitionOrder != 0)
2372  samplesInPartition = blockSize / (1 << partitionOrder);
2373  }
2374 
2375  return DRFLAC_TRUE;
2376 }
2377 
2378 /* Reads and seeks past the residual for the sub-frame the decoder is currently sitting on. This function should be called
2379  * when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be set to 0. The
2380  * <blockSize> and <order> parameters are used to determine how many residual values need to be decoded. */
2381 static drflac_bool32 drflac__read_and_seek_residual(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 order)
2382 {
2383  drflac_uint32 partitionsRemaining;
2384  drflac_uint32 samplesInPartition;
2385  drflac_uint8 partitionOrder;
2386  drflac_uint8 residualMethod;
2387 
2388  drflac_assert(bs != NULL);
2389  drflac_assert(blockSize != 0);
2390 
2391  if (!drflac__read_uint8(bs, 2, &residualMethod))
2392  return DRFLAC_FALSE;
2393 
2394  if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2)
2395  return DRFLAC_FALSE; /* Unknown or unsupported residual coding method. */
2396 
2397  if (!drflac__read_uint8(bs, 4, &partitionOrder))
2398  return DRFLAC_FALSE;
2399 
2400  samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
2401  partitionsRemaining = (1 << partitionOrder);
2402  for (;;)
2403  {
2404  drflac_uint8 riceParam = 0;
2405  if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE)
2406  {
2407  if (!drflac__read_uint8(bs, 4, &riceParam))
2408  return DRFLAC_FALSE;
2409  if (riceParam == 16)
2410  riceParam = 0xFF;
2411  }
2412  else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
2413  if (!drflac__read_uint8(bs, 5, &riceParam))
2414  return DRFLAC_FALSE;
2415  if (riceParam == 32)
2416  riceParam = 0xFF;
2417  }
2418 
2419  if (riceParam != 0xFF)
2420  {
2421  if (!drflac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam))
2422  return DRFLAC_FALSE;
2423  }
2424  else
2425  {
2426  unsigned char unencodedBitsPerSample = 0;
2427  if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample))
2428  return DRFLAC_FALSE;
2429 
2430  if (!drflac__seek_bits(bs, unencodedBitsPerSample * samplesInPartition))
2431  return DRFLAC_FALSE;
2432  }
2433 
2434  if (partitionsRemaining == 1)
2435  break;
2436 
2437  partitionsRemaining -= 1;
2438  samplesInPartition = blockSize / (1 << partitionOrder);
2439  }
2440 
2441  return DRFLAC_TRUE;
2442 }
2443 
2444 
2445 static drflac_bool32 drflac__decode_samples__constant(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_int32* pDecodedSamples)
2446 {
2447  drflac_uint32 i;
2448  /* Only a single sample needs to be decoded here. */
2450  if (!drflac__read_int32(bs, bitsPerSample, &sample))
2451  return DRFLAC_FALSE;
2452 
2453  /* We don't really need to expand this, but it does simplify the process of reading samples. If this becomes a performance issue (unlikely)
2454  * we'll want to look at a more efficient way. */
2455  for (i = 0; i < blockSize; ++i)
2456  pDecodedSamples[i] = sample;
2457 
2458  return DRFLAC_TRUE;
2459 }
2460 
2461 static drflac_bool32 drflac__decode_samples__verbatim(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_int32* pDecodedSamples)
2462 {
2463  drflac_uint32 i;
2464  for (i = 0; i < blockSize; ++i)
2465  {
2467  if (!drflac__read_int32(bs, bitsPerSample, &sample))
2468  return DRFLAC_FALSE;
2469 
2470  pDecodedSamples[i] = sample;
2471  }
2472 
2473  return DRFLAC_TRUE;
2474 }
2475 
2476 static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
2477 {
2478  drflac_uint32 i;
2479  drflac_int32 lpcCoefficientsTable[5][4] = {
2480  {0, 0, 0, 0},
2481  {1, 0, 0, 0},
2482  {2, -1, 0, 0},
2483  {3, -3, 1, 0},
2484  {4, -6, 4, -1}
2485  };
2486 
2487  /* Warm up samples and coefficients. */
2488  for (i = 0; i < lpcOrder; ++i)
2489  {
2491  if (!drflac__read_int32(bs, bitsPerSample, &sample))
2492  return DRFLAC_FALSE;
2493 
2494  pDecodedSamples[i] = sample;
2495  }
2496 
2497 
2498  if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, 0, lpcCoefficientsTable[lpcOrder], pDecodedSamples))
2499  return DRFLAC_FALSE;
2500 
2501  return DRFLAC_TRUE;
2502 }
2503 
2504 static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
2505 {
2506  drflac_uint8 i;
2507  drflac_uint8 lpcPrecision;
2508  drflac_int8 lpcShift;
2509  drflac_int32 coefficients[32];
2510 
2511  /* Warm up samples. */
2512  for (i = 0; i < lpcOrder; ++i)
2513  {
2515  if (!drflac__read_int32(bs, bitsPerSample, &sample))
2516  return DRFLAC_FALSE;
2517 
2518  pDecodedSamples[i] = sample;
2519  }
2520 
2521  if (!drflac__read_uint8(bs, 4, &lpcPrecision))
2522  return DRFLAC_FALSE;
2523  if (lpcPrecision == 15)
2524  return DRFLAC_FALSE; /* Invalid. */
2525  lpcPrecision += 1;
2526 
2527 
2528  if (!drflac__read_int8(bs, 5, &lpcShift))
2529  return DRFLAC_FALSE;
2530 
2531  for (i = 0; i < lpcOrder; ++i)
2532  {
2533  if (!drflac__read_int32(bs, lpcPrecision, coefficients + i))
2534  return DRFLAC_FALSE;
2535  }
2536 
2537  if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, coefficients, pDecodedSamples))
2538  return DRFLAC_FALSE;
2539 
2540  return DRFLAC_TRUE;
2541 }
2542 
2543 
2544 static drflac_bool32 drflac__read_next_frame_header(drflac_bs* bs, drflac_uint8 streaminfoBitsPerSample, drflac_frame_header* header)
2545 {
2546  const drflac_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000};
2547  const drflac_uint8 bitsPerSampleTable[8] = {0, 8, 12, (drflac_uint8)-1, 16, 20, 24, (drflac_uint8)-1}; /* -1 = reserved. */
2548 
2549  drflac_assert(bs != NULL);
2550  drflac_assert(header != NULL);
2551 
2552  /* Keep looping until we find a valid sync code. */
2553  for (;;)
2554  {
2555  drflac_bool32 isVariableBlockSize = false;
2556  drflac_uint8 blockSize = 0;
2557  drflac_uint8 blockingStrategy = 0;
2558  drflac_uint8 crc8 = 0xCE; /* 0xCE = drflac_crc8(0, 0x3FFE, 14); */
2559  drflac_uint8 reserved = 0;
2560  drflac_uint8 sampleRate = 0;
2561  drflac_uint8 channelAssignment = 0;
2562  drflac_uint8 bitsPerSample = 0;
2563 
2564  if (!drflac__find_and_seek_to_next_sync_code(bs))
2565  return DRFLAC_FALSE;
2566 
2567  if (!drflac__read_uint8(bs, 1, &reserved))
2568  return DRFLAC_FALSE;
2569  crc8 = drflac_crc8(crc8, reserved, 1);
2570 
2571  if (!drflac__read_uint8(bs, 1, &blockingStrategy))
2572  return DRFLAC_FALSE;
2573  crc8 = drflac_crc8(crc8, blockingStrategy, 1);
2574 
2575  if (!drflac__read_uint8(bs, 4, &blockSize))
2576  return DRFLAC_FALSE;
2577  crc8 = drflac_crc8(crc8, blockSize, 4);
2578 
2579  if (!drflac__read_uint8(bs, 4, &sampleRate))
2580  return DRFLAC_FALSE;
2581  crc8 = drflac_crc8(crc8, sampleRate, 4);
2582 
2583  if (!drflac__read_uint8(bs, 4, &channelAssignment))
2584  return DRFLAC_FALSE;
2585  crc8 = drflac_crc8(crc8, channelAssignment, 4);
2586 
2587  if (!drflac__read_uint8(bs, 3, &bitsPerSample))
2588  return DRFLAC_FALSE;
2589  crc8 = drflac_crc8(crc8, bitsPerSample, 3);
2590 
2591  if (!drflac__read_uint8(bs, 1, &reserved))
2592  return DRFLAC_FALSE;
2593  crc8 = drflac_crc8(crc8, reserved, 1);
2594 
2595  isVariableBlockSize = blockingStrategy == 1;
2596 
2597  if (isVariableBlockSize)
2598  {
2599  drflac_uint64 sampleNumber;
2600  drflac_result result = drflac__read_utf8_coded_number(bs, &sampleNumber, &crc8);
2601  if (result != DRFLAC_SUCCESS)
2602  {
2603  if (result == DRFLAC_END_OF_STREAM)
2604  return DRFLAC_FALSE;
2605  else
2606  continue;
2607  }
2608  header->frameNumber = 0;
2609  header->sampleNumber = sampleNumber;
2610  }
2611  else
2612  {
2613  drflac_uint64 frameNumber = 0;
2614  drflac_result result = drflac__read_utf8_coded_number(bs, &frameNumber, &crc8);
2615  if (result != DRFLAC_SUCCESS)
2616  {
2617  if (result == DRFLAC_END_OF_STREAM)
2618  return DRFLAC_FALSE;
2619  else
2620  continue;
2621  }
2622  header->frameNumber = (drflac_uint32)frameNumber; /* <-- Safe cast. */
2623  header->sampleNumber = 0;
2624  }
2625 
2626 
2627  if (blockSize == 1)
2628  header->blockSize = 192;
2629  else if (blockSize >= 2 && blockSize <= 5)
2630  header->blockSize = 576 * (1 << (blockSize - 2));
2631  else if (blockSize == 6)
2632  {
2633  if (!drflac__read_uint16(bs, 8, &header->blockSize))
2634  return DRFLAC_FALSE;
2635  crc8 = drflac_crc8(crc8, header->blockSize, 8);
2636  header->blockSize += 1;
2637  }
2638  else if (blockSize == 7)
2639  {
2640  if (!drflac__read_uint16(bs, 16, &header->blockSize))
2641  return DRFLAC_FALSE;
2642  crc8 = drflac_crc8(crc8, header->blockSize, 16);
2643  header->blockSize += 1;
2644  }
2645  else
2646  header->blockSize = 256 * (1 << (blockSize - 8));
2647 
2648  if (sampleRate <= 11)
2649  header->sampleRate = sampleRateTable[sampleRate];
2650  else if (sampleRate == 12)
2651  {
2652  if (!drflac__read_uint32(bs, 8, &header->sampleRate))
2653  return DRFLAC_FALSE;
2654  crc8 = drflac_crc8(crc8, header->sampleRate, 8);
2655  header->sampleRate *= 1000;
2656  }
2657  else if (sampleRate == 13)
2658  {
2659  if (!drflac__read_uint32(bs, 16, &header->sampleRate))
2660  return DRFLAC_FALSE;
2661  crc8 = drflac_crc8(crc8, header->sampleRate, 16);
2662  }
2663  else if (sampleRate == 14)
2664  {
2665  if (!drflac__read_uint32(bs, 16, &header->sampleRate))
2666  return DRFLAC_FALSE;
2667  crc8 = drflac_crc8(crc8, header->sampleRate, 16);
2668  header->sampleRate *= 10;
2669  }
2670  else
2671  continue; /* Invalid. Assume an invalid block. */
2672 
2673  header->channelAssignment = channelAssignment;
2674 
2675  header->bitsPerSample = bitsPerSampleTable[bitsPerSample];
2676  if (header->bitsPerSample == 0)
2677  header->bitsPerSample = streaminfoBitsPerSample;
2678 
2679  if (!drflac__read_uint8(bs, 8, &header->crc8))
2680  return DRFLAC_FALSE;
2681 
2682 #ifndef DR_FLAC_NO_CRC
2683  if (header->crc8 != crc8)
2684  continue; /* CRC mismatch. Loop back to the top and find the next sync code. */
2685 #endif
2686  return DRFLAC_TRUE;
2687  }
2688 }
2689 
2690 static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe* pSubframe)
2691 {
2692  int type;
2693  drflac_uint8 header;
2694  if (!drflac__read_uint8(bs, 8, &header))
2695  return DRFLAC_FALSE;
2696 
2697  /* First bit should always be 0. */
2698  if ((header & 0x80) != 0)
2699  return DRFLAC_FALSE;
2700 
2701  type = (header & 0x7E) >> 1;
2702  if (type == 0)
2703  pSubframe->subframeType = DRFLAC_SUBFRAME_CONSTANT;
2704  else if (type == 1)
2705  pSubframe->subframeType = DRFLAC_SUBFRAME_VERBATIM;
2706  else
2707  {
2708  if ((type & 0x20) != 0) {
2709  pSubframe->subframeType = DRFLAC_SUBFRAME_LPC;
2710  pSubframe->lpcOrder = (type & 0x1F) + 1;
2711  } else if ((type & 0x08) != 0) {
2712  pSubframe->subframeType = DRFLAC_SUBFRAME_FIXED;
2713  pSubframe->lpcOrder = (type & 0x07);
2714  if (pSubframe->lpcOrder > 4) {
2715  pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
2716  pSubframe->lpcOrder = 0;
2717  }
2718  } else {
2719  pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
2720  }
2721  }
2722 
2723  if (pSubframe->subframeType == DRFLAC_SUBFRAME_RESERVED)
2724  return DRFLAC_FALSE;
2725 
2726  /* Wasted bits per sample. */
2727  pSubframe->wastedBitsPerSample = 0;
2728  if ((header & 0x01) == 1)
2729  {
2730  unsigned int wastedBitsPerSample = 0;
2731  if (!drflac__seek_past_next_set_bit(bs, &wastedBitsPerSample))
2732  return DRFLAC_FALSE;
2733  pSubframe->wastedBitsPerSample = (unsigned char)wastedBitsPerSample + 1;
2734  }
2735 
2736  return DRFLAC_TRUE;
2737 }
2738 
2739 static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex, drflac_int32* pDecodedSamplesOut)
2740 {
2741  drflac_subframe* pSubframe = NULL;
2742  drflac_assert(bs != NULL);
2743  drflac_assert(frame != NULL);
2744 
2745  pSubframe = frame->subframes + subframeIndex;
2746  if (!drflac__read_subframe_header(bs, pSubframe))
2747  return DRFLAC_FALSE;
2748 
2749  /* Side channels require an extra bit per sample. Took a while to figure that one out... */
2750  pSubframe->bitsPerSample = frame->header.bitsPerSample;
2751  if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
2752  pSubframe->bitsPerSample += 1;
2753  } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
2754  pSubframe->bitsPerSample += 1;
2755  }
2756 
2757  /* Need to handle wasted bits per sample. */
2758  pSubframe->bitsPerSample -= pSubframe->wastedBitsPerSample;
2759  pSubframe->pDecodedSamples = pDecodedSamplesOut;
2760 
2761  switch (pSubframe->subframeType)
2762  {
2763  case DRFLAC_SUBFRAME_CONSTANT:
2764  {
2765  drflac__decode_samples__constant(bs, frame->header.blockSize, pSubframe->bitsPerSample, pSubframe->pDecodedSamples);
2766  } break;
2767 
2768  case DRFLAC_SUBFRAME_VERBATIM:
2769  {
2770  drflac__decode_samples__verbatim(bs, frame->header.blockSize, pSubframe->bitsPerSample, pSubframe->pDecodedSamples);
2771  } break;
2772 
2773  case DRFLAC_SUBFRAME_FIXED:
2774  {
2775  drflac__decode_samples__fixed(bs, frame->header.blockSize, pSubframe->bitsPerSample, pSubframe->lpcOrder, pSubframe->pDecodedSamples);
2776  } break;
2777 
2778  case DRFLAC_SUBFRAME_LPC:
2779  {
2780  drflac__decode_samples__lpc(bs, frame->header.blockSize, pSubframe->bitsPerSample, pSubframe->lpcOrder, pSubframe->pDecodedSamples);
2781  } break;
2782 
2783  default: return DRFLAC_FALSE;
2784  }
2785 
2786  return DRFLAC_TRUE;
2787 }
2788 
2789 static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex)
2790 {
2791  drflac_subframe *pSubframe;
2792 
2793  drflac_assert(bs != NULL);
2794  drflac_assert(frame != NULL);
2795 
2796  pSubframe = frame->subframes + subframeIndex;
2797  if (!drflac__read_subframe_header(bs, pSubframe))
2798  return DRFLAC_FALSE;
2799 
2800  /* Side channels require an extra bit per sample. Took a while to figure that one out... */
2801  pSubframe->bitsPerSample = frame->header.bitsPerSample;
2802  if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
2803  pSubframe->bitsPerSample += 1;
2804  } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
2805  pSubframe->bitsPerSample += 1;
2806  }
2807 
2808  /* Need to handle wasted bits per sample. */
2809  pSubframe->bitsPerSample -= pSubframe->wastedBitsPerSample;
2810  pSubframe->pDecodedSamples = NULL;
2811 
2812  switch (pSubframe->subframeType)
2813  {
2814  case DRFLAC_SUBFRAME_CONSTANT:
2815  {
2816  if (!drflac__seek_bits(bs, pSubframe->bitsPerSample))
2817  return DRFLAC_FALSE;
2818  } break;
2819 
2820  case DRFLAC_SUBFRAME_VERBATIM:
2821  {
2822  unsigned int bitsToSeek = frame->header.blockSize * pSubframe->bitsPerSample;
2823  if (!drflac__seek_bits(bs, bitsToSeek))
2824  return DRFLAC_FALSE;
2825  } break;
2826 
2827  case DRFLAC_SUBFRAME_FIXED:
2828  {
2829  unsigned int bitsToSeek = pSubframe->lpcOrder * pSubframe->bitsPerSample;
2830  if (!drflac__seek_bits(bs, bitsToSeek))
2831  return DRFLAC_FALSE;
2832 
2833  if (!drflac__read_and_seek_residual(bs, frame->header.blockSize, pSubframe->lpcOrder))
2834  return DRFLAC_FALSE;
2835  } break;
2836 
2837  case DRFLAC_SUBFRAME_LPC:
2838  {
2839  unsigned char lpcPrecision;
2840  unsigned int bitsToSeek = pSubframe->lpcOrder * pSubframe->bitsPerSample;
2841  if (!drflac__seek_bits(bs, bitsToSeek))
2842  return DRFLAC_FALSE;
2843 
2844  if (!drflac__read_uint8(bs, 4, &lpcPrecision))
2845  return DRFLAC_FALSE;
2846  if (lpcPrecision == 15)
2847  return DRFLAC_FALSE; /* Invalid. */
2848  lpcPrecision += 1;
2849 
2850 
2851  bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5; /* +5 for shift. */
2852  if (!drflac__seek_bits(bs, bitsToSeek))
2853  return DRFLAC_FALSE;
2854 
2855  if (!drflac__read_and_seek_residual(bs, frame->header.blockSize, pSubframe->lpcOrder))
2856  return DRFLAC_FALSE;
2857  } break;
2858 
2859  default: return DRFLAC_FALSE;
2860  }
2861 
2862  return DRFLAC_TRUE;
2863 }
2864 
2865 
2866 static DRFLAC_INLINE drflac_uint8 drflac__get_channel_count_from_channel_assignment(drflac_int8 channelAssignment)
2867 {
2868  drflac_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2};
2869 
2870  drflac_assert(channelAssignment <= 10);
2871  return lookup[channelAssignment];
2872 }
2873 
2874 static drflac_result drflac__decode_frame(drflac* pFlac)
2875 {
2876  drflac_uint16 actualCRC16;
2877  drflac_uint8 paddingSizeInBits;
2878  drflac_uint16 desiredCRC16;
2879  int i, channelCount;
2880 
2881  /* This function should be called while the stream is sitting on the first byte after the frame header. */
2882  drflac_zero_memory(pFlac->currentFrame.subframes, sizeof(pFlac->currentFrame.subframes));
2883 
2884  /* The frame block size must never be larger than the maximum block size defined by the FLAC stream. */
2885  if (pFlac->currentFrame.header.blockSize > pFlac->maxBlockSize)
2886  return DRFLAC_ERROR;
2887 
2888  /* The number of channels in the frame must match the channel count from the STREAMINFO block. */
2889  channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment);
2890  if (channelCount != (int)pFlac->channels)
2891  return DRFLAC_ERROR;
2892 
2893  for (i = 0; i < channelCount; ++i)
2894  {
2895  if (!drflac__decode_subframe(&pFlac->bs, &pFlac->currentFrame, i, pFlac->pDecodedSamples + (pFlac->currentFrame.header.blockSize * i)))
2896  return DRFLAC_ERROR;
2897  }
2898 
2899  paddingSizeInBits = DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7;
2900  if (paddingSizeInBits > 0)
2901  {
2902  drflac_uint8 padding = 0;
2903  if (!drflac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding))
2904  return DRFLAC_END_OF_STREAM;
2905  }
2906 
2907 #ifndef DR_FLAC_NO_CRC
2908  actualCRC16 = drflac__flush_crc16(&pFlac->bs);
2909 #endif
2910  if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16))
2911  return DRFLAC_END_OF_STREAM;
2912 
2913 #ifndef DR_FLAC_NO_CRC
2914  if (actualCRC16 != desiredCRC16)
2915  return DRFLAC_CRC_MISMATCH; /* CRC mismatch. */
2916 #endif
2917 
2918  pFlac->currentFrame.samplesRemaining = pFlac->currentFrame.header.blockSize * channelCount;
2919 
2920  return DRFLAC_SUCCESS;
2921 }
2922 
2923 static drflac_result drflac__seek_frame(drflac* pFlac)
2924 {
2925 #ifndef DR_FLAC_NO_CRC
2926  drflac_uint16 actualCRC16;
2927 #endif
2928  drflac_uint16 desiredCRC16;
2929  int i;
2930  int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment);
2931 
2932  for (i = 0; i < channelCount; ++i)
2933  {
2934  if (!drflac__seek_subframe(&pFlac->bs, &pFlac->currentFrame, i))
2935  return DRFLAC_ERROR;
2936  }
2937 
2938  /* Padding. */
2939  if (!drflac__seek_bits(&pFlac->bs, DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7))
2940  return DRFLAC_ERROR;
2941 
2942  /* CRC. */
2943 #ifndef DR_FLAC_NO_CRC
2944  actualCRC16 = drflac__flush_crc16(&pFlac->bs);
2945 #endif
2946  if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16))
2947  return DRFLAC_END_OF_STREAM;
2948 
2949 #ifndef DR_FLAC_NO_CRC
2950  if (actualCRC16 != desiredCRC16)
2951  return DRFLAC_CRC_MISMATCH; /* CRC mismatch. */
2952 #endif
2953 
2954  return DRFLAC_SUCCESS;
2955 }
2956 
2957 static drflac_bool32 drflac__read_and_decode_next_frame(drflac* pFlac)
2958 {
2959  drflac_assert(pFlac != NULL);
2960 
2961  for (;;)
2962  {
2963  drflac_result result;
2964 
2965  if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header))
2966  return DRFLAC_FALSE;
2967 
2968  result = drflac__decode_frame(pFlac);
2969  if (result != DRFLAC_SUCCESS)
2970  {
2971  if (result == DRFLAC_CRC_MISMATCH)
2972  continue; /* CRC mismatch. Skip to the next frame. */
2973  return DRFLAC_FALSE;
2974  }
2975 
2976  return DRFLAC_TRUE;
2977  }
2978 }
2979 
2980 
2981 static void drflac__get_current_frame_sample_range(drflac* pFlac, drflac_uint64* pFirstSampleInFrameOut, drflac_uint64* pLastSampleInFrameOut)
2982 {
2983  unsigned int channelCount;
2984  drflac_uint64 firstSampleInFrame, lastSampleInFrame;
2985 
2986  drflac_assert(pFlac != NULL);
2987 
2988  channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment);
2989 
2990  firstSampleInFrame = pFlac->currentFrame.header.sampleNumber;
2991  if (firstSampleInFrame == 0)
2992  firstSampleInFrame = pFlac->currentFrame.header.frameNumber * pFlac->maxBlockSize*channelCount;
2993 
2994  lastSampleInFrame = firstSampleInFrame + (pFlac->currentFrame.header.blockSize*channelCount);
2995  if (lastSampleInFrame > 0)
2996  lastSampleInFrame -= 1; /* Needs to be zero based. */
2997 
2998  if (pFirstSampleInFrameOut)
2999  *pFirstSampleInFrameOut = firstSampleInFrame;
3000  if (pLastSampleInFrameOut)
3001  *pLastSampleInFrameOut = lastSampleInFrame;
3002 }
3003 
3004 static drflac_bool32 drflac__seek_to_first_frame(drflac* pFlac)
3005 {
3007 
3008  drflac_assert(pFlac != NULL);
3009 
3010  result = drflac__seek_to_byte(&pFlac->bs, pFlac->firstFramePos);
3011 
3012  drflac_zero_memory(&pFlac->currentFrame, sizeof(pFlac->currentFrame));
3013  return result;
3014 }
3015 
3016 static DRFLAC_INLINE drflac_result drflac__seek_to_next_frame(drflac* pFlac)
3017 {
3018  /* This function should only ever be called while the decoder is sitting on the first byte past the FRAME_HEADER section. */
3019  drflac_assert(pFlac != NULL);
3020  return drflac__seek_frame(pFlac);
3021 }
3022 
3023 static drflac_bool32 drflac__seek_to_sample__brute_force(drflac* pFlac, drflac_uint64 sampleIndex)
3024 {
3025  drflac_uint64 runningSampleCount = 0;
3026 
3027  /* We need to find the frame that contains the sample. To do this, we iterate over each frame and inspect it's header. If based on the
3028  * header we can determine that the frame contains the sample, we do a full decode of that frame. */
3029  if (!drflac__seek_to_first_frame(pFlac))
3030  return DRFLAC_FALSE;
3031 
3032  for (;;)
3033  {
3034  drflac_uint64 sampleCountInThisFrame;
3035  drflac_uint64 firstSampleInFrame = 0;
3036  drflac_uint64 lastSampleInFrame = 0;
3037 
3038  if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header))
3039  return DRFLAC_FALSE;
3040 
3041  drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame);
3042 
3043  sampleCountInThisFrame = (lastSampleInFrame - firstSampleInFrame) + 1;
3044  if (sampleIndex < (runningSampleCount + sampleCountInThisFrame))
3045  {
3046  /* The sample should be in this frame. We need to fully decode it, however if it's an invalid frame (a CRC mismatch), we need to pretend
3047  * it never existed and keep iterating. */
3048  drflac_result result = drflac__decode_frame(pFlac);
3049  if (result == DRFLAC_SUCCESS)
3050  {
3051  /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
3052  drflac_uint64 samplesToDecode = (size_t)(sampleIndex - runningSampleCount); /* <-- Safe cast because the maximum number of samples in a frame is 65535. */
3053  if (samplesToDecode == 0)
3054  return DRFLAC_TRUE;
3055  return drflac_read_s32(pFlac, samplesToDecode, NULL) != 0; /* <-- If this fails, something bad has happened (it should never fail). */
3056  }
3057  else
3058  {
3059  if (result == DRFLAC_CRC_MISMATCH)
3060  continue; /* CRC mismatch. Pretend this frame never existed. */
3061  return DRFLAC_FALSE;
3062  }
3063  }
3064  else
3065  {
3066  /* It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this
3067  * frame never existed and leave the running sample count untouched. */
3068  drflac_result result = drflac__seek_to_next_frame(pFlac);
3069  if (result == DRFLAC_SUCCESS)
3070  runningSampleCount += sampleCountInThisFrame;
3071  else
3072  {
3073  if (result == DRFLAC_CRC_MISMATCH)
3074  continue; /* CRC mismatch. Pretend this frame never existed. */
3075  return DRFLAC_FALSE;
3076  }
3077  }
3078  }
3079 }
3080 
3081 
3082 static drflac_bool32 drflac__seek_to_sample__seek_table(drflac* pFlac, drflac_uint64 sampleIndex)
3083 {
3084  drflac_seekpoint closestSeekpoint = {0, 0, 0};
3085  drflac_uint32 seekpointCount;
3086  drflac_uint32 seekpointsRemaining;
3087  drflac_uint64 runningSampleCount;
3088 
3089  drflac_assert(pFlac != NULL);
3090 
3091  if (pFlac->seektablePos == 0)
3092  return DRFLAC_FALSE;
3093 
3094  if (!drflac__seek_to_byte(&pFlac->bs, pFlac->seektablePos))
3095  return DRFLAC_FALSE;
3096 
3097  /* The number of seek points is derived from the size of the SEEKTABLE block. */
3098  seekpointCount = pFlac->seektableSize / 18; /* 18 = the size of each seek point. */
3099  if (seekpointCount == 0)
3100  return DRFLAC_FALSE; /* Would this ever happen? */
3101 
3102  seekpointsRemaining = seekpointCount;
3103  while (seekpointsRemaining > 0)
3104  {
3105  drflac_seekpoint seekpoint;
3106  if (!drflac__read_uint64(&pFlac->bs, 64, &seekpoint.firstSample))
3107  break;
3108  if (!drflac__read_uint64(&pFlac->bs, 64, &seekpoint.frameOffset))
3109  break;
3110  if (!drflac__read_uint16(&pFlac->bs, 16, &seekpoint.sampleCount))
3111  break;
3112 
3113  /* Note that the seekpoint sample is based on a single channel. The input sample (sampleIndex) is based on interleaving, thus
3114  * we need to multiple the seekpoint's sample by the channel count. */
3115  if (seekpoint.firstSample*pFlac->channels > sampleIndex)
3116  break;
3117 
3118  closestSeekpoint = seekpoint;
3119  seekpointsRemaining -= 1;
3120  }
3121 
3122  /* At this point we should have found the seekpoint closest to our sample. We need to seek to it using basically the same
3123  * technique as we use with the brute force method. */
3124  if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFramePos + closestSeekpoint.frameOffset))
3125  return DRFLAC_FALSE;
3126 
3127  runningSampleCount = closestSeekpoint.firstSample*pFlac->channels;
3128  for (;;)
3129  {
3130  drflac_uint64 sampleCountInThisFrame;
3131  drflac_uint64 firstSampleInFrame = 0;
3132  drflac_uint64 lastSampleInFrame = 0;
3133 
3134  if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header))
3135  return DRFLAC_FALSE;
3136 
3137  drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame);
3138 
3139  sampleCountInThisFrame = (lastSampleInFrame - firstSampleInFrame) + 1;
3140  if (sampleIndex < (runningSampleCount + sampleCountInThisFrame))
3141  {
3142  /* The sample should be in this frame. We need to fully decode it, however if it's an invalid frame (a CRC mismatch), we need to pretend
3143  * it never existed and keep iterating. */
3144  drflac_result result = drflac__decode_frame(pFlac);
3145 
3146  if (result == DRFLAC_SUCCESS)
3147  {
3148  /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
3149  drflac_uint64 samplesToDecode = (size_t)(sampleIndex - runningSampleCount); /* <-- Safe cast because the maximum number of samples in a frame is 65535. */
3150  if (samplesToDecode == 0)
3151  return DRFLAC_TRUE;
3152  return drflac_read_s32(pFlac, samplesToDecode, NULL) != 0; /* <-- If this fails, something bad has happened (it should never fail). */
3153  }
3154  else
3155  {
3156  if (result == DRFLAC_CRC_MISMATCH)
3157  continue; /* CRC mismatch. Pretend this frame never existed. */
3158  return DRFLAC_FALSE;
3159  }
3160  }
3161  else
3162  {
3163  /* It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this
3164  * frame never existed and leave the running sample count untouched. */
3165  drflac_result result = drflac__seek_to_next_frame(pFlac);
3166  if (result == DRFLAC_SUCCESS)
3167  runningSampleCount += sampleCountInThisFrame;
3168  else
3169  {
3170  if (result == DRFLAC_CRC_MISMATCH)
3171  continue; /* CRC mismatch. Pretend this frame never existed. */
3172  return DRFLAC_FALSE;
3173  }
3174  }
3175  }
3176 }
3177 
3178 
3179 #ifndef DR_FLAC_NO_OGG
3180 typedef struct
3181 {
3182  drflac_uint8 capturePattern[4]; /* Should be "OggS" */
3183  drflac_uint8 structureVersion; /* Always 0. */
3184  drflac_uint8 headerType;
3185  drflac_uint64 granulePosition;
3186  drflac_uint32 serialNumber;
3187  drflac_uint32 sequenceNumber;
3188  drflac_uint32 checksum;
3189  drflac_uint8 segmentCount;
3190  drflac_uint8 segmentTable[255];
3191 } drflac_ogg_page_header;
3192 #endif
3193 
3194 typedef struct
3195 {
3196  drflac_read_proc onRead;
3197  drflac_seek_proc onSeek;
3198  drflac_meta_proc onMeta;
3199  drflac_container container;
3200  void* pUserData;
3201  void* pUserDataMD;
3202  drflac_uint32 sampleRate;
3203  drflac_uint8 channels;
3204  drflac_uint8 bitsPerSample;
3205  drflac_uint64 totalSampleCount;
3206  drflac_uint16 maxBlockSize;
3207  drflac_uint64 runningFilePos;
3208  drflac_bool32 hasStreamInfoBlock;
3209  drflac_bool32 hasMetadataBlocks;
3210  drflac_bs bs; /* <-- A bit streamer is required for loading data during initialization. */
3211  drflac_frame_header firstFrameHeader; /* <-- The header of the first frame that was read during relaxed initalization. Only set if there is no STREAMINFO block. */
3212 
3213 #ifndef DR_FLAC_NO_OGG
3214  drflac_uint32 oggSerial;
3215  drflac_uint64 oggFirstBytePos;
3216  drflac_ogg_page_header oggBosHeader;
3217 #endif
3218 } drflac_init_info;
3219 
3220 static DRFLAC_INLINE void drflac__decode_block_header(drflac_uint32 blockHeader, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
3221 {
3222  blockHeader = drflac__be2host_32(blockHeader);
3223  *isLastBlock = (blockHeader & (0x01 << 31)) >> 31;
3224  *blockType = (blockHeader & (0x7F << 24)) >> 24;
3225  *blockSize = (blockHeader & 0xFFFFFF);
3226 }
3227 
3228 static DRFLAC_INLINE drflac_bool32 drflac__read_and_decode_block_header(drflac_read_proc onRead, void* pUserData, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
3229 {
3230  drflac_uint32 blockHeader;
3231  if (onRead(pUserData, &blockHeader, 4) != 4) {
3232  return DRFLAC_FALSE;
3233  }
3234 
3235  drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize);
3236  return DRFLAC_TRUE;
3237 }
3238 
3239 drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, drflac_streaminfo* pStreamInfo)
3240 {
3241  drflac_uint32 blockSizes;
3242  drflac_uint64 frameSizes = 0;
3243  drflac_uint64 importantProps;
3244  drflac_uint8 md5[16];
3245 
3246  /* min/max block size. */
3247  if (onRead(pUserData, &blockSizes, 4) != 4)
3248  return DRFLAC_FALSE;
3249 
3250  /* min/max frame size. */
3251  if (onRead(pUserData, &frameSizes, 6) != 6)
3252  return DRFLAC_FALSE;
3253 
3254  /* Sample rate, channels, bits per sample and total sample count. */
3255  if (onRead(pUserData, &importantProps, 8) != 8)
3256  return DRFLAC_FALSE;
3257 
3258  /* MD5 */
3259  if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5))
3260  return DRFLAC_FALSE;
3261 
3262  blockSizes = drflac__be2host_32(blockSizes);
3263  frameSizes = drflac__be2host_64(frameSizes);
3264  importantProps = drflac__be2host_64(importantProps);
3265 
3266  pStreamInfo->minBlockSize = (blockSizes & 0xFFFF0000) >> 16;
3267  pStreamInfo->maxBlockSize = blockSizes & 0x0000FFFF;
3268  pStreamInfo->minFrameSize = (drflac_uint32)((frameSizes & (drflac_uint64)0xFFFFFF0000000000) >> 40);
3269  pStreamInfo->maxFrameSize = (drflac_uint32)((frameSizes & (drflac_uint64)0x000000FFFFFF0000) >> 16);
3270  pStreamInfo->sampleRate = (drflac_uint32)((importantProps & (drflac_uint64)0xFFFFF00000000000) >> 44);
3271  pStreamInfo->channels = (drflac_uint8 )((importantProps & (drflac_uint64)0x00000E0000000000) >> 41) + 1;
3272  pStreamInfo->bitsPerSample = (drflac_uint8 )((importantProps & (drflac_uint64)0x000001F000000000) >> 36) + 1;
3273  pStreamInfo->totalSampleCount = (importantProps & (drflac_uint64)0x0000000FFFFFFFFF) * pStreamInfo->channels;
3274  drflac_copy_memory(pStreamInfo->md5, md5, sizeof(md5));
3275 
3276  return DRFLAC_TRUE;
3277 }
3278 
3279 drflac_bool32 drflac__read_and_decode_metadata(drflac* pFlac)
3280 {
3281  /* 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
3282  * we'll be sitting on byte 42. */
3283  drflac_uint64 runningFilePos = 42;
3284  drflac_uint64 seektablePos = 0;
3285  drflac_uint32 seektableSize = 0;
3286 
3287  drflac_assert(pFlac != NULL);
3288 
3289  for (;;)
3290  {
3292  drflac_uint8 isLastBlock = 0;
3293  drflac_uint8 blockType = 0;
3294  drflac_uint32 blockSize = 0;
3295 
3296  if (!drflac__read_and_decode_block_header(pFlac->bs.onRead, pFlac->bs.pUserData, &isLastBlock, &blockType, &blockSize))
3297  return DRFLAC_FALSE;
3298  runningFilePos += 4;
3299 
3300 
3301  metadata.type = blockType;
3302  metadata.pRawData = NULL;
3303  metadata.rawDataSize = 0;
3304 
3305  switch (blockType)
3306  {
3308  {
3309  if (pFlac->onMeta) {
3310  void* pRawData = DRFLAC_MALLOC(blockSize);
3311  if (pRawData == NULL)
3312  return DRFLAC_FALSE;
3313 
3314  if (pFlac->bs.onRead(pFlac->bs.pUserData, pRawData, blockSize) != blockSize) {
3315  DRFLAC_FREE(pRawData);
3316  return DRFLAC_FALSE;
3317  }
3318 
3319  metadata.pRawData = pRawData;
3320  metadata.rawDataSize = blockSize;
3321  metadata.data.application.id = drflac__be2host_32(*(drflac_uint32*)pRawData);
3322  metadata.data.application.pData = (const void*)((drflac_uint8*)pRawData + sizeof(drflac_uint32));
3323  metadata.data.application.dataSize = blockSize - sizeof(drflac_uint32);
3324  pFlac->onMeta(pFlac->pUserDataMD, &metadata);
3325 
3326  DRFLAC_FREE(pRawData);
3327  }
3328  } break;
3329 
3331  {
3332  seektablePos = runningFilePos;
3333  seektableSize = blockSize;
3334 
3335  if (pFlac->onMeta)
3336  {
3337  drflac_uint32 iSeekpoint;
3338  void* pRawData = DRFLAC_MALLOC(blockSize);
3339  if (pRawData == NULL)
3340  return DRFLAC_FALSE;
3341 
3342  if (pFlac->bs.onRead(pFlac->bs.pUserData, pRawData, blockSize) != blockSize) {
3343  DRFLAC_FREE(pRawData);
3344  return DRFLAC_FALSE;
3345  }
3346 
3347  metadata.pRawData = pRawData;
3348  metadata.rawDataSize = blockSize;
3349  metadata.data.seektable.seekpointCount = blockSize/sizeof(drflac_seekpoint);
3350  metadata.data.seektable.pSeekpoints = (const drflac_seekpoint*)pRawData;
3351 
3352  /* Endian swap. */
3353  for (iSeekpoint = 0; iSeekpoint < metadata.data.seektable.seekpointCount; ++iSeekpoint) {
3354  drflac_seekpoint* pSeekpoint = (drflac_seekpoint*)pRawData + iSeekpoint;
3355  pSeekpoint->firstSample = drflac__be2host_64(pSeekpoint->firstSample);
3356  pSeekpoint->frameOffset = drflac__be2host_64(pSeekpoint->frameOffset);
3357  pSeekpoint->sampleCount = drflac__be2host_16(pSeekpoint->sampleCount);
3358  }
3359 
3360  pFlac->onMeta(pFlac->pUserDataMD, &metadata);
3361 
3362  DRFLAC_FREE(pRawData);
3363  }
3364  } break;
3365 
3367  {
3368  if (pFlac->onMeta)
3369  {
3370  const char* pRunningData;
3371  void* pRawData = DRFLAC_MALLOC(blockSize);
3372  if (pRawData == NULL)
3373  return DRFLAC_FALSE;
3374 
3375  if (pFlac->bs.onRead(pFlac->bs.pUserData, pRawData, blockSize) != blockSize) {
3376  DRFLAC_FREE(pRawData);
3377  return DRFLAC_FALSE;
3378  }
3379 
3380  metadata.pRawData = pRawData;
3381  metadata.rawDataSize = blockSize;
3382 
3383  pRunningData = (const char*)pRawData;
3384  metadata.data.vorbis_comment.vendorLength = drflac__le2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4;
3385  metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength;
3386  metadata.data.vorbis_comment.commentCount = drflac__le2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4;
3387  metadata.data.vorbis_comment.comments = pRunningData;
3388  pFlac->onMeta(pFlac->pUserDataMD, &metadata);
3389 
3390  DRFLAC_FREE(pRawData);
3391  }
3392  } break;
3393 
3395  {
3396  if (pFlac->onMeta)
3397  {
3398  const char* pRunningData;
3399  void* pRawData = DRFLAC_MALLOC(blockSize);
3400  if (pRawData == NULL)
3401  return DRFLAC_FALSE;
3402 
3403  if (pFlac->bs.onRead(pFlac->bs.pUserData, pRawData, blockSize) != blockSize) {
3404  DRFLAC_FREE(pRawData);
3405  return DRFLAC_FALSE;
3406  }
3407 
3408  metadata.pRawData = pRawData;
3409  metadata.rawDataSize = blockSize;
3410 
3411  pRunningData = (const char*)pRawData;
3412  drflac_copy_memory(metadata.data.cuesheet.catalog, pRunningData, 128); pRunningData += 128;
3413  metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*(drflac_uint64*)pRunningData); pRunningData += 4;
3414  metadata.data.cuesheet.isCD = ((pRunningData[0] & 0x80) >> 7) != 0; pRunningData += 259;
3415  metadata.data.cuesheet.trackCount = pRunningData[0]; pRunningData += 1;
3416  metadata.data.cuesheet.pTrackData = (const drflac_uint8*)pRunningData;
3417  pFlac->onMeta(pFlac->pUserDataMD, &metadata);
3418 
3419  DRFLAC_FREE(pRawData);
3420  }
3421  } break;
3422 
3424  {
3425  if (pFlac->onMeta)
3426  {
3427  const char* pRunningData;
3428  void* pRawData = DRFLAC_MALLOC(blockSize);
3429  if (pRawData == NULL)
3430  return DRFLAC_FALSE;
3431 
3432  if (pFlac->bs.onRead(pFlac->bs.pUserData, pRawData, blockSize) != blockSize) {
3433  DRFLAC_FREE(pRawData);
3434  return DRFLAC_FALSE;
3435  }
3436 
3437  metadata.pRawData = pRawData;
3438  metadata.rawDataSize = blockSize;
3439 
3440  pRunningData = (const char*)pRawData;
3441  metadata.data.picture.type = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4;
3442  metadata.data.picture.mimeLength = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4;
3443  metadata.data.picture.mime = pRunningData; pRunningData += metadata.data.picture.mimeLength;
3444  metadata.data.picture.descriptionLength = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4;
3445  metadata.data.picture.description = pRunningData;
3446  metadata.data.picture.width = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4;
3447  metadata.data.picture.height = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4;
3448  metadata.data.picture.colorDepth = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4;
3449  metadata.data.picture.indexColorCount = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4;
3450  metadata.data.picture.pictureDataSize = drflac__be2host_32(*(drflac_uint32*)pRunningData); pRunningData += 4;
3451  metadata.data.picture.pPictureData = (const drflac_uint8*)pRunningData;
3452  pFlac->onMeta(pFlac->pUserDataMD, &metadata);
3453 
3454  DRFLAC_FREE(pRawData);
3455  }
3456  } break;
3457 
3459  {
3460  if (pFlac->onMeta)
3461  {
3462  metadata.data.padding.unused = 0;
3463 
3464  /* Padding doesn't have anything meaningful in it, so just skip over it, but make sure the caller is aware of it by firing the callback. */
3465  if (!pFlac->bs.onSeek(pFlac->bs.pUserData, blockSize, drflac_seek_origin_current))
3466  isLastBlock = DRFLAC_TRUE; /* An error occured while seeking. Attempt to recover by treating this as the last block which will in turn terminate the loop. */
3467  else
3468  pFlac->onMeta(pFlac->pUserDataMD, &metadata);
3469  }
3470  }
3471  break;
3472 
3474  {
3475  /* Invalid chunk. Just skip over this one. */
3476  if (pFlac->onMeta)
3477  {
3478  if (!pFlac->bs.onSeek(pFlac->bs.pUserData, blockSize, drflac_seek_origin_current))
3479  isLastBlock = DRFLAC_TRUE; /* An error occured while seeking. Attempt to recover by treating this as the last block which will in turn terminate the loop. */
3480  }
3481  }
3482 
3483  default:
3484  {
3485  /* It's an unknown chunk, but not necessarily invalid. There's a chance more metadata blocks might be defined later on, so we
3486  * can at the very least report the chunk to the application and let it look at the raw data. */
3487  if (pFlac->onMeta)
3488  {
3489  void* pRawData = DRFLAC_MALLOC(blockSize);
3490  if (pRawData == NULL)
3491  return DRFLAC_FALSE;
3492 
3493  if (pFlac->bs.onRead(pFlac->bs.pUserData, pRawData, blockSize) != blockSize) {
3494  DRFLAC_FREE(pRawData);
3495  return DRFLAC_FALSE;
3496  }
3497 
3498  metadata.pRawData = pRawData;
3499  metadata.rawDataSize = blockSize;
3500  pFlac->onMeta(pFlac->pUserDataMD, &metadata);
3501 
3502  DRFLAC_FREE(pRawData);
3503  }
3504  } break;
3505  }
3506 
3507  /* 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. */
3508  if (pFlac->onMeta == NULL && blockSize > 0)
3509  {
3510  if (!pFlac->bs.onSeek(pFlac->bs.pUserData, blockSize, drflac_seek_origin_current))
3511  isLastBlock = DRFLAC_TRUE;
3512  }
3513 
3514  runningFilePos += blockSize;
3515  if (isLastBlock)
3516  break;
3517  }
3518 
3519  pFlac->seektablePos = seektablePos;
3520  pFlac->seektableSize = seektableSize;
3521  pFlac->firstFramePos = runningFilePos;
3522 
3523  return DRFLAC_TRUE;
3524 }
3525 
3526 drflac_bool32 drflac__init_private__native(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed)
3527 {
3528  drflac_uint8 isLastBlock = 0;
3529  drflac_uint8 blockType = 0;
3530  drflac_uint32 blockSize = 0;
3531 
3532  (void)onSeek;
3533 
3534  /* Pre: The bit stream should be sitting just past the 4-byte id header. */
3535 
3536  pInit->container = drflac_container_native;
3537 
3538  /* The first metadata block should be the STREAMINFO block. */
3539  if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize))
3540  return DRFLAC_FALSE;
3541 
3542  if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34)
3543  {
3544  /* We're opening in strict mode and the first block is not the STREAMINFO block. Error. */
3545  if (!relaxed)
3546  return DRFLAC_FALSE;
3547 
3548  /* Relaxed mode. To open from here we need to just find the first frame and set the sample rate, etc. to whatever is defined
3549  * for that frame. */
3550  pInit->hasStreamInfoBlock = DRFLAC_FALSE;
3551  pInit->hasMetadataBlocks = DRFLAC_FALSE;
3552 
3553  if (!drflac__read_next_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader))
3554  return DRFLAC_FALSE; /* Couldn't find a frame. */
3555 
3556  if (pInit->firstFrameHeader.bitsPerSample == 0)
3557  return DRFLAC_FALSE; /* Failed to initialize because the first frame depends on the STREAMINFO block, which does not exist. */
3558 
3559  pInit->sampleRate = pInit->firstFrameHeader.sampleRate;
3560  pInit->channels = drflac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment);
3561  pInit->bitsPerSample = pInit->firstFrameHeader.bitsPerSample;
3562  pInit->maxBlockSize = 65535; /* <-- See notes here: https://xiph.org/flac/format.html#metadata_block_streaminfo */
3563  return DRFLAC_TRUE;
3564  }
3565  else
3566  {
3567  drflac_streaminfo streaminfo;
3568  if (!drflac__read_streaminfo(onRead, pUserData, &streaminfo))
3569  return DRFLAC_FALSE;
3570 
3571  pInit->hasStreamInfoBlock = DRFLAC_TRUE;
3572  pInit->sampleRate = streaminfo.sampleRate;
3573  pInit->channels = streaminfo.channels;
3574  pInit->bitsPerSample = streaminfo.bitsPerSample;
3575  pInit->totalSampleCount = streaminfo.totalSampleCount;
3576  pInit->maxBlockSize = streaminfo.maxBlockSize; /* Don't care about the min block size - only the max (used for determining the size of the memory allocation). */
3577  pInit->hasMetadataBlocks = !isLastBlock;
3578 
3579  if (onMeta) {
3582  metadata.pRawData = NULL;
3583  metadata.rawDataSize = 0;
3584  metadata.data.streaminfo = streaminfo;
3585  onMeta(pUserDataMD, &metadata);
3586  }
3587 
3588  return DRFLAC_TRUE;
3589  }
3590 }
3591 
3592 #ifndef DR_FLAC_NO_OGG
3593 #define DRFLAC_OGG_MAX_PAGE_SIZE 65307
3594 #define DRFLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199 /* CRC-32 of "OggS". */
3595 
3596 typedef enum
3597 {
3598  drflac_ogg_recover_on_crc_mismatch,
3599  drflac_ogg_fail_on_crc_mismatch
3600 } drflac_ogg_crc_mismatch_recovery;
3601 
3602 
3603 static drflac_uint32 drflac__crc32_table[] = {
3604  0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L,
3605  0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L,
3606  0x2608EDB8L, 0x22C9F00FL, 0x2F8AD6D6L, 0x2B4BCB61L,
3607  0x350C9B64L, 0x31CD86D3L, 0x3C8EA00AL, 0x384FBDBDL,
3608  0x4C11DB70L, 0x48D0C6C7L, 0x4593E01EL, 0x4152FDA9L,
3609  0x5F15ADACL, 0x5BD4B01BL, 0x569796C2L, 0x52568B75L,
3610  0x6A1936C8L, 0x6ED82B7FL, 0x639B0DA6L, 0x675A1011L,
3611  0x791D4014L, 0x7DDC5DA3L, 0x709F7B7AL, 0x745E66CDL,
3612  0x9823B6E0L, 0x9CE2AB57L, 0x91A18D8EL, 0x95609039L,
3613  0x8B27C03CL, 0x8FE6DD8BL, 0x82A5FB52L, 0x8664E6E5L,
3614  0xBE2B5B58L, 0xBAEA46EFL, 0xB7A96036L, 0xB3687D81L,
3615  0xAD2F2D84L, 0xA9EE3033L, 0xA4AD16EAL, 0xA06C0B5DL,
3616  0xD4326D90L, 0xD0F37027L, 0xDDB056FEL, 0xD9714B49L,
3617  0xC7361B4CL, 0xC3F706FBL, 0xCEB42022L, 0xCA753D95L,
3618  0xF23A8028L, 0xF6FB9D9FL, 0xFBB8BB46L, 0xFF79A6F1L,
3619  0xE13EF6F4L, 0xE5FFEB43L, 0xE8BCCD9AL, 0xEC7DD02DL,
3620  0x34867077L, 0x30476DC0L, 0x3D044B19L, 0x39C556AEL,
3621  0x278206ABL, 0x23431B1CL, 0x2E003DC5L, 0x2AC12072L,
3622  0x128E9DCFL, 0x164F8078L, 0x1B0CA6A1L, 0x1FCDBB16L,
3623  0x018AEB13L, 0x054BF6A4L, 0x0808D07DL, 0x0CC9CDCAL,
3624  0x7897AB07L, 0x7C56B6B0L, 0x71159069L, 0x75D48DDEL,
3625  0x6B93DDDBL, 0x6F52C06CL, 0x6211E6B5L, 0x66D0FB02L,
3626  0x5E9F46BFL, 0x5A5E5B08L, 0x571D7DD1L, 0x53DC6066L,
3627  0x4D9B3063L, 0x495A2DD4L, 0x44190B0DL, 0x40D816BAL,
3628  0xACA5C697L, 0xA864DB20L, 0xA527FDF9L, 0xA1E6E04EL,
3629  0xBFA1B04BL, 0xBB60ADFCL, 0xB6238B25L, 0xB2E29692L,
3630  0x8AAD2B2FL, 0x8E6C3698L, 0x832F1041L, 0x87EE0DF6L,
3631  0x99A95DF3L, 0x9D684044L, 0x902B669DL, 0x94EA7B2AL,
3632  0xE0B41DE7L, 0xE4750050L, 0xE9362689L, 0xEDF73B3EL,
3633  0xF3B06B3BL, 0xF771768CL, 0xFA325055L, 0xFEF34DE2L,
3634  0xC6BCF05FL, 0xC27DEDE8L, 0xCF3ECB31L, 0xCBFFD686L,
3635  0xD5B88683L, 0xD1799B34L, 0xDC3ABDEDL, 0xD8FBA05AL,
3636  0x690CE0EEL, 0x6DCDFD59L, 0x608EDB80L, 0x644FC637L,
3637  0x7A089632L, 0x7EC98B85L, 0x738AAD5CL, 0x774BB0EBL,
3638  0x4F040D56L, 0x4BC510E1L, 0x46863638L, 0x42472B8FL,
3639  0x5C007B8AL, 0x58C1663DL, 0x558240E4L, 0x51435D53L,
3640  0x251D3B9EL, 0x21DC2629L, 0x2C9F00F0L, 0x285E1D47L,
3641  0x36194D42L, 0x32D850F5L, 0x3F9B762CL, 0x3B5A6B9BL,
3642  0x0315D626L, 0x07D4CB91L, 0x0A97ED48L, 0x0E56F0FFL,
3643  0x1011A0FAL, 0x14D0BD4DL, 0x19939B94L, 0x1D528623L,
3644  0xF12F560EL, 0xF5EE4BB9L, 0xF8AD6D60L, 0xFC6C70D7L,
3645  0xE22B20D2L, 0xE6EA3D65L, 0xEBA91BBCL, 0xEF68060BL,
3646  0xD727BBB6L, 0xD3E6A601L, 0xDEA580D8L, 0xDA649D6FL,
3647  0xC423CD6AL, 0xC0E2D0DDL, 0xCDA1F604L, 0xC960EBB3L,
3648  0xBD3E8D7EL, 0xB9FF90C9L, 0xB4BCB610L, 0xB07DABA7L,
3649  0xAE3AFBA2L, 0xAAFBE615L, 0xA7B8C0CCL, 0xA379DD7BL,
3650  0x9B3660C6L, 0x9FF77D71L, 0x92B45BA8L, 0x9675461FL,
3651  0x8832161AL, 0x8CF30BADL, 0x81B02D74L, 0x857130C3L,
3652  0x5D8A9099L, 0x594B8D2EL, 0x5408ABF7L, 0x50C9B640L,
3653  0x4E8EE645L, 0x4A4FFBF2L, 0x470CDD2BL, 0x43CDC09CL,
3654  0x7B827D21L, 0x7F436096L, 0x7200464FL, 0x76C15BF8L,
3655  0x68860BFDL, 0x6C47164AL, 0x61043093L, 0x65C52D24L,
3656  0x119B4BE9L, 0x155A565EL, 0x18197087L, 0x1CD86D30L,
3657  0x029F3D35L, 0x065E2082L, 0x0B1D065BL, 0x0FDC1BECL,
3658  0x3793A651L, 0x3352BBE6L, 0x3E119D3FL, 0x3AD08088L,
3659  0x2497D08DL, 0x2056CD3AL, 0x2D15EBE3L, 0x29D4F654L,
3660  0xC5A92679L, 0xC1683BCEL, 0xCC2B1D17L, 0xC8EA00A0L,
3661  0xD6AD50A5L, 0xD26C4D12L, 0xDF2F6BCBL, 0xDBEE767CL,
3662  0xE3A1CBC1L, 0xE760D676L, 0xEA23F0AFL, 0xEEE2ED18L,
3663  0xF0A5BD1DL, 0xF464A0AAL, 0xF9278673L, 0xFDE69BC4L,
3664  0x89B8FD09L, 0x8D79E0BEL, 0x803AC667L, 0x84FBDBD0L,
3665  0x9ABC8BD5L, 0x9E7D9662L, 0x933EB0BBL, 0x97FFAD0CL,
3666  0xAFB010B1L, 0xAB710D06L, 0xA6322BDFL, 0xA2F33668L,
3667  0xBCB4666DL, 0xB8757BDAL, 0xB5365D03L, 0xB1F740B4L
3668 };
3669 
3670 static DRFLAC_INLINE drflac_uint32 drflac_crc32_byte(drflac_uint32 crc32, drflac_uint8 data)
3671 {
3672 #ifndef DR_FLAC_NO_CRC
3673  return (crc32 << 8) ^ drflac__crc32_table[(drflac_uint8)((crc32 >> 24) & 0xFF) ^ data];
3674 #else
3675  (void)data;
3676  return crc32;
3677 #endif
3678 }
3679 
3680 #if 0
3681 static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint32(drflac_uint32 crc32, drflac_uint32 data)
3682 {
3683  crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 24) & 0xFF));
3684  crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 16) & 0xFF));
3685  crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 8) & 0xFF));
3686  crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 0) & 0xFF));
3687  return crc32;
3688 }
3689 
3690 static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint64(drflac_uint32 crc32, drflac_uint64 data)
3691 {
3692  crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 32) & 0xFFFFFFFF));
3693  crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 0) & 0xFFFFFFFF));
3694  return crc32;
3695 }
3696 #endif
3697 
3698 static DRFLAC_INLINE drflac_uint32 drflac_crc32_buffer(drflac_uint32 crc32, drflac_uint8* pData, drflac_uint32 dataSize)
3699 {
3700  drflac_uint32 i;
3701 
3702  /* This can be optimized. */
3703  for (i = 0; i < dataSize; ++i)
3704  crc32 = drflac_crc32_byte(crc32, pData[i]);
3705  return crc32;
3706 }
3707 
3708 
3709 static DRFLAC_INLINE drflac_bool32 drflac_ogg__is_capture_pattern(drflac_uint8 pattern[4])
3710 {
3711  return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S';
3712 }
3713 
3714 static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_header_size(drflac_ogg_page_header* pHeader)
3715 {
3716  return 27 + pHeader->segmentCount;
3717 }
3718 
3719 static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_body_size(drflac_ogg_page_header* pHeader)
3720 {
3721  int i;
3722  drflac_uint32 pageBodySize = 0;
3723 
3724  for (i = 0; i < pHeader->segmentCount; ++i)
3725  pageBodySize += pHeader->segmentTable[i];
3726 
3727  return pageBodySize;
3728 }
3729 
3730 drflac_result drflac_ogg__read_page_header_after_capture_pattern(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32)
3731 {
3732  drflac_uint32 i;
3733  drflac_uint8 data[23];
3734 
3735  drflac_assert(*pCRC32 == DRFLAC_OGG_CAPTURE_PATTERN_CRC32);
3736 
3737  if (onRead(pUserData, data, 23) != 23)
3738  return DRFLAC_END_OF_STREAM;
3739  *pBytesRead += 23;
3740 
3741  pHeader->structureVersion = data[0];
3742  pHeader->headerType = data[1];
3743  drflac_copy_memory(&pHeader->granulePosition, &data[ 2], 8);
3744  drflac_copy_memory(&pHeader->serialNumber, &data[10], 4);
3745  drflac_copy_memory(&pHeader->sequenceNumber, &data[14], 4);
3746  drflac_copy_memory(&pHeader->checksum, &data[18], 4);
3747  pHeader->segmentCount = data[22];
3748 
3749  /* Calculate the CRC. Note that for the calculation the checksum part of the page needs to be set to 0. */
3750  data[18] = 0;
3751  data[19] = 0;
3752  data[20] = 0;
3753  data[21] = 0;
3754 
3755  for (i = 0; i < 23; ++i)
3756  *pCRC32 = drflac_crc32_byte(*pCRC32, data[i]);
3757 
3758  if (onRead(pUserData, pHeader->segmentTable, pHeader->segmentCount) != pHeader->segmentCount)
3759  return DRFLAC_END_OF_STREAM;
3760 
3761  *pBytesRead += pHeader->segmentCount;
3762 
3763  for (i = 0; i < pHeader->segmentCount; ++i)
3764  *pCRC32 = drflac_crc32_byte(*pCRC32, pHeader->segmentTable[i]);
3765 
3766  return DRFLAC_SUCCESS;
3767 }
3768 
3769 drflac_result drflac_ogg__read_page_header(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32)
3770 {
3771  drflac_uint8 id[4];
3772 
3773  *pBytesRead = 0;
3774 
3775  if (onRead(pUserData, id, 4) != 4)
3776  return DRFLAC_END_OF_STREAM;
3777  *pBytesRead += 4;
3778 
3779  /* We need to read byte-by-byte until we find the OggS capture pattern. */
3780  for (;;)
3781  {
3782  if (drflac_ogg__is_capture_pattern(id))
3783  {
3784  drflac_result result;
3785  *pCRC32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
3786 
3787  result = drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32);
3788  if (result == DRFLAC_SUCCESS)
3789  return DRFLAC_SUCCESS;
3790 
3791  if (result == DRFLAC_CRC_MISMATCH)
3792  continue;
3793  return result;
3794  }
3795  else
3796  {
3797  /* The first 4 bytes did not equal the capture pattern. Read the next byte and try again. */
3798  id[0] = id[1];
3799  id[1] = id[2];
3800  id[2] = id[3];
3801  if (onRead(pUserData, &id[3], 1) != 1)
3802  return DRFLAC_END_OF_STREAM;
3803  *pBytesRead += 1;
3804  }
3805  }
3806 }
3807 
3808 
3809 /* The main part of the Ogg encapsulation is the conversion from the physical Ogg bitstream to the native FLAC bitstream. It works
3810  * in three general stages: Ogg Physical Bitstream -> Ogg/FLAC Logical Bitstream -> FLAC Native Bitstream. dr_flac is architecured
3811  * in such a way that the core sections assume everything is delivered in native format. Therefore, for each encapsulation type
3812  * 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
3813  * the physical Ogg bitstream are converted and delivered in native FLAC format. */
3814 typedef struct
3815 {
3816  drflac_read_proc onRead; /* The original onRead callback from drflac_open() and family. */
3817  drflac_seek_proc onSeek; /* The original onSeek callback from drflac_open() and family. */
3818  void* pUserData; /* The user data passed on onRead and onSeek. This is the user data that was passed on drflac_open() and family. */
3819  drflac_uint64 currentBytePos; /* The position of the byte we are sitting on in the physical byte stream. Used for efficient seeking. */
3820  drflac_uint64 firstBytePos; /* The position of the first byte in the physical bitstream. Points to the start of the "OggS" identifier of the FLAC bos page. */
3821  drflac_uint32 serialNumber; /* The serial number of the FLAC audio pages. This is determined by the initial header page that was read during initialization. */
3822  drflac_ogg_page_header bosPageHeader; /* Used for seeking. */
3823  drflac_ogg_page_header currentPageHeader;
3824  drflac_uint32 bytesRemainingInPage;
3825  drflac_uint32 pageDataSize;
3826  drflac_uint8 pageData[DRFLAC_OGG_MAX_PAGE_SIZE];
3827 } drflac_oggbs; /* oggbs = Ogg Bitstream */
3828 
3829 static size_t drflac_oggbs__read_physical(drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead)
3830 {
3831  size_t bytesActuallyRead = oggbs->onRead(oggbs->pUserData, bufferOut, bytesToRead);
3832  oggbs->currentBytePos += bytesActuallyRead;
3833 
3834  return bytesActuallyRead;
3835 }
3836 
3837 static drflac_bool32 drflac_oggbs__seek_physical(drflac_oggbs* oggbs, drflac_uint64 offset, drflac_seek_origin origin)
3838 {
3839  if (origin == drflac_seek_origin_start)
3840  {
3841  if (offset <= 0x7FFFFFFF)
3842  {
3843  if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_start))
3844  return DRFLAC_FALSE;
3845  oggbs->currentBytePos = offset;
3846 
3847  return DRFLAC_TRUE;
3848  }
3849  else
3850  {
3851  if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start))
3852  return DRFLAC_FALSE;
3853  oggbs->currentBytePos = offset;
3854 
3855  return drflac_oggbs__seek_physical(oggbs, offset - 0x7FFFFFFF, drflac_seek_origin_current);
3856  }
3857  }
3858  else
3859  {
3860  while (offset > 0x7FFFFFFF)
3861  {
3862  if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current))
3863  return DRFLAC_FALSE;
3864  oggbs->currentBytePos += 0x7FFFFFFF;
3865  offset -= 0x7FFFFFFF;
3866  }
3867 
3868  if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_current)) /* <-- Safe cast thanks to the loop above. */
3869  return DRFLAC_FALSE;
3870  oggbs->currentBytePos += offset;
3871 
3872  return DRFLAC_TRUE;
3873  }
3874 }
3875 
3876 static drflac_bool32 drflac_oggbs__goto_next_page(drflac_oggbs* oggbs, drflac_ogg_crc_mismatch_recovery recoveryMethod)
3877 {
3878  drflac_ogg_page_header header;
3879  for (;;) {
3880 #ifndef DR_FLAC_NO_CRC
3881  drflac_uint32 actualCRC32;
3882 #endif
3883  drflac_uint32 pageBodySize;
3884  drflac_uint32 crc32 = 0;
3885  drflac_uint32 bytesRead;
3886  if (drflac_ogg__read_page_header(oggbs->onRead, oggbs->pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS)
3887  return DRFLAC_FALSE;
3888  oggbs->currentBytePos += bytesRead;
3889 
3890  pageBodySize = drflac_ogg__get_page_body_size(&header);
3891  if (pageBodySize > DRFLAC_OGG_MAX_PAGE_SIZE)
3892  continue; /* Invalid page size. Assume it's corrupted and just move to the next page. */
3893 
3894  if (header.serialNumber != oggbs->serialNumber)
3895  {
3896  /* It's not a FLAC page. Skip it. */
3897  if (pageBodySize > 0 && !drflac_oggbs__seek_physical(oggbs, pageBodySize, drflac_seek_origin_current))
3898  return DRFLAC_FALSE;
3899  continue;
3900  }
3901 
3902  /* We need to read the entire page and then do a CRC check on it. If there's a CRC mismatch we need to skip this page. */
3903  if (drflac_oggbs__read_physical(oggbs, oggbs->pageData, pageBodySize) != pageBodySize)
3904  return DRFLAC_FALSE;
3905  oggbs->pageDataSize = pageBodySize;
3906 
3907 #ifndef DR_FLAC_NO_CRC
3908  actualCRC32 = drflac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize);
3909  if (actualCRC32 != header.checksum)
3910  {
3911  if (recoveryMethod == drflac_ogg_recover_on_crc_mismatch)
3912  continue; /* CRC mismatch. Skip this page. */
3913 
3914  /* Even though we are failing on a CRC mismatch, we still want our stream to be in a good state. Therefore we
3915  * go to the next valid page to ensure we're in a good state, but return false to let the caller know that the
3916  * seek did not fully complete. */
3917  drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch);
3918  return DRFLAC_FALSE;
3919  }
3920 #endif
3921 
3922  oggbs->currentPageHeader = header;
3923  oggbs->bytesRemainingInPage = pageBodySize;
3924  return DRFLAC_TRUE;
3925  }
3926 }
3927 
3928 /* Function below is unused at the moment, but I might be re-adding it later. */
3929 #if 0
3930 static drflac_uint8 drflac_oggbs__get_current_segment_index(drflac_oggbs* oggbs, drflac_uint8* pBytesRemainingInSeg)
3931 {
3932  drflac_uint32 bytesConsumedInPage = drflac_ogg__get_page_body_size(&oggbs->currentPageHeader) - oggbs->bytesRemainingInPage;
3933  drflac_uint8 iSeg = 0;
3934  drflac_uint32 iByte = 0;
3935  while (iByte < bytesConsumedInPage)
3936  {
3937  drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
3938  if (iByte + segmentSize > bytesConsumedInPage)
3939  break;
3940 
3941  iSeg += 1;
3942  iByte += segmentSize;
3943  }
3944 
3945  *pBytesRemainingInSeg = oggbs->currentPageHeader.segmentTable[iSeg] - (drflac_uint8)(bytesConsumedInPage - iByte);
3946  return iSeg;
3947 }
3948 
3949 static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs)
3950 {
3951  /* The current packet ends when we get to the segment with a lacing value of < 255 which is not at the end of a page. */
3952  for (;;) {
3953  drflac_bool32 atEndOfPage = DRFLAC_FALSE;
3954 
3955  drflac_uint8 bytesRemainingInSeg;
3956  drflac_uint8 iFirstSeg = drflac_oggbs__get_current_segment_index(oggbs, &bytesRemainingInSeg);
3957 
3958  drflac_uint32 bytesToEndOfPacketOrPage = bytesRemainingInSeg;
3959  for (drflac_uint8 iSeg = iFirstSeg; iSeg < oggbs->currentPageHeader.segmentCount; ++iSeg) {
3960  drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
3961  if (segmentSize < 255)
3962  {
3963  if (iSeg == oggbs->currentPageHeader.segmentCount-1)
3964  atEndOfPage = DRFLAC_TRUE;
3965 
3966  break;
3967  }
3968 
3969  bytesToEndOfPacketOrPage += segmentSize;
3970  }
3971 
3972  /* At this point we will have found either the packet or the end of the page. If were at the end of the page we'll
3973  * want to load the next page and keep searching for the end of the packet. */
3974  drflac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, drflac_seek_origin_current);
3975  oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage;
3976 
3977  if (atEndOfPage)
3978  {
3979  /* We're potentially at the next packet, but we need to check the next page first to be sure because the packet may
3980  * straddle pages. */
3981  if (!drflac_oggbs__goto_next_page(oggbs))
3982  return DRFLAC_FALSE;
3983 
3984  /* If it's a fresh packet it most likely means we're at the next packet. */
3985  if ((oggbs->currentPageHeader.headerType & 0x01) == 0)
3986  return DRFLAC_TRUE;
3987  }
3988  else
3989  {
3990  /* We're at the next packet. */
3991  return DRFLAC_TRUE;
3992  }
3993  }
3994 }
3995 
3996 static drflac_bool32 drflac_oggbs__seek_to_next_frame(drflac_oggbs* oggbs)
3997 {
3998  /* The bitstream should be sitting on the first byte just after the header of the frame.
3999 
4000  * What we're actually doing here is seeking to the start of the next packet. */
4001  return drflac_oggbs__seek_to_next_packet(oggbs);
4002 }
4003 #endif
4004 
4005 static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead)
4006 {
4007  size_t bytesRead = 0;
4008  drflac_uint8* pRunningBufferOut = NULL;
4009  drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
4010 
4011  drflac_assert(oggbs != NULL);
4012 
4013  pRunningBufferOut = (drflac_uint8*)bufferOut;
4014 
4015  /* Reading is done page-by-page. If we've run out of bytes in the page we need to move to the next one. */
4016  while (bytesRead < bytesToRead)
4017  {
4018  size_t bytesRemainingToRead = bytesToRead - bytesRead;
4019 
4020  if (oggbs->bytesRemainingInPage >= bytesRemainingToRead) {
4021  drflac_copy_memory(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), bytesRemainingToRead);
4022  bytesRead += bytesRemainingToRead;
4023  oggbs->bytesRemainingInPage -= (drflac_uint32)bytesRemainingToRead;
4024  break;
4025  }
4026 
4027  /* If we get here it means some of the requested data is contained in the next pages. */
4028  if (oggbs->bytesRemainingInPage > 0)
4029  {
4030  drflac_copy_memory(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage);
4031  bytesRead += oggbs->bytesRemainingInPage;
4032  pRunningBufferOut += oggbs->bytesRemainingInPage;
4033  oggbs->bytesRemainingInPage = 0;
4034  }
4035 
4036  drflac_assert(bytesRemainingToRead > 0);
4037  if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch))
4038  break; /* Failed to go to the next page. Might have simply hit the end of the stream. */
4039  }
4040 
4041  return bytesRead;
4042 }
4043 
4044 static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_seek_origin origin)
4045 {
4046  int bytesSeeked = 0;
4047  drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
4048 
4049  drflac_assert(oggbs != NULL);
4050  drflac_assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start));
4051 
4052  /* Seeking is always forward which makes things a lot simpler. */
4053  if (origin == drflac_seek_origin_start)
4054  {
4055  if (!drflac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, drflac_seek_origin_start))
4056  return DRFLAC_FALSE;
4057 
4058  if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch))
4059  return DRFLAC_FALSE;
4060 
4061  return drflac__on_seek_ogg(pUserData, offset, drflac_seek_origin_current);
4062  }
4063 
4064  drflac_assert(origin == drflac_seek_origin_current);
4065 
4066  while (bytesSeeked < offset)
4067  {
4068  int bytesRemainingToSeek = offset - bytesSeeked;
4069  drflac_assert(bytesRemainingToSeek >= 0);
4070 
4071  if (oggbs->bytesRemainingInPage >= (size_t)bytesRemainingToSeek)
4072  {
4073  oggbs->bytesRemainingInPage -= bytesRemainingToSeek;
4074  break;
4075  }
4076 
4077  /* If we get here it means some of the requested data is contained in the next pages. */
4078  if (oggbs->bytesRemainingInPage > 0)
4079  {
4080  bytesSeeked += (int)oggbs->bytesRemainingInPage;
4081  oggbs->bytesRemainingInPage = 0;
4082  }
4083 
4084  drflac_assert(bytesRemainingToSeek > 0);
4085 
4086  /* Failed to go to the next page. We either hit the end of the stream or had a CRC mismatch. */
4087  if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch))
4088  return DRFLAC_FALSE;
4089  }
4090 
4091  return DRFLAC_TRUE;
4092 }
4093 
4094 drflac_bool32 drflac_ogg__seek_to_sample(drflac* pFlac, drflac_uint64 sampleIndex)
4095 {
4096  drflac_uint64 runningSampleCount;
4097  drflac_uint64 runningFrameBytePos;
4098  drflac_uint64 runningGranulePosition = 0;
4099  drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
4100 
4101  drflac_uint64 originalBytePos = oggbs->currentBytePos; /* For recovery. */
4102 
4103  /* First seek to the first frame. */
4104  if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFramePos))
4105  return DRFLAC_FALSE;
4106  oggbs->bytesRemainingInPage = 0;
4107 
4108  for (;;)
4109  {
4110  if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
4111  drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
4112  return DRFLAC_FALSE; /* Never did find that sample... */
4113  }
4114 
4115  runningFrameBytePos = oggbs->currentBytePos - drflac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize;
4116  if (oggbs->currentPageHeader.granulePosition*pFlac->channels >= sampleIndex)
4117  break; /* The sample is somewhere in the previous page. */
4118 
4119  /* At this point we know the sample is not in the previous page. It could possibly be in this page. For simplicity we
4120  * disregard any pages that do not begin a fresh packet. */
4121  if ((oggbs->currentPageHeader.headerType & 0x01) == 0)
4122  { /* <-- Is it a fresh page? */
4123  if (oggbs->currentPageHeader.segmentTable[0] >= 2)
4124  {
4125  drflac_uint8 firstBytesInPage[2];
4126  firstBytesInPage[0] = oggbs->pageData[0];
4127  firstBytesInPage[1] = oggbs->pageData[1];
4128 
4129  if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) /* <-- Does the page begin with a frame's sync code? */
4130  runningGranulePosition = oggbs->currentPageHeader.granulePosition*pFlac->channels;
4131 
4132  continue;
4133  }
4134  }
4135  }
4136 
4137 
4138  /* 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
4139  * 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
4140  * a new frame. This property means that after we've seeked to the page we can immediately start looping over frames until
4141  * we find the one containing the target sample. */
4142  if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, drflac_seek_origin_start))
4143  return DRFLAC_FALSE;
4144  if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch))
4145  return DRFLAC_FALSE;
4146 
4147  /* 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
4148  * looping over these frames until we find the one containing the sample we're after. */
4149  runningSampleCount = runningGranulePosition;
4150  for (;;)
4151  {
4152  drflac_uint64 sampleCountInThisFrame;
4153  drflac_uint64 firstSampleInFrame = 0;
4154  drflac_uint64 lastSampleInFrame = 0;
4155  /* There are two ways to find the sample and seek past irrelevant frames:
4156  * 1) Use the native FLAC decoder.
4157  * 2) Use Ogg's framing system.
4158  *
4159  * Both of these options have their own pros and cons. Using the native FLAC decoder is slower because it needs to
4160  * do a full decode of the frame. Using Ogg's framing system is faster, but more complicated and involves some code
4161  * duplication for the decoding of frame headers.
4162  *
4163  * Another thing to consider is that using the Ogg framing system will perform direct seeking of the physical Ogg
4164  * bitstream. This is important to consider because it means we cannot read data from the drflac_bs object using the
4165  * standard drflac__*() APIs because that will read in extra data for it's own internal caching which in turn breaks
4166  * the positioning of the read pointer of the physical Ogg bitstream. Therefore, anything that would normally be read
4167  * using the native FLAC decoding APIs, such as drflac__read_next_frame_header(), need to be re-implemented so as to
4168  * avoid the use of the drflac_bs object.
4169  *
4170  * Considering these issues, I have decided to use the slower native FLAC decoding method for the following reasons:
4171  * 1) Seeking is already partially accellerated using Ogg's paging system in the code block above.
4172  * 2) Seeking in an Ogg encapsulated FLAC stream is probably quite uncommon.
4173  * 3) Simplicity.
4174  */
4175  if (!drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header))
4176  return DRFLAC_FALSE;
4177 
4178  drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame);
4179 
4180  sampleCountInThisFrame = (lastSampleInFrame - firstSampleInFrame) + 1;
4181  if (sampleIndex < (runningSampleCount + sampleCountInThisFrame)) {
4182  /* The sample should be in this frame. We need to fully decode it, however if it's an invalid frame (a CRC mismatch), we need to pretend
4183  * it never existed and keep iterating. */
4184  drflac_result result = drflac__decode_frame(pFlac);
4185  if (result == DRFLAC_SUCCESS) {
4186  /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
4187  drflac_uint64 samplesToDecode = (size_t)(sampleIndex - runningSampleCount); /* <-- Safe cast because the maximum number of samples in a frame is 65535. */
4188  if (samplesToDecode == 0)
4189  return DRFLAC_TRUE;
4190  return drflac_read_s32(pFlac, samplesToDecode, NULL) != 0; /* <-- If this fails, something bad has happened (it should never fail). */
4191  }
4192  else
4193  {
4194  if (result == DRFLAC_CRC_MISMATCH)
4195  continue; /* CRC mismatch. Pretend this frame never existed. */
4196  return DRFLAC_FALSE;
4197  }
4198  }
4199  else
4200  {
4201  /* It's not in this frame. We need to seek past the frame, but check if there was a CRC mismatch. If so, we pretend this
4202  * frame never existed and leave the running sample count untouched. */
4203  drflac_result result = drflac__seek_to_next_frame(pFlac);
4204  if (result == DRFLAC_SUCCESS)
4205  runningSampleCount += sampleCountInThisFrame;
4206  else
4207  {
4208  if (result == DRFLAC_CRC_MISMATCH)
4209  continue; /* CRC mismatch. Pretend this frame never existed. */
4210  return DRFLAC_FALSE;
4211  }
4212  }
4213  }
4214 }
4215 
4216 
4217 drflac_bool32 drflac__init_private__ogg(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed)
4218 {
4219  /* We'll get here if the first 4 bytes of the stream were the OggS capture pattern, however it doesn't necessarily mean the
4220  * stream includes FLAC encoded audio. To check for this we need to scan the beginning-of-stream page markers and check if
4221  * any match the FLAC specification. Important to keep in mind that the stream may be multiplexed. */
4222  drflac_ogg_page_header header;
4223 
4224  drflac_uint32 crc32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
4225  drflac_uint32 bytesRead = 0;
4226  /* Pre: The bit stream should be sitting just past the 4-byte OggS capture pattern. */
4227  (void)relaxed;
4228 
4229  pInit->container = drflac_container_ogg;
4230  pInit->oggFirstBytePos = 0;
4231 
4232  if (drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS)
4233  return DRFLAC_FALSE;
4234  pInit->runningFilePos += bytesRead;
4235 
4236  for (;;)
4237  {
4238  int pageBodySize;
4239  /* Break if we're past the beginning of stream page. */
4240  if ((header.headerType & 0x02) == 0)
4241  return DRFLAC_FALSE;
4242 
4243  /* Check if it's a FLAC header. */
4244  pageBodySize = drflac_ogg__get_page_body_size(&header);
4245  if (pageBodySize == 51)
4246  {
4247  /* 51 = the lacing value of the FLAC header packet.
4248  * It could be a FLAC page... */
4249  drflac_uint32 bytesRemainingInPage = pageBodySize;
4250 
4251  drflac_uint8 packetType;
4252  if (onRead(pUserData, &packetType, 1) != 1)
4253  return DRFLAC_FALSE;
4254 
4255  bytesRemainingInPage -= 1;
4256  if (packetType == 0x7F)
4257  {
4258  /* Increasingly more likely to be a FLAC page... */
4259  drflac_uint8 sig[4];
4260  if (onRead(pUserData, sig, 4) != 4)
4261  return DRFLAC_FALSE;
4262 
4263  bytesRemainingInPage -= 4;
4264  if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') {
4265  /* Almost certainly a FLAC page... */
4266  drflac_uint8 mappingVersion[2];
4267  if (onRead(pUserData, mappingVersion, 2) != 2)
4268  return DRFLAC_FALSE;
4269 
4270  if (mappingVersion[0] != 1)
4271  return DRFLAC_FALSE; /* Only supporting version 1.x of the Ogg mapping. */
4272 
4273  /* The next 2 bytes are the non-audio packets, not including this one. We don't care about this because we're going to
4274  * be handling it in a generic way based on the serial number and packet types. */
4275  if (!onSeek(pUserData, 2, drflac_seek_origin_current))
4276  return DRFLAC_FALSE;
4277 
4278  /* Expecting the native FLAC signature "fLaC". */
4279  if (onRead(pUserData, sig, 4) != 4)
4280  return DRFLAC_FALSE;
4281 
4282  if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C')
4283  {
4284  drflac_streaminfo streaminfo;
4285  /* The remaining data in the page should be the STREAMINFO block. */
4286  drflac_uint8 isLastBlock = 0;
4287  drflac_uint8 blockType = 0;
4288  drflac_uint32 blockSize = 0;
4289  if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize))
4290  return DRFLAC_FALSE;
4291 
4292  if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34)
4293  return DRFLAC_FALSE; /* Invalid block type. First block must be the STREAMINFO block. */
4294 
4295  if (drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
4296  /* Success! */
4297  pInit->hasStreamInfoBlock = DRFLAC_TRUE;
4298  pInit->sampleRate = streaminfo.sampleRate;
4299  pInit->channels = streaminfo.channels;
4300  pInit->bitsPerSample = streaminfo.bitsPerSample;
4301  pInit->totalSampleCount = streaminfo.totalSampleCount;
4302  pInit->maxBlockSize = streaminfo.maxBlockSize;
4303  pInit->hasMetadataBlocks = !isLastBlock;
4304 
4305  if (onMeta) {
4308  metadata.pRawData = NULL;
4309  metadata.rawDataSize = 0;
4310  metadata.data.streaminfo = streaminfo;
4311  onMeta(pUserDataMD, &metadata);
4312  }
4313 
4314  pInit->runningFilePos += pageBodySize;
4315  pInit->oggFirstBytePos = pInit->runningFilePos - 79; /* Subtracting 79 will place us right on top of the "OggS" identifier of the FLAC bos page. */
4316  pInit->oggSerial = header.serialNumber;
4317  pInit->oggBosHeader = header;
4318  break;
4319  }
4320  else
4321  {
4322  /* Failed to read STREAMINFO block. Aww, so close... */
4323  return DRFLAC_FALSE;
4324  }
4325  }
4326  else
4327  {
4328  /* Invalid file. */
4329  return DRFLAC_FALSE;
4330  }
4331  }
4332  else
4333  {
4334  /* Not a FLAC header. Skip it. */
4335  if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current))
4336  return DRFLAC_FALSE;
4337  }
4338  }
4339  else
4340  {
4341  /* Not a FLAC header. Seek past the entire page and move on to the next. */
4342  if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current))
4343  return DRFLAC_FALSE;
4344  }
4345  }
4346  else
4347  {
4348  if (!onSeek(pUserData, pageBodySize, drflac_seek_origin_current))
4349  return DRFLAC_FALSE;
4350  }
4351 
4352  pInit->runningFilePos += pageBodySize;
4353 
4354  /* Read the header of the next page. */
4355  if (drflac_ogg__read_page_header(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS)
4356  return DRFLAC_FALSE;
4357  pInit->runningFilePos += bytesRead;
4358  }
4359 
4360 
4361  /* 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
4362  * 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
4363  * Ogg bistream object. */
4364  pInit->hasMetadataBlocks = DRFLAC_TRUE; /* <-- Always have at least VORBIS_COMMENT metadata block. */
4365  return DRFLAC_TRUE;
4366 }
4367 #endif
4368 
4369 drflac_bool32 drflac__init_private(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD)
4370 {
4371  drflac_uint8 id[4];
4372  drflac_bool32 relaxed;
4373 
4374  if (pInit == NULL || onRead == NULL || onSeek == NULL)
4375  return DRFLAC_FALSE;
4376 
4377  drflac_zero_memory(pInit, sizeof(*pInit));
4378  pInit->onRead = onRead;
4379  pInit->onSeek = onSeek;
4380  pInit->onMeta = onMeta;
4381  pInit->container = container;
4382  pInit->pUserData = pUserData;
4383  pInit->pUserDataMD = pUserDataMD;
4384 
4385  pInit->bs.onRead = onRead;
4386  pInit->bs.onSeek = onSeek;
4387  pInit->bs.pUserData = pUserData;
4388  drflac__reset_cache(&pInit->bs);
4389 
4390 
4391  /* If the container is explicitly defined then we can try opening in relaxed mode. */
4392  relaxed = container != drflac_container_unknown;
4393 
4394  /* Skip over any ID3 tags. */
4395  for (;;)
4396  {
4397  if (onRead(pUserData, id, 4) != 4)
4398  return DRFLAC_FALSE; /* Ran out of data. */
4399  pInit->runningFilePos += 4;
4400 
4401  if (id[0] == 'I' && id[1] == 'D' && id[2] == '3')
4402  {
4404  drflac_uint32 headerSize;
4405  drflac_uint8 header[6];
4406 
4407  if (onRead(pUserData, header, 6) != 6)
4408  return DRFLAC_FALSE; /* Ran out of data. */
4409  pInit->runningFilePos += 6;
4410 
4411  flags = header[1];
4412  drflac_copy_memory(&headerSize, header+2, 4);
4413  headerSize = drflac__unsynchsafe_32(drflac__be2host_32(headerSize));
4414  if (flags & 0x10)
4415  headerSize += 10;
4416 
4417  if (!onSeek(pUserData, headerSize, drflac_seek_origin_current))
4418  return DRFLAC_FALSE; /* Failed to seek past the tag. */
4419  pInit->runningFilePos += headerSize;
4420  }
4421  else
4422  break;
4423  }
4424 
4425  if (id[0] == 'f' && id[1] == 'L' && id[2] == 'a' && id[3] == 'C') {
4426  return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
4427  }
4428 #ifndef DR_FLAC_NO_OGG
4429  if (id[0] == 'O' && id[1] == 'g' && id[2] == 'g' && id[3] == 'S') {
4430  return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
4431  }
4432 #endif
4433 
4434  /* If we get here it means we likely don't have a header. Try opening in relaxed mode, if applicable. */
4435  if (relaxed)
4436  {
4437  if (container == drflac_container_native)
4438  return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
4439 #ifndef DR_FLAC_NO_OGG
4440  if (container == drflac_container_ogg)
4441  return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
4442 #endif
4443  }
4444 
4445  /* Unsupported container. */
4446  return DRFLAC_FALSE;
4447 }
4448 
4449 void drflac__init_from_info(drflac* pFlac, drflac_init_info* pInit)
4450 {
4451  drflac_assert(pFlac != NULL);
4452  drflac_assert(pInit != NULL);
4453 
4454  drflac_zero_memory(pFlac, sizeof(*pFlac));
4455  pFlac->bs = pInit->bs;
4456  pFlac->onMeta = pInit->onMeta;
4457  pFlac->pUserDataMD = pInit->pUserDataMD;
4458  pFlac->maxBlockSize = pInit->maxBlockSize;
4459  pFlac->sampleRate = pInit->sampleRate;
4460  pFlac->channels = (drflac_uint8)pInit->channels;
4461  pFlac->bitsPerSample = (drflac_uint8)pInit->bitsPerSample;
4462  pFlac->totalSampleCount = pInit->totalSampleCount;
4463  pFlac->container = pInit->container;
4464 }
4465 
4466 drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD)
4467 {
4468  drflac_init_info init;
4469  drflac* pFlac;
4470  drflac_uint32 decodedSamplesAllocationSize;
4471  drflac_uint32 allocationSize;
4472  drflac_uint32 wholeSIMDVectorCountPerChannel;
4473 
4474 #ifndef DRFLAC_NO_CPUID
4475  /* CPU support first. */
4476  drflac__init_cpu_caps();
4477 #endif
4478 
4479  if (!drflac__init_private(&init, onRead, onSeek, onMeta, container, pUserData, pUserDataMD))
4480  return NULL;
4481 
4482  /* The size of the allocation for the drflac object needs to be large enough to fit the following:
4483  * 1) The main members of the drflac structure
4484  * 2) A block of memory large enough to store the decoded samples of the largest frame in the stream
4485  * 3) If the container is Ogg, a drflac_oggbs object
4486  *
4487  * The complicated part of the allocation is making sure there's enough room the decoded samples, taking into consideration
4488  * the different SIMD instruction sets.
4489  */
4490  allocationSize = sizeof(drflac);
4491 
4492  /* The allocation size for decoded frames depends on the number of 32-bit integers that fit inside the largest SIMD vector
4493  * we are supporting. */
4494  if ((init.maxBlockSize % (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) == 0) {
4495  wholeSIMDVectorCountPerChannel = (init.maxBlockSize / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32)));
4496  } else {
4497  wholeSIMDVectorCountPerChannel = (init.maxBlockSize / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) + 1;
4498  }
4499 
4500  decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * DRFLAC_MAX_SIMD_VECTOR_SIZE * init.channels;
4501 
4502  allocationSize += decodedSamplesAllocationSize;
4503  allocationSize += DRFLAC_MAX_SIMD_VECTOR_SIZE; /* Allocate extra bytes to ensure we have enough for alignment. */
4504 
4505 #ifndef DR_FLAC_NO_OGG
4506  /* There's additional data required for Ogg streams. */
4507  if (init.container == drflac_container_ogg)
4508  allocationSize += sizeof(drflac_oggbs);
4509 #endif
4510 
4511  pFlac = (drflac*)DRFLAC_MALLOC(allocationSize);
4512  drflac__init_from_info(pFlac, &init);
4513  pFlac->pDecodedSamples = (drflac_int32*)drflac_align((size_t)pFlac->pExtraData, DRFLAC_MAX_SIMD_VECTOR_SIZE);
4514 
4515 #ifndef DR_FLAC_NO_OGG
4516  if (init.container == drflac_container_ogg) {
4517  drflac_oggbs* oggbs = (drflac_oggbs*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize);
4518  oggbs->onRead = onRead;
4519  oggbs->onSeek = onSeek;
4520  oggbs->pUserData = pUserData;
4521  oggbs->currentBytePos = init.oggFirstBytePos;
4522  oggbs->firstBytePos = init.oggFirstBytePos;
4523  oggbs->serialNumber = init.oggSerial;
4524  oggbs->bosPageHeader = init.oggBosHeader;
4525  oggbs->bytesRemainingInPage = 0;
4526 
4527  /* The Ogg bistream needs to be layered on top of the original bitstream. */
4528  pFlac->bs.onRead = drflac__on_read_ogg;
4529  pFlac->bs.onSeek = drflac__on_seek_ogg;
4530  pFlac->bs.pUserData = (void*)oggbs;
4531  pFlac->_oggbs = (void*)oggbs;
4532  }
4533 #endif
4534 
4535  /* Decode metadata before returning. */
4536  if (init.hasMetadataBlocks)
4537  {
4538  if (!drflac__read_and_decode_metadata(pFlac))
4539  {
4540  DRFLAC_FREE(pFlac);
4541  return NULL;
4542  }
4543  }
4544 
4545  /* If we get here, but don't have a STREAMINFO block, it means we've opened the stream in relaxed mode and need to decode
4546  * the first frame. */
4547  if (!init.hasStreamInfoBlock)
4548  {
4549  pFlac->currentFrame.header = init.firstFrameHeader;
4550  do
4551  {
4552  drflac_result result = drflac__decode_frame(pFlac);
4553  if (result == DRFLAC_SUCCESS)
4554  break;
4555 
4556  if (result == DRFLAC_CRC_MISMATCH)
4557  {
4558  if (drflac__read_next_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFrame.header))
4559  continue;
4560  }
4561  DRFLAC_FREE(pFlac);
4562  return NULL;
4563  } while (1);
4564  }
4565 
4566  return pFlac;
4567 }
4568 
4569 #ifndef DR_FLAC_NO_STDIO
4570 typedef void* drflac_file;
4571 
4572 #if defined(DR_FLAC_NO_WIN32_IO) || !defined(_WIN32)
4573 #include <stdio.h>
4574 
4575 static size_t drflac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead)
4576 {
4577  return fread(bufferOut, 1, bytesToRead, (FILE*)pUserData);
4578 }
4579 
4580 static drflac_bool32 drflac__on_seek_stdio(void* pUserData, int offset, drflac_seek_origin origin)
4581 {
4582  drflac_assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start));
4583 
4584  return fseek((FILE*)pUserData, offset, (origin == drflac_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
4585 }
4586 
4587 static drflac_file drflac__open_file_handle(const char* filename)
4588 {
4589  FILE* pFile;
4590 #ifdef _MSC_VER
4591  if (fopen_s(&pFile, filename, "rb") != 0) {
4592  return NULL;
4593  }
4594 #else
4595  pFile = fopen(filename, "rb");
4596  if (pFile == NULL) {
4597  return NULL;
4598  }
4599 #endif
4600 
4601  return (drflac_file)pFile;
4602 }
4603 
4604 static void drflac__close_file_handle(drflac_file file)
4605 {
4606  fclose((FILE*)file);
4607 }
4608 #else
4609 #include <windows.h>
4610 
4611 /* This doesn't seem to be defined for VC6. */
4612 #ifndef INVALID_SET_FILE_POINTER
4613 #define INVALID_SET_FILE_POINTER ((DWORD)-1)
4614 #endif
4615 
4616 static size_t drflac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead)
4617 {
4618  DWORD bytesRead;
4619 
4620  drflac_assert(bytesToRead < 0xFFFFFFFF); /* dr_flac will never request huge amounts of data at a time. This is a safe assertion. */
4621 
4622  ReadFile((HANDLE)pUserData, bufferOut, (DWORD)bytesToRead, &bytesRead, NULL);
4623 
4624  return (size_t)bytesRead;
4625 }
4626 
4627 static drflac_bool32 drflac__on_seek_stdio(void* pUserData, int offset, drflac_seek_origin origin)
4628 {
4629  drflac_assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start));
4630 
4631  return SetFilePointer((HANDLE)pUserData, offset, NULL, (origin == drflac_seek_origin_current) ? FILE_CURRENT : FILE_BEGIN) != INVALID_SET_FILE_POINTER;
4632 }
4633 
4634 static drflac_file drflac__open_file_handle(const char* filename)
4635 {
4636  HANDLE hFile = CreateFileA(filename, FILE_GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
4637  if (hFile == INVALID_HANDLE_VALUE) {
4638  return NULL;
4639  }
4640 
4641  return (drflac_file)hFile;
4642 }
4643 
4644 static void drflac__close_file_handle(drflac_file file)
4645 {
4646  CloseHandle((HANDLE)file);
4647 }
4648 #endif
4649 
4650 
4651 drflac* drflac_open_file(const char* filename)
4652 {
4653  drflac_file file = drflac__open_file_handle(filename);
4654  if (file == NULL) {
4655  return NULL;
4656  }
4657 
4658  drflac* pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, (void*)file);
4659  if (pFlac == NULL) {
4660  drflac__close_file_handle(file);
4661  return NULL;
4662  }
4663 
4664  return pFlac;
4665 }
4666 
4667 drflac* drflac_open_file_with_metadata(const char* filename, drflac_meta_proc onMeta, void* pUserData)
4668 {
4669  drflac_file file = drflac__open_file_handle(filename);
4670  if (file == NULL) {
4671  return NULL;
4672  }
4673 
4674  drflac* pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, onMeta, drflac_container_unknown, (void*)file, pUserData);
4675  if (pFlac == NULL) {
4676  drflac__close_file_handle(file);
4677  return pFlac;
4678  }
4679 
4680  return pFlac;
4681 }
4682 #endif /* DR_FLAC_NO_STDIO */
4683 
4684 static size_t drflac__on_read_memory(void* pUserData, void* bufferOut, size_t bytesToRead)
4685 {
4686  size_t bytesRemaining;
4687  drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
4688  drflac_assert(memoryStream != NULL);
4689  drflac_assert(memoryStream->dataSize >= memoryStream->currentReadPos);
4690 
4691  bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos;
4692  if (bytesToRead > bytesRemaining)
4693  bytesToRead = bytesRemaining;
4694 
4695  if (bytesToRead > 0)
4696  {
4697  drflac_copy_memory(bufferOut, memoryStream->data + memoryStream->currentReadPos, bytesToRead);
4698  memoryStream->currentReadPos += bytesToRead;
4699  }
4700 
4701  return bytesToRead;
4702 }
4703 
4704 static drflac_bool32 drflac__on_seek_memory(void* pUserData, int offset, drflac_seek_origin origin)
4705 {
4706  drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
4707  drflac_assert(memoryStream != NULL);
4708  drflac_assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start));
4709 
4710  if (origin == drflac_seek_origin_current)
4711  {
4713  memoryStream->currentReadPos += offset;
4714  else
4715  memoryStream->currentReadPos = memoryStream->dataSize; /* Trying to seek too far forward. */
4716  } else {
4718  memoryStream->currentReadPos = offset;
4719  } else {
4720  memoryStream->currentReadPos = memoryStream->dataSize; /* Trying to seek too far forward. */
4721  }
4722  }
4723 
4724  return DRFLAC_TRUE;
4725 }
4726 
4727 drflac* drflac_open_memory(const void* data, size_t dataSize)
4728 {
4729  drflac__memory_stream memoryStream;
4730  drflac* pFlac;
4731 
4732  memoryStream.data = (const unsigned char*)data;
4733  memoryStream.dataSize = dataSize;
4734  memoryStream.currentReadPos = 0;
4735  pFlac = drflac_open(drflac__on_read_memory, drflac__on_seek_memory, &memoryStream);
4736  if (pFlac == NULL)
4737  return NULL;
4738 
4739  pFlac->memoryStream = memoryStream;
4740 
4741  /* This is an awful hack... */
4742 #ifndef DR_FLAC_NO_OGG
4743  if (pFlac->container == drflac_container_ogg)
4744  {
4745  drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
4746  oggbs->pUserData = &pFlac->memoryStream;
4747  }
4748  else
4749 #endif
4750  {
4751  pFlac->bs.pUserData = &pFlac->memoryStream;
4752  }
4753 
4754  return pFlac;
4755 }
4756 
4757 drflac* drflac_open_memory_with_metadata(const void* data, size_t dataSize, drflac_meta_proc onMeta, void* pUserData)
4758 {
4759  drflac__memory_stream memoryStream;
4760  drflac* pFlac;
4761 
4762  memoryStream.data = (const unsigned char*)data;
4763  memoryStream.dataSize = dataSize;
4764  memoryStream.currentReadPos = 0;
4765 
4766  pFlac = drflac_open_with_metadata_private(drflac__on_read_memory, drflac__on_seek_memory, onMeta, drflac_container_unknown, &memoryStream, pUserData);
4767  if (pFlac == NULL)
4768  return NULL;
4769 
4770  pFlac->memoryStream = memoryStream;
4771 
4772  /* This is an awful hack... */
4773 #ifndef DR_FLAC_NO_OGG
4774  if (pFlac->container == drflac_container_ogg)
4775  {
4776  drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
4777  oggbs->pUserData = &pFlac->memoryStream;
4778  }
4779  else
4780 #endif
4781  {
4782  pFlac->bs.pUserData = &pFlac->memoryStream;
4783  }
4784 
4785  return pFlac;
4786 }
4787 
4788 
4789 
4790 drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData)
4791 {
4792  return drflac_open_with_metadata_private(onRead, onSeek, NULL, drflac_container_unknown, pUserData, pUserData);
4793 }
4794 drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData)
4795 {
4796  return drflac_open_with_metadata_private(onRead, onSeek, NULL, container, pUserData, pUserData);
4797 }
4798 
4799 drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData)
4800 {
4801  return drflac_open_with_metadata_private(onRead, onSeek, onMeta, drflac_container_unknown, pUserData, pUserData);
4802 }
4804 {
4805  return drflac_open_with_metadata_private(onRead, onSeek, onMeta, container, pUserData, pUserData);
4806 }
4807 
4808 void drflac_close(drflac* pFlac)
4809 {
4810  if (pFlac == NULL) {
4811  return;
4812  }
4813 
4814 #ifndef DR_FLAC_NO_STDIO
4815  /* If we opened the file with drflac_open_file() we will want to close the file handle. We can know whether or not drflac_open_file()
4816  * was used by looking at the callbacks. */
4817  if (pFlac->bs.onRead == drflac__on_read_stdio)
4818  drflac__close_file_handle((drflac_file)pFlac->bs.pUserData);
4819 
4820 #ifndef DR_FLAC_NO_OGG
4821  /* Need to clean up Ogg streams a bit differently due to the way the bit streaming is chained. */
4822  if (pFlac->container == drflac_container_ogg)
4823  {
4824  drflac_assert(pFlac->bs.onRead == drflac__on_read_ogg);
4825  drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
4826  if (oggbs->onRead == drflac__on_read_stdio)
4827  drflac__close_file_handle((drflac_file)oggbs->pUserData);
4828  }
4829 #endif
4830 #endif
4831 
4832  DRFLAC_FREE(pFlac);
4833 }
4834 
4835 drflac_uint64 drflac__read_s32__misaligned(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int32* bufferOut)
4836 {
4837  drflac_uint64 samplesRead = 0;
4838  unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment);
4839 
4840  /* We should never be calling this when the number of samples to read is >= the sample count. */
4841  drflac_assert(samplesToRead < channelCount);
4842  drflac_assert(pFlac->currentFrame.samplesRemaining > 0 && samplesToRead <= pFlac->currentFrame.samplesRemaining);
4843 
4844  while (samplesToRead > 0)
4845  {
4846  drflac_uint64 totalSamplesInFrame = pFlac->currentFrame.header.blockSize * channelCount;
4847  drflac_uint64 samplesReadFromFrameSoFar = totalSamplesInFrame - pFlac->currentFrame.samplesRemaining;
4848  drflac_uint64 channelIndex = samplesReadFromFrameSoFar % channelCount;
4849 
4850  drflac_uint64 nextSampleInFrame = samplesReadFromFrameSoFar / channelCount;
4851 
4852  int decodedSample = 0;
4853  switch (pFlac->currentFrame.header.channelAssignment)
4854  {
4855  case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
4856  {
4857  if (channelIndex == 0) {
4858  decodedSample = pFlac->currentFrame.subframes[channelIndex].pDecodedSamples[nextSampleInFrame];
4859  } else {
4860  int side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame];
4861  int left = pFlac->currentFrame.subframes[channelIndex - 1].pDecodedSamples[nextSampleInFrame];
4862  decodedSample = left - side;
4863  }
4864  } break;
4865 
4866  case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
4867  {
4868  if (channelIndex == 0) {
4869  int side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame];
4870  int right = pFlac->currentFrame.subframes[channelIndex + 1].pDecodedSamples[nextSampleInFrame];
4871  decodedSample = side + right;
4872  } else {
4873  decodedSample = pFlac->currentFrame.subframes[channelIndex].pDecodedSamples[nextSampleInFrame];
4874  }
4875  } break;
4876 
4877  case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
4878  {
4879  int mid;
4880  int side;
4881  if (channelIndex == 0) {
4882  mid = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame];
4883  side = pFlac->currentFrame.subframes[channelIndex + 1].pDecodedSamples[nextSampleInFrame];
4884 
4885  mid = (((unsigned int)mid) << 1) | (side & 0x01);
4886  decodedSample = (mid + side) >> 1;
4887  } else {
4888  mid = pFlac->currentFrame.subframes[channelIndex - 1].pDecodedSamples[nextSampleInFrame];
4889  side = pFlac->currentFrame.subframes[channelIndex + 0].pDecodedSamples[nextSampleInFrame];
4890 
4891  mid = (((unsigned int)mid) << 1) | (side & 0x01);
4892  decodedSample = (mid - side) >> 1;
4893  }
4894  } break;
4895 
4896  case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
4897  default:
4898  {
4899  decodedSample = pFlac->currentFrame.subframes[channelIndex].pDecodedSamples[nextSampleInFrame];
4900  } break;
4901  }
4902 
4903 
4904  decodedSample <<= ((32 - pFlac->bitsPerSample) + pFlac->currentFrame.subframes[channelIndex].wastedBitsPerSample);
4905 
4906  if (bufferOut) {
4907  *bufferOut++ = decodedSample;
4908  }
4909 
4910  samplesRead += 1;
4911  pFlac->currentFrame.samplesRemaining -= 1;
4912  samplesToRead -= 1;
4913  }
4914 
4915  return samplesRead;
4916 }
4917 
4918 drflac_uint64 drflac__seek_forward_by_samples(drflac* pFlac, drflac_uint64 samplesToRead)
4919 {
4920  drflac_uint64 samplesRead = 0;
4921  while (samplesToRead > 0) {
4922  if (pFlac->currentFrame.samplesRemaining == 0)
4923  {
4924  if (!drflac__read_and_decode_next_frame(pFlac))
4925  break; /* Couldn't read the next frame, so just break from the loop and return. */
4926  }
4927  else
4928  {
4929  samplesRead += 1;
4930  pFlac->currentFrame.samplesRemaining -= 1;
4931  samplesToRead -= 1;
4932  }
4933  }
4934 
4935  return samplesRead;
4936 }
4937 
4938 drflac_uint64 drflac_read_s32(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int32* bufferOut)
4939 {
4940  drflac_uint64 samplesRead = 0;
4941  /* Note that <bufferOut> is allowed to be null, in which case this will be treated as something like a seek. */
4942  if (pFlac == NULL || samplesToRead == 0)
4943  return 0;
4944 
4945  if (bufferOut == NULL)
4946  return drflac__seek_forward_by_samples(pFlac, samplesToRead);
4947 
4948  while (samplesToRead > 0)
4949  {
4950  /* If we've run out of samples in this frame, go to the next. */
4951  if (pFlac->currentFrame.samplesRemaining == 0)
4952  {
4953  if (!drflac__read_and_decode_next_frame(pFlac))
4954  break; /* Couldn't read the next frame, so just break from the loop and return. */
4955  }
4956  else
4957  {
4958  drflac_uint64 alignedSamplesRead;
4959  drflac_uint64 alignedSampleCountPerChannel;
4960  drflac_uint64 firstAlignedSampleInFrame;
4961  unsigned int unusedBitsPerSample;
4962  /* Here is where we grab the samples and interleave them. */
4963  unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFrame.header.channelAssignment);
4964  drflac_uint64 totalSamplesInFrame = pFlac->currentFrame.header.blockSize * channelCount;
4965  drflac_uint64 samplesReadFromFrameSoFar = totalSamplesInFrame - pFlac->currentFrame.samplesRemaining;
4966  drflac_uint64 misalignedSampleCount = samplesReadFromFrameSoFar % channelCount;
4967  if (misalignedSampleCount > 0)
4968  {
4969  drflac_uint64 misalignedSamplesRead = drflac__read_s32__misaligned(pFlac, misalignedSampleCount, bufferOut);
4970  samplesRead += misalignedSamplesRead;
4971  samplesReadFromFrameSoFar += misalignedSamplesRead;
4972  bufferOut += misalignedSamplesRead;
4973  samplesToRead -= misalignedSamplesRead;
4974  }
4975 
4976  alignedSampleCountPerChannel = samplesToRead / channelCount;
4977  if (alignedSampleCountPerChannel > pFlac->currentFrame.samplesRemaining / channelCount)
4978  alignedSampleCountPerChannel = pFlac->currentFrame.samplesRemaining / channelCount;
4979 
4980  firstAlignedSampleInFrame = samplesReadFromFrameSoFar / channelCount;
4981  unusedBitsPerSample = 32 - pFlac->bitsPerSample;
4982 
4983  switch (pFlac->currentFrame.header.channelAssignment)
4984  {
4985  case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
4986  {
4987  drflac_uint64 i;
4988  const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + firstAlignedSampleInFrame;
4989  const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame;
4990 
4991  for (i = 0; i < alignedSampleCountPerChannel; ++i) {
4992  int left = pDecodedSamples0[i];
4993  int side = pDecodedSamples1[i];
4994  int right = left - side;
4995 
4996  bufferOut[i*2+0] = left << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample);
4997  bufferOut[i*2+1] = right << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample);
4998  }
4999  } break;
5000 
5001  case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
5002  {
5003  drflac_uint64 i;
5004  const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + firstAlignedSampleInFrame;
5005  const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame;
5006 
5007  for (i = 0; i < alignedSampleCountPerChannel; ++i) {
5008  int side = pDecodedSamples0[i];
5009  int right = pDecodedSamples1[i];
5010  int left = right + side;
5011 
5012  bufferOut[i*2+0] = left << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample);
5013  bufferOut[i*2+1] = right << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample);
5014  }
5015  } break;
5016 
5017  case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
5018  {
5019  drflac_uint64 i;
5020  const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + firstAlignedSampleInFrame;
5021  const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame;
5022 
5023  for (i = 0; i < alignedSampleCountPerChannel; ++i) {
5024  int side = pDecodedSamples1[i];
5025  int mid = (((drflac_uint32)pDecodedSamples0[i]) << 1) | (side & 0x01);
5026 
5027  bufferOut[i*2+0] = ((mid + side) >> 1) << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample);
5028  bufferOut[i*2+1] = ((mid - side) >> 1) << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample);
5029  }
5030  } break;
5031 
5032  case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
5033  default:
5034  {
5035  if (pFlac->currentFrame.header.channelAssignment == 1) /* 1 = Stereo */
5036  {
5037  drflac_uint64 i;
5038  /* Stereo optimized inner loop unroll. */
5039  const drflac_int32* pDecodedSamples0 = pFlac->currentFrame.subframes[0].pDecodedSamples + firstAlignedSampleInFrame;
5040  const drflac_int32* pDecodedSamples1 = pFlac->currentFrame.subframes[1].pDecodedSamples + firstAlignedSampleInFrame;
5041 
5042  for (i = 0; i < alignedSampleCountPerChannel; ++i) {
5043  bufferOut[i*2+0] = pDecodedSamples0[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[0].wastedBitsPerSample);
5044  bufferOut[i*2+1] = pDecodedSamples1[i] << (unusedBitsPerSample + pFlac->currentFrame.subframes[1].wastedBitsPerSample);
5045  }
5046  }
5047  else
5048  {
5049  drflac_uint64 i;
5050 
5051  /* Generic interleaving. */
5052  for (i = 0; i < alignedSampleCountPerChannel; ++i)
5053  {
5054  unsigned j;
5055  for (j = 0; j < channelCount; ++j)
5056  {
5057  bufferOut[(i*channelCount)+j] = (pFlac->currentFrame.subframes[j].pDecodedSamples[firstAlignedSampleInFrame + i]) << (unusedBitsPerSample + pFlac->currentFrame.subframes[j].wastedBitsPerSample);
5058  }
5059  }
5060  }
5061  } break;
5062  }
5063 
5064  alignedSamplesRead = alignedSampleCountPerChannel * channelCount;
5065  samplesRead += alignedSamplesRead;
5066  samplesReadFromFrameSoFar += alignedSamplesRead;
5067  bufferOut += alignedSamplesRead;
5068  samplesToRead -= alignedSamplesRead;
5069  pFlac->currentFrame.samplesRemaining -= (unsigned int)alignedSamplesRead;
5070 
5071  /* At this point we may still have some excess samples left to read. */
5072  if (samplesToRead > 0 && pFlac->currentFrame.samplesRemaining > 0) {
5073  drflac_uint64 excessSamplesRead = 0;
5074  if (samplesToRead < pFlac->currentFrame.samplesRemaining) {
5075  excessSamplesRead = drflac__read_s32__misaligned(pFlac, samplesToRead, bufferOut);
5076  } else {
5077  excessSamplesRead = drflac__read_s32__misaligned(pFlac, pFlac->currentFrame.samplesRemaining, bufferOut);
5078  }
5079 
5080  samplesRead += excessSamplesRead;
5081  samplesReadFromFrameSoFar += excessSamplesRead;
5082  bufferOut += excessSamplesRead;
5083  samplesToRead -= excessSamplesRead;
5084  }
5085  }
5086  }
5087 
5088  return samplesRead;
5089 }
5090 
5091 drflac_uint64 drflac_read_s16(drflac* pFlac, drflac_uint64 samplesToRead, drflac_int16* pBufferOut)
5092 {
5093  /* This reads samples in 2 passes and can probably be optimized. */
5094  drflac_uint64 totalSamplesRead = 0;
5095 
5096  while (samplesToRead > 0)
5097  {
5098  drflac_uint64 i;
5099  drflac_int32 samples32[4096];
5100  drflac_uint64 samplesJustRead = drflac_read_s32(pFlac, (samplesToRead > 4096) ? 4096 : samplesToRead, samples32);
5101  if (samplesJustRead == 0)
5102  break; /* Reached the end. */
5103 
5104  /* s32 -> s16 */
5105  for (i = 0; i < samplesJustRead; ++i)
5106  pBufferOut[i] = (drflac_int16)(samples32[i] >> 16);
5107 
5108  totalSamplesRead += samplesJustRead;
5109  samplesToRead -= samplesJustRead;
5110  pBufferOut += samplesJustRead;
5111  }
5112 
5113  return totalSamplesRead;
5114 }
5115 
5116 drflac_uint64 drflac_read_f32(drflac* pFlac, drflac_uint64 samplesToRead, float* pBufferOut)
5117 {
5118  /* This reads samples in 2 passes and can probably be optimized. */
5119  drflac_uint64 totalSamplesRead = 0;
5120 
5121  while (samplesToRead > 0)
5122  {
5123  drflac_uint64 i;
5124  drflac_int32 samples32[4096];
5125  drflac_uint64 samplesJustRead = drflac_read_s32(pFlac, (samplesToRead > 4096) ? 4096 : samplesToRead, samples32);
5126  if (samplesJustRead == 0)
5127  break; /* Reached the end. */
5128 
5129  /* s32 -> f32 */
5130  for (i = 0; i < samplesJustRead; ++i)
5131  pBufferOut[i] = (float)(samples32[i] / 2147483648.0);
5132 
5133  totalSamplesRead += samplesJustRead;
5134  samplesToRead -= samplesJustRead;
5135  pBufferOut += samplesJustRead;
5136  }
5137 
5138  return totalSamplesRead;
5139 }
5140 
5142 {
5143  if (pFlac == NULL)
5144  return DRFLAC_FALSE;
5145 
5146  /* 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
5147  * when the decoder was opened. */
5148  if (pFlac->firstFramePos == 0)
5149  return DRFLAC_FALSE;
5150 
5151  if (sampleIndex == 0)
5152  return drflac__seek_to_first_frame(pFlac);
5153 
5154  /* Clamp the sample to the end. */
5155  if (sampleIndex >= pFlac->totalSampleCount)
5156  sampleIndex = pFlac->totalSampleCount - 1;
5157 
5158 
5159  /* Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so
5160  * we'll instead use Ogg's natural seeking facility. */
5161 #ifndef DR_FLAC_NO_OGG
5162  if (pFlac->container == drflac_container_ogg)
5163  return drflac_ogg__seek_to_sample(pFlac, sampleIndex);
5164  else
5165 #endif
5166  {
5167  /* First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower. */
5168  if (!drflac__seek_to_sample__seek_table(pFlac, sampleIndex))
5169  return drflac__seek_to_sample__brute_force(pFlac, sampleIndex);
5170  }
5171 
5172 
5173  return DRFLAC_TRUE;
5174 }
5175 
5176 
5177 
5178 /* High Level APIs */
5179 
5180 /* I couldn't figure out where SIZE_MAX was defined for VC6. If anybody knows, let me know. */
5181 #if defined(_MSC_VER) && _MSC_VER <= 1200
5182 #ifdef DRFLAC_64BIT
5183 #define SIZE_MAX ((drflac_uint64)0xFFFFFFFFFFFFFFFF)
5184 #else
5185 #define SIZE_MAX 0xFFFFFFFF
5186 #endif
5187 #endif
5188 
5189 /* Using a macro as the definition of the drflac__full_decode_and_close_*() API family. Sue me. */
5190 #define DRFLAC_DEFINE_FULL_DECODE_AND_CLOSE(extension, type) \
5191 static type* drflac__full_decode_and_close_ ## extension (drflac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalSampleCountOut)\
5192 { \
5193  drflac_uint64 totalSampleCount; \
5194  type* pSampleData = NULL; \
5195  drflac_assert(pFlac != NULL); \
5196  totalSampleCount = pFlac->totalSampleCount; \
5197  if (totalSampleCount == 0) { \
5198  type buffer[4096]; \
5199  drflac_uint64 samplesRead; \
5200  size_t sampleDataBufferSize = sizeof(buffer); \
5201  pSampleData = (type*)DRFLAC_MALLOC(sampleDataBufferSize); \
5202  if (pSampleData == NULL) \
5203  goto on_error; \
5204  while ((samplesRead = (drflac_uint64)drflac_read_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0]), buffer)) > 0) { \
5205  if (((totalSampleCount + samplesRead) * sizeof(type)) > sampleDataBufferSize) { \
5206  type *pNewSampleData; \
5207  sampleDataBufferSize *= 2; \
5208  pNewSampleData = (type*)DRFLAC_REALLOC(pSampleData, sampleDataBufferSize); \
5209  if (pNewSampleData == NULL) { \
5210  DRFLAC_FREE(pSampleData); \
5211  goto on_error; \
5212  } \
5213  \
5214  pSampleData = pNewSampleData; \
5215  } \
5216  \
5217  drflac_copy_memory(pSampleData + totalSampleCount, buffer, (size_t)(samplesRead*sizeof(type))); \
5218  totalSampleCount += samplesRead; \
5219  } \
5220  \
5221  /* At this point everything should be decoded, but we just want to fill the unused part buffer with silence - need to \
5222  protect those ears from random noise! */ \
5223  drflac_zero_memory(pSampleData + totalSampleCount, (size_t)(sampleDataBufferSize - totalSampleCount*sizeof(type))); \
5224  } else { \
5225  drflac_uint64 dataSize = totalSampleCount * sizeof(type); \
5226  if (dataSize > SIZE_MAX) { \
5227  goto on_error; /* The decoded data is too big. */ \
5228  } \
5229  \
5230  pSampleData = (type*)DRFLAC_MALLOC((size_t)dataSize); /* <-- Safe cast as per the check above. */ \
5231  if (pSampleData == NULL) { \
5232  goto on_error; \
5233  } \
5234  \
5235  totalSampleCount = drflac_read_##extension(pFlac, pFlac->totalSampleCount, pSampleData); \
5236  } \
5237  \
5238  if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \
5239  if (channelsOut) *channelsOut = pFlac->channels; \
5240  if (totalSampleCountOut) *totalSampleCountOut = totalSampleCount; \
5241  \
5242  drflac_close(pFlac); \
5243  return pSampleData; \
5244  \
5245 on_error: \
5246  drflac_close(pFlac); \
5247  return NULL; \
5248 }
5249 
5250 DRFLAC_DEFINE_FULL_DECODE_AND_CLOSE(s32, drflac_int32)
5251 DRFLAC_DEFINE_FULL_DECODE_AND_CLOSE(s16, drflac_int16)
5252 DRFLAC_DEFINE_FULL_DECODE_AND_CLOSE(f32, float)
5253 
5254 drflac_int32* drflac_open_and_decode_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5255 {
5256  drflac* pFlac;
5257  /* Safety. */
5258  if (sampleRate) *sampleRate = 0;
5259  if (channels) *channels = 0;
5260  if (totalSampleCount) *totalSampleCount = 0;
5261 
5262  pFlac = drflac_open(onRead, onSeek, pUserData);
5263  if (pFlac == NULL)
5264  return NULL;
5265 
5266  return drflac__full_decode_and_close_s32(pFlac, channels, sampleRate, totalSampleCount);
5267 }
5268 
5269 drflac_int16* drflac_open_and_decode_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5270 {
5271  drflac* pFlac;
5272  /* Safety. */
5273  if (sampleRate) *sampleRate = 0;
5274  if (channels) *channels = 0;
5275  if (totalSampleCount) *totalSampleCount = 0;
5276 
5277  pFlac = drflac_open(onRead, onSeek, pUserData);
5278  if (pFlac == NULL)
5279  return NULL;
5280 
5281  return drflac__full_decode_and_close_s16(pFlac, channels, sampleRate, totalSampleCount);
5282 }
5283 
5284 float* drflac_open_and_decode_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5285 {
5286  drflac* pFlac;
5287  /* Safety. */
5288  if (sampleRate) *sampleRate = 0;
5289  if (channels) *channels = 0;
5290  if (totalSampleCount) *totalSampleCount = 0;
5291 
5292  pFlac = drflac_open(onRead, onSeek, pUserData);
5293  if (pFlac == NULL)
5294  return NULL;
5295 
5296  return drflac__full_decode_and_close_f32(pFlac, channels, sampleRate, totalSampleCount);
5297 }
5298 
5299 #ifndef DR_FLAC_NO_STDIO
5300 drflac_int32* drflac_open_and_decode_file_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5301 {
5302  drflac* pFlac;
5303  if (sampleRate) *sampleRate = 0;
5304  if (channels) *channels = 0;
5305  if (totalSampleCount) *totalSampleCount = 0;
5306 
5307  pFlac = drflac_open_file(filename);
5308  if (pFlac == NULL)
5309  return NULL;
5310 
5311  return drflac__full_decode_and_close_s32(pFlac, channels, sampleRate, totalSampleCount);
5312 }
5313 
5314 drflac_int16* drflac_open_and_decode_file_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5315 {
5316  drflac* pFlac;
5317  if (sampleRate) *sampleRate = 0;
5318  if (channels) *channels = 0;
5319  if (totalSampleCount) *totalSampleCount = 0;
5320 
5321  pFlac = drflac_open_file(filename);
5322  if (pFlac == NULL)
5323  return NULL;
5324 
5325  return drflac__full_decode_and_close_s16(pFlac, channels, sampleRate, totalSampleCount);
5326 }
5327 
5328 float* drflac_open_and_decode_file_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5329 {
5330  drflac* pFlac;
5331  if (sampleRate) *sampleRate = 0;
5332  if (channels) *channels = 0;
5333  if (totalSampleCount) *totalSampleCount = 0;
5334 
5335  pFlac = drflac_open_file(filename);
5336  if (pFlac == NULL)
5337  return NULL;
5338 
5339  return drflac__full_decode_and_close_f32(pFlac, channels, sampleRate, totalSampleCount);
5340 }
5341 #endif
5342 
5343 drflac_int32* drflac_open_and_decode_memory_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5344 {
5345  drflac *pFlac;
5346 
5347  if (sampleRate) *sampleRate = 0;
5348  if (channels) *channels = 0;
5349  if (totalSampleCount) *totalSampleCount = 0;
5350 
5351  pFlac = drflac_open_memory(data, dataSize);
5352  if (pFlac == NULL)
5353  return NULL;
5354 
5355  return drflac__full_decode_and_close_s32(pFlac, channels, sampleRate, totalSampleCount);
5356 }
5357 
5358 drflac_int16* drflac_open_and_decode_memory_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5359 {
5360  drflac* pFlac;
5361  if (sampleRate) *sampleRate = 0;
5362  if (channels) *channels = 0;
5363  if (totalSampleCount) *totalSampleCount = 0;
5364 
5365  pFlac = drflac_open_memory(data, dataSize);
5366  if (pFlac == NULL)
5367  return NULL;
5368 
5369  return drflac__full_decode_and_close_s16(pFlac, channels, sampleRate, totalSampleCount);
5370 }
5371 
5372 float* drflac_open_and_decode_memory_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalSampleCount)
5373 {
5374  drflac* pFlac;
5375  if (sampleRate) *sampleRate = 0;
5376  if (channels) *channels = 0;
5377  if (totalSampleCount) *totalSampleCount = 0;
5378 
5379  pFlac = drflac_open_memory(data, dataSize);
5380  if (pFlac == NULL)
5381  return NULL;
5382 
5383  return drflac__full_decode_and_close_f32(pFlac, channels, sampleRate, totalSampleCount);
5384 }
5385 
5386 void drflac_free(void* pSampleDataReturnedByOpenAndDecode)
5387 {
5388  DRFLAC_FREE(pSampleDataReturnedByOpenAndDecode);
5389 }
5390 
5391 
5392 
5393 
5394 void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const char* pComments)
5395 {
5396  if (pIter == NULL)
5397  return;
5398 
5399  pIter->countRemaining = commentCount;
5400  pIter->pRunningData = pComments;
5401 }
5402 
5403 const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut)
5404 {
5405  const char* pComment;
5407  /* Safety. */
5408  if (pCommentLengthOut) *pCommentLengthOut = 0;
5409 
5410  if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL)
5411  return NULL;
5412 
5413  length = drflac__le2host_32(*(drflac_uint32*)pIter->pRunningData);
5414  pIter->pRunningData += 4;
5415 
5416  pComment = pIter->pRunningData;
5417  pIter->pRunningData += length;
5418  pIter->countRemaining -= 1;
5419 
5420  if (pCommentLengthOut) *pCommentLengthOut = length;
5421  return pComment;
5422 }
5423 #endif /* DR_FLAC_IMPLEMENTATION */
5424 
5425 /*
5426 This is free and unencumbered software released into the public domain.
5427 
5428 Anyone is free to copy, modify, publish, use, compile, sell, or
5429 distribute this software, either in source code form or as a compiled
5430 binary, for any purpose, commercial or non-commercial, and by any
5431 means.
5432 
5433 In jurisdictions that recognize copyright laws, the author or authors
5434 of this software dedicate any and all copyright interest in the
5435 software to the public domain. We make this dedication for the benefit
5436 of the public at large and to the detriment of our heirs and
5437 successors. We intend this dedication to be an overt act of
5438 relinquishment in perpetuity of all present and future rights to this
5439 software under copyright law.
5440 
5441 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
5442 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
5443 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
5444 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
5445 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
5446 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
5447 OTHER DEALINGS IN THE SOFTWARE.
5448 
5449 For more information, please refer to <http://unlicense.org/>
5450 */
drflac_uint32 seekpointCount
Definition: dr_flac.h:153
Definition: dr_flac.h:121
Definition: dr_flac.h:237
size_t unalignedByteCount
Definition: dr_flac.h:253
drflac_seek_origin
Definition: dr_flac.h:92
drflac_bool32 isCD
Definition: dr_flac.h:169
drflac_bool32 drflac_seek_to_sample(drflac *pFlac, drflac_uint64 sampleIndex)
drflac_uint64 drflac_read_s16(drflac *pFlac, drflac_uint64 samplesToRead, drflac_int16 *pBufferOut)
drflac_uint32 sampleRate
Definition: dr_flac.h:346
void drflac_free(void *p)
int32_t drflac_int32
Definition: dr_flac.h:14
drflac_uint32 drflac_cache_t
Definition: dr_flac.h:49
drflac_uint32 samplesRemaining
Definition: dr_flac.h:330
drflac_uint32 type
Definition: dr_flac.h:124
int32_t s32
32bit signed integer
Definition: gctypes.h:24
const void * pData
Definition: dr_flac.h:147
drflac_uint16 sampleCount
Definition: dr_flac.h:104
drflac_uint32 colorDepth
Definition: dr_flac.h:183
#define INLINE
Definition: retro_inline.h:35
drflac * drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void *pUserData)
drflac_uint8 md5[16]
Definition: dr_flac.h:118
drflac__memory_stream memoryStream
Definition: dr_flac.h:382
#define DRFLAC_METADATA_BLOCK_TYPE_CUESHEET
Definition: dr_flac.h:58
const char * pRunningData
Definition: dr_flac.h:620
__asm__(".arm\n" ".align 4\n" ".globl co_switch_arm\n" ".globl _co_switch_arm\n" "co_switch_arm:\n" "_co_switch_arm:\n" " stmia r1!, {r4, r5, r6, r7, r8, r9, r10, r11, sp, lr}\n" " ldmia r0!, {r4, r5, r6, r7, r8, r9, r10, r11, sp, pc}\n")
static char * ReadFile(const char *filename, Allocator &allocator)
Definition: schematest.cpp:15
Definition: dr_flac.h:617
drflac_uint8 channelAssignment
Definition: dr_flac.h:313
drflac_uint32 dataSize
Definition: dr_flac.h:148
size_t currentReadPos
Definition: dr_flac.h:233
drflac_uint8 trackCount
Definition: dr_flac.h:170
Definition: dr_flac.h:296
drflac_uint32 sampleRate
Definition: dr_flac.h:306
Definition: ffmpeg_core.c:151
drflac_uint8 pExtraData[1]
Definition: dr_flac.h:395
float f32
Definition: gctypes.h:43
drflac_uint32 drflac_bool32
Definition: dr_flac.h:19
Definition: dr_flac.h:229
drflac * drflac_open_memory(const void *data, size_t dataSize)
Definition: libretro.h:2275
GLdouble GLdouble GLdouble r
Definition: glext.h:6406
drflac_uint32 frameNumber
Definition: dr_flac.h:303
drflac_meta_proc onMeta
Definition: dr_flac.h:339
GLdouble GLdouble t
Definition: glext.h:6398
void * pUserDataMD
Definition: dr_flac.h:342
drflac_uint32 pictureDataSize
Definition: dr_flac.h:185
uint64_t drflac_uint64
Definition: dr_flac.h:17
drflac_uint8 bitsPerSample
Definition: dr_flac.h:353
drflac_uint32 nextL2Line
Definition: dr_flac.h:259
void(* drflac_meta_proc)(void *pUserData, drflac_metadata *pMetadata)
Definition: dr_flac.h:225
uint8_t drflac_uint8
Definition: dr_flac.h:11
#define SEEK_CUR
Definition: zconf.h:439
int unused
Definition: dr_flac.h:141
uint16_t drflac_uint16
Definition: dr_flac.h:13
#define DRFLAC_METADATA_BLOCK_TYPE_PADDING
Definition: dr_flac.h:54
drflac_uint8 bitsPerSample
Definition: dr_flac.h:116
Definition: dr_flac.h:336
void * pUserData
Definition: dr_flac.h:246
drflac * drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void *pUserData)
typedef void(__stdcall *PFN_DESTRUCTION_CALLBACK)(void *pData)
#define DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE
Definition: dr_flac.h:56
drflac_uint32 width
Definition: dr_flac.h:181
void drflac_close(drflac *pFlac)
drflac_uint16 maxBlockSize
Definition: dr_flac.h:111
drflac_int32 * drflac_open_and_decode_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void *pUserData, unsigned int *channels, unsigned int *sampleRate, drflac_uint64 *totalSampleCount)
drflac_uint32 vendorLength
Definition: dr_flac.h:159
Definition: ibxm.h:9
void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator *pIter, drflac_uint32 commentCount, const char *pComments)
char type[64]
Definition: chd_stream.c:63
drflac_uint64 totalSampleCount
Definition: dr_flac.h:361
GLdouble GLdouble right
Definition: glext.h:11766
Definition: dr_flac.h:108
drflac_uint32 minFrameSize
Definition: dr_flac.h:112
GLsizei GLsizei GLenum GLenum const GLvoid * data
Definition: glext.h:6303
drflac_uint32 maxFrameSize
Definition: dr_flac.h:113
drflac * drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void *pUserData)
drflac_int16 * drflac_open_and_decode_memory_s16(const void *data, size_t dataSize, unsigned int *channels, unsigned int *sampleRate, drflac_uint64 *totalSampleCount)
GLuint GLuint GLsizei count
Definition: glext.h:6292
size_t dataSize
Definition: dr_flac.h:232
drflac_uint64 firstSample
Definition: dr_flac.h:102
drflac_frame currentFrame
Definition: dr_flac.h:375
drflac_uint32 height
Definition: dr_flac.h:182
#define DRFLAC_METADATA_BLOCK_TYPE_APPLICATION
Definition: dr_flac.h:55
drflac_seek_proc onSeek
Definition: dr_flac.h:243
int16_t drflac_int16
Definition: dr_flac.h:12
drflac_uint32 consumedBits
Definition: dr_flac.h:262
#define NULL
Pointer to 0.
Definition: gctypes.h:65
GLenum type
Definition: glext.h:6233
int64_t drflac_int64
Definition: dr_flac.h:16
set set set set set set set macro pixldst1 abits if abits op else op endif endm macro pixldst2 abits if abits op else op endif endm macro pixldst4 abits if abits op else op endif endm macro pixldst0 abits op endm macro pixldst3 mem_operand op endm macro pixldst30 mem_operand op endm macro pixldst abits if abits elseif abits elseif abits elseif abits elseif abits pixldst0 abits else pixldst0 abits pixldst0 abits pixldst0 abits pixldst0 abits endif elseif abits else pixldst0 abits pixldst0 abits endif elseif abits else error unsupported bpp *numpix else pixst endif endm macro pixld1_s mem_operand if asr adds SRC_WIDTH_FIXED bpl add asl mov asr adds SRC_WIDTH_FIXED bpl add asl mov asr adds SRC_WIDTH_FIXED bpl add asl mov asr adds SRC_WIDTH_FIXED bpl add asl elseif asr adds SRC_WIDTH_FIXED bpl add asl mov asr adds SRC_WIDTH_FIXED bpl add asl else error unsupported endif endm macro pixld2_s mem_operand if mov asr add asl add asl mov asr sub UNIT_X add asl mov asr add asl add asl mov asr add UNIT_X add asl else pixld1_s mem_operand pixld1_s mem_operand endif endm macro pixld0_s mem_operand if asr adds SRC_WIDTH_FIXED bpl add asl elseif asr adds SRC_WIDTH_FIXED bpl add asl endif endm macro pixld_s_internal mem_operand if mem_operand pixld2_s mem_operand pixdeinterleave basereg elseif mem_operand elseif mem_operand elseif mem_operand elseif mem_operand pixld0_s mem_operand else pixld0_s mem_operand pixld0_s mem_operand pixld0_s mem_operand pixld0_s mem_operand endif elseif mem_operand else pixld0_s mem_operand pixld0_s mem_operand endif elseif mem_operand else error unsupported mem_operand if bpp mem_operand endif endm macro vuzp8 reg2 vuzp d d &reg2 endm macro vzip8 reg2 vzip d d &reg2 endm macro pixdeinterleave basereg basereg basereg basereg basereg endif endm macro pixinterleave basereg basereg basereg basereg basereg endif endm macro PF boost_increment endif if endif PF tst PF addne PF subne PF cmp ORIG_W if endif if endif if endif PF subge ORIG_W PF subges if endif if endif if endif endif endm macro cache_preload_simple endif if dst_r_bpp pld [DST_R, #(PREFETCH_DISTANCE_SIMPLE *dst_r_bpp/8)] endif if mask_bpp pld if[MASK, #(PREFETCH_DISTANCE_SIMPLE *mask_bpp/8)] endif endif endm macro fetch_mask_pixblock pixld mask_basereg pixblock_size MASK endm macro ensure_destination_ptr_alignment process_pixblock_tail_head if beq irp local skip1(dst_w_bpp<=(lowbit *8)) &&((lowbit *8)<(pixblock_size *dst_w_bpp)) .if lowbit< 16 tst DST_R
Definition: pixman-arm-neon-asm.h:469
drflac_uint32 id
Definition: dr_flac.h:146
Definition: dr_flac.h:87
#define fclose
Definition: file_stream_transforms.h:53
drflac_uint64 firstFramePos
Definition: dr_flac.h:378
drflac_cache_t crc16Cache
Definition: dr_flac.h:272
Definition: dr_flac.h:100
drflac_uint8 crc8
Definition: dr_flac.h:319
#define SEEK_SET
Definition: zconf.h:438
Definition: dr_flac.h:94
void * _oggbs
Definition: dr_flac.h:389
drflac_uint32 sampleRate
Definition: dr_flac.h:114
drflac_uint64 frameOffset
Definition: dr_flac.h:103
drflac_uint32 commentCount
Definition: dr_flac.h:161
drflac_uint8 lpcOrder
Definition: dr_flac.h:285
#define DRFLAC_TRUE
Definition: dr_flac.h:20
drflac_uint32 crc16CacheIgnoredBytes
Definition: dr_flac.h:273
drflac_uint32 countRemaining
Definition: dr_flac.h:619
#define DRFLAC_METADATA_BLOCK_TYPE_PICTURE
Definition: dr_flac.h:59
char reserved[128]
Definition: scefiber.c:17
#define DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT
Definition: dr_flac.h:57
drflac_cache_t cacheL2[DR_FLAC_BUFFER_SIZE/sizeof(drflac_cache_t)]
Definition: dr_flac.h:266
signed short int16_t
Definition: stdint.h:122
int8_t drflac_int8
Definition: dr_flac.h:10
drflac_uint8 bitsPerSample
Definition: dr_flac.h:316
Definition: chd_stream.c:62
GLint GLint GLint GLint GLint x
Definition: glext.h:6295
const char * description
Definition: dr_flac.h:180
GLuint64EXT * result
Definition: glext.h:12211
float * drflac_open_and_decode_memory_f32(const void *data, size_t dataSize, unsigned int *channels, unsigned int *sampleRate, drflac_uint64 *totalSampleCount)
#define DR_FLAC_BUFFER_SIZE
Definition: dr_flac.h:28
GLuint GLdouble GLdouble GLint GLint order
Definition: glext.h:12101
drflac_container
Definition: dr_flac.h:85
#define md5
Definition: compat-1.3.h:2001
drflac_uint8 wastedBitsPerSample
Definition: dr_flac.h:282
const drflac_uint8 * data
Definition: dr_flac.h:231
drflac_cache_t unalignedCache
Definition: dr_flac.h:256
drflac_uint8 channels
Definition: dr_flac.h:115
drflac_uint32 seektableSize
Definition: dr_flac.h:371
const void * pRawData
Definition: dr_flac.h:130
GLfloat GLfloat p
Definition: glext.h:9809
drflac_bool32(* drflac_seek_proc)(void *pUserData, int offset, drflac_seek_origin origin)
Definition: dr_flac.h:216
const char * drflac_next_vorbis_comment(drflac_vorbis_comment_iterator *pIter, drflac_uint32 *pCommentLengthOut)
Definition: dr_flac.h:88
signed int int32_t
Definition: stdint.h:123
GLenum GLsizei dataSize
Definition: glext.h:12030
drflac_int32 * pDecodedSamples
Definition: dr_flac.h:386
drflac_uint16 blockSize
Definition: dr_flac.h:309
drflac_cache_t cache
Definition: dr_flac.h:267
drflac_int32 * pDecodedSamples
Definition: dr_flac.h:293
int16_t s16
16bit signed integer
Definition: gctypes.h:23
#define FILE
Definition: file_stream_transforms.h:35
drflac_container container
Definition: dr_flac.h:365
#define DRFLAC_FALSE
Definition: dr_flac.h:21
drflac_uint16 crc16
Definition: dr_flac.h:271
drflac_uint8 channels
Definition: dr_flac.h:350
uint32_t drflac_uint32
Definition: dr_flac.h:15
Definition: ibxm.h:34
Definition: dr_flac.h:95
drflac_uint8 drflac_bool8
Definition: dr_flac.h:18
drflac * drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void *pUserData)
Definition: ibxm.h:14
drflac_streaminfo streaminfo
Definition: dr_flac.h:137
Definition: dr_flac.h:276
drflac_uint64 seektablePos
Definition: dr_flac.h:368
GLint j
Definition: nx_glsym.h:307
drflac_int32 * drflac_open_and_decode_memory_s32(const void *data, size_t dataSize, unsigned int *channels, unsigned int *sampleRate, drflac_uint64 *totalSampleCount)
const char * comments
Definition: dr_flac.h:162
drflac_uint8 subframeType
Definition: dr_flac.h:279
const char * mime
Definition: dr_flac.h:178
drflac_uint64 leadInSampleCount
Definition: dr_flac.h:168
signed __int64 int64_t
Definition: stdint.h:135
drflac_uint64 drflac_read_s32(drflac *pFlac, drflac_uint64 samplesToRead, drflac_int32 *pBufferOut)
unsigned long crc32(unsigned long crc, const unsigned char *buf, unsigned int len)
Definition: libz-crc32.c:70
drflac_uint32 descriptionLength
Definition: dr_flac.h:179
Ιστορικό Εικόνα Πληροφορίες Όλοι Οι Χρήστες Χειρίζονται Το Μενού Αριστερό Αναλογικό Αριστερό Αναλογικό Αριστερό Αναλογικό Y Αριστερό Αναλογικό Δεξί Αναλογικό X Δεξί Αναλογικό Δεξί Αναλογικό Y Δεξί Αναλογικό Σκανδάλη Όπλου Όπλο Aux A Όπλο Aux C Όπλο Select Όπλο D pad Κάτω Όπλο D pad Δεξιά Νεκρή Ζώνη Αναλογικού Σύνδεση Όλων Λήξη Χρόνου Σύνδεσης Hide Unbound Core Input Descriptors Κατάλογος Συσκευών Κατάλογος Ποντικιού Duty Cycle Keyboard Gamepad Mapping Enable Κουμπί D pad κάτω Κουμπί Κουμπί L(πίσω)" ) MSG_HASH( MENU_ENUM_LABEL_VALUE_INPUT_JOYPAD_LEFT
Definition: dr_flac.h:89
const drflac_seekpoint * pSeekpoints
Definition: dr_flac.h:154
drflac_read_proc onRead
Definition: dr_flac.h:240
drflac_uint16 minBlockSize
Definition: dr_flac.h:110
drflac_uint32 mimeLength
Definition: dr_flac.h:177
#define fread
Definition: file_stream_transforms.h:56
drflac * drflac_open_memory_with_metadata(const void *data, size_t dataSize, drflac_meta_proc onMeta, void *pUserData)
drflac_uint32 rawDataSize
Definition: dr_flac.h:133
drflac_uint64 totalSampleCount
Definition: dr_flac.h:117
drflac_frame_header header
Definition: dr_flac.h:325
drflac_uint32 indexColorCount
Definition: dr_flac.h:184
#define fopen
Definition: file_stream_transforms.h:52
const drflac_uint8 * pTrackData
Definition: dr_flac.h:171
drflac_subframe subframes[8]
Definition: dr_flac.h:333
Definition: civetweb.c:1024
GLintptr offset
Definition: glext.h:6560
GLint left
Definition: glext.h:8393
GLbitfield flags
Definition: glext.h:7828
#define DRFLAC_METADATA_BLOCK_TYPE_INVALID
Definition: dr_flac.h:60
const char * vendor
Definition: dr_flac.h:160
drflac_int16 * drflac_open_and_decode_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void *pUserData, unsigned int *channels, unsigned int *sampleRate, drflac_uint64 *totalSampleCount)
drflac_bs bs
Definition: dr_flac.h:392
float * drflac_open_and_decode_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void *pUserData, unsigned int *channels, unsigned int *sampleRate, drflac_uint64 *totalSampleCount)
const drflac_uint8 * pPictureData
Definition: dr_flac.h:186
drflac_uint64 sampleNumber
Definition: dr_flac.h:300
size_t(* drflac_read_proc)(void *pUserData, void *pBufferOut, size_t bytesToRead)
Definition: dr_flac.h:203
unsigned short uint16_t
Definition: stdint.h:125
#define DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO
Definition: dr_flac.h:53
unsigned __int64 uint64_t
Definition: stdint.h:136
GLenum GLuint GLenum GLsizei length
Definition: glext.h:6233
GLdouble n
Definition: glext.h:8396
unsigned char uint8_t
Definition: stdint.h:124
unsigned int uint32_t
Definition: stdint.h:126
int fopen_s(FILE **pFile, const char *filename, const char *mode)
Definition: StandAlone.cpp:1437
drflac_uint16 maxBlockSize
Definition: dr_flac.h:356
drflac_uint32 bitsPerSample
Definition: dr_flac.h:289
signed char int8_t
Definition: stdint.h:121
drflac_uint64 drflac_read_f32(drflac *pFlac, drflac_uint64 samplesToRead, float *pBufferOut)
#define fseek
Definition: file_stream_transforms.h:55
set set set set set set set macro pixldst1 abits if abits op else op endif endm macro pixldst2 abits if abits op else op endif endm macro pixldst4 abits if abits op else op endif endm macro pixldst0 abits op endm macro pixldst3 mem_operand op endm macro pixldst30 mem_operand op endm macro pixldst abits if abits elseif abits elseif abits elseif abits elseif abits pixldst0 abits else pixldst0 abits pixldst0 abits pixldst0 abits pixldst0 abits endif elseif abits else pixldst0 abits pixldst0 abits endif elseif abits else error unsupported bpp *numpix else pixst endif endm macro pixld1_s mem_operand if asr adds SRC_WIDTH_FIXED bpl add asl mov asr adds SRC_WIDTH_FIXED bpl add asl mov asr adds SRC_WIDTH_FIXED bpl add asl mov asr adds SRC_WIDTH_FIXED bpl add asl elseif asr adds SRC_WIDTH_FIXED bpl add asl mov asr adds SRC_WIDTH_FIXED bpl add asl else error unsupported endif endm macro pixld2_s mem_operand if mov asr add asl add asl mov asr sub UNIT_X add asl mov asr add asl add asl mov asr add UNIT_X add asl else pixld1_s mem_operand pixld1_s mem_operand endif endm macro pixld0_s mem_operand if asr adds SRC_WIDTH_FIXED bpl add asl elseif asr adds SRC_WIDTH_FIXED bpl add asl endif endm macro pixld_s_internal mem_operand if mem_operand pixld2_s mem_operand pixdeinterleave basereg elseif mem_operand elseif mem_operand elseif mem_operand elseif mem_operand pixld0_s mem_operand else pixld0_s mem_operand pixld0_s mem_operand pixld0_s mem_operand pixld0_s mem_operand endif elseif mem_operand else pixld0_s mem_operand pixld0_s mem_operand endif elseif mem_operand else error unsupported mem_operand if bpp mem_operand endif endm macro vuzp8 reg2 vuzp d d &reg2 endm macro vzip8 reg2 vzip d d &reg2 endm macro pixdeinterleave basereg basereg basereg basereg basereg endif endm macro pixinterleave basereg basereg basereg basereg basereg endif endm macro PF boost_increment endif if endif PF tst PF addne PF subne PF cmp ORIG_W if endif if endif if endif PF subge ORIG_W PF subges if endif if endif if endif endif endm macro cache_preload_simple endif if dst_r_bpp pld [DST_R, #(PREFETCH_DISTANCE_SIMPLE *dst_r_bpp/8)] endif if mask_bpp pld init[MASK, #(PREFETCH_DISTANCE_SIMPLE *mask_bpp/8)] endif endif endm macro fetch_mask_pixblock pixld mask_basereg pixblock_size MASK endm macro ensure_destination_ptr_alignment process_pixblock_tail_head if beq irp local skip1 beq endif SRC MASK if dst_r_bpp DST_R else add endif PF add sub src_basereg pixdeinterleave mask_basereg pixdeinterleave dst_r_basereg process_pixblock_head pixblock_size cache_preload_simple process_pixblock_tail pixinterleave dst_w_basereg irp beq endif process_pixblock_tail_head tst beq irp if pixblock_size chunk_size tst beq pixld_src SRC pixld MASK if DST_R else pixld DST_R endif if src_basereg pixdeinterleave mask_basereg pixdeinterleave dst_r_basereg process_pixblock_head if pixblock_size cache_preload_simple endif process_pixblock_tail pixinterleave dst_w_basereg irp if pixblock_size chunk_size tst beq if DST_W else pixst DST_W else mov ORIG_W endif add lsl if lsl endif if lsl endif lsl endif lsl endif lsl endif subs mov DST_W if regs_shortage str endif bge start_of_loop_label endm macro generate_composite_function
Definition: pixman-arm-neon-asm.h:600
Definition: dr_flac.h:322