Subversion Repositories Kolibri OS

Rev

Blame | Last modification | View Log | RSS feed

  1. /*
  2. FLAC audio decoder. Choice of public domain or MIT-0. See license statements at the end of this file.
  3. dr_flac - v0.12.13 - 2020-05-16
  4.  
  5. David Reid - mackron@gmail.com
  6.  
  7. GitHub: https://github.com/mackron/dr_libs
  8. */
  9.  
  10. /*
  11. RELEASE NOTES - v0.12.0
  12. =======================
  13. Version 0.12.0 has breaking API changes including changes to the existing API and the removal of deprecated APIs.
  14.  
  15.  
  16. Improved Client-Defined Memory Allocation
  17. -----------------------------------------
  18. The main change with this release is the addition of a more flexible way of implementing custom memory allocation routines. The
  19. existing system of DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE are still in place and will be used by default when no custom
  20. allocation callbacks are specified.
  21.  
  22. To use the new system, you pass in a pointer to a drflac_allocation_callbacks object to drflac_open() and family, like this:
  23.  
  24.     void* my_malloc(size_t sz, void* pUserData)
  25.     {
  26.         return malloc(sz);
  27.     }
  28.     void* my_realloc(void* p, size_t sz, void* pUserData)
  29.     {
  30.         return realloc(p, sz);
  31.     }
  32.     void my_free(void* p, void* pUserData)
  33.     {
  34.         free(p);
  35.     }
  36.  
  37.     ...
  38.  
  39.     drflac_allocation_callbacks allocationCallbacks;
  40.     allocationCallbacks.pUserData = &myData;
  41.     allocationCallbacks.onMalloc  = my_malloc;
  42.     allocationCallbacks.onRealloc = my_realloc;
  43.     allocationCallbacks.onFree    = my_free;
  44.     drflac* pFlac = drflac_open_file("my_file.flac", &allocationCallbacks);
  45.  
  46. The advantage of this new system is that it allows you to specify user data which will be passed in to the allocation routines.
  47.  
  48. Passing in null for the allocation callbacks object will cause dr_flac to use defaults which is the same as DRFLAC_MALLOC,
  49. DRFLAC_REALLOC and DRFLAC_FREE and the equivalent of how it worked in previous versions.
  50.  
  51. Every API that opens a drflac object now takes this extra parameter. These include the following:
  52.  
  53.     drflac_open()
  54.     drflac_open_relaxed()
  55.     drflac_open_with_metadata()
  56.     drflac_open_with_metadata_relaxed()
  57.     drflac_open_file()
  58.     drflac_open_file_with_metadata()
  59.     drflac_open_memory()
  60.     drflac_open_memory_with_metadata()
  61.     drflac_open_and_read_pcm_frames_s32()
  62.     drflac_open_and_read_pcm_frames_s16()
  63.     drflac_open_and_read_pcm_frames_f32()
  64.     drflac_open_file_and_read_pcm_frames_s32()
  65.     drflac_open_file_and_read_pcm_frames_s16()
  66.     drflac_open_file_and_read_pcm_frames_f32()
  67.     drflac_open_memory_and_read_pcm_frames_s32()
  68.     drflac_open_memory_and_read_pcm_frames_s16()
  69.     drflac_open_memory_and_read_pcm_frames_f32()
  70.  
  71.  
  72.  
  73. Optimizations
  74. -------------
  75. Seeking performance has been greatly improved. A new binary search based seeking algorithm has been introduced which significantly
  76. improves performance over the brute force method which was used when no seek table was present. Seek table based seeking also takes
  77. advantage of the new binary search seeking system to further improve performance there as well. Note that this depends on CRC which
  78. means it will be disabled when DR_FLAC_NO_CRC is used.
  79.  
  80. The SSE4.1 pipeline has been cleaned up and optimized. You should see some improvements with decoding speed of 24-bit files in
  81. particular. 16-bit streams should also see some improvement.
  82.  
  83. drflac_read_pcm_frames_s16() has been optimized. Previously this sat on top of drflac_read_pcm_frames_s32() and performed it's s32
  84. to s16 conversion in a second pass. This is now all done in a single pass. This includes SSE2 and ARM NEON optimized paths.
  85.  
  86. A minor optimization has been implemented for drflac_read_pcm_frames_s32(). This will now use an SSE2 optimized pipeline for stereo
  87. channel reconstruction which is the last part of the decoding process.
  88.  
  89. The ARM build has seen a few improvements. The CLZ (count leading zeroes) and REV (byte swap) instructions are now used when
  90. compiling with GCC and Clang which is achieved using inline assembly. The CLZ instruction requires ARM architecture version 5 at
  91. compile time and the REV instruction requires ARM architecture version 6.
  92.  
  93. An ARM NEON optimized pipeline has been implemented. To enable this you'll need to add -mfpu=neon to the command line when compiling.
  94.  
  95.  
  96. Removed APIs
  97. ------------
  98. The following APIs were deprecated in version 0.11.0 and have been completely removed in version 0.12.0:
  99.  
  100.     drflac_read_s32()                   -> drflac_read_pcm_frames_s32()
  101.     drflac_read_s16()                   -> drflac_read_pcm_frames_s16()
  102.     drflac_read_f32()                   -> drflac_read_pcm_frames_f32()
  103.     drflac_seek_to_sample()             -> drflac_seek_to_pcm_frame()
  104.     drflac_open_and_decode_s32()        -> drflac_open_and_read_pcm_frames_s32()
  105.     drflac_open_and_decode_s16()        -> drflac_open_and_read_pcm_frames_s16()
  106.     drflac_open_and_decode_f32()        -> drflac_open_and_read_pcm_frames_f32()
  107.     drflac_open_and_decode_file_s32()   -> drflac_open_file_and_read_pcm_frames_s32()
  108.     drflac_open_and_decode_file_s16()   -> drflac_open_file_and_read_pcm_frames_s16()
  109.     drflac_open_and_decode_file_f32()   -> drflac_open_file_and_read_pcm_frames_f32()
  110.     drflac_open_and_decode_memory_s32() -> drflac_open_memory_and_read_pcm_frames_s32()
  111.     drflac_open_and_decode_memory_s16() -> drflac_open_memory_and_read_pcm_frames_s16()
  112.     drflac_open_and_decode_memory_f32() -> drflac_open_memroy_and_read_pcm_frames_f32()
  113.  
  114. Prior versions of dr_flac operated on a per-sample basis whereas now it operates on PCM frames. The removed APIs all relate
  115. to the old per-sample APIs. You now need to use the "pcm_frame" versions.
  116. */
  117.  
  118.  
  119. /*
  120. Introduction
  121. ============
  122. dr_flac is a single file library. To use it, do something like the following in one .c file.
  123.  
  124.     ```c
  125.     #define DR_FLAC_IMPLEMENTATION
  126.     #include "dr_flac.h"
  127.     ```
  128.  
  129. You can then #include this file in other parts of the program as you would with any other header file. To decode audio data, do something like the following:
  130.  
  131.     ```c
  132.     drflac* pFlac = drflac_open_file("MySong.flac", NULL);
  133.     if (pFlac == NULL) {
  134.         // Failed to open FLAC file
  135.     }
  136.  
  137.     drflac_int32* pSamples = malloc(pFlac->totalPCMFrameCount * pFlac->channels * sizeof(drflac_int32));
  138.     drflac_uint64 numberOfInterleavedSamplesActuallyRead = drflac_read_pcm_frames_s32(pFlac, pFlac->totalPCMFrameCount, pSamples);
  139.     ```
  140.  
  141. The drflac object represents the decoder. It is a transparent type so all the information you need, such as the number of channels and the bits per sample,
  142. should be directly accessible - just make sure you don't change their values. Samples are always output as interleaved signed 32-bit PCM. In the example above
  143. a native FLAC stream was opened, however dr_flac has seamless support for Ogg encapsulated FLAC streams as well.
  144.  
  145. You do not need to decode the entire stream in one go - you just specify how many samples you'd like at any given time and the decoder will give you as many
  146. samples as it can, up to the amount requested. Later on when you need the next batch of samples, just call it again. Example:
  147.  
  148.     ```c
  149.     while (drflac_read_pcm_frames_s32(pFlac, chunkSizeInPCMFrames, pChunkSamples) > 0) {
  150.         do_something();
  151.     }
  152.     ```
  153.  
  154. You can seek to a specific PCM frame with `drflac_seek_to_pcm_frame()`.
  155.  
  156. If you just want to quickly decode an entire FLAC file in one go you can do something like this:
  157.  
  158.     ```c
  159.     unsigned int channels;
  160.     unsigned int sampleRate;
  161.     drflac_uint64 totalPCMFrameCount;
  162.     drflac_int32* pSampleData = drflac_open_file_and_read_pcm_frames_s32("MySong.flac", &channels, &sampleRate, &totalPCMFrameCount, NULL);
  163.     if (pSampleData == NULL) {
  164.         // Failed to open and decode FLAC file.
  165.     }
  166.  
  167.     ...
  168.  
  169.     drflac_free(pSampleData);
  170.     ```
  171.  
  172. You can read samples as signed 16-bit integer and 32-bit floating-point PCM with the *_s16() and *_f32() family of APIs respectively, but note that these
  173. should be considered lossy.
  174.  
  175.  
  176. If you need access to metadata (album art, etc.), use `drflac_open_with_metadata()`, `drflac_open_file_with_metdata()` or `drflac_open_memory_with_metadata()`.
  177. The rationale for keeping these APIs separate is that they're slightly slower than the normal versions and also just a little bit harder to use. dr_flac
  178. reports metadata to the application through the use of a callback, and every metadata block is reported before `drflac_open_with_metdata()` returns.
  179.  
  180. The main opening APIs (`drflac_open()`, etc.) will fail if the header is not present. The presents a problem in certain scenarios such as broadcast style
  181. streams or internet radio where the header may not be present because the user has started playback mid-stream. To handle this, use the relaxed APIs:
  182.    
  183.     `drflac_open_relaxed()`
  184.     `drflac_open_with_metadata_relaxed()`
  185.  
  186. It is not recommended to use these APIs for file based streams because a missing header would usually indicate a corrupt or perverse file. In addition, these
  187. APIs can take a long time to initialize because they may need to spend a lot of time finding the first frame.
  188.  
  189.  
  190.  
  191. Build Options
  192. =============
  193. #define these options before including this file.
  194.  
  195. #define DR_FLAC_NO_STDIO
  196.   Disable `drflac_open_file()` and family.
  197.  
  198. #define DR_FLAC_NO_OGG
  199.   Disables support for Ogg/FLAC streams.
  200.  
  201. #define DR_FLAC_BUFFER_SIZE <number>
  202.   Defines the size of the internal buffer to store data from onRead(). This buffer is used to reduce the number of calls back to the client for more data.
  203.   Larger values means more memory, but better performance. My tests show diminishing returns after about 4KB (which is the default). Consider reducing this if
  204.   you have a very efficient implementation of onRead(), or increase it if it's very inefficient. Must be a multiple of 8.
  205.  
  206. #define DR_FLAC_NO_CRC
  207.   Disables CRC checks. This will offer a performance boost when CRC is unnecessary. This will disable binary search seeking. When seeking, the seek table will
  208.   be used if available. Otherwise the seek will be performed using brute force.
  209.  
  210. #define DR_FLAC_NO_SIMD
  211.   Disables SIMD optimizations (SSE on x86/x64 architectures, NEON on ARM architectures). Use this if you are having compatibility issues with your compiler.
  212.  
  213.  
  214.  
  215. Notes
  216. =====
  217. - dr_flac does not support changing the sample rate nor channel count mid stream.
  218. - dr_flac is not thread-safe, but its APIs can be called from any thread so long as you do your own synchronization.
  219. - When using Ogg encapsulation, a corrupted metadata block will result in `drflac_open_with_metadata()` and `drflac_open()` returning inconsistent samples due
  220.   to differences in corrupted stream recorvery logic between the two APIs.
  221. */
  222.  
  223. #ifndef dr_flac_h
  224. #define dr_flac_h
  225.  
  226. #ifdef __cplusplus
  227. extern "C" {
  228. #endif
  229.  
  230. #define DRFLAC_STRINGIFY(x)      #x
  231. #define DRFLAC_XSTRINGIFY(x)     DRFLAC_STRINGIFY(x)
  232.  
  233. #define DRFLAC_VERSION_MAJOR     0
  234. #define DRFLAC_VERSION_MINOR     12
  235. #define DRFLAC_VERSION_REVISION  13
  236. #define DRFLAC_VERSION_STRING    DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MAJOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MINOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_REVISION)
  237.  
  238. #include <stddef.h> /* For size_t. */
  239.  
  240. /* Sized types. Prefer built-in types. Fall back to stdint. */
  241. #ifdef _MSC_VER
  242.     #if defined(__clang__)
  243.         #pragma GCC diagnostic push
  244.         #pragma GCC diagnostic ignored "-Wlanguage-extension-token"
  245.         #pragma GCC diagnostic ignored "-Wlong-long"        
  246.         #pragma GCC diagnostic ignored "-Wc++11-long-long"
  247.     #endif
  248.     typedef   signed __int8  drflac_int8;
  249.     typedef unsigned __int8  drflac_uint8;
  250.     typedef   signed __int16 drflac_int16;
  251.     typedef unsigned __int16 drflac_uint16;
  252.     typedef   signed __int32 drflac_int32;
  253.     typedef unsigned __int32 drflac_uint32;
  254.     typedef   signed __int64 drflac_int64;
  255.     typedef unsigned __int64 drflac_uint64;
  256.     #if defined(__clang__)
  257.         #pragma GCC diagnostic pop
  258.     #endif
  259. #else
  260.     #include <stdint.h>
  261.     typedef int8_t           drflac_int8;
  262.     typedef uint8_t          drflac_uint8;
  263.     typedef int16_t          drflac_int16;
  264.     typedef uint16_t         drflac_uint16;
  265.     typedef int32_t          drflac_int32;
  266.     typedef uint32_t         drflac_uint32;
  267.     typedef int64_t          drflac_int64;
  268.     typedef uint64_t         drflac_uint64;
  269. #endif
  270. typedef drflac_uint8         drflac_bool8;
  271. typedef drflac_uint32        drflac_bool32;
  272. #define DRFLAC_TRUE          1
  273. #define DRFLAC_FALSE         0
  274.  
  275. #if !defined(DRFLAC_API)
  276.     #if defined(DRFLAC_DLL)
  277.         #if defined(_WIN32)
  278.             #define DRFLAC_DLL_IMPORT  __declspec(dllimport)
  279.             #define DRFLAC_DLL_EXPORT  __declspec(dllexport)
  280.             #define DRFLAC_DLL_PRIVATE static
  281.         #else
  282.             #if defined(__GNUC__) && __GNUC__ >= 4
  283.                 #define DRFLAC_DLL_IMPORT  __attribute__((visibility("default")))
  284.                 #define DRFLAC_DLL_EXPORT  __attribute__((visibility("default")))
  285.                 #define DRFLAC_DLL_PRIVATE __attribute__((visibility("hidden")))
  286.             #else
  287.                 #define DRFLAC_DLL_IMPORT
  288.                 #define DRFLAC_DLL_EXPORT
  289.                 #define DRFLAC_DLL_PRIVATE static
  290.             #endif
  291.         #endif
  292.  
  293.         #if defined(DR_FLAC_IMPLEMENTATION) || defined(DRFLAC_IMPLEMENTATION)
  294.             #define DRFLAC_API  DRFLAC_DLL_EXPORT
  295.         #else
  296.             #define DRFLAC_API  DRFLAC_DLL_IMPORT
  297.         #endif
  298.         #define DRFLAC_PRIVATE DRFLAC_DLL_PRIVATE
  299.     #else
  300.         #define DRFLAC_API extern
  301.         #define DRFLAC_PRIVATE static
  302.     #endif
  303. #endif
  304.  
  305. #if defined(_MSC_VER) && _MSC_VER >= 1700   /* Visual Studio 2012 */
  306.     #define DRFLAC_DEPRECATED       __declspec(deprecated)
  307. #elif (defined(__GNUC__) && __GNUC__ >= 4)  /* GCC 4 */
  308.     #define DRFLAC_DEPRECATED       __attribute__((deprecated))
  309. #elif defined(__has_feature)                /* Clang */
  310.     #if __has_feature(attribute_deprecated)
  311.         #define DRFLAC_DEPRECATED   __attribute__((deprecated))
  312.     #else
  313.         #define DRFLAC_DEPRECATED
  314.     #endif
  315. #else
  316.     #define DRFLAC_DEPRECATED
  317. #endif
  318.  
  319. DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision);
  320. DRFLAC_API const char* drflac_version_string();
  321.  
  322. /*
  323. As data is read from the client it is placed into an internal buffer for fast access. This controls the size of that buffer. Larger values means more speed,
  324. but also more memory. In my testing there is diminishing returns after about 4KB, but you can fiddle with this to suit your own needs. Must be a multiple of 8.
  325. */
  326. #ifndef DR_FLAC_BUFFER_SIZE
  327. #define DR_FLAC_BUFFER_SIZE   4096
  328. #endif
  329.  
  330. /* Check if we can enable 64-bit optimizations. */
  331. #if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
  332. #define DRFLAC_64BIT
  333. #endif
  334.  
  335. #ifdef DRFLAC_64BIT
  336. typedef drflac_uint64 drflac_cache_t;
  337. #else
  338. typedef drflac_uint32 drflac_cache_t;
  339. #endif
  340.  
  341. /* The various metadata block types. */
  342. #define DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO       0
  343. #define DRFLAC_METADATA_BLOCK_TYPE_PADDING          1
  344. #define DRFLAC_METADATA_BLOCK_TYPE_APPLICATION      2
  345. #define DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE        3
  346. #define DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT   4
  347. #define DRFLAC_METADATA_BLOCK_TYPE_CUESHEET         5
  348. #define DRFLAC_METADATA_BLOCK_TYPE_PICTURE          6
  349. #define DRFLAC_METADATA_BLOCK_TYPE_INVALID          127
  350.  
  351. /* The various picture types specified in the PICTURE block. */
  352. #define DRFLAC_PICTURE_TYPE_OTHER                   0
  353. #define DRFLAC_PICTURE_TYPE_FILE_ICON               1
  354. #define DRFLAC_PICTURE_TYPE_OTHER_FILE_ICON         2
  355. #define DRFLAC_PICTURE_TYPE_COVER_FRONT             3
  356. #define DRFLAC_PICTURE_TYPE_COVER_BACK              4
  357. #define DRFLAC_PICTURE_TYPE_LEAFLET_PAGE            5
  358. #define DRFLAC_PICTURE_TYPE_MEDIA                   6
  359. #define DRFLAC_PICTURE_TYPE_LEAD_ARTIST             7
  360. #define DRFLAC_PICTURE_TYPE_ARTIST                  8
  361. #define DRFLAC_PICTURE_TYPE_CONDUCTOR               9
  362. #define DRFLAC_PICTURE_TYPE_BAND                    10
  363. #define DRFLAC_PICTURE_TYPE_COMPOSER                11
  364. #define DRFLAC_PICTURE_TYPE_LYRICIST                12
  365. #define DRFLAC_PICTURE_TYPE_RECORDING_LOCATION      13
  366. #define DRFLAC_PICTURE_TYPE_DURING_RECORDING        14
  367. #define DRFLAC_PICTURE_TYPE_DURING_PERFORMANCE      15
  368. #define DRFLAC_PICTURE_TYPE_SCREEN_CAPTURE          16
  369. #define DRFLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH     17
  370. #define DRFLAC_PICTURE_TYPE_ILLUSTRATION            18
  371. #define DRFLAC_PICTURE_TYPE_BAND_LOGOTYPE           19
  372. #define DRFLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE      20
  373.  
  374. typedef enum
  375. {
  376.     drflac_container_native,
  377.     drflac_container_ogg,
  378.     drflac_container_unknown
  379. } drflac_container;
  380.  
  381. typedef enum
  382. {
  383.     drflac_seek_origin_start,
  384.     drflac_seek_origin_current
  385. } drflac_seek_origin;
  386.  
  387. /* Packing is important on this structure because we map this directly to the raw data within the SEEKTABLE metadata block. */
  388. #pragma pack(2)
  389. typedef struct
  390. {
  391.     drflac_uint64 firstPCMFrame;
  392.     drflac_uint64 flacFrameOffset;   /* The offset from the first byte of the header of the first frame. */
  393.     drflac_uint16 pcmFrameCount;
  394. } drflac_seekpoint;
  395. #pragma pack()
  396.  
  397. typedef struct
  398. {
  399.     drflac_uint16 minBlockSizeInPCMFrames;
  400.     drflac_uint16 maxBlockSizeInPCMFrames;
  401.     drflac_uint32 minFrameSizeInPCMFrames;
  402.     drflac_uint32 maxFrameSizeInPCMFrames;
  403.     drflac_uint32 sampleRate;
  404.     drflac_uint8  channels;
  405.     drflac_uint8  bitsPerSample;
  406.     drflac_uint64 totalPCMFrameCount;
  407.     drflac_uint8  md5[16];
  408. } drflac_streaminfo;
  409.  
  410. typedef struct
  411. {
  412.     /* The metadata type. Use this to know how to interpret the data below. */
  413.     drflac_uint32 type;
  414.  
  415.     /*
  416.     A pointer to the raw data. This points to a temporary buffer so don't hold on to it. It's best to
  417.     not modify the contents of this buffer. Use the structures below for more meaningful and structured
  418.     information about the metadata. It's possible for this to be null.
  419.     */
  420.     const void* pRawData;
  421.  
  422.     /* The size in bytes of the block and the buffer pointed to by pRawData if it's non-NULL. */
  423.     drflac_uint32 rawDataSize;
  424.  
  425.     union
  426.     {
  427.         drflac_streaminfo streaminfo;
  428.  
  429.         struct
  430.         {
  431.             int unused;
  432.         } padding;
  433.  
  434.         struct
  435.         {
  436.             drflac_uint32 id;
  437.             const void* pData;
  438.             drflac_uint32 dataSize;
  439.         } application;
  440.  
  441.         struct
  442.         {
  443.             drflac_uint32 seekpointCount;
  444.             const drflac_seekpoint* pSeekpoints;
  445.         } seektable;
  446.  
  447.         struct
  448.         {
  449.             drflac_uint32 vendorLength;
  450.             const char* vendor;
  451.             drflac_uint32 commentCount;
  452.             const void* pComments;
  453.         } vorbis_comment;
  454.  
  455.         struct
  456.         {
  457.             char catalog[128];
  458.             drflac_uint64 leadInSampleCount;
  459.             drflac_bool32 isCD;
  460.             drflac_uint8 trackCount;
  461.             const void* pTrackData;
  462.         } cuesheet;
  463.  
  464.         struct
  465.         {
  466.             drflac_uint32 type;
  467.             drflac_uint32 mimeLength;
  468.             const char* mime;
  469.             drflac_uint32 descriptionLength;
  470.             const char* description;
  471.             drflac_uint32 width;
  472.             drflac_uint32 height;
  473.             drflac_uint32 colorDepth;
  474.             drflac_uint32 indexColorCount;
  475.             drflac_uint32 pictureDataSize;
  476.             const drflac_uint8* pPictureData;
  477.         } picture;
  478.     } data;
  479. } drflac_metadata;
  480.  
  481.  
  482. /*
  483. Callback for when data needs to be read from the client.
  484.  
  485.  
  486. Parameters
  487. ----------
  488. pUserData (in)
  489.     The user data that was passed to drflac_open() and family.
  490.  
  491. pBufferOut (out)
  492.     The output buffer.
  493.  
  494. bytesToRead (in)
  495.     The number of bytes to read.
  496.  
  497.  
  498. Return Value
  499. ------------
  500. The number of bytes actually read.
  501.  
  502.  
  503. Remarks
  504. -------
  505. A return value of less than bytesToRead indicates the end of the stream. Do _not_ return from this callback until either the entire bytesToRead is filled or
  506. you have reached the end of the stream.
  507. */
  508. typedef size_t (* drflac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
  509.  
  510. /*
  511. Callback for when data needs to be seeked.
  512.  
  513.  
  514. Parameters
  515. ----------
  516. pUserData (in)
  517.     The user data that was passed to drflac_open() and family.
  518.  
  519. offset (in)
  520.     The number of bytes to move, relative to the origin. Will never be negative.
  521.  
  522. origin (in)
  523.     The origin of the seek - the current position or the start of the stream.
  524.  
  525.  
  526. Return Value
  527. ------------
  528. Whether or not the seek was successful.
  529.  
  530.  
  531. Remarks
  532. -------
  533. The offset will never be negative. Whether or not it is relative to the beginning or current position is determined by the "origin" parameter which will be
  534. either drflac_seek_origin_start or drflac_seek_origin_current.
  535.  
  536. When seeking to a PCM frame using drflac_seek_to_pcm_frame(), dr_flac may call this with an offset beyond the end of the FLAC stream. This needs to be detected
  537. and handled by returning DRFLAC_FALSE.
  538. */
  539. typedef drflac_bool32 (* drflac_seek_proc)(void* pUserData, int offset, drflac_seek_origin origin);
  540.  
  541. /*
  542. Callback for when a metadata block is read.
  543.  
  544.  
  545. Parameters
  546. ----------
  547. pUserData (in)
  548.     The user data that was passed to drflac_open() and family.
  549.  
  550. pMetadata (in)
  551.     A pointer to a structure containing the data of the metadata block.
  552.  
  553.  
  554. Remarks
  555. -------
  556. Use pMetadata->type to determine which metadata block is being handled and how to read the data.
  557. */
  558. typedef void (* drflac_meta_proc)(void* pUserData, drflac_metadata* pMetadata);
  559.  
  560.  
  561. typedef struct
  562. {
  563.     void* pUserData;
  564.     void* (* onMalloc)(size_t sz, void* pUserData);
  565.     void* (* onRealloc)(void* p, size_t sz, void* pUserData);
  566.     void  (* onFree)(void* p, void* pUserData);
  567. } drflac_allocation_callbacks;
  568.  
  569. /* Structure for internal use. Only used for decoders opened with drflac_open_memory. */
  570. typedef struct
  571. {
  572.     const drflac_uint8* data;
  573.     size_t dataSize;
  574.     size_t currentReadPos;
  575. } drflac__memory_stream;
  576.  
  577. /* Structure for internal use. Used for bit streaming. */
  578. typedef struct
  579. {
  580.     /* The function to call when more data needs to be read. */
  581.     drflac_read_proc onRead;
  582.  
  583.     /* The function to call when the current read position needs to be moved. */
  584.     drflac_seek_proc onSeek;
  585.  
  586.     /* The user data to pass around to onRead and onSeek. */
  587.     void* pUserData;
  588.  
  589.  
  590.     /*
  591.     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
  592.     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
  593.     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).
  594.     */
  595.     size_t unalignedByteCount;
  596.  
  597.     /* The content of the unaligned bytes. */
  598.     drflac_cache_t unalignedCache;
  599.  
  600.     /* The index of the next valid cache line in the "L2" cache. */
  601.     drflac_uint32 nextL2Line;
  602.  
  603.     /* The number of bits that have been consumed by the cache. This is used to determine how many valid bits are remaining. */
  604.     drflac_uint32 consumedBits;
  605.  
  606.     /*
  607.     The cached data which was most recently read from the client. There are two levels of cache. Data flows as such:
  608.     Client -> L2 -> L1. The L2 -> L1 movement is aligned and runs on a fast path in just a few instructions.
  609.     */
  610.     drflac_cache_t cacheL2[DR_FLAC_BUFFER_SIZE/sizeof(drflac_cache_t)];
  611.     drflac_cache_t cache;
  612.  
  613.     /*
  614.     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
  615.     is reset to 0 at the beginning of each frame.
  616.     */
  617.     drflac_uint16 crc16;
  618.     drflac_cache_t crc16Cache;              /* A cache for optimizing CRC calculations. This is filled when when the L1 cache is reloaded. */
  619.     drflac_uint32 crc16CacheIgnoredBytes;   /* The number of bytes to ignore when updating the CRC-16 from the CRC-16 cache. */
  620. } drflac_bs;
  621.  
  622. typedef struct
  623. {
  624.     /* The type of the subframe: SUBFRAME_CONSTANT, SUBFRAME_VERBATIM, SUBFRAME_FIXED or SUBFRAME_LPC. */
  625.     drflac_uint8 subframeType;
  626.  
  627.     /* The number of wasted bits per sample as specified by the sub-frame header. */
  628.     drflac_uint8 wastedBitsPerSample;
  629.  
  630.     /* The order to use for the prediction stage for SUBFRAME_FIXED and SUBFRAME_LPC. */
  631.     drflac_uint8 lpcOrder;
  632.  
  633.     /* A pointer to the buffer containing the decoded samples in the subframe. This pointer is an offset from drflac::pExtraData. */
  634.     drflac_int32* pSamplesS32;
  635. } drflac_subframe;
  636.  
  637. typedef struct
  638. {
  639.     /*
  640.     If the stream uses variable block sizes, this will be set to the index of the first PCM frame. If fixed block sizes are used, this will
  641.     always be set to 0. This is 64-bit because the decoded PCM frame number will be 36 bits.
  642.     */
  643.     drflac_uint64 pcmFrameNumber;
  644.  
  645.     /*
  646.     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. This
  647.     is 32-bit because in fixed block sizes, the maximum frame number will be 31 bits.
  648.     */
  649.     drflac_uint32 flacFrameNumber;
  650.  
  651.     /* The sample rate of this frame. */
  652.     drflac_uint32 sampleRate;
  653.  
  654.     /* The number of PCM frames in each sub-frame within this frame. */
  655.     drflac_uint16 blockSizeInPCMFrames;
  656.  
  657.     /*
  658.     The channel assignment of this frame. This is not always set to the channel count. If interchannel decorrelation is being used this
  659.     will be set to DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE, DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE or DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE.
  660.     */
  661.     drflac_uint8 channelAssignment;
  662.  
  663.     /* The number of bits per sample within this frame. */
  664.     drflac_uint8 bitsPerSample;
  665.  
  666.     /* The frame's CRC. */
  667.     drflac_uint8 crc8;
  668. } drflac_frame_header;
  669.  
  670. typedef struct
  671. {
  672.     /* The header. */
  673.     drflac_frame_header header;
  674.  
  675.     /*
  676.     The number of PCM frames left to be read in this FLAC frame. This is initially set to the block size. As PCM frames are read,
  677.     this will be decremented. When it reaches 0, the decoder will see this frame as fully consumed and load the next frame.
  678.     */
  679.     drflac_uint32 pcmFramesRemaining;
  680.  
  681.     /* The list of sub-frames within the frame. There is one sub-frame for each channel, and there's a maximum of 8 channels. */
  682.     drflac_subframe subframes[8];
  683. } drflac_frame;
  684.  
  685. typedef struct
  686. {
  687.     /* The function to call when a metadata block is read. */
  688.     drflac_meta_proc onMeta;
  689.  
  690.     /* The user data posted to the metadata callback function. */
  691.     void* pUserDataMD;
  692.  
  693.     /* Memory allocation callbacks. */
  694.     drflac_allocation_callbacks allocationCallbacks;
  695.  
  696.  
  697.     /* The sample rate. Will be set to something like 44100. */
  698.     drflac_uint32 sampleRate;
  699.  
  700.     /*
  701.     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
  702.     value specified in the STREAMINFO block.
  703.     */
  704.     drflac_uint8 channels;
  705.  
  706.     /* The bits per sample. Will be set to something like 16, 24, etc. */
  707.     drflac_uint8 bitsPerSample;
  708.  
  709.     /* The maximum block size, in samples. This number represents the number of samples in each channel (not combined). */
  710.     drflac_uint16 maxBlockSizeInPCMFrames;
  711.  
  712.     /*
  713.     The total number of PCM Frames making up the stream. Can be 0 in which case it's still a valid stream, but just means
  714.     the total PCM frame count is unknown. Likely the case with streams like internet radio.
  715.     */
  716.     drflac_uint64 totalPCMFrameCount;
  717.  
  718.  
  719.     /* The container type. This is set based on whether or not the decoder was opened from a native or Ogg stream. */
  720.     drflac_container container;
  721.  
  722.     /* The number of seekpoints in the seektable. */
  723.     drflac_uint32 seekpointCount;
  724.  
  725.  
  726.     /* Information about the frame the decoder is currently sitting on. */
  727.     drflac_frame currentFLACFrame;
  728.  
  729.  
  730.     /* The index of the PCM frame the decoder is currently sitting on. This is only used for seeking. */
  731.     drflac_uint64 currentPCMFrame;
  732.  
  733.     /* The position of the first FLAC frame in the stream. This is only ever used for seeking. */
  734.     drflac_uint64 firstFLACFramePosInBytes;
  735.  
  736.  
  737.     /* A hack to avoid a malloc() when opening a decoder with drflac_open_memory(). */
  738.     drflac__memory_stream memoryStream;
  739.  
  740.  
  741.     /* A pointer to the decoded sample data. This is an offset of pExtraData. */
  742.     drflac_int32* pDecodedSamples;
  743.  
  744.     /* A pointer to the seek table. This is an offset of pExtraData, or NULL if there is no seek table. */
  745.     drflac_seekpoint* pSeekpoints;
  746.  
  747.     /* Internal use only. Only used with Ogg containers. Points to a drflac_oggbs object. This is an offset of pExtraData. */
  748.     void* _oggbs;
  749.  
  750.     /* Internal use only. Used for profiling and testing different seeking modes. */
  751.     drflac_bool32 _noSeekTableSeek    : 1;
  752.     drflac_bool32 _noBinarySearchSeek : 1;
  753.     drflac_bool32 _noBruteForceSeek   : 1;
  754.  
  755.     /* The bit streamer. The raw FLAC data is fed through this object. */
  756.     drflac_bs bs;
  757.  
  758.     /* Variable length extra data. We attach this to the end of the object so we can avoid unnecessary mallocs. */
  759.     drflac_uint8 pExtraData[1];
  760. } drflac;
  761.  
  762.  
  763. /*
  764. Opens a FLAC decoder.
  765.  
  766.  
  767. Parameters
  768. ----------
  769. onRead (in)
  770.     The function to call when data needs to be read from the client.
  771.  
  772. onSeek (in)
  773.     The function to call when the read position of the client data needs to move.
  774.  
  775. pUserData (in, optional)
  776.     A pointer to application defined data that will be passed to onRead and onSeek.
  777.  
  778. pAllocationCallbacks (in, optional)
  779.     A pointer to application defined callbacks for managing memory allocations.
  780.  
  781.  
  782. Return Value
  783. ------------
  784. Returns a pointer to an object representing the decoder.
  785.  
  786.  
  787. Remarks
  788. -------
  789. Close the decoder with `drflac_close()`.
  790.  
  791. `pAllocationCallbacks` can be NULL in which case it will use `DRFLAC_MALLOC`, `DRFLAC_REALLOC` and `DRFLAC_FREE`.
  792.  
  793. This function will automatically detect whether or not you are attempting to open a native or Ogg encapsulated FLAC, both of which should work seamlessly
  794. without any manual intervention. Ogg encapsulation also works with multiplexed streams which basically means it can play FLAC encoded audio tracks in videos.
  795.  
  796. This is the lowest level function for opening a FLAC stream. You can also use `drflac_open_file()` and `drflac_open_memory()` to open the stream from a file or
  797. from a block of memory respectively.
  798.  
  799. The STREAMINFO block must be present for this to succeed. Use `drflac_open_relaxed()` to open a FLAC stream where the header may not be present.
  800.  
  801.  
  802. Seek Also
  803. ---------
  804. drflac_open_file()
  805. drflac_open_memory()
  806. drflac_open_with_metadata()
  807. drflac_close()
  808. */
  809. DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  810.  
  811. /*
  812. Opens a FLAC stream with relaxed validation of the header block.
  813.  
  814.  
  815. Parameters
  816. ----------
  817. onRead (in)
  818.     The function to call when data needs to be read from the client.
  819.  
  820. onSeek (in)
  821.     The function to call when the read position of the client data needs to move.
  822.  
  823. container (in)
  824.     Whether or not the FLAC stream is encapsulated using standard FLAC encapsulation or Ogg encapsulation.
  825.  
  826. pUserData (in, optional)
  827.     A pointer to application defined data that will be passed to onRead and onSeek.
  828.  
  829. pAllocationCallbacks (in, optional)
  830.     A pointer to application defined callbacks for managing memory allocations.
  831.  
  832.  
  833. Return Value
  834. ------------
  835. A pointer to an object representing the decoder.
  836.  
  837.  
  838. Remarks
  839. -------
  840. The same as drflac_open(), except attempts to open the stream even when a header block is not present.
  841.  
  842. Because the header is not necessarily available, the caller must explicitly define the container (Native or Ogg). Do not set this to `drflac_container_unknown`
  843. as that is for internal use only.
  844.  
  845. Opening in relaxed mode will continue reading data from onRead until it finds a valid frame. If a frame is never found it will continue forever. To abort,
  846. force your `onRead` callback to return 0, which dr_flac will use as an indicator that the end of the stream was found.
  847. */
  848. DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  849.  
  850. /*
  851. Opens a FLAC decoder and notifies the caller of the metadata chunks (album art, etc.).
  852.  
  853.  
  854. Parameters
  855. ----------
  856. onRead (in)
  857.     The function to call when data needs to be read from the client.
  858.  
  859. onSeek (in)
  860.     The function to call when the read position of the client data needs to move.
  861.  
  862. onMeta (in)
  863.     The function to call for every metadata block.
  864.  
  865. pUserData (in, optional)
  866.     A pointer to application defined data that will be passed to onRead, onSeek and onMeta.
  867.  
  868. pAllocationCallbacks (in, optional)
  869.     A pointer to application defined callbacks for managing memory allocations.
  870.  
  871.  
  872. Return Value
  873. ------------
  874. A pointer to an object representing the decoder.
  875.  
  876.  
  877. Remarks
  878. -------
  879. Close the decoder with `drflac_close()`.
  880.  
  881. `pAllocationCallbacks` can be NULL in which case it will use `DRFLAC_MALLOC`, `DRFLAC_REALLOC` and `DRFLAC_FREE`.
  882.  
  883. This is slower than `drflac_open()`, so avoid this one if you don't need metadata. Internally, this will allocate and free memory on the heap for every
  884. metadata block except for STREAMINFO and PADDING blocks.
  885.  
  886. The caller is notified of the metadata via the `onMeta` callback. All metadata blocks will be handled before the function returns.
  887.  
  888. The STREAMINFO block must be present for this to succeed. Use `drflac_open_with_metadata_relaxed()` to open a FLAC stream where the header may not be present.
  889.  
  890. Note that this will behave inconsistently with `drflac_open()` if the stream is an Ogg encapsulated stream and a metadata block is corrupted. This is due to
  891. the way the Ogg stream recovers from corrupted pages. When `drflac_open_with_metadata()` is being used, the open routine will try to read the contents of the
  892. metadata block, whereas `drflac_open()` will simply seek past it (for the sake of efficiency). This inconsistency can result in different samples being
  893. returned depending on whether or not the stream is being opened with metadata.
  894.  
  895.  
  896. Seek Also
  897. ---------
  898. drflac_open_file_with_metadata()
  899. drflac_open_memory_with_metadata()
  900. drflac_open()
  901. drflac_close()
  902. */
  903. DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  904.  
  905. /*
  906. The same as drflac_open_with_metadata(), except attempts to open the stream even when a header block is not present.
  907.  
  908. See Also
  909. --------
  910. drflac_open_with_metadata()
  911. drflac_open_relaxed()
  912. */
  913. DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  914.  
  915. /*
  916. Closes the given FLAC decoder.
  917.  
  918.  
  919. Parameters
  920. ----------
  921. pFlac (in)
  922.     The decoder to close.
  923.  
  924.  
  925. Remarks
  926. -------
  927. This will destroy the decoder object.
  928.  
  929.  
  930. See Also
  931. --------
  932. drflac_open()
  933. drflac_open_with_metadata()
  934. drflac_open_file()
  935. drflac_open_file_w()
  936. drflac_open_file_with_metadata()
  937. drflac_open_file_with_metadata_w()
  938. drflac_open_memory()
  939. drflac_open_memory_with_metadata()
  940. */
  941. DRFLAC_API void drflac_close(drflac* pFlac);
  942.  
  943.  
  944. /*
  945. Reads sample data from the given FLAC decoder, output as interleaved signed 32-bit PCM.
  946.  
  947.  
  948. Parameters
  949. ----------
  950. pFlac (in)
  951.     The decoder.
  952.  
  953. framesToRead (in)
  954.     The number of PCM frames to read.
  955.  
  956. pBufferOut (out, optional)
  957.     A pointer to the buffer that will receive the decoded samples.
  958.  
  959.  
  960. Return Value
  961. ------------
  962. Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end.
  963.  
  964.  
  965. Remarks
  966. -------
  967. pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of frames seeked.
  968. */
  969. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut);
  970.  
  971.  
  972. /*
  973. Reads sample data from the given FLAC decoder, output as interleaved signed 16-bit PCM.
  974.  
  975.  
  976. Parameters
  977. ----------
  978. pFlac (in)
  979.     The decoder.
  980.  
  981. framesToRead (in)
  982.     The number of PCM frames to read.
  983.  
  984. pBufferOut (out, optional)
  985.     A pointer to the buffer that will receive the decoded samples.
  986.  
  987.  
  988. Return Value
  989. ------------
  990. Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end.
  991.  
  992.  
  993. Remarks
  994. -------
  995. pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of frames seeked.
  996.  
  997. Note that this is lossy for streams where the bits per sample is larger than 16.
  998. */
  999. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut);
  1000.  
  1001. /*
  1002. Reads sample data from the given FLAC decoder, output as interleaved 32-bit floating point PCM.
  1003.  
  1004.  
  1005. Parameters
  1006. ----------
  1007. pFlac (in)
  1008.     The decoder.
  1009.  
  1010. framesToRead (in)
  1011.     The number of PCM frames to read.
  1012.  
  1013. pBufferOut (out, optional)
  1014.     A pointer to the buffer that will receive the decoded samples.
  1015.  
  1016.  
  1017. Return Value
  1018. ------------
  1019. Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end.
  1020.  
  1021.  
  1022. Remarks
  1023. -------
  1024. pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of frames seeked.
  1025.  
  1026. Note that this should be considered lossy due to the nature of floating point numbers not being able to exactly represent every possible number.
  1027. */
  1028. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut);
  1029.  
  1030. /*
  1031. Seeks to the PCM frame at the given index.
  1032.  
  1033.  
  1034. Parameters
  1035. ----------
  1036. pFlac (in)
  1037.     The decoder.
  1038.  
  1039. pcmFrameIndex (in)
  1040.     The index of the PCM frame to seek to. See notes below.
  1041.  
  1042.  
  1043. Return Value
  1044. -------------
  1045. `DRFLAC_TRUE` if successful; `DRFLAC_FALSE` otherwise.
  1046. */
  1047. DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex);
  1048.  
  1049.  
  1050.  
  1051. #ifndef DR_FLAC_NO_STDIO
  1052. /*
  1053. Opens a FLAC decoder from the file at the given path.
  1054.  
  1055.  
  1056. Parameters
  1057. ----------
  1058. pFileName (in)
  1059.     The path of the file to open, either absolute or relative to the current directory.
  1060.  
  1061. pAllocationCallbacks (in, optional)
  1062.     A pointer to application defined callbacks for managing memory allocations.
  1063.  
  1064.  
  1065. Return Value
  1066. ------------
  1067. A pointer to an object representing the decoder.
  1068.  
  1069.  
  1070. Remarks
  1071. -------
  1072. Close the decoder with drflac_close().
  1073.  
  1074.  
  1075. Remarks
  1076. -------
  1077. This will hold a handle to the file until the decoder is closed with drflac_close(). Some platforms will restrict the number of files a process can have open
  1078. at any given time, so keep this mind if you have many decoders open at the same time.
  1079.  
  1080.  
  1081. See Also
  1082. --------
  1083. drflac_open_file_with_metadata()
  1084. drflac_open()
  1085. drflac_close()
  1086. */
  1087. DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
  1088. DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
  1089.  
  1090. /*
  1091. Opens a FLAC decoder from the file at the given path and notifies the caller of the metadata chunks (album art, etc.)
  1092.  
  1093.  
  1094. Parameters
  1095. ----------
  1096. pFileName (in)
  1097.     The path of the file to open, either absolute or relative to the current directory.
  1098.  
  1099. pAllocationCallbacks (in, optional)
  1100.     A pointer to application defined callbacks for managing memory allocations.
  1101.  
  1102. onMeta (in)
  1103.     The callback to fire for each metadata block.
  1104.  
  1105. pUserData (in)
  1106.     A pointer to the user data to pass to the metadata callback.
  1107.  
  1108. pAllocationCallbacks (in)
  1109.     A pointer to application defined callbacks for managing memory allocations.
  1110.  
  1111.  
  1112. Remarks
  1113. -------
  1114. Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
  1115.  
  1116.  
  1117. See Also
  1118. --------
  1119. drflac_open_with_metadata()
  1120. drflac_open()
  1121. drflac_close()
  1122. */
  1123. DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  1124. DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  1125. #endif
  1126.  
  1127. /*
  1128. Opens a FLAC decoder from a pre-allocated block of memory
  1129.  
  1130.  
  1131. Parameters
  1132. ----------
  1133. pData (in)
  1134.     A pointer to the raw encoded FLAC data.
  1135.  
  1136. dataSize (in)
  1137.     The size in bytes of `data`.
  1138.  
  1139. pAllocationCallbacks (in)
  1140.     A pointer to application defined callbacks for managing memory allocations.
  1141.  
  1142.  
  1143. Return Value
  1144. ------------
  1145. A pointer to an object representing the decoder.
  1146.  
  1147.  
  1148. Remarks
  1149. -------
  1150. This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for the lifetime of the decoder.
  1151.  
  1152.  
  1153. See Also
  1154. --------
  1155. drflac_open()
  1156. drflac_close()
  1157. */
  1158. DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks);
  1159.  
  1160. /*
  1161. Opens a FLAC decoder from a pre-allocated block of memory and notifies the caller of the metadata chunks (album art, etc.)
  1162.  
  1163.  
  1164. Parameters
  1165. ----------
  1166. pData (in)
  1167.     A pointer to the raw encoded FLAC data.
  1168.  
  1169. dataSize (in)
  1170.     The size in bytes of `data`.
  1171.  
  1172. onMeta (in)
  1173.     The callback to fire for each metadata block.
  1174.  
  1175. pUserData (in)
  1176.     A pointer to the user data to pass to the metadata callback.
  1177.  
  1178. pAllocationCallbacks (in)
  1179.     A pointer to application defined callbacks for managing memory allocations.
  1180.  
  1181.  
  1182. Remarks
  1183. -------
  1184. Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
  1185.  
  1186.  
  1187. See Also
  1188. -------
  1189. drflac_open_with_metadata()
  1190. drflac_open()
  1191. drflac_close()
  1192. */
  1193. DRFLAC_API drflac* drflac_open_memory_with_metadata(const void* pData, size_t dataSize, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  1194.  
  1195.  
  1196.  
  1197. /* High Level APIs */
  1198.  
  1199. /*
  1200. Opens a FLAC stream from the given callbacks and fully decodes it in a single operation. The return value is a
  1201. pointer to the sample data as interleaved signed 32-bit PCM. The returned data must be freed with drflac_free().
  1202.  
  1203. You can pass in custom memory allocation callbacks via the pAllocationCallbacks parameter. This can be NULL in which
  1204. case it will use DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE.
  1205.  
  1206. Sometimes a FLAC file won't keep track of the total sample count. In this situation the function will continuously
  1207. read samples into a dynamically sized buffer on the heap until no samples are left.
  1208.  
  1209. Do not call this function on a broadcast type of stream (like internet radio streams and whatnot).
  1210. */
  1211. DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  1212.  
  1213. /* Same as drflac_open_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */
  1214. DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  1215.  
  1216. /* Same as drflac_open_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */
  1217. DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  1218.  
  1219. #ifndef DR_FLAC_NO_STDIO
  1220. /* Same as drflac_open_and_read_pcm_frames_s32() except opens the decoder from a file. */
  1221. DRFLAC_API drflac_int32* drflac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  1222.  
  1223. /* Same as drflac_open_file_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */
  1224. DRFLAC_API drflac_int16* drflac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  1225.  
  1226. /* Same as drflac_open_file_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */
  1227. DRFLAC_API float* drflac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  1228. #endif
  1229.  
  1230. /* Same as drflac_open_and_read_pcm_frames_s32() except opens the decoder from a block of memory. */
  1231. DRFLAC_API drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  1232.  
  1233. /* Same as drflac_open_memory_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */
  1234. DRFLAC_API drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  1235.  
  1236. /* Same as drflac_open_memory_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */
  1237. DRFLAC_API float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  1238.  
  1239. /*
  1240. Frees memory that was allocated internally by dr_flac.
  1241.  
  1242. Set pAllocationCallbacks to the same object that was passed to drflac_open_*_and_read_pcm_frames_*(). If you originally passed in NULL, pass in NULL for this.
  1243. */
  1244. DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks);
  1245.  
  1246.  
  1247. /* Structure representing an iterator for vorbis comments in a VORBIS_COMMENT metadata block. */
  1248. typedef struct
  1249. {
  1250.     drflac_uint32 countRemaining;
  1251.     const char* pRunningData;
  1252. } drflac_vorbis_comment_iterator;
  1253.  
  1254. /*
  1255. Initializes a vorbis comment iterator. This can be used for iterating over the vorbis comments in a VORBIS_COMMENT
  1256. metadata block.
  1257. */
  1258. DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments);
  1259.  
  1260. /*
  1261. Goes to the next vorbis comment in the given iterator. If null is returned it means there are no more comments. The
  1262. returned string is NOT null terminated.
  1263. */
  1264. DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut);
  1265.  
  1266.  
  1267. /* Structure representing an iterator for cuesheet tracks in a CUESHEET metadata block. */
  1268. typedef struct
  1269. {
  1270.     drflac_uint32 countRemaining;
  1271.     const char* pRunningData;
  1272. } drflac_cuesheet_track_iterator;
  1273.  
  1274. /* Packing is important on this structure because we map this directly to the raw data within the CUESHEET metadata block. */
  1275. #pragma pack(4)
  1276. typedef struct
  1277. {
  1278.     drflac_uint64 offset;
  1279.     drflac_uint8 index;
  1280.     drflac_uint8 reserved[3];
  1281. } drflac_cuesheet_track_index;
  1282. #pragma pack()
  1283.  
  1284. typedef struct
  1285. {
  1286.     drflac_uint64 offset;
  1287.     drflac_uint8 trackNumber;
  1288.     char ISRC[12];
  1289.     drflac_bool8 isAudio;
  1290.     drflac_bool8 preEmphasis;
  1291.     drflac_uint8 indexCount;
  1292.     const drflac_cuesheet_track_index* pIndexPoints;
  1293. } drflac_cuesheet_track;
  1294.  
  1295. /*
  1296. Initializes a cuesheet track iterator. This can be used for iterating over the cuesheet tracks in a CUESHEET metadata
  1297. block.
  1298. */
  1299. DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData);
  1300.  
  1301. /* Goes to the next cuesheet track in the given iterator. If DRFLAC_FALSE is returned it means there are no more comments. */
  1302. DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack);
  1303.  
  1304.  
  1305. #ifdef __cplusplus
  1306. }
  1307. #endif
  1308. #endif  /* dr_flac_h */
  1309.  
  1310.  
  1311. /************************************************************************************************************************************************************
  1312.  ************************************************************************************************************************************************************
  1313.  
  1314.  IMPLEMENTATION
  1315.  
  1316.  ************************************************************************************************************************************************************
  1317.  ************************************************************************************************************************************************************/
  1318. #if defined(DR_FLAC_IMPLEMENTATION) || defined(DRFLAC_IMPLEMENTATION)
  1319.  
  1320. /* Disable some annoying warnings. */
  1321. #if defined(__GNUC__)
  1322.     #pragma GCC diagnostic push
  1323.     #if __GNUC__ >= 7
  1324.     #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
  1325.     #endif
  1326. #endif
  1327.  
  1328. #ifdef __linux__
  1329.     #ifndef _BSD_SOURCE
  1330.         #define _BSD_SOURCE
  1331.     #endif
  1332.     #ifndef __USE_BSD
  1333.         #define __USE_BSD
  1334.     #endif
  1335.     #include <endian.h>
  1336. #endif
  1337.  
  1338. #include <stdlib.h>
  1339. #include <string.h>
  1340.  
  1341. #ifdef _MSC_VER
  1342.     #define DRFLAC_INLINE __forceinline
  1343. #elif defined(__GNUC__)
  1344.     /*
  1345.     I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when
  1346.     the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some
  1347.     case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the
  1348.     command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue
  1349.     I am using "__inline__" only when we're compiling in strict ANSI mode.
  1350.     */
  1351.     #if defined(__STRICT_ANSI__)
  1352.         #define DRFLAC_INLINE __inline__ __attribute__((always_inline))
  1353.     #else
  1354.         #define DRFLAC_INLINE inline __attribute__((always_inline))
  1355.     #endif
  1356. #else
  1357.     #define DRFLAC_INLINE
  1358. #endif
  1359.  
  1360. /* CPU architecture. */
  1361. #if defined(__x86_64__) || defined(_M_X64)
  1362.     #define DRFLAC_X64
  1363. #elif defined(__i386) || defined(_M_IX86)
  1364.     #define DRFLAC_X86
  1365. #elif defined(__arm__) || defined(_M_ARM)
  1366.     #define DRFLAC_ARM
  1367. #endif
  1368.  
  1369. /* Intrinsics Support */
  1370. #if !defined(DR_FLAC_NO_SIMD)
  1371.     #if defined(DRFLAC_X64) || defined(DRFLAC_X86)
  1372.         #if defined(_MSC_VER) && !defined(__clang__)
  1373.             /* MSVC. */
  1374.             #if _MSC_VER >= 1400 && !defined(DRFLAC_NO_SSE2)    /* 2005 */
  1375.                 #define DRFLAC_SUPPORT_SSE2
  1376.             #endif
  1377.             #if _MSC_VER >= 1600 && !defined(DRFLAC_NO_SSE41)   /* 2010 */
  1378.                 #define DRFLAC_SUPPORT_SSE41
  1379.             #endif
  1380.         #else
  1381.             /* Assume GNUC-style. */
  1382.             #if defined(__SSE2__) && !defined(DRFLAC_NO_SSE2)
  1383.                 #define DRFLAC_SUPPORT_SSE2
  1384.             #endif
  1385.             #if defined(__SSE4_1__) && !defined(DRFLAC_NO_SSE41)
  1386.                 #define DRFLAC_SUPPORT_SSE41
  1387.             #endif
  1388.         #endif
  1389.  
  1390.         /* If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. */
  1391.         #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
  1392.             #if !defined(DRFLAC_SUPPORT_SSE2) && !defined(DRFLAC_NO_SSE2) && __has_include(<emmintrin.h>)
  1393.                 #define DRFLAC_SUPPORT_SSE2
  1394.             #endif
  1395.             #if !defined(DRFLAC_SUPPORT_SSE41) && !defined(DRFLAC_NO_SSE41) && __has_include(<smmintrin.h>)
  1396.                 #define DRFLAC_SUPPORT_SSE41
  1397.             #endif
  1398.         #endif
  1399.  
  1400.         #if defined(DRFLAC_SUPPORT_SSE41)
  1401.             #include <smmintrin.h>
  1402.         #elif defined(DRFLAC_SUPPORT_SSE2)
  1403.             #include <emmintrin.h>
  1404.         #endif
  1405.     #endif
  1406.  
  1407.     #if defined(DRFLAC_ARM)
  1408.         #if !defined(DRFLAC_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  1409.             #define DRFLAC_SUPPORT_NEON
  1410.         #endif
  1411.  
  1412.         /* Fall back to looking for the #include file. */
  1413.         #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
  1414.             #if !defined(DRFLAC_SUPPORT_NEON) && !defined(DRFLAC_NO_NEON) && __has_include(<arm_neon.h>)
  1415.                 #define DRFLAC_SUPPORT_NEON
  1416.             #endif
  1417.         #endif
  1418.  
  1419.         #if defined(DRFLAC_SUPPORT_NEON)
  1420.             #include <arm_neon.h>
  1421.         #endif
  1422.     #endif
  1423. #endif
  1424.  
  1425. /* Compile-time CPU feature support. */
  1426. #if !defined(DR_FLAC_NO_SIMD) && (defined(DRFLAC_X86) || defined(DRFLAC_X64))
  1427.     #if defined(_MSC_VER) && !defined(__clang__)
  1428.         #if _MSC_VER >= 1400
  1429.             #include <intrin.h>
  1430.             static void drflac__cpuid(int info[4], int fid)
  1431.             {
  1432.                 __cpuid(info, fid);
  1433.             }
  1434.         #else
  1435.             #define DRFLAC_NO_CPUID
  1436.         #endif
  1437.     #else
  1438.         #if defined(__GNUC__) || defined(__clang__)
  1439.             static void drflac__cpuid(int info[4], int fid)
  1440.             {
  1441.                 /*
  1442.                 It looks like the -fPIC option uses the ebx register which GCC complains about. We can work around this by just using a different register, the
  1443.                 specific register of which I'm letting the compiler decide on. The "k" prefix is used to specify a 32-bit register. The {...} syntax is for
  1444.                 supporting different assembly dialects.
  1445.  
  1446.                 What's basically happening is that we're saving and restoring the ebx register manually.
  1447.                 */
  1448.                 #if defined(DRFLAC_X86) && defined(__PIC__)
  1449.                     __asm__ __volatile__ (
  1450.                         "xchg{l} {%%}ebx, %k1;"
  1451.                         "cpuid;"
  1452.                         "xchg{l} {%%}ebx, %k1;"
  1453.                         : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  1454.                     );
  1455.                 #else
  1456.                     __asm__ __volatile__ (
  1457.                         "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  1458.                     );
  1459.                 #endif
  1460.             }
  1461.         #else
  1462.             #define DRFLAC_NO_CPUID
  1463.         #endif
  1464.     #endif
  1465. #else
  1466.     #define DRFLAC_NO_CPUID
  1467. #endif
  1468.  
  1469. static DRFLAC_INLINE drflac_bool32 drflac_has_sse2(void)
  1470. {
  1471. #if defined(DRFLAC_SUPPORT_SSE2)
  1472.     #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE2)
  1473.         #if defined(DRFLAC_X64)
  1474.             return DRFLAC_TRUE;    /* 64-bit targets always support SSE2. */
  1475.         #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)
  1476.             return DRFLAC_TRUE;    /* If the compiler is allowed to freely generate SSE2 code we can assume support. */
  1477.         #else
  1478.             #if defined(DRFLAC_NO_CPUID)
  1479.                 return DRFLAC_FALSE;
  1480.             #else
  1481.                 int info[4];
  1482.                 drflac__cpuid(info, 1);
  1483.                 return (info[3] & (1 << 26)) != 0;
  1484.             #endif
  1485.         #endif
  1486.     #else
  1487.         return DRFLAC_FALSE;       /* SSE2 is only supported on x86 and x64 architectures. */
  1488.     #endif
  1489. #else
  1490.     return DRFLAC_FALSE;           /* No compiler support. */
  1491. #endif
  1492. }
  1493.  
  1494. static DRFLAC_INLINE drflac_bool32 drflac_has_sse41(void)
  1495. {
  1496. #if defined(DRFLAC_SUPPORT_SSE41)
  1497.     #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE41)
  1498.         #if defined(DRFLAC_X64)
  1499.             return DRFLAC_TRUE;    /* 64-bit targets always support SSE4.1. */
  1500.         #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE4_1__)
  1501.             return DRFLAC_TRUE;    /* If the compiler is allowed to freely generate SSE41 code we can assume support. */
  1502.         #else
  1503.             #if defined(DRFLAC_NO_CPUID)
  1504.                 return DRFLAC_FALSE;
  1505.             #else
  1506.                 int info[4];
  1507.                 drflac__cpuid(info, 1);
  1508.                 return (info[2] & (1 << 19)) != 0;
  1509.             #endif
  1510.         #endif
  1511.     #else
  1512.         return DRFLAC_FALSE;       /* SSE41 is only supported on x86 and x64 architectures. */
  1513.     #endif
  1514. #else
  1515.     return DRFLAC_FALSE;           /* No compiler support. */
  1516. #endif
  1517. }
  1518.  
  1519.  
  1520. #if defined(_MSC_VER) && _MSC_VER >= 1500 && (defined(DRFLAC_X86) || defined(DRFLAC_X64))
  1521.     #define DRFLAC_HAS_LZCNT_INTRINSIC
  1522. #elif (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
  1523.     #define DRFLAC_HAS_LZCNT_INTRINSIC
  1524. #elif defined(__clang__)
  1525.     #if defined(__has_builtin)
  1526.         #if __has_builtin(__builtin_clzll) || __has_builtin(__builtin_clzl)
  1527.             #define DRFLAC_HAS_LZCNT_INTRINSIC
  1528.         #endif
  1529.     #endif
  1530. #endif
  1531.  
  1532. #if defined(_MSC_VER) && _MSC_VER >= 1400
  1533.     #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
  1534.     #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
  1535.     #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
  1536. #elif defined(__clang__)
  1537.     #if defined(__has_builtin)
  1538.         #if __has_builtin(__builtin_bswap16)
  1539.             #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
  1540.         #endif
  1541.         #if __has_builtin(__builtin_bswap32)
  1542.             #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
  1543.         #endif
  1544.         #if __has_builtin(__builtin_bswap64)
  1545.             #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
  1546.         #endif
  1547.     #endif
  1548. #elif defined(__GNUC__)
  1549.     #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
  1550.         #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
  1551.         #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
  1552.     #endif
  1553.     #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  1554.         #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
  1555.     #endif
  1556. #endif
  1557.  
  1558.  
  1559. /* Standard library stuff. */
  1560. #ifndef DRFLAC_ASSERT
  1561. #include <assert.h>
  1562. #define DRFLAC_ASSERT(expression)           assert(expression)
  1563. #endif
  1564. #ifndef DRFLAC_MALLOC
  1565. #define DRFLAC_MALLOC(sz)                   malloc((sz))
  1566. #endif
  1567. #ifndef DRFLAC_REALLOC
  1568. #define DRFLAC_REALLOC(p, sz)               realloc((p), (sz))
  1569. #endif
  1570. #ifndef DRFLAC_FREE
  1571. #define DRFLAC_FREE(p)                      free((p))
  1572. #endif
  1573. #ifndef DRFLAC_COPY_MEMORY
  1574. #define DRFLAC_COPY_MEMORY(dst, src, sz)    memcpy((dst), (src), (sz))
  1575. #endif
  1576. #ifndef DRFLAC_ZERO_MEMORY
  1577. #define DRFLAC_ZERO_MEMORY(p, sz)           memset((p), 0, (sz))
  1578. #endif
  1579. #ifndef DRFLAC_ZERO_OBJECT
  1580. #define DRFLAC_ZERO_OBJECT(p)               DRFLAC_ZERO_MEMORY((p), sizeof(*(p)))
  1581. #endif
  1582.  
  1583. #define DRFLAC_MAX_SIMD_VECTOR_SIZE                     64  /* 64 for AVX-512 in the future. */
  1584.  
  1585. typedef drflac_int32 drflac_result;
  1586. #define DRFLAC_SUCCESS                                   0
  1587. #define DRFLAC_ERROR                                    -1   /* A generic error. */
  1588. #define DRFLAC_INVALID_ARGS                             -2
  1589. #define DRFLAC_INVALID_OPERATION                        -3
  1590. #define DRFLAC_OUT_OF_MEMORY                            -4
  1591. #define DRFLAC_OUT_OF_RANGE                             -5
  1592. #define DRFLAC_ACCESS_DENIED                            -6
  1593. #define DRFLAC_DOES_NOT_EXIST                           -7
  1594. #define DRFLAC_ALREADY_EXISTS                           -8
  1595. #define DRFLAC_TOO_MANY_OPEN_FILES                      -9
  1596. #define DRFLAC_INVALID_FILE                             -10
  1597. #define DRFLAC_TOO_BIG                                  -11
  1598. #define DRFLAC_PATH_TOO_LONG                            -12
  1599. #define DRFLAC_NAME_TOO_LONG                            -13
  1600. #define DRFLAC_NOT_DIRECTORY                            -14
  1601. #define DRFLAC_IS_DIRECTORY                             -15
  1602. #define DRFLAC_DIRECTORY_NOT_EMPTY                      -16
  1603. #define DRFLAC_END_OF_FILE                              -17
  1604. #define DRFLAC_NO_SPACE                                 -18
  1605. #define DRFLAC_BUSY                                     -19
  1606. #define DRFLAC_IO_ERROR                                 -20
  1607. #define DRFLAC_INTERRUPT                                -21
  1608. #define DRFLAC_UNAVAILABLE                              -22
  1609. #define DRFLAC_ALREADY_IN_USE                           -23
  1610. #define DRFLAC_BAD_ADDRESS                              -24
  1611. #define DRFLAC_BAD_SEEK                                 -25
  1612. #define DRFLAC_BAD_PIPE                                 -26
  1613. #define DRFLAC_DEADLOCK                                 -27
  1614. #define DRFLAC_TOO_MANY_LINKS                           -28
  1615. #define DRFLAC_NOT_IMPLEMENTED                          -29
  1616. #define DRFLAC_NO_MESSAGE                               -30
  1617. #define DRFLAC_BAD_MESSAGE                              -31
  1618. #define DRFLAC_NO_DATA_AVAILABLE                        -32
  1619. #define DRFLAC_INVALID_DATA                             -33
  1620. #define DRFLAC_TIMEOUT                                  -34
  1621. #define DRFLAC_NO_NETWORK                               -35
  1622. #define DRFLAC_NOT_UNIQUE                               -36
  1623. #define DRFLAC_NOT_SOCKET                               -37
  1624. #define DRFLAC_NO_ADDRESS                               -38
  1625. #define DRFLAC_BAD_PROTOCOL                             -39
  1626. #define DRFLAC_PROTOCOL_UNAVAILABLE                     -40
  1627. #define DRFLAC_PROTOCOL_NOT_SUPPORTED                   -41
  1628. #define DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED            -42
  1629. #define DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED             -43
  1630. #define DRFLAC_SOCKET_NOT_SUPPORTED                     -44
  1631. #define DRFLAC_CONNECTION_RESET                         -45
  1632. #define DRFLAC_ALREADY_CONNECTED                        -46
  1633. #define DRFLAC_NOT_CONNECTED                            -47
  1634. #define DRFLAC_CONNECTION_REFUSED                       -48
  1635. #define DRFLAC_NO_HOST                                  -49
  1636. #define DRFLAC_IN_PROGRESS                              -50
  1637. #define DRFLAC_CANCELLED                                -51
  1638. #define DRFLAC_MEMORY_ALREADY_MAPPED                    -52
  1639. #define DRFLAC_AT_END                                   -53
  1640. #define DRFLAC_CRC_MISMATCH                             -128
  1641.  
  1642. #define DRFLAC_SUBFRAME_CONSTANT                        0
  1643. #define DRFLAC_SUBFRAME_VERBATIM                        1
  1644. #define DRFLAC_SUBFRAME_FIXED                           8
  1645. #define DRFLAC_SUBFRAME_LPC                             32
  1646. #define DRFLAC_SUBFRAME_RESERVED                        255
  1647.  
  1648. #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE  0
  1649. #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 1
  1650.  
  1651. #define DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT           0
  1652. #define DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE             8
  1653. #define DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE            9
  1654. #define DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE              10
  1655.  
  1656. #define drflac_align(x, a)                              ((((x) + (a) - 1) / (a)) * (a))
  1657.  
  1658.  
  1659. DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision)
  1660. {
  1661.     if (pMajor) {
  1662.         *pMajor = DRFLAC_VERSION_MAJOR;
  1663.     }
  1664.  
  1665.     if (pMinor) {
  1666.         *pMinor = DRFLAC_VERSION_MINOR;
  1667.     }
  1668.  
  1669.     if (pRevision) {
  1670.         *pRevision = DRFLAC_VERSION_REVISION;
  1671.     }
  1672. }
  1673.  
  1674. DRFLAC_API const char* drflac_version_string()
  1675. {
  1676.     return DRFLAC_VERSION_STRING;
  1677. }
  1678.  
  1679.  
  1680. /* CPU caps. */
  1681. #if defined(__has_feature)
  1682.     #if __has_feature(thread_sanitizer)
  1683.         #define DRFLAC_NO_THREAD_SANITIZE __attribute__((no_sanitize("thread")))
  1684.     #else
  1685.         #define DRFLAC_NO_THREAD_SANITIZE
  1686.     #endif
  1687. #else
  1688.     #define DRFLAC_NO_THREAD_SANITIZE
  1689. #endif
  1690.  
  1691. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
  1692. static drflac_bool32 drflac__gIsLZCNTSupported = DRFLAC_FALSE;
  1693. #endif
  1694.  
  1695. #ifndef DRFLAC_NO_CPUID
  1696. static drflac_bool32 drflac__gIsSSE2Supported  = DRFLAC_FALSE;
  1697. static drflac_bool32 drflac__gIsSSE41Supported = DRFLAC_FALSE;
  1698.  
  1699. /*
  1700. I've had a bug report that Clang's ThreadSanitizer presents a warning in this function. Having reviewed this, this does
  1701. actually make sense. However, since CPU caps should never differ for a running process, I don't think the trade off of
  1702. complicating internal API's by passing around CPU caps versus just disabling the warnings is worthwhile. I'm therefore
  1703. just going to disable these warnings. This is disabled via the DRFLAC_NO_THREAD_SANITIZE attribute.
  1704. */
  1705. DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void)
  1706. {
  1707.     static drflac_bool32 isCPUCapsInitialized = DRFLAC_FALSE;
  1708.  
  1709.     if (!isCPUCapsInitialized) {
  1710.         /* LZCNT */
  1711. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
  1712.         int info[4] = {0};
  1713.         drflac__cpuid(info, 0x80000001);
  1714.         drflac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0;
  1715. #endif
  1716.  
  1717.         /* SSE2 */
  1718.         drflac__gIsSSE2Supported = drflac_has_sse2();
  1719.  
  1720.         /* SSE4.1 */
  1721.         drflac__gIsSSE41Supported = drflac_has_sse41();
  1722.  
  1723.         /* Initialized. */
  1724.         isCPUCapsInitialized = DRFLAC_TRUE;
  1725.     }
  1726. }
  1727. #else
  1728. static drflac_bool32 drflac__gIsNEONSupported  = DRFLAC_FALSE;
  1729.  
  1730. static DRFLAC_INLINE drflac_bool32 drflac__has_neon(void)
  1731. {
  1732. #if defined(DRFLAC_SUPPORT_NEON)
  1733.     #if defined(DRFLAC_ARM) && !defined(DRFLAC_NO_NEON)
  1734.         #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  1735.             return DRFLAC_TRUE;    /* If the compiler is allowed to freely generate NEON code we can assume support. */
  1736.         #else
  1737.             /* TODO: Runtime check. */
  1738.             return DRFLAC_FALSE;
  1739.         #endif
  1740.     #else
  1741.         return DRFLAC_FALSE;       /* NEON is only supported on ARM architectures. */
  1742.     #endif
  1743. #else
  1744.     return DRFLAC_FALSE;           /* No compiler support. */
  1745. #endif
  1746. }
  1747.  
  1748. DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void)
  1749. {
  1750.     drflac__gIsNEONSupported = drflac__has_neon();
  1751.  
  1752. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
  1753.     drflac__gIsLZCNTSupported = DRFLAC_TRUE;
  1754. #endif
  1755. }
  1756. #endif
  1757.  
  1758.  
  1759. /* Endian Management */
  1760. static DRFLAC_INLINE drflac_bool32 drflac__is_little_endian(void)
  1761. {
  1762. #if defined(DRFLAC_X86) || defined(DRFLAC_X64)
  1763.     return DRFLAC_TRUE;
  1764. #elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
  1765.     return DRFLAC_TRUE;
  1766. #else
  1767.     int n = 1;
  1768.     return (*(char*)&n) == 1;
  1769. #endif
  1770. }
  1771.  
  1772. static DRFLAC_INLINE drflac_uint16 drflac__swap_endian_uint16(drflac_uint16 n)
  1773. {
  1774. #ifdef DRFLAC_HAS_BYTESWAP16_INTRINSIC
  1775.     #if defined(_MSC_VER)
  1776.         return _byteswap_ushort(n);
  1777.     #elif defined(__GNUC__) || defined(__clang__)
  1778.         return __builtin_bswap16(n);
  1779.     #else
  1780.         #error "This compiler does not support the byte swap intrinsic."
  1781.     #endif
  1782. #else
  1783.     return ((n & 0xFF00) >> 8) |
  1784.            ((n & 0x00FF) << 8);
  1785. #endif
  1786. }
  1787.  
  1788. static DRFLAC_INLINE drflac_uint32 drflac__swap_endian_uint32(drflac_uint32 n)
  1789. {
  1790. #ifdef DRFLAC_HAS_BYTESWAP32_INTRINSIC
  1791.     #if defined(_MSC_VER)
  1792.         return _byteswap_ulong(n);
  1793.     #elif defined(__GNUC__) || defined(__clang__)
  1794.         #if defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(DRFLAC_64BIT)   /* <-- 64-bit inline assembly has not been tested, so disabling for now. */
  1795.             /* Inline assembly optimized implementation for ARM. In my testing, GCC does not generate optimized code with __builtin_bswap32(). */
  1796.             drflac_uint32 r;
  1797.             __asm__ __volatile__ (
  1798.             #if defined(DRFLAC_64BIT)
  1799.                 "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n)   /* <-- This is untested. If someone in the community could test this, that would be appreciated! */
  1800.             #else
  1801.                 "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
  1802.             #endif
  1803.             );
  1804.             return r;
  1805.         #else
  1806.             return __builtin_bswap32(n);
  1807.         #endif
  1808.     #else
  1809.         #error "This compiler does not support the byte swap intrinsic."
  1810.     #endif
  1811. #else
  1812.     return ((n & 0xFF000000) >> 24) |
  1813.            ((n & 0x00FF0000) >>  8) |
  1814.            ((n & 0x0000FF00) <<  8) |
  1815.            ((n & 0x000000FF) << 24);
  1816. #endif
  1817. }
  1818.  
  1819. static DRFLAC_INLINE drflac_uint64 drflac__swap_endian_uint64(drflac_uint64 n)
  1820. {
  1821. #ifdef DRFLAC_HAS_BYTESWAP64_INTRINSIC
  1822.     #if defined(_MSC_VER)
  1823.         return _byteswap_uint64(n);
  1824.     #elif defined(__GNUC__) || defined(__clang__)
  1825.         return __builtin_bswap64(n);
  1826.     #else
  1827.         #error "This compiler does not support the byte swap intrinsic."
  1828.     #endif
  1829. #else
  1830.     return ((n & (drflac_uint64)0xFF00000000000000) >> 56) |
  1831.            ((n & (drflac_uint64)0x00FF000000000000) >> 40) |
  1832.            ((n & (drflac_uint64)0x0000FF0000000000) >> 24) |
  1833.            ((n & (drflac_uint64)0x000000FF00000000) >>  8) |
  1834.            ((n & (drflac_uint64)0x00000000FF000000) <<  8) |
  1835.            ((n & (drflac_uint64)0x0000000000FF0000) << 24) |
  1836.            ((n & (drflac_uint64)0x000000000000FF00) << 40) |
  1837.            ((n & (drflac_uint64)0x00000000000000FF) << 56);
  1838. #endif
  1839. }
  1840.  
  1841.  
  1842. static DRFLAC_INLINE drflac_uint16 drflac__be2host_16(drflac_uint16 n)
  1843. {
  1844.     if (drflac__is_little_endian()) {
  1845.         return drflac__swap_endian_uint16(n);
  1846.     }
  1847.  
  1848.     return n;
  1849. }
  1850.  
  1851. static DRFLAC_INLINE drflac_uint32 drflac__be2host_32(drflac_uint32 n)
  1852. {
  1853.     if (drflac__is_little_endian()) {
  1854.         return drflac__swap_endian_uint32(n);
  1855.     }
  1856.  
  1857.     return n;
  1858. }
  1859.  
  1860. static DRFLAC_INLINE drflac_uint64 drflac__be2host_64(drflac_uint64 n)
  1861. {
  1862.     if (drflac__is_little_endian()) {
  1863.         return drflac__swap_endian_uint64(n);
  1864.     }
  1865.  
  1866.     return n;
  1867. }
  1868.  
  1869.  
  1870. static DRFLAC_INLINE drflac_uint32 drflac__le2host_32(drflac_uint32 n)
  1871. {
  1872.     if (!drflac__is_little_endian()) {
  1873.         return drflac__swap_endian_uint32(n);
  1874.     }
  1875.  
  1876.     return n;
  1877. }
  1878.  
  1879.  
  1880. static DRFLAC_INLINE drflac_uint32 drflac__unsynchsafe_32(drflac_uint32 n)
  1881. {
  1882.     drflac_uint32 result = 0;
  1883.     result |= (n & 0x7F000000) >> 3;
  1884.     result |= (n & 0x007F0000) >> 2;
  1885.     result |= (n & 0x00007F00) >> 1;
  1886.     result |= (n & 0x0000007F) >> 0;
  1887.  
  1888.     return result;
  1889. }
  1890.  
  1891.  
  1892.  
  1893. /* The CRC code below is based on this document: http://zlib.net/crc_v3.txt */
  1894. static drflac_uint8 drflac__crc8_table[] = {
  1895.     0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  1896.     0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  1897.     0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  1898.     0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  1899.     0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  1900.     0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  1901.     0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  1902.     0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  1903.     0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  1904.     0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  1905.     0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  1906.     0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  1907.     0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  1908.     0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  1909.     0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  1910.     0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  1911. };
  1912.  
  1913. static drflac_uint16 drflac__crc16_table[] = {
  1914.     0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
  1915.     0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022,
  1916.     0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072,
  1917.     0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041,
  1918.     0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2,
  1919.     0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1,
  1920.     0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1,
  1921.     0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
  1922.     0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192,
  1923.     0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1,
  1924.     0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1,
  1925.     0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2,
  1926.     0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151,
  1927.     0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162,
  1928.     0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132,
  1929.     0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101,
  1930.     0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312,
  1931.     0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
  1932.     0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371,
  1933.     0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342,
  1934.     0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1,
  1935.     0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
  1936.     0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2,
  1937.     0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381,
  1938.     0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291,
  1939.     0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2,
  1940.     0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2,
  1941.     0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1,
  1942.     0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252,
  1943.     0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261,
  1944.     0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231,
  1945.     0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202
  1946. };
  1947.  
  1948. static DRFLAC_INLINE drflac_uint8 drflac_crc8_byte(drflac_uint8 crc, drflac_uint8 data)
  1949. {
  1950.     return drflac__crc8_table[crc ^ data];
  1951. }
  1952.  
  1953. static DRFLAC_INLINE drflac_uint8 drflac_crc8(drflac_uint8 crc, drflac_uint32 data, drflac_uint32 count)
  1954. {
  1955. #ifdef DR_FLAC_NO_CRC
  1956.     (void)crc;
  1957.     (void)data;
  1958.     (void)count;
  1959.     return 0;
  1960. #else
  1961. #if 0
  1962.     /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc8(crc, 0, 8);") */
  1963.     drflac_uint8 p = 0x07;
  1964.     for (int i = count-1; i >= 0; --i) {
  1965.         drflac_uint8 bit = (data & (1 << i)) >> i;
  1966.         if (crc & 0x80) {
  1967.             crc = ((crc << 1) | bit) ^ p;
  1968.         } else {
  1969.             crc = ((crc << 1) | bit);
  1970.         }
  1971.     }
  1972.     return crc;
  1973. #else
  1974.     drflac_uint32 wholeBytes;
  1975.     drflac_uint32 leftoverBits;
  1976.     drflac_uint64 leftoverDataMask;
  1977.  
  1978.     static drflac_uint64 leftoverDataMaskTable[8] = {
  1979.         0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
  1980.     };
  1981.  
  1982.     DRFLAC_ASSERT(count <= 32);
  1983.  
  1984.     wholeBytes = count >> 3;
  1985.     leftoverBits = count - (wholeBytes*8);
  1986.     leftoverDataMask = leftoverDataMaskTable[leftoverBits];
  1987.  
  1988.     switch (wholeBytes) {
  1989.         case 4: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
  1990.         case 3: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
  1991.         case 2: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
  1992.         case 1: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
  1993.         case 0: if (leftoverBits > 0) crc = (drflac_uint8)((crc << leftoverBits) ^ drflac__crc8_table[(crc >> (8 - leftoverBits)) ^ (data & leftoverDataMask)]);
  1994.     }
  1995.     return crc;
  1996. #endif
  1997. #endif
  1998. }
  1999.  
  2000. static DRFLAC_INLINE drflac_uint16 drflac_crc16_byte(drflac_uint16 crc, drflac_uint8 data)
  2001. {
  2002.     return (crc << 8) ^ drflac__crc16_table[(drflac_uint8)(crc >> 8) ^ data];
  2003. }
  2004.  
  2005. static DRFLAC_INLINE drflac_uint16 drflac_crc16_cache(drflac_uint16 crc, drflac_cache_t data)
  2006. {
  2007. #ifdef DRFLAC_64BIT
  2008.     crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
  2009.     crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
  2010.     crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
  2011.     crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
  2012. #endif
  2013.     crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
  2014.     crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
  2015.     crc = drflac_crc16_byte(crc, (drflac_uint8)((data >>  8) & 0xFF));
  2016.     crc = drflac_crc16_byte(crc, (drflac_uint8)((data >>  0) & 0xFF));
  2017.  
  2018.     return crc;
  2019. }
  2020.  
  2021. static DRFLAC_INLINE drflac_uint16 drflac_crc16_bytes(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 byteCount)
  2022. {
  2023.     switch (byteCount)
  2024.     {
  2025. #ifdef DRFLAC_64BIT
  2026.     case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
  2027.     case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
  2028.     case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
  2029.     case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
  2030. #endif
  2031.     case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
  2032.     case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
  2033.     case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >>  8) & 0xFF));
  2034.     case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >>  0) & 0xFF));
  2035.     }
  2036.  
  2037.     return crc;
  2038. }
  2039.  
  2040. #if 0
  2041. static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac_uint32 data, drflac_uint32 count)
  2042. {
  2043. #ifdef DR_FLAC_NO_CRC
  2044.     (void)crc;
  2045.     (void)data;
  2046.     (void)count;
  2047.     return 0;
  2048. #else
  2049. #if 0
  2050.     /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc16(crc, 0, 16);") */
  2051.     drflac_uint16 p = 0x8005;
  2052.     for (int i = count-1; i >= 0; --i) {
  2053.         drflac_uint16 bit = (data & (1ULL << i)) >> i;
  2054.         if (r & 0x8000) {
  2055.             r = ((r << 1) | bit) ^ p;
  2056.         } else {
  2057.             r = ((r << 1) | bit);
  2058.         }
  2059.     }
  2060.  
  2061.     return crc;
  2062. #else
  2063.     drflac_uint32 wholeBytes;
  2064.     drflac_uint32 leftoverBits;
  2065.     drflac_uint64 leftoverDataMask;
  2066.  
  2067.     static drflac_uint64 leftoverDataMaskTable[8] = {
  2068.         0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
  2069.     };
  2070.  
  2071.     DRFLAC_ASSERT(count <= 64);
  2072.  
  2073.     wholeBytes = count >> 3;
  2074.     leftoverBits = count & 7;
  2075.     leftoverDataMask = leftoverDataMaskTable[leftoverBits];
  2076.  
  2077.     switch (wholeBytes) {
  2078.         default:
  2079.         case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
  2080.         case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
  2081.         case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
  2082.         case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
  2083.         case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
  2084.     }
  2085.     return crc;
  2086. #endif
  2087. #endif
  2088. }
  2089.  
  2090. static DRFLAC_INLINE drflac_uint16 drflac_crc16__64bit(drflac_uint16 crc, drflac_uint64 data, drflac_uint32 count)
  2091. {
  2092. #ifdef DR_FLAC_NO_CRC
  2093.     (void)crc;
  2094.     (void)data;
  2095.     (void)count;
  2096.     return 0;
  2097. #else
  2098.     drflac_uint32 wholeBytes;
  2099.     drflac_uint32 leftoverBits;
  2100.     drflac_uint64 leftoverDataMask;
  2101.  
  2102.     static drflac_uint64 leftoverDataMaskTable[8] = {
  2103.         0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
  2104.     };
  2105.  
  2106.     DRFLAC_ASSERT(count <= 64);
  2107.  
  2108.     wholeBytes = count >> 3;
  2109.     leftoverBits = count & 7;
  2110.     leftoverDataMask = leftoverDataMaskTable[leftoverBits];
  2111.  
  2112.     switch (wholeBytes) {
  2113.         default:
  2114.         case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 << 32) << leftoverBits)) >> (56 + leftoverBits)));    /* Weird "<< 32" bitshift is required for C89 because it doesn't support 64-bit constants. Should be optimized out by a good compiler. */
  2115.         case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 << 32) << leftoverBits)) >> (48 + leftoverBits)));
  2116.         case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 << 32) << leftoverBits)) >> (40 + leftoverBits)));
  2117.         case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF << 32) << leftoverBits)) >> (32 + leftoverBits)));
  2118.         case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000      ) << leftoverBits)) >> (24 + leftoverBits)));
  2119.         case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000      ) << leftoverBits)) >> (16 + leftoverBits)));
  2120.         case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00      ) << leftoverBits)) >> ( 8 + leftoverBits)));
  2121.         case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF      ) << leftoverBits)) >> ( 0 + leftoverBits)));
  2122.         case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
  2123.     }
  2124.     return crc;
  2125. #endif
  2126. }
  2127.  
  2128.  
  2129. static DRFLAC_INLINE drflac_uint16 drflac_crc16(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 count)
  2130. {
  2131. #ifdef DRFLAC_64BIT
  2132.     return drflac_crc16__64bit(crc, data, count);
  2133. #else
  2134.     return drflac_crc16__32bit(crc, data, count);
  2135. #endif
  2136. }
  2137. #endif
  2138.  
  2139.  
  2140. #ifdef DRFLAC_64BIT
  2141. #define drflac__be2host__cache_line drflac__be2host_64
  2142. #else
  2143. #define drflac__be2host__cache_line drflac__be2host_32
  2144. #endif
  2145.  
  2146. /*
  2147. BIT READING ATTEMPT #2
  2148.  
  2149. 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
  2150. on the most significant bit. It uses the notion of an L1 and L2 cache (borrowed from CPU architecture), where the L1 cache
  2151. 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
  2152. 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
  2153. from onRead() is read into.
  2154. */
  2155. #define DRFLAC_CACHE_L1_SIZE_BYTES(bs)                      (sizeof((bs)->cache))
  2156. #define DRFLAC_CACHE_L1_SIZE_BITS(bs)                       (sizeof((bs)->cache)*8)
  2157. #define DRFLAC_CACHE_L1_BITS_REMAINING(bs)                  (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (bs)->consumedBits)
  2158. #define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount)           (~((~(drflac_cache_t)0) >> (_bitCount)))
  2159. #define DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount)      (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount))
  2160. #define DRFLAC_CACHE_L1_SELECT(bs, _bitCount)               (((bs)->cache) & DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount))
  2161. #define DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount)     (DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >>  DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)))
  2162. #define DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, _bitCount)(DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> (DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)) & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1)))
  2163. #define DRFLAC_CACHE_L2_SIZE_BYTES(bs)                      (sizeof((bs)->cacheL2))
  2164. #define DRFLAC_CACHE_L2_LINE_COUNT(bs)                      (DRFLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0]))
  2165. #define DRFLAC_CACHE_L2_LINES_REMAINING(bs)                 (DRFLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line)
  2166.  
  2167.  
  2168. #ifndef DR_FLAC_NO_CRC
  2169. static DRFLAC_INLINE void drflac__reset_crc16(drflac_bs* bs)
  2170. {
  2171.     bs->crc16 = 0;
  2172.     bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
  2173. }
  2174.  
  2175. static DRFLAC_INLINE void drflac__update_crc16(drflac_bs* bs)
  2176. {
  2177.     if (bs->crc16CacheIgnoredBytes == 0) {
  2178.         bs->crc16 = drflac_crc16_cache(bs->crc16, bs->crc16Cache);
  2179.     } else {
  2180.         bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache, DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bs->crc16CacheIgnoredBytes);
  2181.         bs->crc16CacheIgnoredBytes = 0;
  2182.     }
  2183. }
  2184.  
  2185. static DRFLAC_INLINE drflac_uint16 drflac__flush_crc16(drflac_bs* bs)
  2186. {
  2187.     /* We should never be flushing in a situation where we are not aligned on a byte boundary. */
  2188.     DRFLAC_ASSERT((DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7) == 0);
  2189.  
  2190.     /*
  2191.     The bits that were read from the L1 cache need to be accumulated. The number of bytes needing to be accumulated is determined
  2192.     by the number of bits that have been consumed.
  2193.     */
  2194.     if (DRFLAC_CACHE_L1_BITS_REMAINING(bs) == 0) {
  2195.         drflac__update_crc16(bs);
  2196.     } else {
  2197.         /* We only accumulate the consumed bits. */
  2198.         bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache >> DRFLAC_CACHE_L1_BITS_REMAINING(bs), (bs->consumedBits >> 3) - bs->crc16CacheIgnoredBytes);
  2199.  
  2200.         /*
  2201.         The bits that we just accumulated should never be accumulated again. We need to keep track of how many bytes were accumulated
  2202.         so we can handle that later.
  2203.         */
  2204.         bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
  2205.     }
  2206.  
  2207.     return bs->crc16;
  2208. }
  2209. #endif
  2210.  
  2211. static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs)
  2212. {
  2213.     size_t bytesRead;
  2214.     size_t alignedL1LineCount;
  2215.  
  2216.     /* Fast path. Try loading straight from L2. */
  2217.     if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  2218.         bs->cache = bs->cacheL2[bs->nextL2Line++];
  2219.         return DRFLAC_TRUE;
  2220.     }
  2221.  
  2222.     /*
  2223.     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
  2224.     any left.
  2225.     */
  2226.     if (bs->unalignedByteCount > 0) {
  2227.         return DRFLAC_FALSE;   /* If we have any unaligned bytes it means there's no more aligned bytes left in the client. */
  2228.     }
  2229.  
  2230.     bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, DRFLAC_CACHE_L2_SIZE_BYTES(bs));
  2231.  
  2232.     bs->nextL2Line = 0;
  2233.     if (bytesRead == DRFLAC_CACHE_L2_SIZE_BYTES(bs)) {
  2234.         bs->cache = bs->cacheL2[bs->nextL2Line++];
  2235.         return DRFLAC_TRUE;
  2236.     }
  2237.  
  2238.  
  2239.     /*
  2240.     If we get here it means we were unable to retrieve enough data to fill the entire L2 cache. It probably
  2241.     means we've just reached the end of the file. We need to move the valid data down to the end of the buffer
  2242.     and adjust the index of the next line accordingly. Also keep in mind that the L2 cache must be aligned to
  2243.     the size of the L1 so we'll need to seek backwards by any misaligned bytes.
  2244.     */
  2245.     alignedL1LineCount = bytesRead / DRFLAC_CACHE_L1_SIZE_BYTES(bs);
  2246.  
  2247.     /* We need to keep track of any unaligned bytes for later use. */
  2248.     bs->unalignedByteCount = bytesRead - (alignedL1LineCount * DRFLAC_CACHE_L1_SIZE_BYTES(bs));
  2249.     if (bs->unalignedByteCount > 0) {
  2250.         bs->unalignedCache = bs->cacheL2[alignedL1LineCount];
  2251.     }
  2252.  
  2253.     if (alignedL1LineCount > 0) {
  2254.         size_t offset = DRFLAC_CACHE_L2_LINE_COUNT(bs) - alignedL1LineCount;
  2255.         size_t i;
  2256.         for (i = alignedL1LineCount; i > 0; --i) {
  2257.             bs->cacheL2[i-1 + offset] = bs->cacheL2[i-1];
  2258.         }
  2259.  
  2260.         bs->nextL2Line = (drflac_uint32)offset;
  2261.         bs->cache = bs->cacheL2[bs->nextL2Line++];
  2262.         return DRFLAC_TRUE;
  2263.     } else {
  2264.         /* If we get into this branch it means we weren't able to load any L1-aligned data. */
  2265.         bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs);
  2266.         return DRFLAC_FALSE;
  2267.     }
  2268. }
  2269.  
  2270. static drflac_bool32 drflac__reload_cache(drflac_bs* bs)
  2271. {
  2272.     size_t bytesRead;
  2273.  
  2274. #ifndef DR_FLAC_NO_CRC
  2275.     drflac__update_crc16(bs);
  2276. #endif
  2277.  
  2278.     /* Fast path. Try just moving the next value in the L2 cache to the L1 cache. */
  2279.     if (drflac__reload_l1_cache_from_l2(bs)) {
  2280.         bs->cache = drflac__be2host__cache_line(bs->cache);
  2281.         bs->consumedBits = 0;
  2282. #ifndef DR_FLAC_NO_CRC
  2283.         bs->crc16Cache = bs->cache;
  2284. #endif
  2285.         return DRFLAC_TRUE;
  2286.     }
  2287.  
  2288.     /* Slow path. */
  2289.  
  2290.     /*
  2291.     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
  2292.     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
  2293.     data from the unaligned cache.
  2294.     */
  2295.     bytesRead = bs->unalignedByteCount;
  2296.     if (bytesRead == 0) {
  2297.         bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);   /* <-- The stream has been exhausted, so marked the bits as consumed. */
  2298.         return DRFLAC_FALSE;
  2299.     }
  2300.  
  2301.     DRFLAC_ASSERT(bytesRead < DRFLAC_CACHE_L1_SIZE_BYTES(bs));
  2302.     bs->consumedBits = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bytesRead) * 8;
  2303.  
  2304.     bs->cache = drflac__be2host__cache_line(bs->unalignedCache);
  2305.     bs->cache &= DRFLAC_CACHE_L1_SELECTION_MASK(DRFLAC_CACHE_L1_BITS_REMAINING(bs));    /* <-- Make sure the consumed bits are always set to zero. Other parts of the library depend on this property. */
  2306.     bs->unalignedByteCount = 0;     /* <-- At this point the unaligned bytes have been moved into the cache and we thus have no more unaligned bytes. */
  2307.  
  2308. #ifndef DR_FLAC_NO_CRC
  2309.     bs->crc16Cache = bs->cache >> bs->consumedBits;
  2310.     bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
  2311. #endif
  2312.     return DRFLAC_TRUE;
  2313. }
  2314.  
  2315. static void drflac__reset_cache(drflac_bs* bs)
  2316. {
  2317.     bs->nextL2Line   = DRFLAC_CACHE_L2_LINE_COUNT(bs);  /* <-- This clears the L2 cache. */
  2318.     bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);   /* <-- This clears the L1 cache. */
  2319.     bs->cache = 0;
  2320.     bs->unalignedByteCount = 0;                         /* <-- This clears the trailing unaligned bytes. */
  2321.     bs->unalignedCache = 0;
  2322.  
  2323. #ifndef DR_FLAC_NO_CRC
  2324.     bs->crc16Cache = 0;
  2325.     bs->crc16CacheIgnoredBytes = 0;
  2326. #endif
  2327. }
  2328.  
  2329.  
  2330. static DRFLAC_INLINE drflac_bool32 drflac__read_uint32(drflac_bs* bs, unsigned int bitCount, drflac_uint32* pResultOut)
  2331. {
  2332.     DRFLAC_ASSERT(bs != NULL);
  2333.     DRFLAC_ASSERT(pResultOut != NULL);
  2334.     DRFLAC_ASSERT(bitCount > 0);
  2335.     DRFLAC_ASSERT(bitCount <= 32);
  2336.  
  2337.     if (bs->consumedBits == DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
  2338.         if (!drflac__reload_cache(bs)) {
  2339.             return DRFLAC_FALSE;
  2340.         }
  2341.     }
  2342.  
  2343.     if (bitCount <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  2344.         /*
  2345.         If we want to load all 32-bits from a 32-bit cache we need to do it slightly differently because we can't do
  2346.         a 32-bit shift on a 32-bit integer. This will never be the case on 64-bit caches, so we can have a slightly
  2347.         more optimal solution for this.
  2348.         */
  2349. #ifdef DRFLAC_64BIT
  2350.         *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
  2351.         bs->consumedBits += bitCount;
  2352.         bs->cache <<= bitCount;
  2353. #else
  2354.         if (bitCount < DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
  2355.             *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
  2356.             bs->consumedBits += bitCount;
  2357.             bs->cache <<= bitCount;
  2358.         } else {
  2359.             /* Cannot shift by 32-bits, so need to do it differently. */
  2360.             *pResultOut = (drflac_uint32)bs->cache;
  2361.             bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);
  2362.             bs->cache = 0;
  2363.         }
  2364. #endif
  2365.  
  2366.         return DRFLAC_TRUE;
  2367.     } else {
  2368.         /* 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. */
  2369.         drflac_uint32 bitCountHi = DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  2370.         drflac_uint32 bitCountLo = bitCount - bitCountHi;
  2371.         drflac_uint32 resultHi;
  2372.  
  2373.         DRFLAC_ASSERT(bitCountHi > 0);
  2374.         DRFLAC_ASSERT(bitCountHi < 32);
  2375.         resultHi = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountHi);
  2376.  
  2377.         if (!drflac__reload_cache(bs)) {
  2378.             return DRFLAC_FALSE;
  2379.         }
  2380.  
  2381.         *pResultOut = (resultHi << bitCountLo) | (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo);
  2382.         bs->consumedBits += bitCountLo;
  2383.         bs->cache <<= bitCountLo;
  2384.         return DRFLAC_TRUE;
  2385.     }
  2386. }
  2387.  
  2388. static drflac_bool32 drflac__read_int32(drflac_bs* bs, unsigned int bitCount, drflac_int32* pResult)
  2389. {
  2390.     drflac_uint32 result;
  2391.     drflac_uint32 signbit;
  2392.  
  2393.     DRFLAC_ASSERT(bs != NULL);
  2394.     DRFLAC_ASSERT(pResult != NULL);
  2395.     DRFLAC_ASSERT(bitCount > 0);
  2396.     DRFLAC_ASSERT(bitCount <= 32);
  2397.  
  2398.     if (!drflac__read_uint32(bs, bitCount, &result)) {
  2399.         return DRFLAC_FALSE;
  2400.     }
  2401.  
  2402.     signbit = ((result >> (bitCount-1)) & 0x01);
  2403.     result |= (~signbit + 1) << bitCount;
  2404.  
  2405.     *pResult = (drflac_int32)result;
  2406.     return DRFLAC_TRUE;
  2407. }
  2408.  
  2409. #ifdef DRFLAC_64BIT
  2410. static drflac_bool32 drflac__read_uint64(drflac_bs* bs, unsigned int bitCount, drflac_uint64* pResultOut)
  2411. {
  2412.     drflac_uint32 resultHi;
  2413.     drflac_uint32 resultLo;
  2414.  
  2415.     DRFLAC_ASSERT(bitCount <= 64);
  2416.     DRFLAC_ASSERT(bitCount >  32);
  2417.  
  2418.     if (!drflac__read_uint32(bs, bitCount - 32, &resultHi)) {
  2419.         return DRFLAC_FALSE;
  2420.     }
  2421.  
  2422.     if (!drflac__read_uint32(bs, 32, &resultLo)) {
  2423.         return DRFLAC_FALSE;
  2424.     }
  2425.  
  2426.     *pResultOut = (((drflac_uint64)resultHi) << 32) | ((drflac_uint64)resultLo);
  2427.     return DRFLAC_TRUE;
  2428. }
  2429. #endif
  2430.  
  2431. /* Function below is unused, but leaving it here in case I need to quickly add it again. */
  2432. #if 0
  2433. static drflac_bool32 drflac__read_int64(drflac_bs* bs, unsigned int bitCount, drflac_int64* pResultOut)
  2434. {
  2435.     drflac_uint64 result;
  2436.     drflac_uint64 signbit;
  2437.  
  2438.     DRFLAC_ASSERT(bitCount <= 64);
  2439.  
  2440.     if (!drflac__read_uint64(bs, bitCount, &result)) {
  2441.         return DRFLAC_FALSE;
  2442.     }
  2443.  
  2444.     signbit = ((result >> (bitCount-1)) & 0x01);
  2445.     result |= (~signbit + 1) << bitCount;
  2446.  
  2447.     *pResultOut = (drflac_int64)result;
  2448.     return DRFLAC_TRUE;
  2449. }
  2450. #endif
  2451.  
  2452. static drflac_bool32 drflac__read_uint16(drflac_bs* bs, unsigned int bitCount, drflac_uint16* pResult)
  2453. {
  2454.     drflac_uint32 result;
  2455.  
  2456.     DRFLAC_ASSERT(bs != NULL);
  2457.     DRFLAC_ASSERT(pResult != NULL);
  2458.     DRFLAC_ASSERT(bitCount > 0);
  2459.     DRFLAC_ASSERT(bitCount <= 16);
  2460.  
  2461.     if (!drflac__read_uint32(bs, bitCount, &result)) {
  2462.         return DRFLAC_FALSE;
  2463.     }
  2464.  
  2465.     *pResult = (drflac_uint16)result;
  2466.     return DRFLAC_TRUE;
  2467. }
  2468.  
  2469. #if 0
  2470. static drflac_bool32 drflac__read_int16(drflac_bs* bs, unsigned int bitCount, drflac_int16* pResult)
  2471. {
  2472.     drflac_int32 result;
  2473.  
  2474.     DRFLAC_ASSERT(bs != NULL);
  2475.     DRFLAC_ASSERT(pResult != NULL);
  2476.     DRFLAC_ASSERT(bitCount > 0);
  2477.     DRFLAC_ASSERT(bitCount <= 16);
  2478.  
  2479.     if (!drflac__read_int32(bs, bitCount, &result)) {
  2480.         return DRFLAC_FALSE;
  2481.     }
  2482.  
  2483.     *pResult = (drflac_int16)result;
  2484.     return DRFLAC_TRUE;
  2485. }
  2486. #endif
  2487.  
  2488. static drflac_bool32 drflac__read_uint8(drflac_bs* bs, unsigned int bitCount, drflac_uint8* pResult)
  2489. {
  2490.     drflac_uint32 result;
  2491.  
  2492.     DRFLAC_ASSERT(bs != NULL);
  2493.     DRFLAC_ASSERT(pResult != NULL);
  2494.     DRFLAC_ASSERT(bitCount > 0);
  2495.     DRFLAC_ASSERT(bitCount <= 8);
  2496.  
  2497.     if (!drflac__read_uint32(bs, bitCount, &result)) {
  2498.         return DRFLAC_FALSE;
  2499.     }
  2500.  
  2501.     *pResult = (drflac_uint8)result;
  2502.     return DRFLAC_TRUE;
  2503. }
  2504.  
  2505. static drflac_bool32 drflac__read_int8(drflac_bs* bs, unsigned int bitCount, drflac_int8* pResult)
  2506. {
  2507.     drflac_int32 result;
  2508.  
  2509.     DRFLAC_ASSERT(bs != NULL);
  2510.     DRFLAC_ASSERT(pResult != NULL);
  2511.     DRFLAC_ASSERT(bitCount > 0);
  2512.     DRFLAC_ASSERT(bitCount <= 8);
  2513.  
  2514.     if (!drflac__read_int32(bs, bitCount, &result)) {
  2515.         return DRFLAC_FALSE;
  2516.     }
  2517.  
  2518.     *pResult = (drflac_int8)result;
  2519.     return DRFLAC_TRUE;
  2520. }
  2521.  
  2522.  
  2523. static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek)
  2524. {
  2525.     if (bitsToSeek <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  2526.         bs->consumedBits += (drflac_uint32)bitsToSeek;
  2527.         bs->cache <<= bitsToSeek;
  2528.         return DRFLAC_TRUE;
  2529.     } else {
  2530.         /* It straddles the cached data. This function isn't called too frequently so I'm favouring simplicity here. */
  2531.         bitsToSeek       -= DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  2532.         bs->consumedBits += DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  2533.         bs->cache         = 0;
  2534.  
  2535.         /* Simple case. Seek in groups of the same number as bits that fit within a cache line. */
  2536. #ifdef DRFLAC_64BIT
  2537.         while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
  2538.             drflac_uint64 bin;
  2539.             if (!drflac__read_uint64(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
  2540.                 return DRFLAC_FALSE;
  2541.             }
  2542.             bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
  2543.         }
  2544. #else
  2545.         while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
  2546.             drflac_uint32 bin;
  2547.             if (!drflac__read_uint32(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
  2548.                 return DRFLAC_FALSE;
  2549.             }
  2550.             bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
  2551.         }
  2552. #endif
  2553.  
  2554.         /* Whole leftover bytes. */
  2555.         while (bitsToSeek >= 8) {
  2556.             drflac_uint8 bin;
  2557.             if (!drflac__read_uint8(bs, 8, &bin)) {
  2558.                 return DRFLAC_FALSE;
  2559.             }
  2560.             bitsToSeek -= 8;
  2561.         }
  2562.  
  2563.         /* Leftover bits. */
  2564.         if (bitsToSeek > 0) {
  2565.             drflac_uint8 bin;
  2566.             if (!drflac__read_uint8(bs, (drflac_uint32)bitsToSeek, &bin)) {
  2567.                 return DRFLAC_FALSE;
  2568.             }
  2569.             bitsToSeek = 0; /* <-- Necessary for the assert below. */
  2570.         }
  2571.  
  2572.         DRFLAC_ASSERT(bitsToSeek == 0);
  2573.         return DRFLAC_TRUE;
  2574.     }
  2575. }
  2576.  
  2577.  
  2578. /* 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. */
  2579. static drflac_bool32 drflac__find_and_seek_to_next_sync_code(drflac_bs* bs)
  2580. {
  2581.     DRFLAC_ASSERT(bs != NULL);
  2582.  
  2583.     /*
  2584.     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
  2585.     thing to do is align to the next byte.
  2586.     */
  2587.     if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
  2588.         return DRFLAC_FALSE;
  2589.     }
  2590.  
  2591.     for (;;) {
  2592.         drflac_uint8 hi;
  2593.  
  2594. #ifndef DR_FLAC_NO_CRC
  2595.         drflac__reset_crc16(bs);
  2596. #endif
  2597.  
  2598.         if (!drflac__read_uint8(bs, 8, &hi)) {
  2599.             return DRFLAC_FALSE;
  2600.         }
  2601.  
  2602.         if (hi == 0xFF) {
  2603.             drflac_uint8 lo;
  2604.             if (!drflac__read_uint8(bs, 6, &lo)) {
  2605.                 return DRFLAC_FALSE;
  2606.             }
  2607.  
  2608.             if (lo == 0x3E) {
  2609.                 return DRFLAC_TRUE;
  2610.             } else {
  2611.                 if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
  2612.                     return DRFLAC_FALSE;
  2613.                 }
  2614.             }
  2615.         }
  2616.     }
  2617.  
  2618.     /* Should never get here. */
  2619.     /*return DRFLAC_FALSE;*/
  2620. }
  2621.  
  2622.  
  2623. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
  2624. #define DRFLAC_IMPLEMENT_CLZ_LZCNT
  2625. #endif
  2626. #if  defined(_MSC_VER) && _MSC_VER >= 1400 && (defined(DRFLAC_X64) || defined(DRFLAC_X86))
  2627. #define DRFLAC_IMPLEMENT_CLZ_MSVC
  2628. #endif
  2629.  
  2630. static DRFLAC_INLINE drflac_uint32 drflac__clz_software(drflac_cache_t x)
  2631. {
  2632.     drflac_uint32 n;
  2633.     static drflac_uint32 clz_table_4[] = {
  2634.         0,
  2635.         4,
  2636.         3, 3,
  2637.         2, 2, 2, 2,
  2638.         1, 1, 1, 1, 1, 1, 1, 1
  2639.     };
  2640.  
  2641.     if (x == 0) {
  2642.         return sizeof(x)*8;
  2643.     }
  2644.  
  2645.     n = clz_table_4[x >> (sizeof(x)*8 - 4)];
  2646.     if (n == 0) {
  2647. #ifdef DRFLAC_64BIT
  2648.         if ((x & ((drflac_uint64)0xFFFFFFFF << 32)) == 0) { n  = 32; x <<= 32; }
  2649.         if ((x & ((drflac_uint64)0xFFFF0000 << 32)) == 0) { n += 16; x <<= 16; }
  2650.         if ((x & ((drflac_uint64)0xFF000000 << 32)) == 0) { n += 8;  x <<= 8;  }
  2651.         if ((x & ((drflac_uint64)0xF0000000 << 32)) == 0) { n += 4;  x <<= 4;  }
  2652. #else
  2653.         if ((x & 0xFFFF0000) == 0) { n  = 16; x <<= 16; }
  2654.         if ((x & 0xFF000000) == 0) { n += 8;  x <<= 8;  }
  2655.         if ((x & 0xF0000000) == 0) { n += 4;  x <<= 4;  }
  2656. #endif
  2657.         n += clz_table_4[x >> (sizeof(x)*8 - 4)];
  2658.     }
  2659.  
  2660.     return n - 1;
  2661. }
  2662.  
  2663. #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
  2664. static DRFLAC_INLINE drflac_bool32 drflac__is_lzcnt_supported(void)
  2665. {
  2666.     /* Fast compile time check for ARM. */
  2667. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
  2668.     return DRFLAC_TRUE;
  2669. #else
  2670.     /* If the compiler itself does not support the intrinsic then we'll need to return false. */
  2671.     #ifdef DRFLAC_HAS_LZCNT_INTRINSIC
  2672.         return drflac__gIsLZCNTSupported;
  2673.     #else
  2674.         return DRFLAC_FALSE;
  2675.     #endif
  2676. #endif
  2677. }
  2678.  
  2679. static DRFLAC_INLINE drflac_uint32 drflac__clz_lzcnt(drflac_cache_t x)
  2680. {
  2681. #if defined(_MSC_VER) && !defined(__clang__)
  2682.     #ifdef DRFLAC_64BIT
  2683.         return (drflac_uint32)__lzcnt64(x);
  2684.     #else
  2685.         return (drflac_uint32)__lzcnt(x);
  2686.     #endif
  2687. #else
  2688.     #if defined(__GNUC__) || defined(__clang__)
  2689.         #if defined(DRFLAC_X64)
  2690.             {
  2691.                 drflac_uint64 r;
  2692.                 __asm__ __volatile__ (
  2693.                     "lzcnt{ %1, %0| %0, %1}" : "=r"(r) : "r"(x)
  2694.                 );
  2695.  
  2696.                 return (drflac_uint32)r;
  2697.             }
  2698.         #elif defined(DRFLAC_X86)
  2699.             {
  2700.                 drflac_uint32 r;
  2701.                 __asm__ __volatile__ (
  2702.                     "lzcnt{l %1, %0| %0, %1}" : "=r"(r) : "r"(x)
  2703.                 );
  2704.  
  2705.                 return r;
  2706.             }
  2707.         #elif defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) && !defined(DRFLAC_64BIT)   /* <-- I haven't tested 64-bit inline assembly, so only enabling this for the 32-bit build for now. */
  2708.             {
  2709.                 unsigned int r;
  2710.                 __asm__ __volatile__ (
  2711.                 #if defined(DRFLAC_64BIT)
  2712.                     "clz %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(x)   /* <-- This is untested. If someone in the community could test this, that would be appreciated! */
  2713.                 #else
  2714.                     "clz %[out], %[in]" : [out]"=r"(r) : [in]"r"(x)
  2715.                 #endif
  2716.                 );
  2717.  
  2718.                 return r;
  2719.             }
  2720.         #else
  2721.             if (x == 0) {
  2722.                 return sizeof(x)*8;
  2723.             }
  2724.             #ifdef DRFLAC_64BIT
  2725.                 return (drflac_uint32)__builtin_clzll((drflac_uint64)x);
  2726.             #else
  2727.                 return (drflac_uint32)__builtin_clzl((drflac_uint32)x);
  2728.             #endif
  2729.         #endif
  2730.     #else
  2731.         /* Unsupported compiler. */
  2732.         #error "This compiler does not support the lzcnt intrinsic."
  2733.     #endif
  2734. #endif
  2735. }
  2736. #endif
  2737.  
  2738. #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
  2739. #include <intrin.h> /* For BitScanReverse(). */
  2740.  
  2741. static DRFLAC_INLINE drflac_uint32 drflac__clz_msvc(drflac_cache_t x)
  2742. {
  2743.     drflac_uint32 n;
  2744.  
  2745.     if (x == 0) {
  2746.         return sizeof(x)*8;
  2747.     }
  2748.  
  2749. #ifdef DRFLAC_64BIT
  2750.     _BitScanReverse64((unsigned long*)&n, x);
  2751. #else
  2752.     _BitScanReverse((unsigned long*)&n, x);
  2753. #endif
  2754.     return sizeof(x)*8 - n - 1;
  2755. }
  2756. #endif
  2757.  
  2758. static DRFLAC_INLINE drflac_uint32 drflac__clz(drflac_cache_t x)
  2759. {
  2760. #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
  2761.     if (drflac__is_lzcnt_supported()) {
  2762.         return drflac__clz_lzcnt(x);
  2763.     } else
  2764. #endif
  2765.     {
  2766. #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
  2767.         return drflac__clz_msvc(x);
  2768. #else
  2769.         return drflac__clz_software(x);
  2770. #endif
  2771.     }
  2772. }
  2773.  
  2774.  
  2775. static DRFLAC_INLINE drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsigned int* pOffsetOut)
  2776. {
  2777.     drflac_uint32 zeroCounter = 0;
  2778.     drflac_uint32 setBitOffsetPlus1;
  2779.  
  2780.     while (bs->cache == 0) {
  2781.         zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  2782.         if (!drflac__reload_cache(bs)) {
  2783.             return DRFLAC_FALSE;
  2784.         }
  2785.     }
  2786.  
  2787.     setBitOffsetPlus1 = drflac__clz(bs->cache);
  2788.     setBitOffsetPlus1 += 1;
  2789.  
  2790.     bs->consumedBits += setBitOffsetPlus1;
  2791.     bs->cache <<= setBitOffsetPlus1;
  2792.  
  2793.     *pOffsetOut = zeroCounter + setBitOffsetPlus1 - 1;
  2794.     return DRFLAC_TRUE;
  2795. }
  2796.  
  2797.  
  2798.  
  2799. static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFromStart)
  2800. {
  2801.     DRFLAC_ASSERT(bs != NULL);
  2802.     DRFLAC_ASSERT(offsetFromStart > 0);
  2803.  
  2804.     /*
  2805.     Seeking from the start is not quite as trivial as it sounds because the onSeek callback takes a signed 32-bit integer (which
  2806.     is intentional because it simplifies the implementation of the onSeek callbacks), however offsetFromStart is unsigned 64-bit.
  2807.     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.
  2808.     */
  2809.     if (offsetFromStart > 0x7FFFFFFF) {
  2810.         drflac_uint64 bytesRemaining = offsetFromStart;
  2811.         if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start)) {
  2812.             return DRFLAC_FALSE;
  2813.         }
  2814.         bytesRemaining -= 0x7FFFFFFF;
  2815.  
  2816.         while (bytesRemaining > 0x7FFFFFFF) {
  2817.             if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current)) {
  2818.                 return DRFLAC_FALSE;
  2819.             }
  2820.             bytesRemaining -= 0x7FFFFFFF;
  2821.         }
  2822.  
  2823.         if (bytesRemaining > 0) {
  2824.             if (!bs->onSeek(bs->pUserData, (int)bytesRemaining, drflac_seek_origin_current)) {
  2825.                 return DRFLAC_FALSE;
  2826.             }
  2827.         }
  2828.     } else {
  2829.         if (!bs->onSeek(bs->pUserData, (int)offsetFromStart, drflac_seek_origin_start)) {
  2830.             return DRFLAC_FALSE;
  2831.         }
  2832.     }
  2833.  
  2834.     /* The cache should be reset to force a reload of fresh data from the client. */
  2835.     drflac__reset_cache(bs);
  2836.     return DRFLAC_TRUE;
  2837. }
  2838.  
  2839.  
  2840. static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64* pNumberOut, drflac_uint8* pCRCOut)
  2841. {
  2842.     drflac_uint8 crc;
  2843.     drflac_uint64 result;
  2844.     drflac_uint8 utf8[7] = {0};
  2845.     int byteCount;
  2846.     int i;
  2847.  
  2848.     DRFLAC_ASSERT(bs != NULL);
  2849.     DRFLAC_ASSERT(pNumberOut != NULL);
  2850.     DRFLAC_ASSERT(pCRCOut != NULL);
  2851.  
  2852.     crc = *pCRCOut;
  2853.  
  2854.     if (!drflac__read_uint8(bs, 8, utf8)) {
  2855.         *pNumberOut = 0;
  2856.         return DRFLAC_AT_END;
  2857.     }
  2858.     crc = drflac_crc8(crc, utf8[0], 8);
  2859.  
  2860.     if ((utf8[0] & 0x80) == 0) {
  2861.         *pNumberOut = utf8[0];
  2862.         *pCRCOut = crc;
  2863.         return DRFLAC_SUCCESS;
  2864.     }
  2865.  
  2866.     /*byteCount = 1;*/
  2867.     if ((utf8[0] & 0xE0) == 0xC0) {
  2868.         byteCount = 2;
  2869.     } else if ((utf8[0] & 0xF0) == 0xE0) {
  2870.         byteCount = 3;
  2871.     } else if ((utf8[0] & 0xF8) == 0xF0) {
  2872.         byteCount = 4;
  2873.     } else if ((utf8[0] & 0xFC) == 0xF8) {
  2874.         byteCount = 5;
  2875.     } else if ((utf8[0] & 0xFE) == 0xFC) {
  2876.         byteCount = 6;
  2877.     } else if ((utf8[0] & 0xFF) == 0xFE) {
  2878.         byteCount = 7;
  2879.     } else {
  2880.         *pNumberOut = 0;
  2881.         return DRFLAC_CRC_MISMATCH;     /* Bad UTF-8 encoding. */
  2882.     }
  2883.  
  2884.     /* Read extra bytes. */
  2885.     DRFLAC_ASSERT(byteCount > 1);
  2886.  
  2887.     result = (drflac_uint64)(utf8[0] & (0xFF >> (byteCount + 1)));
  2888.     for (i = 1; i < byteCount; ++i) {
  2889.         if (!drflac__read_uint8(bs, 8, utf8 + i)) {
  2890.             *pNumberOut = 0;
  2891.             return DRFLAC_AT_END;
  2892.         }
  2893.         crc = drflac_crc8(crc, utf8[i], 8);
  2894.  
  2895.         result = (result << 6) | (utf8[i] & 0x3F);
  2896.     }
  2897.  
  2898.     *pNumberOut = result;
  2899.     *pCRCOut = crc;
  2900.     return DRFLAC_SUCCESS;
  2901. }
  2902.  
  2903.  
  2904.  
  2905. /*
  2906. The next two functions are responsible for calculating the prediction.
  2907.  
  2908. 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
  2909. 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.
  2910. */
  2911. static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_32(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
  2912. {
  2913.     drflac_int32 prediction = 0;
  2914.  
  2915.     DRFLAC_ASSERT(order <= 32);
  2916.  
  2917.     /* 32-bit version. */
  2918.  
  2919.     /* VC++ optimizes this to a single jmp. I've not yet verified this for other compilers. */
  2920.     switch (order)
  2921.     {
  2922.     case 32: prediction += coefficients[31] * pDecodedSamples[-32];
  2923.     case 31: prediction += coefficients[30] * pDecodedSamples[-31];
  2924.     case 30: prediction += coefficients[29] * pDecodedSamples[-30];
  2925.     case 29: prediction += coefficients[28] * pDecodedSamples[-29];
  2926.     case 28: prediction += coefficients[27] * pDecodedSamples[-28];
  2927.     case 27: prediction += coefficients[26] * pDecodedSamples[-27];
  2928.     case 26: prediction += coefficients[25] * pDecodedSamples[-26];
  2929.     case 25: prediction += coefficients[24] * pDecodedSamples[-25];
  2930.     case 24: prediction += coefficients[23] * pDecodedSamples[-24];
  2931.     case 23: prediction += coefficients[22] * pDecodedSamples[-23];
  2932.     case 22: prediction += coefficients[21] * pDecodedSamples[-22];
  2933.     case 21: prediction += coefficients[20] * pDecodedSamples[-21];
  2934.     case 20: prediction += coefficients[19] * pDecodedSamples[-20];
  2935.     case 19: prediction += coefficients[18] * pDecodedSamples[-19];
  2936.     case 18: prediction += coefficients[17] * pDecodedSamples[-18];
  2937.     case 17: prediction += coefficients[16] * pDecodedSamples[-17];
  2938.     case 16: prediction += coefficients[15] * pDecodedSamples[-16];
  2939.     case 15: prediction += coefficients[14] * pDecodedSamples[-15];
  2940.     case 14: prediction += coefficients[13] * pDecodedSamples[-14];
  2941.     case 13: prediction += coefficients[12] * pDecodedSamples[-13];
  2942.     case 12: prediction += coefficients[11] * pDecodedSamples[-12];
  2943.     case 11: prediction += coefficients[10] * pDecodedSamples[-11];
  2944.     case 10: prediction += coefficients[ 9] * pDecodedSamples[-10];
  2945.     case  9: prediction += coefficients[ 8] * pDecodedSamples[- 9];
  2946.     case  8: prediction += coefficients[ 7] * pDecodedSamples[- 8];
  2947.     case  7: prediction += coefficients[ 6] * pDecodedSamples[- 7];
  2948.     case  6: prediction += coefficients[ 5] * pDecodedSamples[- 6];
  2949.     case  5: prediction += coefficients[ 4] * pDecodedSamples[- 5];
  2950.     case  4: prediction += coefficients[ 3] * pDecodedSamples[- 4];
  2951.     case  3: prediction += coefficients[ 2] * pDecodedSamples[- 3];
  2952.     case  2: prediction += coefficients[ 1] * pDecodedSamples[- 2];
  2953.     case  1: prediction += coefficients[ 0] * pDecodedSamples[- 1];
  2954.     }
  2955.  
  2956.     return (drflac_int32)(prediction >> shift);
  2957. }
  2958.  
  2959. static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
  2960. {
  2961.     drflac_int64 prediction;
  2962.  
  2963.     DRFLAC_ASSERT(order <= 32);
  2964.  
  2965.     /* 64-bit version. */
  2966.  
  2967.     /* This method is faster on the 32-bit build when compiling with VC++. See note below. */
  2968. #ifndef DRFLAC_64BIT
  2969.     if (order == 8)
  2970.     {
  2971.         prediction  = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  2972.         prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  2973.         prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  2974.         prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  2975.         prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  2976.         prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  2977.         prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  2978.         prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
  2979.     }
  2980.     else if (order == 7)
  2981.     {
  2982.         prediction  = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  2983.         prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  2984.         prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  2985.         prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  2986.         prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  2987.         prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  2988.         prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  2989.     }
  2990.     else if (order == 3)
  2991.     {
  2992.         prediction  = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  2993.         prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  2994.         prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  2995.     }
  2996.     else if (order == 6)
  2997.     {
  2998.         prediction  = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  2999.         prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  3000.         prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  3001.         prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  3002.         prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  3003.         prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  3004.     }
  3005.     else if (order == 5)
  3006.     {
  3007.         prediction  = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  3008.         prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  3009.         prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  3010.         prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  3011.         prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  3012.     }
  3013.     else if (order == 4)
  3014.     {
  3015.         prediction  = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  3016.         prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  3017.         prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  3018.         prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  3019.     }
  3020.     else if (order == 12)
  3021.     {
  3022.         prediction  = coefficients[0]  * (drflac_int64)pDecodedSamples[-1];
  3023.         prediction += coefficients[1]  * (drflac_int64)pDecodedSamples[-2];
  3024.         prediction += coefficients[2]  * (drflac_int64)pDecodedSamples[-3];
  3025.         prediction += coefficients[3]  * (drflac_int64)pDecodedSamples[-4];
  3026.         prediction += coefficients[4]  * (drflac_int64)pDecodedSamples[-5];
  3027.         prediction += coefficients[5]  * (drflac_int64)pDecodedSamples[-6];
  3028.         prediction += coefficients[6]  * (drflac_int64)pDecodedSamples[-7];
  3029.         prediction += coefficients[7]  * (drflac_int64)pDecodedSamples[-8];
  3030.         prediction += coefficients[8]  * (drflac_int64)pDecodedSamples[-9];
  3031.         prediction += coefficients[9]  * (drflac_int64)pDecodedSamples[-10];
  3032.         prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
  3033.         prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
  3034.     }
  3035.     else if (order == 2)
  3036.     {
  3037.         prediction  = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  3038.         prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  3039.     }
  3040.     else if (order == 1)
  3041.     {
  3042.         prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  3043.     }
  3044.     else if (order == 10)
  3045.     {
  3046.         prediction  = coefficients[0]  * (drflac_int64)pDecodedSamples[-1];
  3047.         prediction += coefficients[1]  * (drflac_int64)pDecodedSamples[-2];
  3048.         prediction += coefficients[2]  * (drflac_int64)pDecodedSamples[-3];
  3049.         prediction += coefficients[3]  * (drflac_int64)pDecodedSamples[-4];
  3050.         prediction += coefficients[4]  * (drflac_int64)pDecodedSamples[-5];
  3051.         prediction += coefficients[5]  * (drflac_int64)pDecodedSamples[-6];
  3052.         prediction += coefficients[6]  * (drflac_int64)pDecodedSamples[-7];
  3053.         prediction += coefficients[7]  * (drflac_int64)pDecodedSamples[-8];
  3054.         prediction += coefficients[8]  * (drflac_int64)pDecodedSamples[-9];
  3055.         prediction += coefficients[9]  * (drflac_int64)pDecodedSamples[-10];
  3056.     }
  3057.     else if (order == 9)
  3058.     {
  3059.         prediction  = coefficients[0]  * (drflac_int64)pDecodedSamples[-1];
  3060.         prediction += coefficients[1]  * (drflac_int64)pDecodedSamples[-2];
  3061.         prediction += coefficients[2]  * (drflac_int64)pDecodedSamples[-3];
  3062.         prediction += coefficients[3]  * (drflac_int64)pDecodedSamples[-4];
  3063.         prediction += coefficients[4]  * (drflac_int64)pDecodedSamples[-5];
  3064.         prediction += coefficients[5]  * (drflac_int64)pDecodedSamples[-6];
  3065.         prediction += coefficients[6]  * (drflac_int64)pDecodedSamples[-7];
  3066.         prediction += coefficients[7]  * (drflac_int64)pDecodedSamples[-8];
  3067.         prediction += coefficients[8]  * (drflac_int64)pDecodedSamples[-9];
  3068.     }
  3069.     else if (order == 11)
  3070.     {
  3071.         prediction  = coefficients[0]  * (drflac_int64)pDecodedSamples[-1];
  3072.         prediction += coefficients[1]  * (drflac_int64)pDecodedSamples[-2];
  3073.         prediction += coefficients[2]  * (drflac_int64)pDecodedSamples[-3];
  3074.         prediction += coefficients[3]  * (drflac_int64)pDecodedSamples[-4];
  3075.         prediction += coefficients[4]  * (drflac_int64)pDecodedSamples[-5];
  3076.         prediction += coefficients[5]  * (drflac_int64)pDecodedSamples[-6];
  3077.         prediction += coefficients[6]  * (drflac_int64)pDecodedSamples[-7];
  3078.         prediction += coefficients[7]  * (drflac_int64)pDecodedSamples[-8];
  3079.         prediction += coefficients[8]  * (drflac_int64)pDecodedSamples[-9];
  3080.         prediction += coefficients[9]  * (drflac_int64)pDecodedSamples[-10];
  3081.         prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
  3082.     }
  3083.     else
  3084.     {
  3085.         int j;
  3086.  
  3087.         prediction = 0;
  3088.         for (j = 0; j < (int)order; ++j) {
  3089.             prediction += coefficients[j] * (drflac_int64)pDecodedSamples[-j-1];
  3090.         }
  3091.     }
  3092. #endif
  3093.  
  3094.     /*
  3095.     VC++ optimizes this to a single jmp instruction, but only the 64-bit build. The 32-bit build generates less efficient code for some
  3096.     reason. The ugly version above is faster so we'll just switch between the two depending on the target platform.
  3097.     */
  3098. #ifdef DRFLAC_64BIT
  3099.     prediction = 0;
  3100.     switch (order)
  3101.     {
  3102.     case 32: prediction += coefficients[31] * (drflac_int64)pDecodedSamples[-32];
  3103.     case 31: prediction += coefficients[30] * (drflac_int64)pDecodedSamples[-31];
  3104.     case 30: prediction += coefficients[29] * (drflac_int64)pDecodedSamples[-30];
  3105.     case 29: prediction += coefficients[28] * (drflac_int64)pDecodedSamples[-29];
  3106.     case 28: prediction += coefficients[27] * (drflac_int64)pDecodedSamples[-28];
  3107.     case 27: prediction += coefficients[26] * (drflac_int64)pDecodedSamples[-27];
  3108.     case 26: prediction += coefficients[25] * (drflac_int64)pDecodedSamples[-26];
  3109.     case 25: prediction += coefficients[24] * (drflac_int64)pDecodedSamples[-25];
  3110.     case 24: prediction += coefficients[23] * (drflac_int64)pDecodedSamples[-24];
  3111.     case 23: prediction += coefficients[22] * (drflac_int64)pDecodedSamples[-23];
  3112.     case 22: prediction += coefficients[21] * (drflac_int64)pDecodedSamples[-22];
  3113.     case 21: prediction += coefficients[20] * (drflac_int64)pDecodedSamples[-21];
  3114.     case 20: prediction += coefficients[19] * (drflac_int64)pDecodedSamples[-20];
  3115.     case 19: prediction += coefficients[18] * (drflac_int64)pDecodedSamples[-19];
  3116.     case 18: prediction += coefficients[17] * (drflac_int64)pDecodedSamples[-18];
  3117.     case 17: prediction += coefficients[16] * (drflac_int64)pDecodedSamples[-17];
  3118.     case 16: prediction += coefficients[15] * (drflac_int64)pDecodedSamples[-16];
  3119.     case 15: prediction += coefficients[14] * (drflac_int64)pDecodedSamples[-15];
  3120.     case 14: prediction += coefficients[13] * (drflac_int64)pDecodedSamples[-14];
  3121.     case 13: prediction += coefficients[12] * (drflac_int64)pDecodedSamples[-13];
  3122.     case 12: prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
  3123.     case 11: prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
  3124.     case 10: prediction += coefficients[ 9] * (drflac_int64)pDecodedSamples[-10];
  3125.     case  9: prediction += coefficients[ 8] * (drflac_int64)pDecodedSamples[- 9];
  3126.     case  8: prediction += coefficients[ 7] * (drflac_int64)pDecodedSamples[- 8];
  3127.     case  7: prediction += coefficients[ 6] * (drflac_int64)pDecodedSamples[- 7];
  3128.     case  6: prediction += coefficients[ 5] * (drflac_int64)pDecodedSamples[- 6];
  3129.     case  5: prediction += coefficients[ 4] * (drflac_int64)pDecodedSamples[- 5];
  3130.     case  4: prediction += coefficients[ 3] * (drflac_int64)pDecodedSamples[- 4];
  3131.     case  3: prediction += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 3];
  3132.     case  2: prediction += coefficients[ 1] * (drflac_int64)pDecodedSamples[- 2];
  3133.     case  1: prediction += coefficients[ 0] * (drflac_int64)pDecodedSamples[- 1];
  3134.     }
  3135. #endif
  3136.  
  3137.     return (drflac_int32)(prediction >> shift);
  3138. }
  3139.  
  3140.  
  3141. #if 0
  3142. /*
  3143. Reference implementation for reading and decoding samples with residual. This is intentionally left unoptimized for the
  3144. sake of readability and should only be used as a reference.
  3145. */
  3146. 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)
  3147. {
  3148.     drflac_uint32 i;
  3149.  
  3150.     DRFLAC_ASSERT(bs != NULL);
  3151.     DRFLAC_ASSERT(count > 0);
  3152.     DRFLAC_ASSERT(pSamplesOut != NULL);
  3153.  
  3154.     for (i = 0; i < count; ++i) {
  3155.         drflac_uint32 zeroCounter = 0;
  3156.         for (;;) {
  3157.             drflac_uint8 bit;
  3158.             if (!drflac__read_uint8(bs, 1, &bit)) {
  3159.                 return DRFLAC_FALSE;
  3160.             }
  3161.  
  3162.             if (bit == 0) {
  3163.                 zeroCounter += 1;
  3164.             } else {
  3165.                 break;
  3166.             }
  3167.         }
  3168.  
  3169.         drflac_uint32 decodedRice;
  3170.         if (riceParam > 0) {
  3171.             if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
  3172.                 return DRFLAC_FALSE;
  3173.             }
  3174.         } else {
  3175.             decodedRice = 0;
  3176.         }
  3177.  
  3178.         decodedRice |= (zeroCounter << riceParam);
  3179.         if ((decodedRice & 0x01)) {
  3180.             decodedRice = ~(decodedRice >> 1);
  3181.         } else {
  3182.             decodedRice =  (decodedRice >> 1);
  3183.         }
  3184.  
  3185.  
  3186.         if (bitsPerSample+shift >= 32) {
  3187.             pSamplesOut[i] = decodedRice + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + i);
  3188.         } else {
  3189.             pSamplesOut[i] = decodedRice + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + i);
  3190.         }
  3191.     }
  3192.  
  3193.     return DRFLAC_TRUE;
  3194. }
  3195. #endif
  3196.  
  3197. #if 0
  3198. static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
  3199. {
  3200.     drflac_uint32 zeroCounter = 0;
  3201.     drflac_uint32 decodedRice;
  3202.  
  3203.     for (;;) {
  3204.         drflac_uint8 bit;
  3205.         if (!drflac__read_uint8(bs, 1, &bit)) {
  3206.             return DRFLAC_FALSE;
  3207.         }
  3208.  
  3209.         if (bit == 0) {
  3210.             zeroCounter += 1;
  3211.         } else {
  3212.             break;
  3213.         }
  3214.     }
  3215.  
  3216.     if (riceParam > 0) {
  3217.         if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
  3218.             return DRFLAC_FALSE;
  3219.         }
  3220.     } else {
  3221.         decodedRice = 0;
  3222.     }
  3223.  
  3224.     *pZeroCounterOut = zeroCounter;
  3225.     *pRiceParamPartOut = decodedRice;
  3226.     return DRFLAC_TRUE;
  3227. }
  3228. #endif
  3229.  
  3230. #if 0
  3231. static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
  3232. {
  3233.     drflac_cache_t riceParamMask;
  3234.     drflac_uint32 zeroCounter;
  3235.     drflac_uint32 setBitOffsetPlus1;
  3236.     drflac_uint32 riceParamPart;
  3237.     drflac_uint32 riceLength;
  3238.  
  3239.     DRFLAC_ASSERT(riceParam > 0);   /* <-- riceParam should never be 0. drflac__read_rice_parts__param_equals_zero() should be used instead for this case. */
  3240.  
  3241.     riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParam);
  3242.  
  3243.     zeroCounter = 0;
  3244.     while (bs->cache == 0) {
  3245.         zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  3246.         if (!drflac__reload_cache(bs)) {
  3247.             return DRFLAC_FALSE;
  3248.         }
  3249.     }
  3250.  
  3251.     setBitOffsetPlus1 = drflac__clz(bs->cache);
  3252.     zeroCounter += setBitOffsetPlus1;
  3253.     setBitOffsetPlus1 += 1;
  3254.  
  3255.     riceLength = setBitOffsetPlus1 + riceParam;
  3256.     if (riceLength < DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  3257.         riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength));
  3258.  
  3259.         bs->consumedBits += riceLength;
  3260.         bs->cache <<= riceLength;
  3261.     } else {
  3262.         drflac_uint32 bitCountLo;
  3263.         drflac_cache_t resultHi;
  3264.  
  3265.         bs->consumedBits += riceLength;
  3266.         bs->cache <<= setBitOffsetPlus1 & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1);    /* <-- Equivalent to "if (setBitOffsetPlus1 < DRFLAC_CACHE_L1_SIZE_BITS(bs)) { bs->cache <<= setBitOffsetPlus1; }" */
  3267.  
  3268.         /* 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. */
  3269.         bitCountLo = bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs);
  3270.         resultHi = DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, riceParam);  /* <-- Use DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE() if ever this function allows riceParam=0. */
  3271.  
  3272.         if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  3273. #ifndef DR_FLAC_NO_CRC
  3274.             drflac__update_crc16(bs);
  3275. #endif
  3276.             bs->cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  3277.             bs->consumedBits = 0;
  3278. #ifndef DR_FLAC_NO_CRC
  3279.             bs->crc16Cache = bs->cache;
  3280. #endif
  3281.         } else {
  3282.             /* Slow path. We need to fetch more data from the client. */
  3283.             if (!drflac__reload_cache(bs)) {
  3284.                 return DRFLAC_FALSE;
  3285.             }
  3286.         }
  3287.  
  3288.         riceParamPart = (drflac_uint32)(resultHi | DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo));
  3289.  
  3290.         bs->consumedBits += bitCountLo;
  3291.         bs->cache <<= bitCountLo;
  3292.     }
  3293.  
  3294.     pZeroCounterOut[0] = zeroCounter;
  3295.     pRiceParamPartOut[0] = riceParamPart;
  3296.  
  3297.     return DRFLAC_TRUE;
  3298. }
  3299. #endif
  3300.  
  3301. static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts_x1(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
  3302. {
  3303.     drflac_uint32  riceParamPlus1 = riceParam + 1;
  3304.     /*drflac_cache_t riceParamPlus1Mask  = DRFLAC_CACHE_L1_SELECTION_MASK(riceParamPlus1);*/
  3305.     drflac_uint32  riceParamPlus1Shift = DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPlus1);
  3306.     drflac_uint32  riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
  3307.  
  3308.     /*
  3309.     The idea here is to use local variables for the cache in an attempt to encourage the compiler to store them in registers. I have
  3310.     no idea how this will work in practice...
  3311.     */
  3312.     drflac_cache_t bs_cache = bs->cache;
  3313.     drflac_uint32  bs_consumedBits = bs->consumedBits;
  3314.  
  3315.     /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */
  3316.     drflac_uint32  lzcount = drflac__clz(bs_cache);
  3317.     if (lzcount < sizeof(bs_cache)*8) {
  3318.         pZeroCounterOut[0] = lzcount;
  3319.  
  3320.         /*
  3321.         It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting
  3322.         this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled
  3323.         outside of this function at a higher level.
  3324.         */
  3325.     extract_rice_param_part:
  3326.         bs_cache       <<= lzcount;
  3327.         bs_consumedBits += lzcount;
  3328.  
  3329.         if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
  3330.             /* Getting here means the rice parameter part is wholly contained within the current cache line. */
  3331.             pRiceParamPartOut[0] = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
  3332.             bs_cache       <<= riceParamPlus1;
  3333.             bs_consumedBits += riceParamPlus1;
  3334.         } else {
  3335.             drflac_uint32 riceParamPartHi;
  3336.             drflac_uint32 riceParamPartLo;
  3337.             drflac_uint32 riceParamPartLoBitCount;
  3338.  
  3339.             /*
  3340.             Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache
  3341.             line, reload the cache, and then combine it with the head of the next cache line.
  3342.             */
  3343.  
  3344.             /* Grab the high part of the rice parameter part. */
  3345.             riceParamPartHi = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
  3346.  
  3347.             /* Before reloading the cache we need to grab the size in bits of the low part. */
  3348.             riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
  3349.             DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
  3350.  
  3351.             /* Now reload the cache. */
  3352.             if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  3353.             #ifndef DR_FLAC_NO_CRC
  3354.                 drflac__update_crc16(bs);
  3355.             #endif
  3356.                 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  3357.                 bs_consumedBits = riceParamPartLoBitCount;
  3358.             #ifndef DR_FLAC_NO_CRC
  3359.                 bs->crc16Cache = bs_cache;
  3360.             #endif
  3361.             } else {
  3362.                 /* Slow path. We need to fetch more data from the client. */
  3363.                 if (!drflac__reload_cache(bs)) {
  3364.                     return DRFLAC_FALSE;
  3365.                 }
  3366.  
  3367.                 bs_cache = bs->cache;
  3368.                 bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
  3369.             }
  3370.  
  3371.             /* We should now have enough information to construct the rice parameter part. */
  3372.             riceParamPartLo = (drflac_uint32)(bs_cache >> (DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPartLoBitCount)));
  3373.             pRiceParamPartOut[0] = riceParamPartHi | riceParamPartLo;
  3374.  
  3375.             bs_cache <<= riceParamPartLoBitCount;
  3376.         }
  3377.     } else {
  3378.         /*
  3379.         Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call
  3380.         to drflac__clz() and we need to reload the cache.
  3381.         */
  3382.         drflac_uint32 zeroCounter = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BITS(bs) - bs_consumedBits);
  3383.         for (;;) {
  3384.             if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  3385.             #ifndef DR_FLAC_NO_CRC
  3386.                 drflac__update_crc16(bs);
  3387.             #endif
  3388.                 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  3389.                 bs_consumedBits = 0;
  3390.             #ifndef DR_FLAC_NO_CRC
  3391.                 bs->crc16Cache = bs_cache;
  3392.             #endif
  3393.             } else {
  3394.                 /* Slow path. We need to fetch more data from the client. */
  3395.                 if (!drflac__reload_cache(bs)) {
  3396.                     return DRFLAC_FALSE;
  3397.                 }
  3398.  
  3399.                 bs_cache = bs->cache;
  3400.                 bs_consumedBits = bs->consumedBits;
  3401.             }
  3402.  
  3403.             lzcount = drflac__clz(bs_cache);
  3404.             zeroCounter += lzcount;
  3405.  
  3406.             if (lzcount < sizeof(bs_cache)*8) {
  3407.                 break;
  3408.             }
  3409.         }
  3410.  
  3411.         pZeroCounterOut[0] = zeroCounter;
  3412.         goto extract_rice_param_part;
  3413.     }
  3414.  
  3415.     /* Make sure the cache is restored at the end of it all. */
  3416.     bs->cache = bs_cache;
  3417.     bs->consumedBits = bs_consumedBits;
  3418.  
  3419.     return DRFLAC_TRUE;
  3420. }
  3421.  
  3422. static DRFLAC_INLINE drflac_bool32 drflac__seek_rice_parts(drflac_bs* bs, drflac_uint8 riceParam)
  3423. {
  3424.     drflac_uint32  riceParamPlus1 = riceParam + 1;
  3425.     drflac_uint32  riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
  3426.  
  3427.     /*
  3428.     The idea here is to use local variables for the cache in an attempt to encourage the compiler to store them in registers. I have
  3429.     no idea how this will work in practice...
  3430.     */
  3431.     drflac_cache_t bs_cache = bs->cache;
  3432.     drflac_uint32  bs_consumedBits = bs->consumedBits;
  3433.  
  3434.     /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */
  3435.     drflac_uint32  lzcount = drflac__clz(bs_cache);
  3436.     if (lzcount < sizeof(bs_cache)*8) {
  3437.         /*
  3438.         It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting
  3439.         this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled
  3440.         outside of this function at a higher level.
  3441.         */
  3442.     extract_rice_param_part:
  3443.         bs_cache       <<= lzcount;
  3444.         bs_consumedBits += lzcount;
  3445.  
  3446.         if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
  3447.             /* Getting here means the rice parameter part is wholly contained within the current cache line. */
  3448.             bs_cache       <<= riceParamPlus1;
  3449.             bs_consumedBits += riceParamPlus1;
  3450.         } else {
  3451.             /*
  3452.             Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache
  3453.             line, reload the cache, and then combine it with the head of the next cache line.
  3454.             */
  3455.  
  3456.             /* Before reloading the cache we need to grab the size in bits of the low part. */
  3457.             drflac_uint32 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
  3458.             DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
  3459.  
  3460.             /* Now reload the cache. */
  3461.             if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  3462.             #ifndef DR_FLAC_NO_CRC
  3463.                 drflac__update_crc16(bs);
  3464.             #endif
  3465.                 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  3466.                 bs_consumedBits = riceParamPartLoBitCount;
  3467.             #ifndef DR_FLAC_NO_CRC
  3468.                 bs->crc16Cache = bs_cache;
  3469.             #endif
  3470.             } else {
  3471.                 /* Slow path. We need to fetch more data from the client. */
  3472.                 if (!drflac__reload_cache(bs)) {
  3473.                     return DRFLAC_FALSE;
  3474.                 }
  3475.  
  3476.                 bs_cache = bs->cache;
  3477.                 bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
  3478.             }
  3479.  
  3480.             bs_cache <<= riceParamPartLoBitCount;
  3481.         }
  3482.     } else {
  3483.         /*
  3484.         Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call
  3485.         to drflac__clz() and we need to reload the cache.
  3486.         */
  3487.         for (;;) {
  3488.             if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  3489.             #ifndef DR_FLAC_NO_CRC
  3490.                 drflac__update_crc16(bs);
  3491.             #endif
  3492.                 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  3493.                 bs_consumedBits = 0;
  3494.             #ifndef DR_FLAC_NO_CRC
  3495.                 bs->crc16Cache = bs_cache;
  3496.             #endif
  3497.             } else {
  3498.                 /* Slow path. We need to fetch more data from the client. */
  3499.                 if (!drflac__reload_cache(bs)) {
  3500.                     return DRFLAC_FALSE;
  3501.                 }
  3502.  
  3503.                 bs_cache = bs->cache;
  3504.                 bs_consumedBits = bs->consumedBits;
  3505.             }
  3506.  
  3507.             lzcount = drflac__clz(bs_cache);
  3508.             if (lzcount < sizeof(bs_cache)*8) {
  3509.                 break;
  3510.             }
  3511.         }
  3512.  
  3513.         goto extract_rice_param_part;
  3514.     }
  3515.  
  3516.     /* Make sure the cache is restored at the end of it all. */
  3517.     bs->cache = bs_cache;
  3518.     bs->consumedBits = bs_consumedBits;
  3519.  
  3520.     return DRFLAC_TRUE;
  3521. }
  3522.  
  3523.  
  3524. static drflac_bool32 drflac__decode_samples_with_residual__rice__scalar_zeroorder(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)
  3525. {
  3526.     drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  3527.     drflac_uint32 zeroCountPart0;
  3528.     drflac_uint32 riceParamPart0;
  3529.     drflac_uint32 riceParamMask;
  3530.     drflac_uint32 i;
  3531.  
  3532.     DRFLAC_ASSERT(bs != NULL);
  3533.     DRFLAC_ASSERT(count > 0);
  3534.     DRFLAC_ASSERT(pSamplesOut != NULL);
  3535.  
  3536.     (void)bitsPerSample;
  3537.     (void)order;
  3538.     (void)shift;
  3539.     (void)coefficients;
  3540.  
  3541.     riceParamMask  = (drflac_uint32)~((~0UL) << riceParam);
  3542.  
  3543.     i = 0;
  3544.     while (i < count) {
  3545.         /* Rice extraction. */
  3546.         if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
  3547.             return DRFLAC_FALSE;
  3548.         }
  3549.  
  3550.         /* Rice reconstruction. */
  3551.         riceParamPart0 &= riceParamMask;
  3552.         riceParamPart0 |= (zeroCountPart0 << riceParam);
  3553.         riceParamPart0  = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  3554.  
  3555.         pSamplesOut[i] = riceParamPart0;
  3556.  
  3557.         i += 1;
  3558.     }
  3559.  
  3560.     return DRFLAC_TRUE;
  3561. }
  3562.  
  3563. static drflac_bool32 drflac__decode_samples_with_residual__rice__scalar(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)
  3564. {
  3565.     drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  3566.     drflac_uint32 zeroCountPart0 = 0;
  3567.     drflac_uint32 zeroCountPart1 = 0;
  3568.     drflac_uint32 zeroCountPart2 = 0;
  3569.     drflac_uint32 zeroCountPart3 = 0;
  3570.     drflac_uint32 riceParamPart0 = 0;
  3571.     drflac_uint32 riceParamPart1 = 0;
  3572.     drflac_uint32 riceParamPart2 = 0;
  3573.     drflac_uint32 riceParamPart3 = 0;
  3574.     drflac_uint32 riceParamMask;
  3575.     const drflac_int32* pSamplesOutEnd;
  3576.     drflac_uint32 i;
  3577.  
  3578.     DRFLAC_ASSERT(bs != NULL);
  3579.     DRFLAC_ASSERT(count > 0);
  3580.     DRFLAC_ASSERT(pSamplesOut != NULL);
  3581.  
  3582.     if (order == 0) {
  3583.         return drflac__decode_samples_with_residual__rice__scalar_zeroorder(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut);
  3584.     }
  3585.  
  3586.     riceParamMask  = (drflac_uint32)~((~0UL) << riceParam);
  3587.     pSamplesOutEnd = pSamplesOut + (count & ~3);
  3588.  
  3589.     if (bitsPerSample+shift > 32) {
  3590.         while (pSamplesOut < pSamplesOutEnd) {
  3591.             /*
  3592.             Rice extraction. It's faster to do this one at a time against local variables than it is to use the x4 version
  3593.             against an array. Not sure why, but perhaps it's making more efficient use of registers?
  3594.             */
  3595.             if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
  3596.                 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
  3597.                 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
  3598.                 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
  3599.                 return DRFLAC_FALSE;
  3600.             }
  3601.  
  3602.             riceParamPart0 &= riceParamMask;
  3603.             riceParamPart1 &= riceParamMask;
  3604.             riceParamPart2 &= riceParamMask;
  3605.             riceParamPart3 &= riceParamMask;
  3606.  
  3607.             riceParamPart0 |= (zeroCountPart0 << riceParam);
  3608.             riceParamPart1 |= (zeroCountPart1 << riceParam);
  3609.             riceParamPart2 |= (zeroCountPart2 << riceParam);
  3610.             riceParamPart3 |= (zeroCountPart3 << riceParam);
  3611.  
  3612.             riceParamPart0  = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  3613.             riceParamPart1  = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
  3614.             riceParamPart2  = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
  3615.             riceParamPart3  = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
  3616.  
  3617.             pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 0);
  3618.             pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 1);
  3619.             pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 2);
  3620.             pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 3);
  3621.  
  3622.             pSamplesOut += 4;
  3623.         }
  3624.     } else {
  3625.         while (pSamplesOut < pSamplesOutEnd) {
  3626.             if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
  3627.                 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
  3628.                 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
  3629.                 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
  3630.                 return DRFLAC_FALSE;
  3631.             }
  3632.  
  3633.             riceParamPart0 &= riceParamMask;
  3634.             riceParamPart1 &= riceParamMask;
  3635.             riceParamPart2 &= riceParamMask;
  3636.             riceParamPart3 &= riceParamMask;
  3637.  
  3638.             riceParamPart0 |= (zeroCountPart0 << riceParam);
  3639.             riceParamPart1 |= (zeroCountPart1 << riceParam);
  3640.             riceParamPart2 |= (zeroCountPart2 << riceParam);
  3641.             riceParamPart3 |= (zeroCountPart3 << riceParam);
  3642.  
  3643.             riceParamPart0  = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  3644.             riceParamPart1  = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
  3645.             riceParamPart2  = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
  3646.             riceParamPart3  = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
  3647.  
  3648.             pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 0);
  3649.             pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 1);
  3650.             pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 2);
  3651.             pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 3);
  3652.  
  3653.             pSamplesOut += 4;
  3654.         }
  3655.     }
  3656.  
  3657.     i = (count & ~3);
  3658.     while (i < count) {
  3659.         /* Rice extraction. */
  3660.         if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
  3661.             return DRFLAC_FALSE;
  3662.         }
  3663.  
  3664.         /* Rice reconstruction. */
  3665.         riceParamPart0 &= riceParamMask;
  3666.         riceParamPart0 |= (zeroCountPart0 << riceParam);
  3667.         riceParamPart0  = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  3668.         /*riceParamPart0  = (riceParamPart0 >> 1) ^ (~(riceParamPart0 & 0x01) + 1);*/
  3669.  
  3670.         /* Sample reconstruction. */
  3671.         if (bitsPerSample+shift > 32) {
  3672.             pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + 0);
  3673.         } else {
  3674.             pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + 0);
  3675.         }
  3676.  
  3677.         i += 1;
  3678.         pSamplesOut += 1;
  3679.     }
  3680.  
  3681.     return DRFLAC_TRUE;
  3682. }
  3683.  
  3684. #if defined(DRFLAC_SUPPORT_SSE2)
  3685. static DRFLAC_INLINE __m128i drflac__mm_packs_interleaved_epi32(__m128i a, __m128i b)
  3686. {
  3687.     __m128i r;
  3688.  
  3689.     /* Pack. */
  3690.     r = _mm_packs_epi32(a, b);
  3691.  
  3692.     /* a3a2 a1a0 b3b2 b1b0 -> a3a2 b3b2 a1a0 b1b0 */
  3693.     r = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 1, 2, 0));
  3694.  
  3695.     /* a3a2 b3b2 a1a0 b1b0 -> a3b3 a2b2 a1b1 a0b0 */
  3696.     r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
  3697.     r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
  3698.  
  3699.     return r;
  3700. }
  3701. #endif
  3702.  
  3703. #if defined(DRFLAC_SUPPORT_SSE41)
  3704. static DRFLAC_INLINE __m128i drflac__mm_not_si128(__m128i a)
  3705. {
  3706.     return _mm_xor_si128(a, _mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128()));
  3707. }
  3708.  
  3709. static DRFLAC_INLINE __m128i drflac__mm_hadd_epi32(__m128i x)
  3710. {
  3711.     __m128i x64 = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
  3712.     __m128i x32 = _mm_shufflelo_epi16(x64, _MM_SHUFFLE(1, 0, 3, 2));
  3713.     return _mm_add_epi32(x64, x32);
  3714. }
  3715.  
  3716. static DRFLAC_INLINE __m128i drflac__mm_hadd_epi64(__m128i x)
  3717. {
  3718.     return _mm_add_epi64(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
  3719. }
  3720.  
  3721. static DRFLAC_INLINE __m128i drflac__mm_srai_epi64(__m128i x, int count)
  3722. {
  3723.     /*
  3724.     To simplify this we are assuming count < 32. This restriction allows us to work on a low side and a high side. The low side
  3725.     is shifted with zero bits, whereas the right side is shifted with sign bits.
  3726.     */
  3727.     __m128i lo = _mm_srli_epi64(x, count);
  3728.     __m128i hi = _mm_srai_epi32(x, count);
  3729.  
  3730.     hi = _mm_and_si128(hi, _mm_set_epi32(0xFFFFFFFF, 0, 0xFFFFFFFF, 0));    /* The high part needs to have the low part cleared. */
  3731.  
  3732.     return _mm_or_si128(lo, hi);
  3733. }
  3734.  
  3735. static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41_32(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  3736. {
  3737.     int i;
  3738.     drflac_uint32 riceParamMask;
  3739.     drflac_int32* pDecodedSamples    = pSamplesOut;
  3740.     drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  3741.     drflac_uint32 zeroCountParts0 = 0;
  3742.     drflac_uint32 zeroCountParts1 = 0;
  3743.     drflac_uint32 zeroCountParts2 = 0;
  3744.     drflac_uint32 zeroCountParts3 = 0;
  3745.     drflac_uint32 riceParamParts0 = 0;
  3746.     drflac_uint32 riceParamParts1 = 0;
  3747.     drflac_uint32 riceParamParts2 = 0;
  3748.     drflac_uint32 riceParamParts3 = 0;
  3749.     __m128i coefficients128_0;
  3750.     __m128i coefficients128_4;
  3751.     __m128i coefficients128_8;
  3752.     __m128i samples128_0;
  3753.     __m128i samples128_4;
  3754.     __m128i samples128_8;
  3755.     __m128i riceParamMask128;
  3756.  
  3757.     const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  3758.  
  3759.     riceParamMask    = (drflac_uint32)~((~0UL) << riceParam);
  3760.     riceParamMask128 = _mm_set1_epi32(riceParamMask);
  3761.  
  3762.     /* Pre-load. */
  3763.     coefficients128_0 = _mm_setzero_si128();
  3764.     coefficients128_4 = _mm_setzero_si128();
  3765.     coefficients128_8 = _mm_setzero_si128();
  3766.  
  3767.     samples128_0 = _mm_setzero_si128();
  3768.     samples128_4 = _mm_setzero_si128();
  3769.     samples128_8 = _mm_setzero_si128();
  3770.  
  3771.     /*
  3772.     Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
  3773.     what's available in the input buffers. It would be convenient to use a fall-through switch to do this, but this results
  3774.     in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
  3775.     so I think there's opportunity for this to be simplified.
  3776.     */
  3777. #if 1
  3778.     {
  3779.         int runningOrder = order;
  3780.  
  3781.         /* 0 - 3. */
  3782.         if (runningOrder >= 4) {
  3783.             coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
  3784.             samples128_0      = _mm_loadu_si128((const __m128i*)(pSamplesOut  - 4));
  3785.             runningOrder -= 4;
  3786.         } else {
  3787.             switch (runningOrder) {
  3788.                 case 3: coefficients128_0 = _mm_set_epi32(0, coefficients[2], coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], pSamplesOut[-3], 0); break;
  3789.                 case 2: coefficients128_0 = _mm_set_epi32(0, 0,               coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], 0,               0); break;
  3790.                 case 1: coefficients128_0 = _mm_set_epi32(0, 0,               0,               coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0,               0,               0); break;
  3791.             }
  3792.             runningOrder = 0;
  3793.         }
  3794.  
  3795.         /* 4 - 7 */
  3796.         if (runningOrder >= 4) {
  3797.             coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
  3798.             samples128_4      = _mm_loadu_si128((const __m128i*)(pSamplesOut  - 8));
  3799.             runningOrder -= 4;
  3800.         } else {
  3801.             switch (runningOrder) {
  3802.                 case 3: coefficients128_4 = _mm_set_epi32(0, coefficients[6], coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], pSamplesOut[-7], 0); break;
  3803.                 case 2: coefficients128_4 = _mm_set_epi32(0, 0,               coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], 0,               0); break;
  3804.                 case 1: coefficients128_4 = _mm_set_epi32(0, 0,               0,               coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0,               0,               0); break;
  3805.             }
  3806.             runningOrder = 0;
  3807.         }
  3808.  
  3809.         /* 8 - 11 */
  3810.         if (runningOrder == 4) {
  3811.             coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
  3812.             samples128_8      = _mm_loadu_si128((const __m128i*)(pSamplesOut  - 12));
  3813.             runningOrder -= 4;
  3814.         } else {
  3815.             switch (runningOrder) {
  3816.                 case 3: coefficients128_8 = _mm_set_epi32(0, coefficients[10], coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], pSamplesOut[-11], 0); break;
  3817.                 case 2: coefficients128_8 = _mm_set_epi32(0, 0,                coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], 0,                0); break;
  3818.                 case 1: coefficients128_8 = _mm_set_epi32(0, 0,                0,               coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0,                0,                0); break;
  3819.             }
  3820.             runningOrder = 0;
  3821.         }
  3822.  
  3823.         /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
  3824.         coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
  3825.         coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
  3826.         coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
  3827.     }
  3828. #else
  3829.     /* This causes strict-aliasing warnings with GCC. */
  3830.     switch (order)
  3831.     {
  3832.     case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
  3833.     case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
  3834.     case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
  3835.     case 9:  ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
  3836.     case 8:  ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
  3837.     case 7:  ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
  3838.     case 6:  ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
  3839.     case 5:  ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
  3840.     case 4:  ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
  3841.     case 3:  ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
  3842.     case 2:  ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
  3843.     case 1:  ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
  3844.     }
  3845. #endif
  3846.  
  3847.     /* For this version we are doing one sample at a time. */
  3848.     while (pDecodedSamples < pDecodedSamplesEnd) {
  3849.         __m128i prediction128;
  3850.         __m128i zeroCountPart128;
  3851.         __m128i riceParamPart128;
  3852.  
  3853.         if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
  3854.             !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
  3855.             !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
  3856.             !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
  3857.             return DRFLAC_FALSE;
  3858.         }
  3859.  
  3860.         zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
  3861.         riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
  3862.  
  3863.         riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
  3864.         riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
  3865.         riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_add_epi32(drflac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(0x01))), _mm_set1_epi32(0x01)));  /* <-- SSE2 compatible */
  3866.         /*riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_mullo_epi32(_mm_and_si128(riceParamPart128, _mm_set1_epi32(0x01)), _mm_set1_epi32(0xFFFFFFFF)));*/   /* <-- Only supported from SSE4.1 and is slower in my testing... */
  3867.  
  3868.         if (order <= 4) {
  3869.             for (i = 0; i < 4; i += 1) {
  3870.                 prediction128 = _mm_mullo_epi32(coefficients128_0, samples128_0);
  3871.  
  3872.                 /* Horizontal add and shift. */
  3873.                 prediction128 = drflac__mm_hadd_epi32(prediction128);
  3874.                 prediction128 = _mm_srai_epi32(prediction128, shift);
  3875.                 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  3876.  
  3877.                 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  3878.                 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  3879.             }
  3880.         } else if (order <= 8) {
  3881.             for (i = 0; i < 4; i += 1) {
  3882.                 prediction128 =                              _mm_mullo_epi32(coefficients128_4, samples128_4);
  3883.                 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
  3884.  
  3885.                 /* Horizontal add and shift. */
  3886.                 prediction128 = drflac__mm_hadd_epi32(prediction128);
  3887.                 prediction128 = _mm_srai_epi32(prediction128, shift);
  3888.                 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  3889.  
  3890.                 samples128_4 = _mm_alignr_epi8(samples128_0,  samples128_4, 4);
  3891.                 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  3892.                 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  3893.             }
  3894.         } else {
  3895.             for (i = 0; i < 4; i += 1) {
  3896.                 prediction128 =                              _mm_mullo_epi32(coefficients128_8, samples128_8);
  3897.                 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_4, samples128_4));
  3898.                 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
  3899.  
  3900.                 /* Horizontal add and shift. */
  3901.                 prediction128 = drflac__mm_hadd_epi32(prediction128);
  3902.                 prediction128 = _mm_srai_epi32(prediction128, shift);
  3903.                 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  3904.  
  3905.                 samples128_8 = _mm_alignr_epi8(samples128_4,  samples128_8, 4);
  3906.                 samples128_4 = _mm_alignr_epi8(samples128_0,  samples128_4, 4);
  3907.                 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  3908.                 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  3909.             }
  3910.         }
  3911.  
  3912.         /* We store samples in groups of 4. */
  3913.         _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
  3914.         pDecodedSamples += 4;
  3915.     }
  3916.  
  3917.     /* Make sure we process the last few samples. */
  3918.     i = (count & ~3);
  3919.     while (i < (int)count) {
  3920.         /* Rice extraction. */
  3921.         if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
  3922.             return DRFLAC_FALSE;
  3923.         }
  3924.  
  3925.         /* Rice reconstruction. */
  3926.         riceParamParts0 &= riceParamMask;
  3927.         riceParamParts0 |= (zeroCountParts0 << riceParam);
  3928.         riceParamParts0  = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
  3929.  
  3930.         /* Sample reconstruction. */
  3931.         pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
  3932.  
  3933.         i += 1;
  3934.         pDecodedSamples += 1;
  3935.     }
  3936.  
  3937.     return DRFLAC_TRUE;
  3938. }
  3939.  
  3940. static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41_64(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  3941. {
  3942.     int i;
  3943.     drflac_uint32 riceParamMask;
  3944.     drflac_int32* pDecodedSamples    = pSamplesOut;
  3945.     drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  3946.     drflac_uint32 zeroCountParts0 = 0;
  3947.     drflac_uint32 zeroCountParts1 = 0;
  3948.     drflac_uint32 zeroCountParts2 = 0;
  3949.     drflac_uint32 zeroCountParts3 = 0;
  3950.     drflac_uint32 riceParamParts0 = 0;
  3951.     drflac_uint32 riceParamParts1 = 0;
  3952.     drflac_uint32 riceParamParts2 = 0;
  3953.     drflac_uint32 riceParamParts3 = 0;
  3954.     __m128i coefficients128_0;
  3955.     __m128i coefficients128_4;
  3956.     __m128i coefficients128_8;
  3957.     __m128i samples128_0;
  3958.     __m128i samples128_4;
  3959.     __m128i samples128_8;
  3960.     __m128i prediction128;
  3961.     __m128i riceParamMask128;
  3962.  
  3963.     const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  3964.  
  3965.     DRFLAC_ASSERT(order <= 12);
  3966.  
  3967.     riceParamMask    = (drflac_uint32)~((~0UL) << riceParam);
  3968.     riceParamMask128 = _mm_set1_epi32(riceParamMask);
  3969.  
  3970.     prediction128 = _mm_setzero_si128();
  3971.  
  3972.     /* Pre-load. */
  3973.     coefficients128_0  = _mm_setzero_si128();
  3974.     coefficients128_4  = _mm_setzero_si128();
  3975.     coefficients128_8  = _mm_setzero_si128();
  3976.  
  3977.     samples128_0  = _mm_setzero_si128();
  3978.     samples128_4  = _mm_setzero_si128();
  3979.     samples128_8  = _mm_setzero_si128();
  3980.  
  3981. #if 1
  3982.     {
  3983.         int runningOrder = order;
  3984.  
  3985.         /* 0 - 3. */
  3986.         if (runningOrder >= 4) {
  3987.             coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
  3988.             samples128_0      = _mm_loadu_si128((const __m128i*)(pSamplesOut  - 4));
  3989.             runningOrder -= 4;
  3990.         } else {
  3991.             switch (runningOrder) {
  3992.                 case 3: coefficients128_0 = _mm_set_epi32(0, coefficients[2], coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], pSamplesOut[-3], 0); break;
  3993.                 case 2: coefficients128_0 = _mm_set_epi32(0, 0,               coefficients[1], coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], pSamplesOut[-2], 0,               0); break;
  3994.                 case 1: coefficients128_0 = _mm_set_epi32(0, 0,               0,               coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0,               0,               0); break;
  3995.             }
  3996.             runningOrder = 0;
  3997.         }
  3998.  
  3999.         /* 4 - 7 */
  4000.         if (runningOrder >= 4) {
  4001.             coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
  4002.             samples128_4      = _mm_loadu_si128((const __m128i*)(pSamplesOut  - 8));
  4003.             runningOrder -= 4;
  4004.         } else {
  4005.             switch (runningOrder) {
  4006.                 case 3: coefficients128_4 = _mm_set_epi32(0, coefficients[6], coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], pSamplesOut[-7], 0); break;
  4007.                 case 2: coefficients128_4 = _mm_set_epi32(0, 0,               coefficients[5], coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], pSamplesOut[-6], 0,               0); break;
  4008.                 case 1: coefficients128_4 = _mm_set_epi32(0, 0,               0,               coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0,               0,               0); break;
  4009.             }
  4010.             runningOrder = 0;
  4011.         }
  4012.  
  4013.         /* 8 - 11 */
  4014.         if (runningOrder == 4) {
  4015.             coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
  4016.             samples128_8      = _mm_loadu_si128((const __m128i*)(pSamplesOut  - 12));
  4017.             runningOrder -= 4;
  4018.         } else {
  4019.             switch (runningOrder) {
  4020.                 case 3: coefficients128_8 = _mm_set_epi32(0, coefficients[10], coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], pSamplesOut[-11], 0); break;
  4021.                 case 2: coefficients128_8 = _mm_set_epi32(0, 0,                coefficients[9], coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], pSamplesOut[-10], 0,                0); break;
  4022.                 case 1: coefficients128_8 = _mm_set_epi32(0, 0,                0,               coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0,                0,                0); break;
  4023.             }
  4024.             runningOrder = 0;
  4025.         }
  4026.  
  4027.         /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
  4028.         coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
  4029.         coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
  4030.         coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
  4031.     }
  4032. #else
  4033.     switch (order)
  4034.     {
  4035.     case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
  4036.     case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
  4037.     case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
  4038.     case 9:  ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
  4039.     case 8:  ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
  4040.     case 7:  ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
  4041.     case 6:  ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
  4042.     case 5:  ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
  4043.     case 4:  ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
  4044.     case 3:  ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
  4045.     case 2:  ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
  4046.     case 1:  ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
  4047.     }
  4048. #endif
  4049.  
  4050.     /* For this version we are doing one sample at a time. */
  4051.     while (pDecodedSamples < pDecodedSamplesEnd) {
  4052.         __m128i zeroCountPart128;
  4053.         __m128i riceParamPart128;
  4054.  
  4055.         if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
  4056.             !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
  4057.             !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
  4058.             !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
  4059.             return DRFLAC_FALSE;
  4060.         }
  4061.  
  4062.         zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
  4063.         riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
  4064.  
  4065.         riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
  4066.         riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
  4067.         riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_add_epi32(drflac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(1))), _mm_set1_epi32(1)));
  4068.  
  4069.         for (i = 0; i < 4; i += 1) {
  4070.             prediction128 = _mm_xor_si128(prediction128, prediction128);    /* Reset to 0. */
  4071.  
  4072.             switch (order)
  4073.             {
  4074.             case 12:
  4075.             case 11: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(1, 1, 0, 0)), _mm_shuffle_epi32(samples128_8, _MM_SHUFFLE(1, 1, 0, 0))));
  4076.             case 10:
  4077.             case  9: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_epi32(samples128_8, _MM_SHUFFLE(3, 3, 2, 2))));
  4078.             case  8:
  4079.             case  7: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(1, 1, 0, 0)), _mm_shuffle_epi32(samples128_4, _MM_SHUFFLE(1, 1, 0, 0))));
  4080.             case  6:
  4081.             case  5: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_epi32(samples128_4, _MM_SHUFFLE(3, 3, 2, 2))));
  4082.             case  4:
  4083.             case  3: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(1, 1, 0, 0)), _mm_shuffle_epi32(samples128_0, _MM_SHUFFLE(1, 1, 0, 0))));
  4084.             case  2:
  4085.             case  1: prediction128 = _mm_add_epi64(prediction128, _mm_mul_epi32(_mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(3, 3, 2, 2)), _mm_shuffle_epi32(samples128_0, _MM_SHUFFLE(3, 3, 2, 2))));
  4086.             }
  4087.  
  4088.             /* Horizontal add and shift. */
  4089.             prediction128 = drflac__mm_hadd_epi64(prediction128);
  4090.             prediction128 = drflac__mm_srai_epi64(prediction128, shift);
  4091.             prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  4092.  
  4093.             /* Our value should be sitting in prediction128[0]. We need to combine this with our SSE samples. */
  4094.             samples128_8 = _mm_alignr_epi8(samples128_4,  samples128_8, 4);
  4095.             samples128_4 = _mm_alignr_epi8(samples128_0,  samples128_4, 4);
  4096.             samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  4097.  
  4098.             /* Slide our rice parameter down so that the value in position 0 contains the next one to process. */
  4099.             riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  4100.         }
  4101.  
  4102.         /* We store samples in groups of 4. */
  4103.         _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
  4104.         pDecodedSamples += 4;
  4105.     }
  4106.  
  4107.     /* Make sure we process the last few samples. */
  4108.     i = (count & ~3);
  4109.     while (i < (int)count) {
  4110.         /* Rice extraction. */
  4111.         if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
  4112.             return DRFLAC_FALSE;
  4113.         }
  4114.  
  4115.         /* Rice reconstruction. */
  4116.         riceParamParts0 &= riceParamMask;
  4117.         riceParamParts0 |= (zeroCountParts0 << riceParam);
  4118.         riceParamParts0  = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
  4119.  
  4120.         /* Sample reconstruction. */
  4121.         pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
  4122.  
  4123.         i += 1;
  4124.         pDecodedSamples += 1;
  4125.     }
  4126.  
  4127.     return DRFLAC_TRUE;
  4128. }
  4129.  
  4130. static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41(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)
  4131. {
  4132.     DRFLAC_ASSERT(bs != NULL);
  4133.     DRFLAC_ASSERT(count > 0);
  4134.     DRFLAC_ASSERT(pSamplesOut != NULL);
  4135.  
  4136.     /* In my testing the order is rarely > 12, so in this case I'm going to simplify the SSE implementation by only handling order <= 12. */
  4137.     if (order > 0 && order <= 12) {
  4138.         if (bitsPerSample+shift > 32) {
  4139.             return drflac__decode_samples_with_residual__rice__sse41_64(bs, count, riceParam, order, shift, coefficients, pSamplesOut);
  4140.         } else {
  4141.             return drflac__decode_samples_with_residual__rice__sse41_32(bs, count, riceParam, order, shift, coefficients, pSamplesOut);
  4142.         }
  4143.     } else {
  4144.         return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut);
  4145.     }
  4146. }
  4147. #endif
  4148.  
  4149. #if defined(DRFLAC_SUPPORT_NEON)
  4150. static DRFLAC_INLINE void drflac__vst2q_s32(drflac_int32* p, int32x4x2_t x)
  4151. {
  4152.     vst1q_s32(p+0, x.val[0]);
  4153.     vst1q_s32(p+4, x.val[1]);
  4154. }
  4155.  
  4156. static DRFLAC_INLINE void drflac__vst2q_u32(drflac_uint32* p, uint32x4x2_t x)
  4157. {
  4158.     vst1q_u32(p+0, x.val[0]);
  4159.     vst1q_u32(p+4, x.val[1]);
  4160. }
  4161.  
  4162. static DRFLAC_INLINE void drflac__vst2q_f32(float* p, float32x4x2_t x)
  4163. {
  4164.     vst1q_f32(p+0, x.val[0]);
  4165.     vst1q_f32(p+4, x.val[1]);
  4166. }
  4167.  
  4168. static DRFLAC_INLINE void drflac__vst2q_s16(drflac_int16* p, int16x4x2_t x)
  4169. {
  4170.     vst1q_s16(p, vcombine_s16(x.val[0], x.val[1]));
  4171. }
  4172.  
  4173. static DRFLAC_INLINE void drflac__vst2q_u16(drflac_uint16* p, uint16x4x2_t x)
  4174. {
  4175.     vst1q_u16(p, vcombine_u16(x.val[0], x.val[1]));
  4176. }
  4177.  
  4178. static DRFLAC_INLINE int32x4_t drflac__vdupq_n_s32x4(drflac_int32 x3, drflac_int32 x2, drflac_int32 x1, drflac_int32 x0)
  4179. {
  4180.     drflac_int32 x[4];
  4181.     x[3] = x3;
  4182.     x[2] = x2;
  4183.     x[1] = x1;
  4184.     x[0] = x0;
  4185.     return vld1q_s32(x);
  4186. }
  4187.  
  4188. static DRFLAC_INLINE int32x4_t drflac__valignrq_s32_1(int32x4_t a, int32x4_t b)
  4189. {
  4190.     /* Equivalent to SSE's _mm_alignr_epi8(a, b, 4) */
  4191.  
  4192.     /* Reference */
  4193.     /*return drflac__vdupq_n_s32x4(
  4194.         vgetq_lane_s32(a, 0),
  4195.         vgetq_lane_s32(b, 3),
  4196.         vgetq_lane_s32(b, 2),
  4197.         vgetq_lane_s32(b, 1)
  4198.     );*/
  4199.  
  4200.     return vextq_s32(b, a, 1);
  4201. }
  4202.  
  4203. static DRFLAC_INLINE uint32x4_t drflac__valignrq_u32_1(uint32x4_t a, uint32x4_t b)
  4204. {
  4205.     /* Equivalent to SSE's _mm_alignr_epi8(a, b, 4) */
  4206.  
  4207.     /* Reference */
  4208.     /*return drflac__vdupq_n_s32x4(
  4209.         vgetq_lane_s32(a, 0),
  4210.         vgetq_lane_s32(b, 3),
  4211.         vgetq_lane_s32(b, 2),
  4212.         vgetq_lane_s32(b, 1)
  4213.     );*/
  4214.  
  4215.     return vextq_u32(b, a, 1);
  4216. }
  4217.  
  4218. static DRFLAC_INLINE int32x2_t drflac__vhaddq_s32(int32x4_t x)
  4219. {
  4220.     /* The sum must end up in position 0. */
  4221.  
  4222.     /* Reference */
  4223.     /*return vdupq_n_s32(
  4224.         vgetq_lane_s32(x, 3) +
  4225.         vgetq_lane_s32(x, 2) +
  4226.         vgetq_lane_s32(x, 1) +
  4227.         vgetq_lane_s32(x, 0)
  4228.     );*/
  4229.  
  4230.     int32x2_t r = vadd_s32(vget_high_s32(x), vget_low_s32(x));
  4231.     return vpadd_s32(r, r);
  4232. }
  4233.  
  4234. static DRFLAC_INLINE int64x1_t drflac__vhaddq_s64(int64x2_t x)
  4235. {
  4236.     return vadd_s64(vget_high_s64(x), vget_low_s64(x));
  4237. }
  4238.  
  4239. static DRFLAC_INLINE int32x4_t drflac__vrevq_s32(int32x4_t x)
  4240. {
  4241.     /* Reference */
  4242.     /*return drflac__vdupq_n_s32x4(
  4243.         vgetq_lane_s32(x, 0),
  4244.         vgetq_lane_s32(x, 1),
  4245.         vgetq_lane_s32(x, 2),
  4246.         vgetq_lane_s32(x, 3)
  4247.     );*/
  4248.  
  4249.     return vrev64q_s32(vcombine_s32(vget_high_s32(x), vget_low_s32(x)));
  4250. }
  4251.  
  4252. static DRFLAC_INLINE int32x4_t drflac__vnotq_s32(int32x4_t x)
  4253. {
  4254.     return veorq_s32(x, vdupq_n_s32(0xFFFFFFFF));
  4255. }
  4256.  
  4257. static DRFLAC_INLINE uint32x4_t drflac__vnotq_u32(uint32x4_t x)
  4258. {
  4259.     return veorq_u32(x, vdupq_n_u32(0xFFFFFFFF));
  4260. }
  4261.  
  4262. static drflac_bool32 drflac__decode_samples_with_residual__rice__neon_32(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  4263. {
  4264.     int i;
  4265.     drflac_uint32 riceParamMask;
  4266.     drflac_int32* pDecodedSamples    = pSamplesOut;
  4267.     drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  4268.     drflac_uint32 zeroCountParts[4];
  4269.     drflac_uint32 riceParamParts[4];
  4270.     int32x4_t coefficients128_0;
  4271.     int32x4_t coefficients128_4;
  4272.     int32x4_t coefficients128_8;
  4273.     int32x4_t samples128_0;
  4274.     int32x4_t samples128_4;
  4275.     int32x4_t samples128_8;
  4276.     uint32x4_t riceParamMask128;
  4277.     int32x4_t riceParam128;
  4278.     int32x2_t shift64;
  4279.     uint32x4_t one128;
  4280.  
  4281.     const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  4282.  
  4283.     riceParamMask    = ~((~0UL) << riceParam);
  4284.     riceParamMask128 = vdupq_n_u32(riceParamMask);
  4285.  
  4286.     riceParam128 = vdupq_n_s32(riceParam);
  4287.     shift64 = vdup_n_s32(-shift); /* Negate the shift because we'll be doing a variable shift using vshlq_s32(). */
  4288.     one128 = vdupq_n_u32(1);
  4289.  
  4290.     /*
  4291.     Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
  4292.     what's available in the input buffers. It would be conenient to use a fall-through switch to do this, but this results
  4293.     in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
  4294.     so I think there's opportunity for this to be simplified.
  4295.     */
  4296.     {
  4297.         int runningOrder = order;
  4298.         drflac_int32 tempC[4] = {0, 0, 0, 0};
  4299.         drflac_int32 tempS[4] = {0, 0, 0, 0};
  4300.  
  4301.         /* 0 - 3. */
  4302.         if (runningOrder >= 4) {
  4303.             coefficients128_0 = vld1q_s32(coefficients + 0);
  4304.             samples128_0      = vld1q_s32(pSamplesOut  - 4);
  4305.             runningOrder -= 4;
  4306.         } else {
  4307.             switch (runningOrder) {
  4308.                 case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3]; /* fallthrough */
  4309.                 case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2]; /* fallthrough */
  4310.                 case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1]; /* fallthrough */
  4311.             }
  4312.  
  4313.             coefficients128_0 = vld1q_s32(tempC);
  4314.             samples128_0      = vld1q_s32(tempS);
  4315.             runningOrder = 0;
  4316.         }
  4317.  
  4318.         /* 4 - 7 */
  4319.         if (runningOrder >= 4) {
  4320.             coefficients128_4 = vld1q_s32(coefficients + 4);
  4321.             samples128_4      = vld1q_s32(pSamplesOut  - 8);
  4322.             runningOrder -= 4;
  4323.         } else {
  4324.             switch (runningOrder) {
  4325.                 case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7]; /* fallthrough */
  4326.                 case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6]; /* fallthrough */
  4327.                 case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5]; /* fallthrough */
  4328.             }
  4329.  
  4330.             coefficients128_4 = vld1q_s32(tempC);
  4331.             samples128_4      = vld1q_s32(tempS);
  4332.             runningOrder = 0;
  4333.         }
  4334.  
  4335.         /* 8 - 11 */
  4336.         if (runningOrder == 4) {
  4337.             coefficients128_8 = vld1q_s32(coefficients + 8);
  4338.             samples128_8      = vld1q_s32(pSamplesOut  - 12);
  4339.             runningOrder -= 4;
  4340.         } else {
  4341.             switch (runningOrder) {
  4342.                 case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11]; /* fallthrough */
  4343.                 case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10]; /* fallthrough */
  4344.                 case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9]; /* fallthrough */
  4345.             }
  4346.  
  4347.             coefficients128_8 = vld1q_s32(tempC);
  4348.             samples128_8      = vld1q_s32(tempS);
  4349.             runningOrder = 0;
  4350.         }
  4351.  
  4352.         /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
  4353.         coefficients128_0 = drflac__vrevq_s32(coefficients128_0);
  4354.         coefficients128_4 = drflac__vrevq_s32(coefficients128_4);
  4355.         coefficients128_8 = drflac__vrevq_s32(coefficients128_8);
  4356.     }
  4357.  
  4358.     /* For this version we are doing one sample at a time. */
  4359.     while (pDecodedSamples < pDecodedSamplesEnd) {
  4360.         int32x4_t prediction128;
  4361.         int32x2_t prediction64;
  4362.         uint32x4_t zeroCountPart128;
  4363.         uint32x4_t riceParamPart128;
  4364.  
  4365.         if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
  4366.             !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
  4367.             !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
  4368.             !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
  4369.             return DRFLAC_FALSE;
  4370.         }
  4371.  
  4372.         zeroCountPart128 = vld1q_u32(zeroCountParts);
  4373.         riceParamPart128 = vld1q_u32(riceParamParts);
  4374.  
  4375.         riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
  4376.         riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
  4377.         riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
  4378.  
  4379.         if (order <= 4) {
  4380.             for (i = 0; i < 4; i += 1) {
  4381.                 prediction128 = vmulq_s32(coefficients128_0, samples128_0);
  4382.  
  4383.                 /* Horizontal add and shift. */
  4384.                 prediction64 = drflac__vhaddq_s32(prediction128);
  4385.                 prediction64 = vshl_s32(prediction64, shift64);
  4386.                 prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
  4387.  
  4388.                 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
  4389.                 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  4390.             }
  4391.         } else if (order <= 8) {
  4392.             for (i = 0; i < 4; i += 1) {
  4393.                 prediction128 =                vmulq_s32(coefficients128_4, samples128_4);
  4394.                 prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
  4395.  
  4396.                 /* Horizontal add and shift. */
  4397.                 prediction64 = drflac__vhaddq_s32(prediction128);
  4398.                 prediction64 = vshl_s32(prediction64, shift64);
  4399.                 prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
  4400.  
  4401.                 samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
  4402.                 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
  4403.                 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  4404.             }
  4405.         } else {
  4406.             for (i = 0; i < 4; i += 1) {
  4407.                 prediction128 =                vmulq_s32(coefficients128_8, samples128_8);
  4408.                 prediction128 = vmlaq_s32(prediction128, coefficients128_4, samples128_4);
  4409.                 prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
  4410.  
  4411.                 /* Horizontal add and shift. */
  4412.                 prediction64 = drflac__vhaddq_s32(prediction128);
  4413.                 prediction64 = vshl_s32(prediction64, shift64);
  4414.                 prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
  4415.  
  4416.                 samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8);
  4417.                 samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
  4418.                 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
  4419.                 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  4420.             }
  4421.         }
  4422.  
  4423.         /* We store samples in groups of 4. */
  4424.         vst1q_s32(pDecodedSamples, samples128_0);
  4425.         pDecodedSamples += 4;
  4426.     }
  4427.  
  4428.     /* Make sure we process the last few samples. */
  4429.     i = (count & ~3);
  4430.     while (i < (int)count) {
  4431.         /* Rice extraction. */
  4432.         if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
  4433.             return DRFLAC_FALSE;
  4434.         }
  4435.  
  4436.         /* Rice reconstruction. */
  4437.         riceParamParts[0] &= riceParamMask;
  4438.         riceParamParts[0] |= (zeroCountParts[0] << riceParam);
  4439.         riceParamParts[0]  = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
  4440.  
  4441.         /* Sample reconstruction. */
  4442.         pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
  4443.  
  4444.         i += 1;
  4445.         pDecodedSamples += 1;
  4446.     }
  4447.  
  4448.     return DRFLAC_TRUE;
  4449. }
  4450.  
  4451. static drflac_bool32 drflac__decode_samples_with_residual__rice__neon_64(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  4452. {
  4453.     int i;
  4454.     drflac_uint32 riceParamMask;
  4455.     drflac_int32* pDecodedSamples    = pSamplesOut;
  4456.     drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  4457.     drflac_uint32 zeroCountParts[4];
  4458.     drflac_uint32 riceParamParts[4];
  4459.     int32x4_t coefficients128_0;
  4460.     int32x4_t coefficients128_4;
  4461.     int32x4_t coefficients128_8;
  4462.     int32x4_t samples128_0;
  4463.     int32x4_t samples128_4;
  4464.     int32x4_t samples128_8;
  4465.     uint32x4_t riceParamMask128;
  4466.     int32x4_t riceParam128;
  4467.     int64x1_t shift64;
  4468.     uint32x4_t one128;
  4469.  
  4470.     const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  4471.  
  4472.     riceParamMask    = ~((~0UL) << riceParam);
  4473.     riceParamMask128 = vdupq_n_u32(riceParamMask);
  4474.  
  4475.     riceParam128 = vdupq_n_s32(riceParam);
  4476.     shift64 = vdup_n_s64(-shift); /* Negate the shift because we'll be doing a variable shift using vshlq_s32(). */
  4477.     one128 = vdupq_n_u32(1);
  4478.  
  4479.     /*
  4480.     Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
  4481.     what's available in the input buffers. It would be conenient to use a fall-through switch to do this, but this results
  4482.     in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
  4483.     so I think there's opportunity for this to be simplified.
  4484.     */
  4485.     {
  4486.         int runningOrder = order;
  4487.         drflac_int32 tempC[4] = {0, 0, 0, 0};
  4488.         drflac_int32 tempS[4] = {0, 0, 0, 0};
  4489.  
  4490.         /* 0 - 3. */
  4491.         if (runningOrder >= 4) {
  4492.             coefficients128_0 = vld1q_s32(coefficients + 0);
  4493.             samples128_0      = vld1q_s32(pSamplesOut  - 4);
  4494.             runningOrder -= 4;
  4495.         } else {
  4496.             switch (runningOrder) {
  4497.                 case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3]; /* fallthrough */
  4498.                 case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2]; /* fallthrough */
  4499.                 case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1]; /* fallthrough */
  4500.             }
  4501.  
  4502.             coefficients128_0 = vld1q_s32(tempC);
  4503.             samples128_0      = vld1q_s32(tempS);
  4504.             runningOrder = 0;
  4505.         }
  4506.  
  4507.         /* 4 - 7 */
  4508.         if (runningOrder >= 4) {
  4509.             coefficients128_4 = vld1q_s32(coefficients + 4);
  4510.             samples128_4      = vld1q_s32(pSamplesOut  - 8);
  4511.             runningOrder -= 4;
  4512.         } else {
  4513.             switch (runningOrder) {
  4514.                 case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7]; /* fallthrough */
  4515.                 case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6]; /* fallthrough */
  4516.                 case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5]; /* fallthrough */
  4517.             }
  4518.  
  4519.             coefficients128_4 = vld1q_s32(tempC);
  4520.             samples128_4      = vld1q_s32(tempS);
  4521.             runningOrder = 0;
  4522.         }
  4523.  
  4524.         /* 8 - 11 */
  4525.         if (runningOrder == 4) {
  4526.             coefficients128_8 = vld1q_s32(coefficients + 8);
  4527.             samples128_8      = vld1q_s32(pSamplesOut  - 12);
  4528.             runningOrder -= 4;
  4529.         } else {
  4530.             switch (runningOrder) {
  4531.                 case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11]; /* fallthrough */
  4532.                 case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10]; /* fallthrough */
  4533.                 case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9]; /* fallthrough */
  4534.             }
  4535.  
  4536.             coefficients128_8 = vld1q_s32(tempC);
  4537.             samples128_8      = vld1q_s32(tempS);
  4538.             runningOrder = 0;
  4539.         }
  4540.  
  4541.         /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
  4542.         coefficients128_0 = drflac__vrevq_s32(coefficients128_0);
  4543.         coefficients128_4 = drflac__vrevq_s32(coefficients128_4);
  4544.         coefficients128_8 = drflac__vrevq_s32(coefficients128_8);
  4545.     }
  4546.  
  4547.     /* For this version we are doing one sample at a time. */
  4548.     while (pDecodedSamples < pDecodedSamplesEnd) {
  4549.         int64x2_t prediction128;
  4550.         uint32x4_t zeroCountPart128;
  4551.         uint32x4_t riceParamPart128;
  4552.  
  4553.         if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
  4554.             !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
  4555.             !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
  4556.             !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
  4557.             return DRFLAC_FALSE;
  4558.         }
  4559.  
  4560.         zeroCountPart128 = vld1q_u32(zeroCountParts);
  4561.         riceParamPart128 = vld1q_u32(riceParamParts);
  4562.  
  4563.         riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
  4564.         riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
  4565.         riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
  4566.  
  4567.         for (i = 0; i < 4; i += 1) {
  4568.             int64x1_t prediction64;
  4569.  
  4570.             prediction128 = veorq_s64(prediction128, prediction128);    /* Reset to 0. */
  4571.             switch (order)
  4572.             {
  4573.             case 12:
  4574.             case 11: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_8), vget_low_s32(samples128_8)));
  4575.             case 10:
  4576.             case  9: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_8), vget_high_s32(samples128_8)));
  4577.             case  8:
  4578.             case  7: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_4), vget_low_s32(samples128_4)));
  4579.             case  6:
  4580.             case  5: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_4), vget_high_s32(samples128_4)));
  4581.             case  4:
  4582.             case  3: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_0), vget_low_s32(samples128_0)));
  4583.             case  2:
  4584.             case  1: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_0), vget_high_s32(samples128_0)));
  4585.             }
  4586.  
  4587.             /* Horizontal add and shift. */
  4588.             prediction64 = drflac__vhaddq_s64(prediction128);
  4589.             prediction64 = vshl_s64(prediction64, shift64);
  4590.             prediction64 = vadd_s64(prediction64, vdup_n_s64(vgetq_lane_u32(riceParamPart128, 0)));
  4591.  
  4592.             /* Our value should be sitting in prediction64[0]. We need to combine this with our SSE samples. */
  4593.             samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8);
  4594.             samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
  4595.             samples128_0 = drflac__valignrq_s32_1(vcombine_s32(vreinterpret_s32_s64(prediction64), vdup_n_s32(0)), samples128_0);
  4596.  
  4597.             /* Slide our rice parameter down so that the value in position 0 contains the next one to process. */
  4598.             riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  4599.         }
  4600.  
  4601.         /* We store samples in groups of 4. */
  4602.         vst1q_s32(pDecodedSamples, samples128_0);
  4603.         pDecodedSamples += 4;
  4604.     }
  4605.  
  4606.     /* Make sure we process the last few samples. */
  4607.     i = (count & ~3);
  4608.     while (i < (int)count) {
  4609.         /* Rice extraction. */
  4610.         if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
  4611.             return DRFLAC_FALSE;
  4612.         }
  4613.  
  4614.         /* Rice reconstruction. */
  4615.         riceParamParts[0] &= riceParamMask;
  4616.         riceParamParts[0] |= (zeroCountParts[0] << riceParam);
  4617.         riceParamParts[0]  = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
  4618.  
  4619.         /* Sample reconstruction. */
  4620.         pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
  4621.  
  4622.         i += 1;
  4623.         pDecodedSamples += 1;
  4624.     }
  4625.  
  4626.     return DRFLAC_TRUE;
  4627. }
  4628.  
  4629. static drflac_bool32 drflac__decode_samples_with_residual__rice__neon(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)
  4630. {
  4631.     DRFLAC_ASSERT(bs != NULL);
  4632.     DRFLAC_ASSERT(count > 0);
  4633.     DRFLAC_ASSERT(pSamplesOut != NULL);
  4634.  
  4635.     /* In my testing the order is rarely > 12, so in this case I'm going to simplify the NEON implementation by only handling order <= 12. */
  4636.     if (order > 0 && order <= 12) {
  4637.         if (bitsPerSample+shift > 32) {
  4638.             return drflac__decode_samples_with_residual__rice__neon_64(bs, count, riceParam, order, shift, coefficients, pSamplesOut);
  4639.         } else {
  4640.             return drflac__decode_samples_with_residual__rice__neon_32(bs, count, riceParam, order, shift, coefficients, pSamplesOut);
  4641.         }
  4642.     } else {
  4643.         return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut);
  4644.     }
  4645. }
  4646. #endif
  4647.  
  4648. 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)
  4649. {
  4650. #if defined(DRFLAC_SUPPORT_SSE41)
  4651.     if (drflac__gIsSSE41Supported) {
  4652.         return drflac__decode_samples_with_residual__rice__sse41(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut);
  4653.     } else
  4654. #elif defined(DRFLAC_SUPPORT_NEON)
  4655.     if (drflac__gIsNEONSupported) {
  4656.         return drflac__decode_samples_with_residual__rice__neon(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut);
  4657.     } else
  4658. #endif
  4659.     {
  4660.         /* Scalar fallback. */
  4661.     #if 0
  4662.         return drflac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut);
  4663.     #else
  4664.         return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, order, shift, coefficients, pSamplesOut);
  4665.     #endif
  4666.     }
  4667. }
  4668.  
  4669. /* 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. */
  4670. static drflac_bool32 drflac__read_and_seek_residual__rice(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam)
  4671. {
  4672.     drflac_uint32 i;
  4673.  
  4674.     DRFLAC_ASSERT(bs != NULL);
  4675.     DRFLAC_ASSERT(count > 0);
  4676.  
  4677.     for (i = 0; i < count; ++i) {
  4678.         if (!drflac__seek_rice_parts(bs, riceParam)) {
  4679.             return DRFLAC_FALSE;
  4680.         }
  4681.     }
  4682.  
  4683.     return DRFLAC_TRUE;
  4684. }
  4685.  
  4686. 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)
  4687. {
  4688.     drflac_uint32 i;
  4689.  
  4690.     DRFLAC_ASSERT(bs != NULL);
  4691.     DRFLAC_ASSERT(count > 0);
  4692.     DRFLAC_ASSERT(unencodedBitsPerSample <= 31);    /* <-- unencodedBitsPerSample is a 5 bit number, so cannot exceed 31. */
  4693.     DRFLAC_ASSERT(pSamplesOut != NULL);
  4694.  
  4695.     for (i = 0; i < count; ++i) {
  4696.         if (unencodedBitsPerSample > 0) {
  4697.             if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i)) {
  4698.                 return DRFLAC_FALSE;
  4699.             }
  4700.         } else {
  4701.             pSamplesOut[i] = 0;
  4702.         }
  4703.  
  4704.         if (bitsPerSample >= 24) {
  4705.             pSamplesOut[i] += drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut + i);
  4706.         } else {
  4707.             pSamplesOut[i] += drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut + i);
  4708.         }
  4709.     }
  4710.  
  4711.     return DRFLAC_TRUE;
  4712. }
  4713.  
  4714.  
  4715. /*
  4716. Reads and decodes the residual for the sub-frame the decoder is currently sitting on. This function should be called
  4717. when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be ignored. The
  4718. <blockSize> and <order> parameters are used to determine how many residual values need to be decoded.
  4719. */
  4720. 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)
  4721. {
  4722.     drflac_uint8 residualMethod;
  4723.     drflac_uint8 partitionOrder;
  4724.     drflac_uint32 samplesInPartition;
  4725.     drflac_uint32 partitionsRemaining;
  4726.  
  4727.     DRFLAC_ASSERT(bs != NULL);
  4728.     DRFLAC_ASSERT(blockSize != 0);
  4729.     DRFLAC_ASSERT(pDecodedSamples != NULL);       /* <-- Should we allow NULL, in which case we just seek past the residual rather than do a full decode? */
  4730.  
  4731.     if (!drflac__read_uint8(bs, 2, &residualMethod)) {
  4732.         return DRFLAC_FALSE;
  4733.     }
  4734.  
  4735.     if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  4736.         return DRFLAC_FALSE;    /* Unknown or unsupported residual coding method. */
  4737.     }
  4738.  
  4739.     /* Ignore the first <order> values. */
  4740.     pDecodedSamples += order;
  4741.  
  4742.     if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
  4743.         return DRFLAC_FALSE;
  4744.     }
  4745.  
  4746.     /*
  4747.     From the FLAC spec:
  4748.       The Rice partition order in a Rice-coded residual section must be less than or equal to 8.
  4749.     */
  4750.     if (partitionOrder > 8) {
  4751.         return DRFLAC_FALSE;
  4752.     }
  4753.  
  4754.     /* Validation check. */
  4755.     if ((blockSize / (1 << partitionOrder)) <= order) {
  4756.         return DRFLAC_FALSE;
  4757.     }
  4758.  
  4759.     samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
  4760.     partitionsRemaining = (1 << partitionOrder);
  4761.     for (;;) {
  4762.         drflac_uint8 riceParam = 0;
  4763.         if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
  4764.             if (!drflac__read_uint8(bs, 4, &riceParam)) {
  4765.                 return DRFLAC_FALSE;
  4766.             }
  4767.             if (riceParam == 15) {
  4768.                 riceParam = 0xFF;
  4769.             }
  4770.         } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  4771.             if (!drflac__read_uint8(bs, 5, &riceParam)) {
  4772.                 return DRFLAC_FALSE;
  4773.             }
  4774.             if (riceParam == 31) {
  4775.                 riceParam = 0xFF;
  4776.             }
  4777.         }
  4778.  
  4779.         if (riceParam != 0xFF) {
  4780.             if (!drflac__decode_samples_with_residual__rice(bs, bitsPerSample, samplesInPartition, riceParam, order, shift, coefficients, pDecodedSamples)) {
  4781.                 return DRFLAC_FALSE;
  4782.             }
  4783.         } else {
  4784.             drflac_uint8 unencodedBitsPerSample = 0;
  4785.             if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
  4786.                 return DRFLAC_FALSE;
  4787.             }
  4788.  
  4789.             if (!drflac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, order, shift, coefficients, pDecodedSamples)) {
  4790.                 return DRFLAC_FALSE;
  4791.             }
  4792.         }
  4793.  
  4794.         pDecodedSamples += samplesInPartition;
  4795.  
  4796.         if (partitionsRemaining == 1) {
  4797.             break;
  4798.         }
  4799.  
  4800.         partitionsRemaining -= 1;
  4801.  
  4802.         if (partitionOrder != 0) {
  4803.             samplesInPartition = blockSize / (1 << partitionOrder);
  4804.         }
  4805.     }
  4806.  
  4807.     return DRFLAC_TRUE;
  4808. }
  4809.  
  4810. /*
  4811. Reads and seeks past the residual for the sub-frame the decoder is currently sitting on. This function should be called
  4812. when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be set to 0. The
  4813. <blockSize> and <order> parameters are used to determine how many residual values need to be decoded.
  4814. */
  4815. static drflac_bool32 drflac__read_and_seek_residual(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 order)
  4816. {
  4817.     drflac_uint8 residualMethod;
  4818.     drflac_uint8 partitionOrder;
  4819.     drflac_uint32 samplesInPartition;
  4820.     drflac_uint32 partitionsRemaining;
  4821.  
  4822.     DRFLAC_ASSERT(bs != NULL);
  4823.     DRFLAC_ASSERT(blockSize != 0);
  4824.  
  4825.     if (!drflac__read_uint8(bs, 2, &residualMethod)) {
  4826.         return DRFLAC_FALSE;
  4827.     }
  4828.  
  4829.     if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  4830.         return DRFLAC_FALSE;    /* Unknown or unsupported residual coding method. */
  4831.     }
  4832.  
  4833.     if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
  4834.         return DRFLAC_FALSE;
  4835.     }
  4836.  
  4837.     /*
  4838.     From the FLAC spec:
  4839.       The Rice partition order in a Rice-coded residual section must be less than or equal to 8.
  4840.     */
  4841.     if (partitionOrder > 8) {
  4842.         return DRFLAC_FALSE;
  4843.     }
  4844.  
  4845.     /* Validation check. */
  4846.     if ((blockSize / (1 << partitionOrder)) <= order) {
  4847.         return DRFLAC_FALSE;
  4848.     }
  4849.  
  4850.     samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
  4851.     partitionsRemaining = (1 << partitionOrder);
  4852.     for (;;)
  4853.     {
  4854.         drflac_uint8 riceParam = 0;
  4855.         if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
  4856.             if (!drflac__read_uint8(bs, 4, &riceParam)) {
  4857.                 return DRFLAC_FALSE;
  4858.             }
  4859.             if (riceParam == 15) {
  4860.                 riceParam = 0xFF;
  4861.             }
  4862.         } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  4863.             if (!drflac__read_uint8(bs, 5, &riceParam)) {
  4864.                 return DRFLAC_FALSE;
  4865.             }
  4866.             if (riceParam == 31) {
  4867.                 riceParam = 0xFF;
  4868.             }
  4869.         }
  4870.  
  4871.         if (riceParam != 0xFF) {
  4872.             if (!drflac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) {
  4873.                 return DRFLAC_FALSE;
  4874.             }
  4875.         } else {
  4876.             drflac_uint8 unencodedBitsPerSample = 0;
  4877.             if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
  4878.                 return DRFLAC_FALSE;
  4879.             }
  4880.  
  4881.             if (!drflac__seek_bits(bs, unencodedBitsPerSample * samplesInPartition)) {
  4882.                 return DRFLAC_FALSE;
  4883.             }
  4884.         }
  4885.  
  4886.  
  4887.         if (partitionsRemaining == 1) {
  4888.             break;
  4889.         }
  4890.  
  4891.         partitionsRemaining -= 1;
  4892.         samplesInPartition = blockSize / (1 << partitionOrder);
  4893.     }
  4894.  
  4895.     return DRFLAC_TRUE;
  4896. }
  4897.  
  4898.  
  4899. static drflac_bool32 drflac__decode_samples__constant(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
  4900. {
  4901.     drflac_uint32 i;
  4902.  
  4903.     /* Only a single sample needs to be decoded here. */
  4904.     drflac_int32 sample;
  4905.     if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
  4906.         return DRFLAC_FALSE;
  4907.     }
  4908.  
  4909.     /*
  4910.     We don't really need to expand this, but it does simplify the process of reading samples. If this becomes a performance issue (unlikely)
  4911.     we'll want to look at a more efficient way.
  4912.     */
  4913.     for (i = 0; i < blockSize; ++i) {
  4914.         pDecodedSamples[i] = sample;
  4915.     }
  4916.  
  4917.     return DRFLAC_TRUE;
  4918. }
  4919.  
  4920. static drflac_bool32 drflac__decode_samples__verbatim(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
  4921. {
  4922.     drflac_uint32 i;
  4923.  
  4924.     for (i = 0; i < blockSize; ++i) {
  4925.         drflac_int32 sample;
  4926.         if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
  4927.             return DRFLAC_FALSE;
  4928.         }
  4929.  
  4930.         pDecodedSamples[i] = sample;
  4931.     }
  4932.  
  4933.     return DRFLAC_TRUE;
  4934. }
  4935.  
  4936. static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
  4937. {
  4938.     drflac_uint32 i;
  4939.  
  4940.     static drflac_int32 lpcCoefficientsTable[5][4] = {
  4941.         {0,  0, 0,  0},
  4942.         {1,  0, 0,  0},
  4943.         {2, -1, 0,  0},
  4944.         {3, -3, 1,  0},
  4945.         {4, -6, 4, -1}
  4946.     };
  4947.  
  4948.     /* Warm up samples and coefficients. */
  4949.     for (i = 0; i < lpcOrder; ++i) {
  4950.         drflac_int32 sample;
  4951.         if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
  4952.             return DRFLAC_FALSE;
  4953.         }
  4954.  
  4955.         pDecodedSamples[i] = sample;
  4956.     }
  4957.  
  4958.     if (!drflac__decode_samples_with_residual(bs, subframeBitsPerSample, blockSize, lpcOrder, 0, lpcCoefficientsTable[lpcOrder], pDecodedSamples)) {
  4959.         return DRFLAC_FALSE;
  4960.     }
  4961.  
  4962.     return DRFLAC_TRUE;
  4963. }
  4964.  
  4965. static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
  4966. {
  4967.     drflac_uint8 i;
  4968.     drflac_uint8 lpcPrecision;
  4969.     drflac_int8 lpcShift;
  4970.     drflac_int32 coefficients[32];
  4971.  
  4972.     /* Warm up samples. */
  4973.     for (i = 0; i < lpcOrder; ++i) {
  4974.         drflac_int32 sample;
  4975.         if (!drflac__read_int32(bs, bitsPerSample, &sample)) {
  4976.             return DRFLAC_FALSE;
  4977.         }
  4978.  
  4979.         pDecodedSamples[i] = sample;
  4980.     }
  4981.  
  4982.     if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
  4983.         return DRFLAC_FALSE;
  4984.     }
  4985.     if (lpcPrecision == 15) {
  4986.         return DRFLAC_FALSE;    /* Invalid. */
  4987.     }
  4988.     lpcPrecision += 1;
  4989.  
  4990.     if (!drflac__read_int8(bs, 5, &lpcShift)) {
  4991.         return DRFLAC_FALSE;
  4992.     }
  4993.  
  4994.     DRFLAC_ZERO_MEMORY(coefficients, sizeof(coefficients));
  4995.     for (i = 0; i < lpcOrder; ++i) {
  4996.         if (!drflac__read_int32(bs, lpcPrecision, coefficients + i)) {
  4997.             return DRFLAC_FALSE;
  4998.         }
  4999.     }
  5000.  
  5001.     if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, coefficients, pDecodedSamples)) {
  5002.         return DRFLAC_FALSE;
  5003.     }
  5004.  
  5005.     return DRFLAC_TRUE;
  5006. }
  5007.  
  5008.  
  5009. static drflac_bool32 drflac__read_next_flac_frame_header(drflac_bs* bs, drflac_uint8 streaminfoBitsPerSample, drflac_frame_header* header)
  5010. {
  5011.     const drflac_uint32 sampleRateTable[12]  = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000};
  5012.     const drflac_uint8 bitsPerSampleTable[8] = {0, 8, 12, (drflac_uint8)-1, 16, 20, 24, (drflac_uint8)-1};   /* -1 = reserved. */
  5013.  
  5014.     DRFLAC_ASSERT(bs != NULL);
  5015.     DRFLAC_ASSERT(header != NULL);
  5016.  
  5017.     /* Keep looping until we find a valid sync code. */
  5018.     for (;;) {
  5019.         drflac_uint8 crc8 = 0xCE; /* 0xCE = drflac_crc8(0, 0x3FFE, 14); */
  5020.         drflac_uint8 reserved = 0;
  5021.         drflac_uint8 blockingStrategy = 0;
  5022.         drflac_uint8 blockSize = 0;
  5023.         drflac_uint8 sampleRate = 0;
  5024.         drflac_uint8 channelAssignment = 0;
  5025.         drflac_uint8 bitsPerSample = 0;
  5026.         drflac_bool32 isVariableBlockSize;
  5027.  
  5028.         if (!drflac__find_and_seek_to_next_sync_code(bs)) {
  5029.             return DRFLAC_FALSE;
  5030.         }
  5031.  
  5032.         if (!drflac__read_uint8(bs, 1, &reserved)) {
  5033.             return DRFLAC_FALSE;
  5034.         }
  5035.         if (reserved == 1) {
  5036.             continue;
  5037.         }
  5038.         crc8 = drflac_crc8(crc8, reserved, 1);
  5039.  
  5040.         if (!drflac__read_uint8(bs, 1, &blockingStrategy)) {
  5041.             return DRFLAC_FALSE;
  5042.         }
  5043.         crc8 = drflac_crc8(crc8, blockingStrategy, 1);
  5044.  
  5045.         if (!drflac__read_uint8(bs, 4, &blockSize)) {
  5046.             return DRFLAC_FALSE;
  5047.         }
  5048.         if (blockSize == 0) {
  5049.             continue;
  5050.         }
  5051.         crc8 = drflac_crc8(crc8, blockSize, 4);
  5052.  
  5053.         if (!drflac__read_uint8(bs, 4, &sampleRate)) {
  5054.             return DRFLAC_FALSE;
  5055.         }
  5056.         crc8 = drflac_crc8(crc8, sampleRate, 4);
  5057.  
  5058.         if (!drflac__read_uint8(bs, 4, &channelAssignment)) {
  5059.             return DRFLAC_FALSE;
  5060.         }
  5061.         if (channelAssignment > 10) {
  5062.             continue;
  5063.         }
  5064.         crc8 = drflac_crc8(crc8, channelAssignment, 4);
  5065.  
  5066.         if (!drflac__read_uint8(bs, 3, &bitsPerSample)) {
  5067.             return DRFLAC_FALSE;
  5068.         }
  5069.         if (bitsPerSample == 3 || bitsPerSample == 7) {
  5070.             continue;
  5071.         }
  5072.         crc8 = drflac_crc8(crc8, bitsPerSample, 3);
  5073.  
  5074.  
  5075.         if (!drflac__read_uint8(bs, 1, &reserved)) {
  5076.             return DRFLAC_FALSE;
  5077.         }
  5078.         if (reserved == 1) {
  5079.             continue;
  5080.         }
  5081.         crc8 = drflac_crc8(crc8, reserved, 1);
  5082.  
  5083.  
  5084.         isVariableBlockSize = blockingStrategy == 1;
  5085.         if (isVariableBlockSize) {
  5086.             drflac_uint64 pcmFrameNumber;
  5087.             drflac_result result = drflac__read_utf8_coded_number(bs, &pcmFrameNumber, &crc8);
  5088.             if (result != DRFLAC_SUCCESS) {
  5089.                 if (result == DRFLAC_AT_END) {
  5090.                     return DRFLAC_FALSE;
  5091.                 } else {
  5092.                     continue;
  5093.                 }
  5094.             }
  5095.             header->flacFrameNumber  = 0;
  5096.             header->pcmFrameNumber = pcmFrameNumber;
  5097.         } else {
  5098.             drflac_uint64 flacFrameNumber = 0;
  5099.             drflac_result result = drflac__read_utf8_coded_number(bs, &flacFrameNumber, &crc8);
  5100.             if (result != DRFLAC_SUCCESS) {
  5101.                 if (result == DRFLAC_AT_END) {
  5102.                     return DRFLAC_FALSE;
  5103.                 } else {
  5104.                     continue;
  5105.                 }
  5106.             }
  5107.             header->flacFrameNumber  = (drflac_uint32)flacFrameNumber;   /* <-- Safe cast. */
  5108.             header->pcmFrameNumber = 0;
  5109.         }
  5110.  
  5111.  
  5112.         DRFLAC_ASSERT(blockSize > 0);
  5113.         if (blockSize == 1) {
  5114.             header->blockSizeInPCMFrames = 192;
  5115.         } else if (blockSize >= 2 && blockSize <= 5) {
  5116.             header->blockSizeInPCMFrames = 576 * (1 << (blockSize - 2));
  5117.         } else if (blockSize == 6) {
  5118.             if (!drflac__read_uint16(bs, 8, &header->blockSizeInPCMFrames)) {
  5119.                 return DRFLAC_FALSE;
  5120.             }
  5121.             crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 8);
  5122.             header->blockSizeInPCMFrames += 1;
  5123.         } else if (blockSize == 7) {
  5124.             if (!drflac__read_uint16(bs, 16, &header->blockSizeInPCMFrames)) {
  5125.                 return DRFLAC_FALSE;
  5126.             }
  5127.             crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 16);
  5128.             header->blockSizeInPCMFrames += 1;
  5129.         } else {
  5130.             DRFLAC_ASSERT(blockSize >= 8);
  5131.             header->blockSizeInPCMFrames = 256 * (1 << (blockSize - 8));
  5132.         }
  5133.  
  5134.  
  5135.         if (sampleRate <= 11) {
  5136.             header->sampleRate = sampleRateTable[sampleRate];
  5137.         } else if (sampleRate == 12) {
  5138.             if (!drflac__read_uint32(bs, 8, &header->sampleRate)) {
  5139.                 return DRFLAC_FALSE;
  5140.             }
  5141.             crc8 = drflac_crc8(crc8, header->sampleRate, 8);
  5142.             header->sampleRate *= 1000;
  5143.         } else if (sampleRate == 13) {
  5144.             if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
  5145.                 return DRFLAC_FALSE;
  5146.             }
  5147.             crc8 = drflac_crc8(crc8, header->sampleRate, 16);
  5148.         } else if (sampleRate == 14) {
  5149.             if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
  5150.                 return DRFLAC_FALSE;
  5151.             }
  5152.             crc8 = drflac_crc8(crc8, header->sampleRate, 16);
  5153.             header->sampleRate *= 10;
  5154.         } else {
  5155.             continue;  /* Invalid. Assume an invalid block. */
  5156.         }
  5157.  
  5158.  
  5159.         header->channelAssignment = channelAssignment;
  5160.  
  5161.         header->bitsPerSample = bitsPerSampleTable[bitsPerSample];
  5162.         if (header->bitsPerSample == 0) {
  5163.             header->bitsPerSample = streaminfoBitsPerSample;
  5164.         }
  5165.  
  5166.         if (!drflac__read_uint8(bs, 8, &header->crc8)) {
  5167.             return DRFLAC_FALSE;
  5168.         }
  5169.  
  5170. #ifndef DR_FLAC_NO_CRC
  5171.         if (header->crc8 != crc8) {
  5172.             continue;    /* CRC mismatch. Loop back to the top and find the next sync code. */
  5173.         }
  5174. #endif
  5175.         return DRFLAC_TRUE;
  5176.     }
  5177. }
  5178.  
  5179. static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe* pSubframe)
  5180. {
  5181.     drflac_uint8 header;
  5182.     int type;
  5183.  
  5184.     if (!drflac__read_uint8(bs, 8, &header)) {
  5185.         return DRFLAC_FALSE;
  5186.     }
  5187.  
  5188.     /* First bit should always be 0. */
  5189.     if ((header & 0x80) != 0) {
  5190.         return DRFLAC_FALSE;
  5191.     }
  5192.  
  5193.     type = (header & 0x7E) >> 1;
  5194.     if (type == 0) {
  5195.         pSubframe->subframeType = DRFLAC_SUBFRAME_CONSTANT;
  5196.     } else if (type == 1) {
  5197.         pSubframe->subframeType = DRFLAC_SUBFRAME_VERBATIM;
  5198.     } else {
  5199.         if ((type & 0x20) != 0) {
  5200.             pSubframe->subframeType = DRFLAC_SUBFRAME_LPC;
  5201.             pSubframe->lpcOrder = (drflac_uint8)(type & 0x1F) + 1;
  5202.         } else if ((type & 0x08) != 0) {
  5203.             pSubframe->subframeType = DRFLAC_SUBFRAME_FIXED;
  5204.             pSubframe->lpcOrder = (drflac_uint8)(type & 0x07);
  5205.             if (pSubframe->lpcOrder > 4) {
  5206.                 pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
  5207.                 pSubframe->lpcOrder = 0;
  5208.             }
  5209.         } else {
  5210.             pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
  5211.         }
  5212.     }
  5213.  
  5214.     if (pSubframe->subframeType == DRFLAC_SUBFRAME_RESERVED) {
  5215.         return DRFLAC_FALSE;
  5216.     }
  5217.  
  5218.     /* Wasted bits per sample. */
  5219.     pSubframe->wastedBitsPerSample = 0;
  5220.     if ((header & 0x01) == 1) {
  5221.         unsigned int wastedBitsPerSample;
  5222.         if (!drflac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) {
  5223.             return DRFLAC_FALSE;
  5224.         }
  5225.         pSubframe->wastedBitsPerSample = (drflac_uint8)wastedBitsPerSample + 1;
  5226.     }
  5227.  
  5228.     return DRFLAC_TRUE;
  5229. }
  5230.  
  5231. static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex, drflac_int32* pDecodedSamplesOut)
  5232. {
  5233.     drflac_subframe* pSubframe;
  5234.     drflac_uint32 subframeBitsPerSample;
  5235.  
  5236.     DRFLAC_ASSERT(bs != NULL);
  5237.     DRFLAC_ASSERT(frame != NULL);
  5238.  
  5239.     pSubframe = frame->subframes + subframeIndex;
  5240.     if (!drflac__read_subframe_header(bs, pSubframe)) {
  5241.         return DRFLAC_FALSE;
  5242.     }
  5243.  
  5244.     /* Side channels require an extra bit per sample. Took a while to figure that one out... */
  5245.     subframeBitsPerSample = frame->header.bitsPerSample;
  5246.     if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
  5247.         subframeBitsPerSample += 1;
  5248.     } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
  5249.         subframeBitsPerSample += 1;
  5250.     }
  5251.  
  5252.     /* Need to handle wasted bits per sample. */
  5253.     if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
  5254.         return DRFLAC_FALSE;
  5255.     }
  5256.     subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
  5257.  
  5258.     pSubframe->pSamplesS32 = pDecodedSamplesOut;
  5259.  
  5260.     switch (pSubframe->subframeType)
  5261.     {
  5262.         case DRFLAC_SUBFRAME_CONSTANT:
  5263.         {
  5264.             drflac__decode_samples__constant(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
  5265.         } break;
  5266.  
  5267.         case DRFLAC_SUBFRAME_VERBATIM:
  5268.         {
  5269.             drflac__decode_samples__verbatim(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
  5270.         } break;
  5271.  
  5272.         case DRFLAC_SUBFRAME_FIXED:
  5273.         {
  5274.             drflac__decode_samples__fixed(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
  5275.         } break;
  5276.  
  5277.         case DRFLAC_SUBFRAME_LPC:
  5278.         {
  5279.             drflac__decode_samples__lpc(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
  5280.         } break;
  5281.  
  5282.         default: return DRFLAC_FALSE;
  5283.     }
  5284.  
  5285.     return DRFLAC_TRUE;
  5286. }
  5287.  
  5288. static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex)
  5289. {
  5290.     drflac_subframe* pSubframe;
  5291.     drflac_uint32 subframeBitsPerSample;
  5292.  
  5293.     DRFLAC_ASSERT(bs != NULL);
  5294.     DRFLAC_ASSERT(frame != NULL);
  5295.  
  5296.     pSubframe = frame->subframes + subframeIndex;
  5297.     if (!drflac__read_subframe_header(bs, pSubframe)) {
  5298.         return DRFLAC_FALSE;
  5299.     }
  5300.  
  5301.     /* Side channels require an extra bit per sample. Took a while to figure that one out... */
  5302.     subframeBitsPerSample = frame->header.bitsPerSample;
  5303.     if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
  5304.         subframeBitsPerSample += 1;
  5305.     } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
  5306.         subframeBitsPerSample += 1;
  5307.     }
  5308.  
  5309.     /* Need to handle wasted bits per sample. */
  5310.     if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
  5311.         return DRFLAC_FALSE;
  5312.     }
  5313.     subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
  5314.  
  5315.     pSubframe->pSamplesS32 = NULL;
  5316.  
  5317.     switch (pSubframe->subframeType)
  5318.     {
  5319.         case DRFLAC_SUBFRAME_CONSTANT:
  5320.         {
  5321.             if (!drflac__seek_bits(bs, subframeBitsPerSample)) {
  5322.                 return DRFLAC_FALSE;
  5323.             }
  5324.         } break;
  5325.  
  5326.         case DRFLAC_SUBFRAME_VERBATIM:
  5327.         {
  5328.             unsigned int bitsToSeek = frame->header.blockSizeInPCMFrames * subframeBitsPerSample;
  5329.             if (!drflac__seek_bits(bs, bitsToSeek)) {
  5330.                 return DRFLAC_FALSE;
  5331.             }
  5332.         } break;
  5333.  
  5334.         case DRFLAC_SUBFRAME_FIXED:
  5335.         {
  5336.             unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
  5337.             if (!drflac__seek_bits(bs, bitsToSeek)) {
  5338.                 return DRFLAC_FALSE;
  5339.             }
  5340.  
  5341.             if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
  5342.                 return DRFLAC_FALSE;
  5343.             }
  5344.         } break;
  5345.  
  5346.         case DRFLAC_SUBFRAME_LPC:
  5347.         {
  5348.             drflac_uint8 lpcPrecision;
  5349.  
  5350.             unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
  5351.             if (!drflac__seek_bits(bs, bitsToSeek)) {
  5352.                 return DRFLAC_FALSE;
  5353.             }
  5354.  
  5355.             if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
  5356.                 return DRFLAC_FALSE;
  5357.             }
  5358.             if (lpcPrecision == 15) {
  5359.                 return DRFLAC_FALSE;    /* Invalid. */
  5360.             }
  5361.             lpcPrecision += 1;
  5362.  
  5363.  
  5364.             bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5;    /* +5 for shift. */
  5365.             if (!drflac__seek_bits(bs, bitsToSeek)) {
  5366.                 return DRFLAC_FALSE;
  5367.             }
  5368.  
  5369.             if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
  5370.                 return DRFLAC_FALSE;
  5371.             }
  5372.         } break;
  5373.  
  5374.         default: return DRFLAC_FALSE;
  5375.     }
  5376.  
  5377.     return DRFLAC_TRUE;
  5378. }
  5379.  
  5380.  
  5381. static DRFLAC_INLINE drflac_uint8 drflac__get_channel_count_from_channel_assignment(drflac_int8 channelAssignment)
  5382. {
  5383.     drflac_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2};
  5384.  
  5385.     DRFLAC_ASSERT(channelAssignment <= 10);
  5386.     return lookup[channelAssignment];
  5387. }
  5388.  
  5389. static drflac_result drflac__decode_flac_frame(drflac* pFlac)
  5390. {
  5391.     int channelCount;
  5392.     int i;
  5393.     drflac_uint8 paddingSizeInBits;
  5394.     drflac_uint16 desiredCRC16;
  5395. #ifndef DR_FLAC_NO_CRC
  5396.     drflac_uint16 actualCRC16;
  5397. #endif
  5398.  
  5399.     /* This function should be called while the stream is sitting on the first byte after the frame header. */
  5400.     DRFLAC_ZERO_MEMORY(pFlac->currentFLACFrame.subframes, sizeof(pFlac->currentFLACFrame.subframes));
  5401.  
  5402.     /* The frame block size must never be larger than the maximum block size defined by the FLAC stream. */
  5403.     if (pFlac->currentFLACFrame.header.blockSizeInPCMFrames > pFlac->maxBlockSizeInPCMFrames) {
  5404.         return DRFLAC_ERROR;
  5405.     }
  5406.  
  5407.     /* The number of channels in the frame must match the channel count from the STREAMINFO block. */
  5408.     channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  5409.     if (channelCount != (int)pFlac->channels) {
  5410.         return DRFLAC_ERROR;
  5411.     }
  5412.  
  5413.     for (i = 0; i < channelCount; ++i) {
  5414.         if (!drflac__decode_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i, pFlac->pDecodedSamples + (pFlac->currentFLACFrame.header.blockSizeInPCMFrames * i))) {
  5415.             return DRFLAC_ERROR;
  5416.         }
  5417.     }
  5418.  
  5419.     paddingSizeInBits = (drflac_uint8)(DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7);
  5420.     if (paddingSizeInBits > 0) {
  5421.         drflac_uint8 padding = 0;
  5422.         if (!drflac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding)) {
  5423.             return DRFLAC_AT_END;
  5424.         }
  5425.     }
  5426.  
  5427. #ifndef DR_FLAC_NO_CRC
  5428.     actualCRC16 = drflac__flush_crc16(&pFlac->bs);
  5429. #endif
  5430.     if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
  5431.         return DRFLAC_AT_END;
  5432.     }
  5433.  
  5434. #ifndef DR_FLAC_NO_CRC
  5435.     if (actualCRC16 != desiredCRC16) {
  5436.         return DRFLAC_CRC_MISMATCH;    /* CRC mismatch. */
  5437.     }
  5438. #endif
  5439.  
  5440.     pFlac->currentFLACFrame.pcmFramesRemaining = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
  5441.  
  5442.     return DRFLAC_SUCCESS;
  5443. }
  5444.  
  5445. static drflac_result drflac__seek_flac_frame(drflac* pFlac)
  5446. {
  5447.     int channelCount;
  5448.     int i;
  5449.     drflac_uint16 desiredCRC16;
  5450. #ifndef DR_FLAC_NO_CRC
  5451.     drflac_uint16 actualCRC16;
  5452. #endif
  5453.  
  5454.     channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  5455.     for (i = 0; i < channelCount; ++i) {
  5456.         if (!drflac__seek_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i)) {
  5457.             return DRFLAC_ERROR;
  5458.         }
  5459.     }
  5460.  
  5461.     /* Padding. */
  5462.     if (!drflac__seek_bits(&pFlac->bs, DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7)) {
  5463.         return DRFLAC_ERROR;
  5464.     }
  5465.  
  5466.     /* CRC. */
  5467. #ifndef DR_FLAC_NO_CRC
  5468.     actualCRC16 = drflac__flush_crc16(&pFlac->bs);
  5469. #endif
  5470.     if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
  5471.         return DRFLAC_AT_END;
  5472.     }
  5473.  
  5474. #ifndef DR_FLAC_NO_CRC
  5475.     if (actualCRC16 != desiredCRC16) {
  5476.         return DRFLAC_CRC_MISMATCH;    /* CRC mismatch. */
  5477.     }
  5478. #endif
  5479.  
  5480.     return DRFLAC_SUCCESS;
  5481. }
  5482.  
  5483. static drflac_bool32 drflac__read_and_decode_next_flac_frame(drflac* pFlac)
  5484. {
  5485.     DRFLAC_ASSERT(pFlac != NULL);
  5486.  
  5487.     for (;;) {
  5488.         drflac_result result;
  5489.  
  5490.         if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  5491.             return DRFLAC_FALSE;
  5492.         }
  5493.  
  5494.         result = drflac__decode_flac_frame(pFlac);
  5495.         if (result != DRFLAC_SUCCESS) {
  5496.             if (result == DRFLAC_CRC_MISMATCH) {
  5497.                 continue;   /* CRC mismatch. Skip to the next frame. */
  5498.             } else {
  5499.                 return DRFLAC_FALSE;
  5500.             }
  5501.         }
  5502.  
  5503.         return DRFLAC_TRUE;
  5504.     }
  5505. }
  5506.  
  5507. static void drflac__get_pcm_frame_range_of_current_flac_frame(drflac* pFlac, drflac_uint64* pFirstPCMFrame, drflac_uint64* pLastPCMFrame)
  5508. {
  5509.     drflac_uint64 firstPCMFrame;
  5510.     drflac_uint64 lastPCMFrame;
  5511.  
  5512.     DRFLAC_ASSERT(pFlac != NULL);
  5513.  
  5514.     firstPCMFrame = pFlac->currentFLACFrame.header.pcmFrameNumber;
  5515.     if (firstPCMFrame == 0) {
  5516.         firstPCMFrame = ((drflac_uint64)pFlac->currentFLACFrame.header.flacFrameNumber) * pFlac->maxBlockSizeInPCMFrames;
  5517.     }
  5518.  
  5519.     lastPCMFrame = firstPCMFrame + pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
  5520.     if (lastPCMFrame > 0) {
  5521.         lastPCMFrame -= 1; /* Needs to be zero based. */
  5522.     }
  5523.  
  5524.     if (pFirstPCMFrame) {
  5525.         *pFirstPCMFrame = firstPCMFrame;
  5526.     }
  5527.     if (pLastPCMFrame) {
  5528.         *pLastPCMFrame = lastPCMFrame;
  5529.     }
  5530. }
  5531.  
  5532. static drflac_bool32 drflac__seek_to_first_frame(drflac* pFlac)
  5533. {
  5534.     drflac_bool32 result;
  5535.  
  5536.     DRFLAC_ASSERT(pFlac != NULL);
  5537.  
  5538.     result = drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes);
  5539.  
  5540.     DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
  5541.     pFlac->currentPCMFrame = 0;
  5542.  
  5543.     return result;
  5544. }
  5545.  
  5546. static DRFLAC_INLINE drflac_result drflac__seek_to_next_flac_frame(drflac* pFlac)
  5547. {
  5548.     /* This function should only ever be called while the decoder is sitting on the first byte past the FRAME_HEADER section. */
  5549.     DRFLAC_ASSERT(pFlac != NULL);
  5550.     return drflac__seek_flac_frame(pFlac);
  5551. }
  5552.  
  5553.  
  5554. static drflac_uint64 drflac__seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 pcmFramesToSeek)
  5555. {
  5556.     drflac_uint64 pcmFramesRead = 0;
  5557.     while (pcmFramesToSeek > 0) {
  5558.         if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  5559.             if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  5560.                 break;  /* Couldn't read the next frame, so just break from the loop and return. */
  5561.             }
  5562.         } else {
  5563.             if (pFlac->currentFLACFrame.pcmFramesRemaining > pcmFramesToSeek) {
  5564.                 pcmFramesRead   += pcmFramesToSeek;
  5565.                 pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)pcmFramesToSeek;   /* <-- Safe cast. Will always be < currentFrame.pcmFramesRemaining < 65536. */
  5566.                 pcmFramesToSeek  = 0;
  5567.             } else {
  5568.                 pcmFramesRead   += pFlac->currentFLACFrame.pcmFramesRemaining;
  5569.                 pcmFramesToSeek -= pFlac->currentFLACFrame.pcmFramesRemaining;
  5570.                 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  5571.             }
  5572.         }
  5573.     }
  5574.  
  5575.     pFlac->currentPCMFrame += pcmFramesRead;
  5576.     return pcmFramesRead;
  5577. }
  5578.  
  5579.  
  5580. static drflac_bool32 drflac__seek_to_pcm_frame__brute_force(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  5581. {
  5582.     drflac_bool32 isMidFrame = DRFLAC_FALSE;
  5583.     drflac_uint64 runningPCMFrameCount;
  5584.  
  5585.     DRFLAC_ASSERT(pFlac != NULL);
  5586.  
  5587.     /* If we are seeking forward we start from the current position. Otherwise we need to start all the way from the start of the file. */
  5588.     if (pcmFrameIndex >= pFlac->currentPCMFrame) {
  5589.         /* Seeking forward. Need to seek from the current position. */
  5590.         runningPCMFrameCount = pFlac->currentPCMFrame;
  5591.  
  5592.         /* The frame header for the first frame may not yet have been read. We need to do that if necessary. */
  5593.         if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  5594.             if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  5595.                 return DRFLAC_FALSE;
  5596.             }
  5597.         } else {
  5598.             isMidFrame = DRFLAC_TRUE;
  5599.         }
  5600.     } else {
  5601.         /* Seeking backwards. Need to seek from the start of the file. */
  5602.         runningPCMFrameCount = 0;
  5603.  
  5604.         /* Move back to the start. */
  5605.         if (!drflac__seek_to_first_frame(pFlac)) {
  5606.             return DRFLAC_FALSE;
  5607.         }
  5608.  
  5609.         /* Decode the first frame in preparation for sample-exact seeking below. */
  5610.         if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  5611.             return DRFLAC_FALSE;
  5612.         }
  5613.     }
  5614.  
  5615.     /*
  5616.     We need to as quickly as possible find the frame that contains the target sample. To do this, we iterate over each frame and inspect its
  5617.     header. If based on the header we can determine that the frame contains the sample, we do a full decode of that frame.
  5618.     */
  5619.     for (;;) {
  5620.         drflac_uint64 pcmFrameCountInThisFLACFrame;
  5621.         drflac_uint64 firstPCMFrameInFLACFrame = 0;
  5622.         drflac_uint64 lastPCMFrameInFLACFrame = 0;
  5623.  
  5624.         drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
  5625.  
  5626.         pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
  5627.         if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
  5628.             /*
  5629.             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
  5630.             it never existed and keep iterating.
  5631.             */
  5632.             drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
  5633.  
  5634.             if (!isMidFrame) {
  5635.                 drflac_result result = drflac__decode_flac_frame(pFlac);
  5636.                 if (result == DRFLAC_SUCCESS) {
  5637.                     /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
  5638.                     return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;  /* <-- If this fails, something bad has happened (it should never fail). */
  5639.                 } else {
  5640.                     if (result == DRFLAC_CRC_MISMATCH) {
  5641.                         goto next_iteration;   /* CRC mismatch. Pretend this frame never existed. */
  5642.                     } else {
  5643.                         return DRFLAC_FALSE;
  5644.                     }
  5645.                 }
  5646.             } else {
  5647.                 /* We started seeking mid-frame which means we need to skip the frame decoding part. */
  5648.                 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  5649.             }
  5650.         } else {
  5651.             /*
  5652.             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
  5653.             frame never existed and leave the running sample count untouched.
  5654.             */
  5655.             if (!isMidFrame) {
  5656.                 drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
  5657.                 if (result == DRFLAC_SUCCESS) {
  5658.                     runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
  5659.                 } else {
  5660.                     if (result == DRFLAC_CRC_MISMATCH) {
  5661.                         goto next_iteration;   /* CRC mismatch. Pretend this frame never existed. */
  5662.                     } else {
  5663.                         return DRFLAC_FALSE;
  5664.                     }
  5665.                 }
  5666.             } else {
  5667.                 /*
  5668.                 We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with
  5669.                 drflac__seek_to_next_flac_frame() which only works if the decoder is sitting on the byte just after the frame header.
  5670.                 */
  5671.                 runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
  5672.                 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  5673.                 isMidFrame = DRFLAC_FALSE;
  5674.             }
  5675.  
  5676.             /* If we are seeking to the end of the file and we've just hit it, we're done. */
  5677.             if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
  5678.                 return DRFLAC_TRUE;
  5679.             }
  5680.         }
  5681.  
  5682.     next_iteration:
  5683.         /* Grab the next frame in preparation for the next iteration. */
  5684.         if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  5685.             return DRFLAC_FALSE;
  5686.         }
  5687.     }
  5688. }
  5689.  
  5690.  
  5691. #if !defined(DR_FLAC_NO_CRC)
  5692. /*
  5693. We use an average compression ratio to determine our approximate start location. FLAC files are generally about 50%-70% the size of their
  5694. uncompressed counterparts so we'll use this as a basis. I'm going to split the middle and use a factor of 0.6 to determine the starting
  5695. location.
  5696. */
  5697. #define DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO 0.6f
  5698.  
  5699. static drflac_bool32 drflac__seek_to_approximate_flac_frame_to_byte(drflac* pFlac, drflac_uint64 targetByte, drflac_uint64 rangeLo, drflac_uint64 rangeHi, drflac_uint64* pLastSuccessfulSeekOffset)
  5700. {
  5701.     DRFLAC_ASSERT(pFlac != NULL);
  5702.     DRFLAC_ASSERT(pLastSuccessfulSeekOffset != NULL);
  5703.     DRFLAC_ASSERT(targetByte >= rangeLo);
  5704.     DRFLAC_ASSERT(targetByte <= rangeHi);
  5705.  
  5706.     *pLastSuccessfulSeekOffset = pFlac->firstFLACFramePosInBytes;
  5707.  
  5708.     for (;;) {
  5709.         /* When seeking to a byte, failure probably means we've attempted to seek beyond the end of the stream. To counter this we just halve it each attempt. */
  5710.         if (!drflac__seek_to_byte(&pFlac->bs, targetByte)) {
  5711.             /* If we couldn't even seek to the first byte in the stream we have a problem. Just abandon the whole thing. */
  5712.             if (targetByte == 0) {
  5713.                 drflac__seek_to_first_frame(pFlac); /* Try to recover. */
  5714.                 return DRFLAC_FALSE;
  5715.             }
  5716.  
  5717.             /* Halve the byte location and continue. */
  5718.             targetByte = rangeLo + ((rangeHi - rangeLo)/2);
  5719.             rangeHi = targetByte;
  5720.         } else {
  5721.             /* Getting here should mean that we have seeked to an appropriate byte. */
  5722.  
  5723.             /* Clear the details of the FLAC frame so we don't misreport data. */
  5724.             DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
  5725.  
  5726.             /*
  5727.             Now seek to the next FLAC frame. We need to decode the entire frame (not just the header) because it's possible for the header to incorrectly pass the
  5728.             CRC check and return bad data. We need to decode the entire frame to be more certain. Although this seems unlikely, this has happened to me in testing
  5729.             so it needs to stay this way for now.
  5730.             */
  5731. #if 1
  5732.             if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  5733.                 /* Halve the byte location and continue. */
  5734.                 targetByte = rangeLo + ((rangeHi - rangeLo)/2);
  5735.                 rangeHi = targetByte;
  5736.             } else {
  5737.                 break;
  5738.             }
  5739. #else
  5740.             if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  5741.                 /* Halve the byte location and continue. */
  5742.                 targetByte = rangeLo + ((rangeHi - rangeLo)/2);
  5743.                 rangeHi = targetByte;
  5744.             } else {
  5745.                 break;
  5746.             }
  5747. #endif
  5748.         }
  5749.     }
  5750.  
  5751.     /* The current PCM frame needs to be updated based on the frame we just seeked to. */
  5752.     drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
  5753.  
  5754.     DRFLAC_ASSERT(targetByte <= rangeHi);
  5755.  
  5756.     *pLastSuccessfulSeekOffset = targetByte;
  5757.     return DRFLAC_TRUE;
  5758. }
  5759.  
  5760. static drflac_bool32 drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 offset)
  5761. {
  5762.     /* This section of code would be used if we were only decoding the FLAC frame header when calling drflac__seek_to_approximate_flac_frame_to_byte(). */
  5763. #if 0
  5764.     if (drflac__decode_flac_frame(pFlac) != DRFLAC_SUCCESS) {
  5765.         /* We failed to decode this frame which may be due to it being corrupt. We'll just use the next valid FLAC frame. */
  5766.         if (drflac__read_and_decode_next_flac_frame(pFlac) == DRFLAC_FALSE) {
  5767.             return DRFLAC_FALSE;
  5768.         }
  5769.     }
  5770. #endif
  5771.  
  5772.     return drflac__seek_forward_by_pcm_frames(pFlac, offset) == offset;
  5773. }
  5774.  
  5775.  
  5776. static drflac_bool32 drflac__seek_to_pcm_frame__binary_search_internal(drflac* pFlac, drflac_uint64 pcmFrameIndex, drflac_uint64 byteRangeLo, drflac_uint64 byteRangeHi)
  5777. {
  5778.     /* This assumes pFlac->currentPCMFrame is sitting on byteRangeLo upon entry. */
  5779.  
  5780.     drflac_uint64 targetByte;
  5781.     drflac_uint64 pcmRangeLo = pFlac->totalPCMFrameCount;
  5782.     drflac_uint64 pcmRangeHi = 0;
  5783.     drflac_uint64 lastSuccessfulSeekOffset = (drflac_uint64)-1;
  5784.     drflac_uint64 closestSeekOffsetBeforeTargetPCMFrame = byteRangeLo;
  5785.     drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
  5786.  
  5787.     targetByte = byteRangeLo + (drflac_uint64)(((drflac_int64)((pcmFrameIndex - pFlac->currentPCMFrame) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO);
  5788.     if (targetByte > byteRangeHi) {
  5789.         targetByte = byteRangeHi;
  5790.     }
  5791.  
  5792.     for (;;) {
  5793.         if (drflac__seek_to_approximate_flac_frame_to_byte(pFlac, targetByte, byteRangeLo, byteRangeHi, &lastSuccessfulSeekOffset)) {
  5794.             /* We found a FLAC frame. We need to check if it contains the sample we're looking for. */
  5795.             drflac_uint64 newPCMRangeLo;
  5796.             drflac_uint64 newPCMRangeHi;
  5797.             drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &newPCMRangeLo, &newPCMRangeHi);
  5798.  
  5799.             /* If we selected the same frame, it means we should be pretty close. Just decode the rest. */
  5800.             if (pcmRangeLo == newPCMRangeLo) {
  5801.                 if (!drflac__seek_to_approximate_flac_frame_to_byte(pFlac, closestSeekOffsetBeforeTargetPCMFrame, closestSeekOffsetBeforeTargetPCMFrame, byteRangeHi, &lastSuccessfulSeekOffset)) {
  5802.                     break;  /* Failed to seek to closest frame. */
  5803.                 }
  5804.  
  5805.                 if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
  5806.                     return DRFLAC_TRUE;
  5807.                 } else {
  5808.                     break;  /* Failed to seek forward. */
  5809.                 }
  5810.             }
  5811.  
  5812.             pcmRangeLo = newPCMRangeLo;
  5813.             pcmRangeHi = newPCMRangeHi;
  5814.  
  5815.             if (pcmRangeLo <= pcmFrameIndex && pcmRangeHi >= pcmFrameIndex) {
  5816.                 /* The target PCM frame is in this FLAC frame. */
  5817.                 if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame) ) {
  5818.                     return DRFLAC_TRUE;
  5819.                 } else {
  5820.                     break;  /* Failed to seek to FLAC frame. */
  5821.                 }
  5822.             } else {
  5823.                 const float approxCompressionRatio = (drflac_int64)(lastSuccessfulSeekOffset - pFlac->firstFLACFramePosInBytes) / ((drflac_int64)(pcmRangeLo * pFlac->channels * pFlac->bitsPerSample)/8.0f);
  5824.  
  5825.                 if (pcmRangeLo > pcmFrameIndex) {
  5826.                     /* We seeked too far forward. We need to move our target byte backward and try again. */
  5827.                     byteRangeHi = lastSuccessfulSeekOffset;
  5828.                     if (byteRangeLo > byteRangeHi) {
  5829.                         byteRangeLo = byteRangeHi;
  5830.                     }
  5831.  
  5832.                     targetByte = byteRangeLo + ((byteRangeHi - byteRangeLo) / 2);
  5833.                     if (targetByte < byteRangeLo) {
  5834.                         targetByte = byteRangeLo;
  5835.                     }
  5836.                 } else /*if (pcmRangeHi < pcmFrameIndex)*/ {
  5837.                     /* We didn't seek far enough. We need to move our target byte forward and try again. */
  5838.  
  5839.                     /* If we're close enough we can just seek forward. */
  5840.                     if ((pcmFrameIndex - pcmRangeLo) < seekForwardThreshold) {
  5841.                         if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
  5842.                             return DRFLAC_TRUE;
  5843.                         } else {
  5844.                             break;  /* Failed to seek to FLAC frame. */
  5845.                         }
  5846.                     } else {
  5847.                         byteRangeLo = lastSuccessfulSeekOffset;
  5848.                         if (byteRangeHi < byteRangeLo) {
  5849.                             byteRangeHi = byteRangeLo;
  5850.                         }
  5851.  
  5852.                         targetByte = lastSuccessfulSeekOffset + (drflac_uint64)(((drflac_int64)((pcmFrameIndex-pcmRangeLo) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * approxCompressionRatio);
  5853.                         if (targetByte > byteRangeHi) {
  5854.                             targetByte = byteRangeHi;
  5855.                         }
  5856.  
  5857.                         if (closestSeekOffsetBeforeTargetPCMFrame < lastSuccessfulSeekOffset) {
  5858.                             closestSeekOffsetBeforeTargetPCMFrame = lastSuccessfulSeekOffset;
  5859.                         }
  5860.                     }
  5861.                 }
  5862.             }
  5863.         } else {
  5864.             /* Getting here is really bad. We just recover as best we can, but moving to the first frame in the stream, and then abort. */
  5865.             break;
  5866.         }
  5867.     }
  5868.  
  5869.     drflac__seek_to_first_frame(pFlac); /* <-- Try to recover. */
  5870.     return DRFLAC_FALSE;
  5871. }
  5872.  
  5873. static drflac_bool32 drflac__seek_to_pcm_frame__binary_search(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  5874. {
  5875.     drflac_uint64 byteRangeLo;
  5876.     drflac_uint64 byteRangeHi;
  5877.     drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
  5878.  
  5879.     /* Our algorithm currently assumes the FLAC stream is currently sitting at the start. */
  5880.     if (drflac__seek_to_first_frame(pFlac) == DRFLAC_FALSE) {
  5881.         return DRFLAC_FALSE;
  5882.     }
  5883.  
  5884.     /* If we're close enough to the start, just move to the start and seek forward. */
  5885.     if (pcmFrameIndex < seekForwardThreshold) {
  5886.         return drflac__seek_forward_by_pcm_frames(pFlac, pcmFrameIndex) == pcmFrameIndex;
  5887.     }
  5888.  
  5889.     /*
  5890.     Our starting byte range is the byte position of the first FLAC frame and the approximate end of the file as if it were completely uncompressed. This ensures
  5891.     the entire file is included, even though most of the time it'll exceed the end of the actual stream. This is OK as the frame searching logic will handle it.
  5892.     */
  5893.     byteRangeLo = pFlac->firstFLACFramePosInBytes;
  5894.     byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
  5895.  
  5896.     return drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi);
  5897. }
  5898. #endif  /* !DR_FLAC_NO_CRC */
  5899.  
  5900. static drflac_bool32 drflac__seek_to_pcm_frame__seek_table(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  5901. {
  5902.     drflac_uint32 iClosestSeekpoint = 0;
  5903.     drflac_bool32 isMidFrame = DRFLAC_FALSE;
  5904.     drflac_uint64 runningPCMFrameCount;
  5905.     drflac_uint32 iSeekpoint;
  5906.  
  5907.  
  5908.     DRFLAC_ASSERT(pFlac != NULL);
  5909.  
  5910.     if (pFlac->pSeekpoints == NULL || pFlac->seekpointCount == 0) {
  5911.         return DRFLAC_FALSE;
  5912.     }
  5913.  
  5914.     for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
  5915.         if (pFlac->pSeekpoints[iSeekpoint].firstPCMFrame >= pcmFrameIndex) {
  5916.             break;
  5917.         }
  5918.  
  5919.         iClosestSeekpoint = iSeekpoint;
  5920.     }
  5921.  
  5922.     /* There's been cases where the seek table contains only zeros. We need to do some basic validation on the closest seekpoint. */
  5923.     if (pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount == 0 || pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount > pFlac->maxBlockSizeInPCMFrames) {
  5924.         return DRFLAC_FALSE;
  5925.     }
  5926.     if (pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame > pFlac->totalPCMFrameCount && pFlac->totalPCMFrameCount > 0) {
  5927.         return DRFLAC_FALSE;
  5928.     }
  5929.  
  5930. #if !defined(DR_FLAC_NO_CRC)
  5931.     /* At this point we should know the closest seek point. We can use a binary search for this. We need to know the total sample count for this. */
  5932.     if (pFlac->totalPCMFrameCount > 0) {
  5933.         drflac_uint64 byteRangeLo;
  5934.         drflac_uint64 byteRangeHi;
  5935.  
  5936.         byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
  5937.         byteRangeLo = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset;
  5938.  
  5939.         /*
  5940.         If our closest seek point is not the last one, we only need to search between it and the next one. The section below calculates an appropriate starting
  5941.         value for byteRangeHi which will clamp it appropriately.
  5942.  
  5943.         Note that the next seekpoint must have an offset greater than the closest seekpoint because otherwise our binary search algorithm will break down. There
  5944.         have been cases where a seektable consists of seek points where every byte offset is set to 0 which causes problems. If this happens we need to abort.
  5945.         */
  5946.         if (iClosestSeekpoint < pFlac->seekpointCount-1) {
  5947.             drflac_uint32 iNextSeekpoint = iClosestSeekpoint + 1;
  5948.  
  5949.             /* Basic validation on the seekpoints to ensure they're usable. */
  5950.             if (pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset >= pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset || pFlac->pSeekpoints[iNextSeekpoint].pcmFrameCount == 0) {
  5951.                 return DRFLAC_FALSE;    /* The next seekpoint doesn't look right. The seek table cannot be trusted from here. Abort. */
  5952.             }
  5953.  
  5954.             if (pFlac->pSeekpoints[iNextSeekpoint].firstPCMFrame != (((drflac_uint64)0xFFFFFFFF << 32) | 0xFFFFFFFF)) { /* Make sure it's not a placeholder seekpoint. */
  5955.                 byteRangeHi = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset - 1; /* byteRangeHi must be zero based. */
  5956.             }
  5957.         }
  5958.  
  5959.         if (drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
  5960.             if (drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  5961.                 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
  5962.  
  5963.                 if (drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi)) {
  5964.                     return DRFLAC_TRUE;
  5965.                 }
  5966.             }
  5967.         }
  5968.     }
  5969. #endif  /* !DR_FLAC_NO_CRC */
  5970.  
  5971.     /* Getting here means we need to use a slower algorithm because the binary search method failed or cannot be used. */
  5972.  
  5973.     /*
  5974.     If we are seeking forward and the closest seekpoint is _before_ the current sample, we just seek forward from where we are. Otherwise we start seeking
  5975.     from the seekpoint's first sample.
  5976.     */
  5977.     if (pcmFrameIndex >= pFlac->currentPCMFrame && pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame <= pFlac->currentPCMFrame) {
  5978.         /* Optimized case. Just seek forward from where we are. */
  5979.         runningPCMFrameCount = pFlac->currentPCMFrame;
  5980.  
  5981.         /* The frame header for the first frame may not yet have been read. We need to do that if necessary. */
  5982.         if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  5983.             if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  5984.                 return DRFLAC_FALSE;
  5985.             }
  5986.         } else {
  5987.             isMidFrame = DRFLAC_TRUE;
  5988.         }
  5989.     } else {
  5990.         /* Slower case. Seek to the start of the seekpoint and then seek forward from there. */
  5991.         runningPCMFrameCount = pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame;
  5992.  
  5993.         if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
  5994.             return DRFLAC_FALSE;
  5995.         }
  5996.  
  5997.         /* Grab the frame the seekpoint is sitting on in preparation for the sample-exact seeking below. */
  5998.         if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  5999.             return DRFLAC_FALSE;
  6000.         }
  6001.     }
  6002.  
  6003.     for (;;) {
  6004.         drflac_uint64 pcmFrameCountInThisFLACFrame;
  6005.         drflac_uint64 firstPCMFrameInFLACFrame = 0;
  6006.         drflac_uint64 lastPCMFrameInFLACFrame = 0;
  6007.  
  6008.         drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
  6009.  
  6010.         pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
  6011.         if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
  6012.             /*
  6013.             The sample should be in this frame. We need to fully decode it, but if it's an invalid frame (a CRC mismatch) we need to pretend
  6014.             it never existed and keep iterating.
  6015.             */
  6016.             drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
  6017.  
  6018.             if (!isMidFrame) {
  6019.                 drflac_result result = drflac__decode_flac_frame(pFlac);
  6020.                 if (result == DRFLAC_SUCCESS) {
  6021.                     /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
  6022.                     return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;  /* <-- If this fails, something bad has happened (it should never fail). */
  6023.                 } else {
  6024.                     if (result == DRFLAC_CRC_MISMATCH) {
  6025.                         goto next_iteration;   /* CRC mismatch. Pretend this frame never existed. */
  6026.                     } else {
  6027.                         return DRFLAC_FALSE;
  6028.                     }
  6029.                 }
  6030.             } else {
  6031.                 /* We started seeking mid-frame which means we need to skip the frame decoding part. */
  6032.                 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  6033.             }
  6034.         } else {
  6035.             /*
  6036.             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
  6037.             frame never existed and leave the running sample count untouched.
  6038.             */
  6039.             if (!isMidFrame) {
  6040.                 drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
  6041.                 if (result == DRFLAC_SUCCESS) {
  6042.                     runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
  6043.                 } else {
  6044.                     if (result == DRFLAC_CRC_MISMATCH) {
  6045.                         goto next_iteration;   /* CRC mismatch. Pretend this frame never existed. */
  6046.                     } else {
  6047.                         return DRFLAC_FALSE;
  6048.                     }
  6049.                 }
  6050.             } else {
  6051.                 /*
  6052.                 We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with
  6053.                 drflac__seek_to_next_flac_frame() which only works if the decoder is sitting on the byte just after the frame header.
  6054.                 */
  6055.                 runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
  6056.                 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  6057.                 isMidFrame = DRFLAC_FALSE;
  6058.             }
  6059.  
  6060.             /* If we are seeking to the end of the file and we've just hit it, we're done. */
  6061.             if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
  6062.                 return DRFLAC_TRUE;
  6063.             }
  6064.         }
  6065.  
  6066.     next_iteration:
  6067.         /* Grab the next frame in preparation for the next iteration. */
  6068.         if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  6069.             return DRFLAC_FALSE;
  6070.         }
  6071.     }
  6072. }
  6073.  
  6074.  
  6075. #ifndef DR_FLAC_NO_OGG
  6076. typedef struct
  6077. {
  6078.     drflac_uint8 capturePattern[4];  /* Should be "OggS" */
  6079.     drflac_uint8 structureVersion;   /* Always 0. */
  6080.     drflac_uint8 headerType;
  6081.     drflac_uint64 granulePosition;
  6082.     drflac_uint32 serialNumber;
  6083.     drflac_uint32 sequenceNumber;
  6084.     drflac_uint32 checksum;
  6085.     drflac_uint8 segmentCount;
  6086.     drflac_uint8 segmentTable[255];
  6087. } drflac_ogg_page_header;
  6088. #endif
  6089.  
  6090. typedef struct
  6091. {
  6092.     drflac_read_proc onRead;
  6093.     drflac_seek_proc onSeek;
  6094.     drflac_meta_proc onMeta;
  6095.     drflac_container container;
  6096.     void* pUserData;
  6097.     void* pUserDataMD;
  6098.     drflac_uint32 sampleRate;
  6099.     drflac_uint8  channels;
  6100.     drflac_uint8  bitsPerSample;
  6101.     drflac_uint64 totalPCMFrameCount;
  6102.     drflac_uint16 maxBlockSizeInPCMFrames;
  6103.     drflac_uint64 runningFilePos;
  6104.     drflac_bool32 hasStreamInfoBlock;
  6105.     drflac_bool32 hasMetadataBlocks;
  6106.     drflac_bs bs;                           /* <-- A bit streamer is required for loading data during initialization. */
  6107.     drflac_frame_header firstFrameHeader;   /* <-- The header of the first frame that was read during relaxed initalization. Only set if there is no STREAMINFO block. */
  6108.  
  6109. #ifndef DR_FLAC_NO_OGG
  6110.     drflac_uint32 oggSerial;
  6111.     drflac_uint64 oggFirstBytePos;
  6112.     drflac_ogg_page_header oggBosHeader;
  6113. #endif
  6114. } drflac_init_info;
  6115.  
  6116. static DRFLAC_INLINE void drflac__decode_block_header(drflac_uint32 blockHeader, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
  6117. {
  6118.     blockHeader = drflac__be2host_32(blockHeader);
  6119.     *isLastBlock = (drflac_uint8)((blockHeader & 0x80000000UL) >> 31);
  6120.     *blockType   = (drflac_uint8)((blockHeader & 0x7F000000UL) >> 24);
  6121.     *blockSize   =                (blockHeader & 0x00FFFFFFUL);
  6122. }
  6123.  
  6124. 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)
  6125. {
  6126.     drflac_uint32 blockHeader;
  6127.  
  6128.     *blockSize = 0;
  6129.     if (onRead(pUserData, &blockHeader, 4) != 4) {
  6130.         return DRFLAC_FALSE;
  6131.     }
  6132.  
  6133.     drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize);
  6134.     return DRFLAC_TRUE;
  6135. }
  6136.  
  6137. static drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, drflac_streaminfo* pStreamInfo)
  6138. {
  6139.     drflac_uint32 blockSizes;
  6140.     drflac_uint64 frameSizes = 0;
  6141.     drflac_uint64 importantProps;
  6142.     drflac_uint8 md5[16];
  6143.  
  6144.     /* min/max block size. */
  6145.     if (onRead(pUserData, &blockSizes, 4) != 4) {
  6146.         return DRFLAC_FALSE;
  6147.     }
  6148.  
  6149.     /* min/max frame size. */
  6150.     if (onRead(pUserData, &frameSizes, 6) != 6) {
  6151.         return DRFLAC_FALSE;
  6152.     }
  6153.  
  6154.     /* Sample rate, channels, bits per sample and total sample count. */
  6155.     if (onRead(pUserData, &importantProps, 8) != 8) {
  6156.         return DRFLAC_FALSE;
  6157.     }
  6158.  
  6159.     /* MD5 */
  6160.     if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5)) {
  6161.         return DRFLAC_FALSE;
  6162.     }
  6163.  
  6164.     blockSizes     = drflac__be2host_32(blockSizes);
  6165.     frameSizes     = drflac__be2host_64(frameSizes);
  6166.     importantProps = drflac__be2host_64(importantProps);
  6167.  
  6168.     pStreamInfo->minBlockSizeInPCMFrames = (drflac_uint16)((blockSizes & 0xFFFF0000) >> 16);
  6169.     pStreamInfo->maxBlockSizeInPCMFrames = (drflac_uint16) (blockSizes & 0x0000FFFF);
  6170.     pStreamInfo->minFrameSizeInPCMFrames = (drflac_uint32)((frameSizes     &  (((drflac_uint64)0x00FFFFFF << 16) << 24)) >> 40);
  6171.     pStreamInfo->maxFrameSizeInPCMFrames = (drflac_uint32)((frameSizes     &  (((drflac_uint64)0x00FFFFFF << 16) <<  0)) >> 16);
  6172.     pStreamInfo->sampleRate              = (drflac_uint32)((importantProps &  (((drflac_uint64)0x000FFFFF << 16) << 28)) >> 44);
  6173.     pStreamInfo->channels                = (drflac_uint8 )((importantProps &  (((drflac_uint64)0x0000000E << 16) << 24)) >> 41) + 1;
  6174.     pStreamInfo->bitsPerSample           = (drflac_uint8 )((importantProps &  (((drflac_uint64)0x0000001F << 16) << 20)) >> 36) + 1;
  6175.     pStreamInfo->totalPCMFrameCount      =                ((importantProps & ((((drflac_uint64)0x0000000F << 16) << 16) | 0xFFFFFFFF)));
  6176.     DRFLAC_COPY_MEMORY(pStreamInfo->md5, md5, sizeof(md5));
  6177.  
  6178.     return DRFLAC_TRUE;
  6179. }
  6180.  
  6181.  
  6182. static void* drflac__malloc_default(size_t sz, void* pUserData)
  6183. {
  6184.     (void)pUserData;
  6185.     return DRFLAC_MALLOC(sz);
  6186. }
  6187.  
  6188. static void* drflac__realloc_default(void* p, size_t sz, void* pUserData)
  6189. {
  6190.     (void)pUserData;
  6191.     return DRFLAC_REALLOC(p, sz);
  6192. }
  6193.  
  6194. static void drflac__free_default(void* p, void* pUserData)
  6195. {
  6196.     (void)pUserData;
  6197.     DRFLAC_FREE(p);
  6198. }
  6199.  
  6200.  
  6201. static void* drflac__malloc_from_callbacks(size_t sz, const drflac_allocation_callbacks* pAllocationCallbacks)
  6202. {
  6203.     if (pAllocationCallbacks == NULL) {
  6204.         return NULL;
  6205.     }
  6206.  
  6207.     if (pAllocationCallbacks->onMalloc != NULL) {
  6208.         return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  6209.     }
  6210.  
  6211.     /* Try using realloc(). */
  6212.     if (pAllocationCallbacks->onRealloc != NULL) {
  6213.         return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
  6214.     }
  6215.  
  6216.     return NULL;
  6217. }
  6218.  
  6219. static void* drflac__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drflac_allocation_callbacks* pAllocationCallbacks)
  6220. {
  6221.     if (pAllocationCallbacks == NULL) {
  6222.         return NULL;
  6223.     }
  6224.  
  6225.     if (pAllocationCallbacks->onRealloc != NULL) {
  6226.         return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
  6227.     }
  6228.  
  6229.     /* Try emulating realloc() in terms of malloc()/free(). */
  6230.     if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
  6231.         void* p2;
  6232.  
  6233.         p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
  6234.         if (p2 == NULL) {
  6235.             return NULL;
  6236.         }
  6237.  
  6238.         if (p != NULL) {
  6239.             DRFLAC_COPY_MEMORY(p2, p, szOld);
  6240.             pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  6241.         }
  6242.  
  6243.         return p2;
  6244.     }
  6245.  
  6246.     return NULL;
  6247. }
  6248.  
  6249. static void drflac__free_from_callbacks(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
  6250. {
  6251.     if (p == NULL || pAllocationCallbacks == NULL) {
  6252.         return;
  6253.     }
  6254.  
  6255.     if (pAllocationCallbacks->onFree != NULL) {
  6256.         pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  6257.     }
  6258. }
  6259.  
  6260.  
  6261. static drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_uint64* pFirstFramePos, drflac_uint64* pSeektablePos, drflac_uint32* pSeektableSize, drflac_allocation_callbacks* pAllocationCallbacks)
  6262. {
  6263.     /*
  6264.     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
  6265.     we'll be sitting on byte 42.
  6266.     */
  6267.     drflac_uint64 runningFilePos = 42;
  6268.     drflac_uint64 seektablePos   = 0;
  6269.     drflac_uint32 seektableSize  = 0;
  6270.  
  6271.     for (;;) {
  6272.         drflac_metadata metadata;
  6273.         drflac_uint8 isLastBlock = 0;
  6274.         drflac_uint8 blockType;
  6275.         drflac_uint32 blockSize;
  6276.         if (drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize) == DRFLAC_FALSE) {
  6277.             return DRFLAC_FALSE;
  6278.         }
  6279.         runningFilePos += 4;
  6280.  
  6281.         metadata.type = blockType;
  6282.         metadata.pRawData = NULL;
  6283.         metadata.rawDataSize = 0;
  6284.  
  6285.         switch (blockType)
  6286.         {
  6287.             case DRFLAC_METADATA_BLOCK_TYPE_APPLICATION:
  6288.             {
  6289.                 if (blockSize < 4) {
  6290.                     return DRFLAC_FALSE;
  6291.                 }
  6292.  
  6293.                 if (onMeta) {
  6294.                     void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  6295.                     if (pRawData == NULL) {
  6296.                         return DRFLAC_FALSE;
  6297.                     }
  6298.  
  6299.                     if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  6300.                         drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6301.                         return DRFLAC_FALSE;
  6302.                     }
  6303.  
  6304.                     metadata.pRawData = pRawData;
  6305.                     metadata.rawDataSize = blockSize;
  6306.                     metadata.data.application.id       = drflac__be2host_32(*(drflac_uint32*)pRawData);
  6307.                     metadata.data.application.pData    = (const void*)((drflac_uint8*)pRawData + sizeof(drflac_uint32));
  6308.                     metadata.data.application.dataSize = blockSize - sizeof(drflac_uint32);
  6309.                     onMeta(pUserDataMD, &metadata);
  6310.  
  6311.                     drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6312.                 }
  6313.             } break;
  6314.  
  6315.             case DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE:
  6316.             {
  6317.                 seektablePos  = runningFilePos;
  6318.                 seektableSize = blockSize;
  6319.  
  6320.                 if (onMeta) {
  6321.                     drflac_uint32 iSeekpoint;
  6322.                     void* pRawData;
  6323.  
  6324.                     pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  6325.                     if (pRawData == NULL) {
  6326.                         return DRFLAC_FALSE;
  6327.                     }
  6328.  
  6329.                     if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  6330.                         drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6331.                         return DRFLAC_FALSE;
  6332.                     }
  6333.  
  6334.                     metadata.pRawData = pRawData;
  6335.                     metadata.rawDataSize = blockSize;
  6336.                     metadata.data.seektable.seekpointCount = blockSize/sizeof(drflac_seekpoint);
  6337.                     metadata.data.seektable.pSeekpoints = (const drflac_seekpoint*)pRawData;
  6338.  
  6339.                     /* Endian swap. */
  6340.                     for (iSeekpoint = 0; iSeekpoint < metadata.data.seektable.seekpointCount; ++iSeekpoint) {
  6341.                         drflac_seekpoint* pSeekpoint = (drflac_seekpoint*)pRawData + iSeekpoint;
  6342.                         pSeekpoint->firstPCMFrame   = drflac__be2host_64(pSeekpoint->firstPCMFrame);
  6343.                         pSeekpoint->flacFrameOffset = drflac__be2host_64(pSeekpoint->flacFrameOffset);
  6344.                         pSeekpoint->pcmFrameCount   = drflac__be2host_16(pSeekpoint->pcmFrameCount);
  6345.                     }
  6346.  
  6347.                     onMeta(pUserDataMD, &metadata);
  6348.  
  6349.                     drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6350.                 }
  6351.             } break;
  6352.  
  6353.             case DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT:
  6354.             {
  6355.                 if (blockSize < 8) {
  6356.                     return DRFLAC_FALSE;
  6357.                 }
  6358.  
  6359.                 if (onMeta) {
  6360.                     void* pRawData;
  6361.                     const char* pRunningData;
  6362.                     const char* pRunningDataEnd;
  6363.                     drflac_uint32 i;
  6364.  
  6365.                     pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  6366.                     if (pRawData == NULL) {
  6367.                         return DRFLAC_FALSE;
  6368.                     }
  6369.  
  6370.                     if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  6371.                         drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6372.                         return DRFLAC_FALSE;
  6373.                     }
  6374.  
  6375.                     metadata.pRawData = pRawData;
  6376.                     metadata.rawDataSize = blockSize;
  6377.  
  6378.                     pRunningData    = (const char*)pRawData;
  6379.                     pRunningDataEnd = (const char*)pRawData + blockSize;
  6380.  
  6381.                     metadata.data.vorbis_comment.vendorLength = drflac__le2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  6382.  
  6383.                     /* Need space for the rest of the block */
  6384.                     if ((pRunningDataEnd - pRunningData) - 4 < (drflac_int64)metadata.data.vorbis_comment.vendorLength) { /* <-- Note the order of operations to avoid overflow to a valid value */
  6385.                         drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6386.                         return DRFLAC_FALSE;
  6387.                     }
  6388.                     metadata.data.vorbis_comment.vendor       = pRunningData;                                            pRunningData += metadata.data.vorbis_comment.vendorLength;
  6389.                     metadata.data.vorbis_comment.commentCount = drflac__le2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  6390.  
  6391.                     /* Need space for 'commentCount' comments after the block, which at minimum is a drflac_uint32 per comment */
  6392.                     if ((pRunningDataEnd - pRunningData) / sizeof(drflac_uint32) < metadata.data.vorbis_comment.commentCount) { /* <-- Note the order of operations to avoid overflow to a valid value */
  6393.                         drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6394.                         return DRFLAC_FALSE;
  6395.                     }
  6396.                     metadata.data.vorbis_comment.pComments    = pRunningData;
  6397.  
  6398.                     /* Check that the comments section is valid before passing it to the callback */
  6399.                     for (i = 0; i < metadata.data.vorbis_comment.commentCount; ++i) {
  6400.                         drflac_uint32 commentLength;
  6401.  
  6402.                         if (pRunningDataEnd - pRunningData < 4) {
  6403.                             drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6404.                             return DRFLAC_FALSE;
  6405.                         }
  6406.  
  6407.                         commentLength = drflac__le2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  6408.                         if (pRunningDataEnd - pRunningData < (drflac_int64)commentLength) { /* <-- Note the order of operations to avoid overflow to a valid value */
  6409.                             drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6410.                             return DRFLAC_FALSE;
  6411.                         }
  6412.                         pRunningData += commentLength;
  6413.                     }
  6414.  
  6415.                     onMeta(pUserDataMD, &metadata);
  6416.  
  6417.                     drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6418.                 }
  6419.             } break;
  6420.  
  6421.             case DRFLAC_METADATA_BLOCK_TYPE_CUESHEET:
  6422.             {
  6423.                 if (blockSize < 396) {
  6424.                     return DRFLAC_FALSE;
  6425.                 }
  6426.  
  6427.                 if (onMeta) {
  6428.                     void* pRawData;
  6429.                     const char* pRunningData;
  6430.                     const char* pRunningDataEnd;
  6431.                     drflac_uint8 iTrack;
  6432.                     drflac_uint8 iIndex;
  6433.  
  6434.                     pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  6435.                     if (pRawData == NULL) {
  6436.                         return DRFLAC_FALSE;
  6437.                     }
  6438.  
  6439.                     if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  6440.                         drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6441.                         return DRFLAC_FALSE;
  6442.                     }
  6443.  
  6444.                     metadata.pRawData = pRawData;
  6445.                     metadata.rawDataSize = blockSize;
  6446.  
  6447.                     pRunningData    = (const char*)pRawData;
  6448.                     pRunningDataEnd = (const char*)pRawData + blockSize;
  6449.  
  6450.                     DRFLAC_COPY_MEMORY(metadata.data.cuesheet.catalog, pRunningData, 128);                              pRunningData += 128;
  6451.                     metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*(const drflac_uint64*)pRunningData); pRunningData += 8;
  6452.                     metadata.data.cuesheet.isCD              = (pRunningData[0] & 0x80) != 0;                           pRunningData += 259;
  6453.                     metadata.data.cuesheet.trackCount        = pRunningData[0];                                         pRunningData += 1;
  6454.                     metadata.data.cuesheet.pTrackData        = pRunningData;
  6455.  
  6456.                     /* Check that the cuesheet tracks are valid before passing it to the callback */
  6457.                     for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) {
  6458.                         drflac_uint8 indexCount;
  6459.                         drflac_uint32 indexPointSize;
  6460.  
  6461.                         if (pRunningDataEnd - pRunningData < 36) {
  6462.                             drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6463.                             return DRFLAC_FALSE;
  6464.                         }
  6465.  
  6466.                         /* Skip to the index point count */
  6467.                         pRunningData += 35;
  6468.                         indexCount = pRunningData[0]; pRunningData += 1;
  6469.                         indexPointSize = indexCount * sizeof(drflac_cuesheet_track_index);
  6470.                         if (pRunningDataEnd - pRunningData < (drflac_int64)indexPointSize) {
  6471.                             drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6472.                             return DRFLAC_FALSE;
  6473.                         }
  6474.  
  6475.                         /* Endian swap. */
  6476.                         for (iIndex = 0; iIndex < indexCount; ++iIndex) {
  6477.                             drflac_cuesheet_track_index* pTrack = (drflac_cuesheet_track_index*)pRunningData;
  6478.                             pRunningData += sizeof(drflac_cuesheet_track_index);
  6479.                             pTrack->offset = drflac__be2host_64(pTrack->offset);
  6480.                         }
  6481.                     }
  6482.  
  6483.                     onMeta(pUserDataMD, &metadata);
  6484.  
  6485.                     drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6486.                 }
  6487.             } break;
  6488.  
  6489.             case DRFLAC_METADATA_BLOCK_TYPE_PICTURE:
  6490.             {
  6491.                 if (blockSize < 32) {
  6492.                     return DRFLAC_FALSE;
  6493.                 }
  6494.  
  6495.                 if (onMeta) {
  6496.                     void* pRawData;
  6497.                     const char* pRunningData;
  6498.                     const char* pRunningDataEnd;
  6499.  
  6500.                     pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  6501.                     if (pRawData == NULL) {
  6502.                         return DRFLAC_FALSE;
  6503.                     }
  6504.  
  6505.                     if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  6506.                         drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6507.                         return DRFLAC_FALSE;
  6508.                     }
  6509.  
  6510.                     metadata.pRawData = pRawData;
  6511.                     metadata.rawDataSize = blockSize;
  6512.  
  6513.                     pRunningData    = (const char*)pRawData;
  6514.                     pRunningDataEnd = (const char*)pRawData + blockSize;
  6515.  
  6516.                     metadata.data.picture.type       = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  6517.                     metadata.data.picture.mimeLength = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  6518.  
  6519.                     /* Need space for the rest of the block */
  6520.                     if ((pRunningDataEnd - pRunningData) - 24 < (drflac_int64)metadata.data.picture.mimeLength) { /* <-- Note the order of operations to avoid overflow to a valid value */
  6521.                         drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6522.                         return DRFLAC_FALSE;
  6523.                     }
  6524.                     metadata.data.picture.mime              = pRunningData;                                            pRunningData += metadata.data.picture.mimeLength;
  6525.                     metadata.data.picture.descriptionLength = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  6526.  
  6527.                     /* Need space for the rest of the block */
  6528.                     if ((pRunningDataEnd - pRunningData) - 20 < (drflac_int64)metadata.data.picture.descriptionLength) { /* <-- Note the order of operations to avoid overflow to a valid value */
  6529.                         drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6530.                         return DRFLAC_FALSE;
  6531.                     }
  6532.                     metadata.data.picture.description     = pRunningData;                                            pRunningData += metadata.data.picture.descriptionLength;
  6533.                     metadata.data.picture.width           = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  6534.                     metadata.data.picture.height          = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  6535.                     metadata.data.picture.colorDepth      = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  6536.                     metadata.data.picture.indexColorCount = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  6537.                     metadata.data.picture.pictureDataSize = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  6538.                     metadata.data.picture.pPictureData    = (const drflac_uint8*)pRunningData;
  6539.  
  6540.                     /* Need space for the picture after the block */
  6541.                     if (pRunningDataEnd - pRunningData < (drflac_int64)metadata.data.picture.pictureDataSize) { /* <-- Note the order of operations to avoid overflow to a valid value */
  6542.                         drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6543.                         return DRFLAC_FALSE;
  6544.                     }
  6545.  
  6546.                     onMeta(pUserDataMD, &metadata);
  6547.  
  6548.                     drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6549.                 }
  6550.             } break;
  6551.  
  6552.             case DRFLAC_METADATA_BLOCK_TYPE_PADDING:
  6553.             {
  6554.                 if (onMeta) {
  6555.                     metadata.data.padding.unused = 0;
  6556.  
  6557.                     /* 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. */
  6558.                     if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
  6559.                         isLastBlock = DRFLAC_TRUE;  /* An error occurred while seeking. Attempt to recover by treating this as the last block which will in turn terminate the loop. */
  6560.                     } else {
  6561.                         onMeta(pUserDataMD, &metadata);
  6562.                     }
  6563.                 }
  6564.             } break;
  6565.  
  6566.             case DRFLAC_METADATA_BLOCK_TYPE_INVALID:
  6567.             {
  6568.                 /* Invalid chunk. Just skip over this one. */
  6569.                 if (onMeta) {
  6570.                     if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
  6571.                         isLastBlock = DRFLAC_TRUE;  /* An error occurred while seeking. Attempt to recover by treating this as the last block which will in turn terminate the loop. */
  6572.                     }
  6573.                 }
  6574.             } break;
  6575.  
  6576.             default:
  6577.             {
  6578.                 /*
  6579.                 It's an unknown chunk, but not necessarily invalid. There's a chance more metadata blocks might be defined later on, so we
  6580.                 can at the very least report the chunk to the application and let it look at the raw data.
  6581.                 */
  6582.                 if (onMeta) {
  6583.                     void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  6584.                     if (pRawData == NULL) {
  6585.                         return DRFLAC_FALSE;
  6586.                     }
  6587.  
  6588.                     if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  6589.                         drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6590.                         return DRFLAC_FALSE;
  6591.                     }
  6592.  
  6593.                     metadata.pRawData = pRawData;
  6594.                     metadata.rawDataSize = blockSize;
  6595.                     onMeta(pUserDataMD, &metadata);
  6596.  
  6597.                     drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  6598.                 }
  6599.             } break;
  6600.         }
  6601.  
  6602.         /* 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. */
  6603.         if (onMeta == NULL && blockSize > 0) {
  6604.             if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
  6605.                 isLastBlock = DRFLAC_TRUE;
  6606.             }
  6607.         }
  6608.  
  6609.         runningFilePos += blockSize;
  6610.         if (isLastBlock) {
  6611.             break;
  6612.         }
  6613.     }
  6614.  
  6615.     *pSeektablePos = seektablePos;
  6616.     *pSeektableSize = seektableSize;
  6617.     *pFirstFramePos = runningFilePos;
  6618.  
  6619.     return DRFLAC_TRUE;
  6620. }
  6621.  
  6622. static 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)
  6623. {
  6624.     /* Pre Condition: The bit stream should be sitting just past the 4-byte id header. */
  6625.  
  6626.     drflac_uint8 isLastBlock;
  6627.     drflac_uint8 blockType;
  6628.     drflac_uint32 blockSize;
  6629.  
  6630.     (void)onSeek;
  6631.  
  6632.     pInit->container = drflac_container_native;
  6633.  
  6634.     /* The first metadata block should be the STREAMINFO block. */
  6635.     if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
  6636.         return DRFLAC_FALSE;
  6637.     }
  6638.  
  6639.     if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
  6640.         if (!relaxed) {
  6641.             /* We're opening in strict mode and the first block is not the STREAMINFO block. Error. */
  6642.             return DRFLAC_FALSE;
  6643.         } else {
  6644.             /*
  6645.             Relaxed mode. To open from here we need to just find the first frame and set the sample rate, etc. to whatever is defined
  6646.             for that frame.
  6647.             */
  6648.             pInit->hasStreamInfoBlock = DRFLAC_FALSE;
  6649.             pInit->hasMetadataBlocks  = DRFLAC_FALSE;
  6650.  
  6651.             if (!drflac__read_next_flac_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) {
  6652.                 return DRFLAC_FALSE;    /* Couldn't find a frame. */
  6653.             }
  6654.  
  6655.             if (pInit->firstFrameHeader.bitsPerSample == 0) {
  6656.                 return DRFLAC_FALSE;    /* Failed to initialize because the first frame depends on the STREAMINFO block, which does not exist. */
  6657.             }
  6658.  
  6659.             pInit->sampleRate              = pInit->firstFrameHeader.sampleRate;
  6660.             pInit->channels                = drflac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment);
  6661.             pInit->bitsPerSample           = pInit->firstFrameHeader.bitsPerSample;
  6662.             pInit->maxBlockSizeInPCMFrames = 65535;   /* <-- See notes here: https://xiph.org/flac/format.html#metadata_block_streaminfo */
  6663.             return DRFLAC_TRUE;
  6664.         }
  6665.     } else {
  6666.         drflac_streaminfo streaminfo;
  6667.         if (!drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
  6668.             return DRFLAC_FALSE;
  6669.         }
  6670.  
  6671.         pInit->hasStreamInfoBlock      = DRFLAC_TRUE;
  6672.         pInit->sampleRate              = streaminfo.sampleRate;
  6673.         pInit->channels                = streaminfo.channels;
  6674.         pInit->bitsPerSample           = streaminfo.bitsPerSample;
  6675.         pInit->totalPCMFrameCount      = streaminfo.totalPCMFrameCount;
  6676.         pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames;    /* Don't care about the min block size - only the max (used for determining the size of the memory allocation). */
  6677.         pInit->hasMetadataBlocks       = !isLastBlock;
  6678.  
  6679.         if (onMeta) {
  6680.             drflac_metadata metadata;
  6681.             metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
  6682.             metadata.pRawData = NULL;
  6683.             metadata.rawDataSize = 0;
  6684.             metadata.data.streaminfo = streaminfo;
  6685.             onMeta(pUserDataMD, &metadata);
  6686.         }
  6687.  
  6688.         return DRFLAC_TRUE;
  6689.     }
  6690. }
  6691.  
  6692. #ifndef DR_FLAC_NO_OGG
  6693. #define DRFLAC_OGG_MAX_PAGE_SIZE            65307
  6694. #define DRFLAC_OGG_CAPTURE_PATTERN_CRC32    1605413199  /* CRC-32 of "OggS". */
  6695.  
  6696. typedef enum
  6697. {
  6698.     drflac_ogg_recover_on_crc_mismatch,
  6699.     drflac_ogg_fail_on_crc_mismatch
  6700. } drflac_ogg_crc_mismatch_recovery;
  6701.  
  6702. #ifndef DR_FLAC_NO_CRC
  6703. static drflac_uint32 drflac__crc32_table[] = {
  6704.     0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L,
  6705.     0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L,
  6706.     0x2608EDB8L, 0x22C9F00FL, 0x2F8AD6D6L, 0x2B4BCB61L,
  6707.     0x350C9B64L, 0x31CD86D3L, 0x3C8EA00AL, 0x384FBDBDL,
  6708.     0x4C11DB70L, 0x48D0C6C7L, 0x4593E01EL, 0x4152FDA9L,
  6709.     0x5F15ADACL, 0x5BD4B01BL, 0x569796C2L, 0x52568B75L,
  6710.     0x6A1936C8L, 0x6ED82B7FL, 0x639B0DA6L, 0x675A1011L,
  6711.     0x791D4014L, 0x7DDC5DA3L, 0x709F7B7AL, 0x745E66CDL,
  6712.     0x9823B6E0L, 0x9CE2AB57L, 0x91A18D8EL, 0x95609039L,
  6713.     0x8B27C03CL, 0x8FE6DD8BL, 0x82A5FB52L, 0x8664E6E5L,
  6714.     0xBE2B5B58L, 0xBAEA46EFL, 0xB7A96036L, 0xB3687D81L,
  6715.     0xAD2F2D84L, 0xA9EE3033L, 0xA4AD16EAL, 0xA06C0B5DL,
  6716.     0xD4326D90L, 0xD0F37027L, 0xDDB056FEL, 0xD9714B49L,
  6717.     0xC7361B4CL, 0xC3F706FBL, 0xCEB42022L, 0xCA753D95L,
  6718.     0xF23A8028L, 0xF6FB9D9FL, 0xFBB8BB46L, 0xFF79A6F1L,
  6719.     0xE13EF6F4L, 0xE5FFEB43L, 0xE8BCCD9AL, 0xEC7DD02DL,
  6720.     0x34867077L, 0x30476DC0L, 0x3D044B19L, 0x39C556AEL,
  6721.     0x278206ABL, 0x23431B1CL, 0x2E003DC5L, 0x2AC12072L,
  6722.     0x128E9DCFL, 0x164F8078L, 0x1B0CA6A1L, 0x1FCDBB16L,
  6723.     0x018AEB13L, 0x054BF6A4L, 0x0808D07DL, 0x0CC9CDCAL,
  6724.     0x7897AB07L, 0x7C56B6B0L, 0x71159069L, 0x75D48DDEL,
  6725.     0x6B93DDDBL, 0x6F52C06CL, 0x6211E6B5L, 0x66D0FB02L,
  6726.     0x5E9F46BFL, 0x5A5E5B08L, 0x571D7DD1L, 0x53DC6066L,
  6727.     0x4D9B3063L, 0x495A2DD4L, 0x44190B0DL, 0x40D816BAL,
  6728.     0xACA5C697L, 0xA864DB20L, 0xA527FDF9L, 0xA1E6E04EL,
  6729.     0xBFA1B04BL, 0xBB60ADFCL, 0xB6238B25L, 0xB2E29692L,
  6730.     0x8AAD2B2FL, 0x8E6C3698L, 0x832F1041L, 0x87EE0DF6L,
  6731.     0x99A95DF3L, 0x9D684044L, 0x902B669DL, 0x94EA7B2AL,
  6732.     0xE0B41DE7L, 0xE4750050L, 0xE9362689L, 0xEDF73B3EL,
  6733.     0xF3B06B3BL, 0xF771768CL, 0xFA325055L, 0xFEF34DE2L,
  6734.     0xC6BCF05FL, 0xC27DEDE8L, 0xCF3ECB31L, 0xCBFFD686L,
  6735.     0xD5B88683L, 0xD1799B34L, 0xDC3ABDEDL, 0xD8FBA05AL,
  6736.     0x690CE0EEL, 0x6DCDFD59L, 0x608EDB80L, 0x644FC637L,
  6737.     0x7A089632L, 0x7EC98B85L, 0x738AAD5CL, 0x774BB0EBL,
  6738.     0x4F040D56L, 0x4BC510E1L, 0x46863638L, 0x42472B8FL,
  6739.     0x5C007B8AL, 0x58C1663DL, 0x558240E4L, 0x51435D53L,
  6740.     0x251D3B9EL, 0x21DC2629L, 0x2C9F00F0L, 0x285E1D47L,
  6741.     0x36194D42L, 0x32D850F5L, 0x3F9B762CL, 0x3B5A6B9BL,
  6742.     0x0315D626L, 0x07D4CB91L, 0x0A97ED48L, 0x0E56F0FFL,
  6743.     0x1011A0FAL, 0x14D0BD4DL, 0x19939B94L, 0x1D528623L,
  6744.     0xF12F560EL, 0xF5EE4BB9L, 0xF8AD6D60L, 0xFC6C70D7L,
  6745.     0xE22B20D2L, 0xE6EA3D65L, 0xEBA91BBCL, 0xEF68060BL,
  6746.     0xD727BBB6L, 0xD3E6A601L, 0xDEA580D8L, 0xDA649D6FL,
  6747.     0xC423CD6AL, 0xC0E2D0DDL, 0xCDA1F604L, 0xC960EBB3L,
  6748.     0xBD3E8D7EL, 0xB9FF90C9L, 0xB4BCB610L, 0xB07DABA7L,
  6749.     0xAE3AFBA2L, 0xAAFBE615L, 0xA7B8C0CCL, 0xA379DD7BL,
  6750.     0x9B3660C6L, 0x9FF77D71L, 0x92B45BA8L, 0x9675461FL,
  6751.     0x8832161AL, 0x8CF30BADL, 0x81B02D74L, 0x857130C3L,
  6752.     0x5D8A9099L, 0x594B8D2EL, 0x5408ABF7L, 0x50C9B640L,
  6753.     0x4E8EE645L, 0x4A4FFBF2L, 0x470CDD2BL, 0x43CDC09CL,
  6754.     0x7B827D21L, 0x7F436096L, 0x7200464FL, 0x76C15BF8L,
  6755.     0x68860BFDL, 0x6C47164AL, 0x61043093L, 0x65C52D24L,
  6756.     0x119B4BE9L, 0x155A565EL, 0x18197087L, 0x1CD86D30L,
  6757.     0x029F3D35L, 0x065E2082L, 0x0B1D065BL, 0x0FDC1BECL,
  6758.     0x3793A651L, 0x3352BBE6L, 0x3E119D3FL, 0x3AD08088L,
  6759.     0x2497D08DL, 0x2056CD3AL, 0x2D15EBE3L, 0x29D4F654L,
  6760.     0xC5A92679L, 0xC1683BCEL, 0xCC2B1D17L, 0xC8EA00A0L,
  6761.     0xD6AD50A5L, 0xD26C4D12L, 0xDF2F6BCBL, 0xDBEE767CL,
  6762.     0xE3A1CBC1L, 0xE760D676L, 0xEA23F0AFL, 0xEEE2ED18L,
  6763.     0xF0A5BD1DL, 0xF464A0AAL, 0xF9278673L, 0xFDE69BC4L,
  6764.     0x89B8FD09L, 0x8D79E0BEL, 0x803AC667L, 0x84FBDBD0L,
  6765.     0x9ABC8BD5L, 0x9E7D9662L, 0x933EB0BBL, 0x97FFAD0CL,
  6766.     0xAFB010B1L, 0xAB710D06L, 0xA6322BDFL, 0xA2F33668L,
  6767.     0xBCB4666DL, 0xB8757BDAL, 0xB5365D03L, 0xB1F740B4L
  6768. };
  6769. #endif
  6770.  
  6771. static DRFLAC_INLINE drflac_uint32 drflac_crc32_byte(drflac_uint32 crc32, drflac_uint8 data)
  6772. {
  6773. #ifndef DR_FLAC_NO_CRC
  6774.     return (crc32 << 8) ^ drflac__crc32_table[(drflac_uint8)((crc32 >> 24) & 0xFF) ^ data];
  6775. #else
  6776.     (void)data;
  6777.     return crc32;
  6778. #endif
  6779. }
  6780.  
  6781. #if 0
  6782. static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint32(drflac_uint32 crc32, drflac_uint32 data)
  6783. {
  6784.     crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 24) & 0xFF));
  6785.     crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 16) & 0xFF));
  6786.     crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >>  8) & 0xFF));
  6787.     crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >>  0) & 0xFF));
  6788.     return crc32;
  6789. }
  6790.  
  6791. static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint64(drflac_uint32 crc32, drflac_uint64 data)
  6792. {
  6793.     crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 32) & 0xFFFFFFFF));
  6794.     crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >>  0) & 0xFFFFFFFF));
  6795.     return crc32;
  6796. }
  6797. #endif
  6798.  
  6799. static DRFLAC_INLINE drflac_uint32 drflac_crc32_buffer(drflac_uint32 crc32, drflac_uint8* pData, drflac_uint32 dataSize)
  6800. {
  6801.     /* This can be optimized. */
  6802.     drflac_uint32 i;
  6803.     for (i = 0; i < dataSize; ++i) {
  6804.         crc32 = drflac_crc32_byte(crc32, pData[i]);
  6805.     }
  6806.     return crc32;
  6807. }
  6808.  
  6809.  
  6810. static DRFLAC_INLINE drflac_bool32 drflac_ogg__is_capture_pattern(drflac_uint8 pattern[4])
  6811. {
  6812.     return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S';
  6813. }
  6814.  
  6815. static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_header_size(drflac_ogg_page_header* pHeader)
  6816. {
  6817.     return 27 + pHeader->segmentCount;
  6818. }
  6819.  
  6820. static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_body_size(drflac_ogg_page_header* pHeader)
  6821. {
  6822.     drflac_uint32 pageBodySize = 0;
  6823.     int i;
  6824.  
  6825.     for (i = 0; i < pHeader->segmentCount; ++i) {
  6826.         pageBodySize += pHeader->segmentTable[i];
  6827.     }
  6828.  
  6829.     return pageBodySize;
  6830. }
  6831.  
  6832. static 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)
  6833. {
  6834.     drflac_uint8 data[23];
  6835.     drflac_uint32 i;
  6836.  
  6837.     DRFLAC_ASSERT(*pCRC32 == DRFLAC_OGG_CAPTURE_PATTERN_CRC32);
  6838.  
  6839.     if (onRead(pUserData, data, 23) != 23) {
  6840.         return DRFLAC_AT_END;
  6841.     }
  6842.     *pBytesRead += 23;
  6843.  
  6844.     /*
  6845.     It's not actually used, but set the capture pattern to 'OggS' for completeness. Not doing this will cause static analysers to complain about
  6846.     us trying to access uninitialized data. We could alternatively just comment out this member of the drflac_ogg_page_header structure, but I
  6847.     like to have it map to the structure of the underlying data.
  6848.     */
  6849.     pHeader->capturePattern[0] = 'O';
  6850.     pHeader->capturePattern[1] = 'g';
  6851.     pHeader->capturePattern[2] = 'g';
  6852.     pHeader->capturePattern[3] = 'S';
  6853.  
  6854.     pHeader->structureVersion = data[0];
  6855.     pHeader->headerType       = data[1];
  6856.     DRFLAC_COPY_MEMORY(&pHeader->granulePosition, &data[ 2], 8);
  6857.     DRFLAC_COPY_MEMORY(&pHeader->serialNumber,    &data[10], 4);
  6858.     DRFLAC_COPY_MEMORY(&pHeader->sequenceNumber,  &data[14], 4);
  6859.     DRFLAC_COPY_MEMORY(&pHeader->checksum,        &data[18], 4);
  6860.     pHeader->segmentCount     = data[22];
  6861.  
  6862.     /* Calculate the CRC. Note that for the calculation the checksum part of the page needs to be set to 0. */
  6863.     data[18] = 0;
  6864.     data[19] = 0;
  6865.     data[20] = 0;
  6866.     data[21] = 0;
  6867.  
  6868.     for (i = 0; i < 23; ++i) {
  6869.         *pCRC32 = drflac_crc32_byte(*pCRC32, data[i]);
  6870.     }
  6871.  
  6872.  
  6873.     if (onRead(pUserData, pHeader->segmentTable, pHeader->segmentCount) != pHeader->segmentCount) {
  6874.         return DRFLAC_AT_END;
  6875.     }
  6876.     *pBytesRead += pHeader->segmentCount;
  6877.  
  6878.     for (i = 0; i < pHeader->segmentCount; ++i) {
  6879.         *pCRC32 = drflac_crc32_byte(*pCRC32, pHeader->segmentTable[i]);
  6880.     }
  6881.  
  6882.     return DRFLAC_SUCCESS;
  6883. }
  6884.  
  6885. static drflac_result drflac_ogg__read_page_header(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32)
  6886. {
  6887.     drflac_uint8 id[4];
  6888.  
  6889.     *pBytesRead = 0;
  6890.  
  6891.     if (onRead(pUserData, id, 4) != 4) {
  6892.         return DRFLAC_AT_END;
  6893.     }
  6894.     *pBytesRead += 4;
  6895.  
  6896.     /* We need to read byte-by-byte until we find the OggS capture pattern. */
  6897.     for (;;) {
  6898.         if (drflac_ogg__is_capture_pattern(id)) {
  6899.             drflac_result result;
  6900.  
  6901.             *pCRC32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
  6902.  
  6903.             result = drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32);
  6904.             if (result == DRFLAC_SUCCESS) {
  6905.                 return DRFLAC_SUCCESS;
  6906.             } else {
  6907.                 if (result == DRFLAC_CRC_MISMATCH) {
  6908.                     continue;
  6909.                 } else {
  6910.                     return result;
  6911.                 }
  6912.             }
  6913.         } else {
  6914.             /* The first 4 bytes did not equal the capture pattern. Read the next byte and try again. */
  6915.             id[0] = id[1];
  6916.             id[1] = id[2];
  6917.             id[2] = id[3];
  6918.             if (onRead(pUserData, &id[3], 1) != 1) {
  6919.                 return DRFLAC_AT_END;
  6920.             }
  6921.             *pBytesRead += 1;
  6922.         }
  6923.     }
  6924. }
  6925.  
  6926.  
  6927. /*
  6928. The main part of the Ogg encapsulation is the conversion from the physical Ogg bitstream to the native FLAC bitstream. It works
  6929. in three general stages: Ogg Physical Bitstream -> Ogg/FLAC Logical Bitstream -> FLAC Native Bitstream. dr_flac is designed
  6930. in such a way that the core sections assume everything is delivered in native format. Therefore, for each encapsulation type
  6931. 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
  6932. the physical Ogg bitstream are converted and delivered in native FLAC format.
  6933. */
  6934. typedef struct
  6935. {
  6936.     drflac_read_proc onRead;                /* The original onRead callback from drflac_open() and family. */
  6937.     drflac_seek_proc onSeek;                /* The original onSeek callback from drflac_open() and family. */
  6938.     void* pUserData;                        /* The user data passed on onRead and onSeek. This is the user data that was passed on drflac_open() and family. */
  6939.     drflac_uint64 currentBytePos;           /* The position of the byte we are sitting on in the physical byte stream. Used for efficient seeking. */
  6940.     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. */
  6941.     drflac_uint32 serialNumber;             /* The serial number of the FLAC audio pages. This is determined by the initial header page that was read during initialization. */
  6942.     drflac_ogg_page_header bosPageHeader;   /* Used for seeking. */
  6943.     drflac_ogg_page_header currentPageHeader;
  6944.     drflac_uint32 bytesRemainingInPage;
  6945.     drflac_uint32 pageDataSize;
  6946.     drflac_uint8 pageData[DRFLAC_OGG_MAX_PAGE_SIZE];
  6947. } drflac_oggbs; /* oggbs = Ogg Bitstream */
  6948.  
  6949. static size_t drflac_oggbs__read_physical(drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead)
  6950. {
  6951.     size_t bytesActuallyRead = oggbs->onRead(oggbs->pUserData, bufferOut, bytesToRead);
  6952.     oggbs->currentBytePos += bytesActuallyRead;
  6953.  
  6954.     return bytesActuallyRead;
  6955. }
  6956.  
  6957. static drflac_bool32 drflac_oggbs__seek_physical(drflac_oggbs* oggbs, drflac_uint64 offset, drflac_seek_origin origin)
  6958. {
  6959.     if (origin == drflac_seek_origin_start) {
  6960.         if (offset <= 0x7FFFFFFF) {
  6961.             if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_start)) {
  6962.                 return DRFLAC_FALSE;
  6963.             }
  6964.             oggbs->currentBytePos = offset;
  6965.  
  6966.             return DRFLAC_TRUE;
  6967.         } else {
  6968.             if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start)) {
  6969.                 return DRFLAC_FALSE;
  6970.             }
  6971.             oggbs->currentBytePos = offset;
  6972.  
  6973.             return drflac_oggbs__seek_physical(oggbs, offset - 0x7FFFFFFF, drflac_seek_origin_current);
  6974.         }
  6975.     } else {
  6976.         while (offset > 0x7FFFFFFF) {
  6977.             if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current)) {
  6978.                 return DRFLAC_FALSE;
  6979.             }
  6980.             oggbs->currentBytePos += 0x7FFFFFFF;
  6981.             offset -= 0x7FFFFFFF;
  6982.         }
  6983.  
  6984.         if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_current)) {    /* <-- Safe cast thanks to the loop above. */
  6985.             return DRFLAC_FALSE;
  6986.         }
  6987.         oggbs->currentBytePos += offset;
  6988.  
  6989.         return DRFLAC_TRUE;
  6990.     }
  6991. }
  6992.  
  6993. static drflac_bool32 drflac_oggbs__goto_next_page(drflac_oggbs* oggbs, drflac_ogg_crc_mismatch_recovery recoveryMethod)
  6994. {
  6995.     drflac_ogg_page_header header;
  6996.     for (;;) {
  6997.         drflac_uint32 crc32 = 0;
  6998.         drflac_uint32 bytesRead;
  6999.         drflac_uint32 pageBodySize;
  7000. #ifndef DR_FLAC_NO_CRC
  7001.         drflac_uint32 actualCRC32;
  7002. #endif
  7003.  
  7004.         if (drflac_ogg__read_page_header(oggbs->onRead, oggbs->pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
  7005.             return DRFLAC_FALSE;
  7006.         }
  7007.         oggbs->currentBytePos += bytesRead;
  7008.  
  7009.         pageBodySize = drflac_ogg__get_page_body_size(&header);
  7010.         if (pageBodySize > DRFLAC_OGG_MAX_PAGE_SIZE) {
  7011.             continue;   /* Invalid page size. Assume it's corrupted and just move to the next page. */
  7012.         }
  7013.  
  7014.         if (header.serialNumber != oggbs->serialNumber) {
  7015.             /* It's not a FLAC page. Skip it. */
  7016.             if (pageBodySize > 0 && !drflac_oggbs__seek_physical(oggbs, pageBodySize, drflac_seek_origin_current)) {
  7017.                 return DRFLAC_FALSE;
  7018.             }
  7019.             continue;
  7020.         }
  7021.  
  7022.  
  7023.         /* 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. */
  7024.         if (drflac_oggbs__read_physical(oggbs, oggbs->pageData, pageBodySize) != pageBodySize) {
  7025.             return DRFLAC_FALSE;
  7026.         }
  7027.         oggbs->pageDataSize = pageBodySize;
  7028.  
  7029. #ifndef DR_FLAC_NO_CRC
  7030.         actualCRC32 = drflac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize);
  7031.         if (actualCRC32 != header.checksum) {
  7032.             if (recoveryMethod == drflac_ogg_recover_on_crc_mismatch) {
  7033.                 continue;   /* CRC mismatch. Skip this page. */
  7034.             } else {
  7035.                 /*
  7036.                 Even though we are failing on a CRC mismatch, we still want our stream to be in a good state. Therefore we
  7037.                 go to the next valid page to ensure we're in a good state, but return false to let the caller know that the
  7038.                 seek did not fully complete.
  7039.                 */
  7040.                 drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch);
  7041.                 return DRFLAC_FALSE;
  7042.             }
  7043.         }
  7044. #else
  7045.         (void)recoveryMethod;   /* <-- Silence a warning. */
  7046. #endif
  7047.  
  7048.         oggbs->currentPageHeader = header;
  7049.         oggbs->bytesRemainingInPage = pageBodySize;
  7050.         return DRFLAC_TRUE;
  7051.     }
  7052. }
  7053.  
  7054. /* Function below is unused at the moment, but I might be re-adding it later. */
  7055. #if 0
  7056. static drflac_uint8 drflac_oggbs__get_current_segment_index(drflac_oggbs* oggbs, drflac_uint8* pBytesRemainingInSeg)
  7057. {
  7058.     drflac_uint32 bytesConsumedInPage = drflac_ogg__get_page_body_size(&oggbs->currentPageHeader) - oggbs->bytesRemainingInPage;
  7059.     drflac_uint8 iSeg = 0;
  7060.     drflac_uint32 iByte = 0;
  7061.     while (iByte < bytesConsumedInPage) {
  7062.         drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
  7063.         if (iByte + segmentSize > bytesConsumedInPage) {
  7064.             break;
  7065.         } else {
  7066.             iSeg += 1;
  7067.             iByte += segmentSize;
  7068.         }
  7069.     }
  7070.  
  7071.     *pBytesRemainingInSeg = oggbs->currentPageHeader.segmentTable[iSeg] - (drflac_uint8)(bytesConsumedInPage - iByte);
  7072.     return iSeg;
  7073. }
  7074.  
  7075. static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs)
  7076. {
  7077.     /* 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. */
  7078.     for (;;) {
  7079.         drflac_bool32 atEndOfPage = DRFLAC_FALSE;
  7080.  
  7081.         drflac_uint8 bytesRemainingInSeg;
  7082.         drflac_uint8 iFirstSeg = drflac_oggbs__get_current_segment_index(oggbs, &bytesRemainingInSeg);
  7083.  
  7084.         drflac_uint32 bytesToEndOfPacketOrPage = bytesRemainingInSeg;
  7085.         for (drflac_uint8 iSeg = iFirstSeg; iSeg < oggbs->currentPageHeader.segmentCount; ++iSeg) {
  7086.             drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
  7087.             if (segmentSize < 255) {
  7088.                 if (iSeg == oggbs->currentPageHeader.segmentCount-1) {
  7089.                     atEndOfPage = DRFLAC_TRUE;
  7090.                 }
  7091.  
  7092.                 break;
  7093.             }
  7094.  
  7095.             bytesToEndOfPacketOrPage += segmentSize;
  7096.         }
  7097.  
  7098.         /*
  7099.         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
  7100.         want to load the next page and keep searching for the end of the packet.
  7101.         */
  7102.         drflac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, drflac_seek_origin_current);
  7103.         oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage;
  7104.  
  7105.         if (atEndOfPage) {
  7106.             /*
  7107.             We're potentially at the next packet, but we need to check the next page first to be sure because the packet may
  7108.             straddle pages.
  7109.             */
  7110.             if (!drflac_oggbs__goto_next_page(oggbs)) {
  7111.                 return DRFLAC_FALSE;
  7112.             }
  7113.  
  7114.             /* If it's a fresh packet it most likely means we're at the next packet. */
  7115.             if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
  7116.                 return DRFLAC_TRUE;
  7117.             }
  7118.         } else {
  7119.             /* We're at the next packet. */
  7120.             return DRFLAC_TRUE;
  7121.         }
  7122.     }
  7123. }
  7124.  
  7125. static drflac_bool32 drflac_oggbs__seek_to_next_frame(drflac_oggbs* oggbs)
  7126. {
  7127.     /* The bitstream should be sitting on the first byte just after the header of the frame. */
  7128.  
  7129.     /* What we're actually doing here is seeking to the start of the next packet. */
  7130.     return drflac_oggbs__seek_to_next_packet(oggbs);
  7131. }
  7132. #endif
  7133.  
  7134. static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead)
  7135. {
  7136.     drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
  7137.     drflac_uint8* pRunningBufferOut = (drflac_uint8*)bufferOut;
  7138.     size_t bytesRead = 0;
  7139.  
  7140.     DRFLAC_ASSERT(oggbs != NULL);
  7141.     DRFLAC_ASSERT(pRunningBufferOut != NULL);
  7142.  
  7143.     /* Reading is done page-by-page. If we've run out of bytes in the page we need to move to the next one. */
  7144.     while (bytesRead < bytesToRead) {
  7145.         size_t bytesRemainingToRead = bytesToRead - bytesRead;
  7146.  
  7147.         if (oggbs->bytesRemainingInPage >= bytesRemainingToRead) {
  7148.             DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), bytesRemainingToRead);
  7149.             bytesRead += bytesRemainingToRead;
  7150.             oggbs->bytesRemainingInPage -= (drflac_uint32)bytesRemainingToRead;
  7151.             break;
  7152.         }
  7153.  
  7154.         /* If we get here it means some of the requested data is contained in the next pages. */
  7155.         if (oggbs->bytesRemainingInPage > 0) {
  7156.             DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage);
  7157.             bytesRead += oggbs->bytesRemainingInPage;
  7158.             pRunningBufferOut += oggbs->bytesRemainingInPage;
  7159.             oggbs->bytesRemainingInPage = 0;
  7160.         }
  7161.  
  7162.         DRFLAC_ASSERT(bytesRemainingToRead > 0);
  7163.         if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
  7164.             break;  /* Failed to go to the next page. Might have simply hit the end of the stream. */
  7165.         }
  7166.     }
  7167.  
  7168.     return bytesRead;
  7169. }
  7170.  
  7171. static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_seek_origin origin)
  7172. {
  7173.     drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
  7174.     int bytesSeeked = 0;
  7175.  
  7176.     DRFLAC_ASSERT(oggbs != NULL);
  7177.     DRFLAC_ASSERT(offset >= 0);  /* <-- Never seek backwards. */
  7178.  
  7179.     /* Seeking is always forward which makes things a lot simpler. */
  7180.     if (origin == drflac_seek_origin_start) {
  7181.         if (!drflac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, drflac_seek_origin_start)) {
  7182.             return DRFLAC_FALSE;
  7183.         }
  7184.  
  7185.         if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
  7186.             return DRFLAC_FALSE;
  7187.         }
  7188.  
  7189.         return drflac__on_seek_ogg(pUserData, offset, drflac_seek_origin_current);
  7190.     }
  7191.  
  7192.     DRFLAC_ASSERT(origin == drflac_seek_origin_current);
  7193.  
  7194.     while (bytesSeeked < offset) {
  7195.         int bytesRemainingToSeek = offset - bytesSeeked;
  7196.         DRFLAC_ASSERT(bytesRemainingToSeek >= 0);
  7197.  
  7198.         if (oggbs->bytesRemainingInPage >= (size_t)bytesRemainingToSeek) {
  7199.             bytesSeeked += bytesRemainingToSeek;
  7200.             (void)bytesSeeked;  /* <-- Silence a dead store warning emitted by Clang Static Analyzer. */
  7201.             oggbs->bytesRemainingInPage -= bytesRemainingToSeek;
  7202.             break;
  7203.         }
  7204.  
  7205.         /* If we get here it means some of the requested data is contained in the next pages. */
  7206.         if (oggbs->bytesRemainingInPage > 0) {
  7207.             bytesSeeked += (int)oggbs->bytesRemainingInPage;
  7208.             oggbs->bytesRemainingInPage = 0;
  7209.         }
  7210.  
  7211.         DRFLAC_ASSERT(bytesRemainingToSeek > 0);
  7212.         if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
  7213.             /* Failed to go to the next page. We either hit the end of the stream or had a CRC mismatch. */
  7214.             return DRFLAC_FALSE;
  7215.         }
  7216.     }
  7217.  
  7218.     return DRFLAC_TRUE;
  7219. }
  7220.  
  7221.  
  7222. static drflac_bool32 drflac_ogg__seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  7223. {
  7224.     drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
  7225.     drflac_uint64 originalBytePos;
  7226.     drflac_uint64 runningGranulePosition;
  7227.     drflac_uint64 runningFrameBytePos;
  7228.     drflac_uint64 runningPCMFrameCount;
  7229.  
  7230.     DRFLAC_ASSERT(oggbs != NULL);
  7231.  
  7232.     originalBytePos = oggbs->currentBytePos;   /* For recovery. Points to the OggS identifier. */
  7233.  
  7234.     /* First seek to the first frame. */
  7235.     if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes)) {
  7236.         return DRFLAC_FALSE;
  7237.     }
  7238.     oggbs->bytesRemainingInPage = 0;
  7239.  
  7240.     runningGranulePosition = 0;
  7241.     for (;;) {
  7242.         if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
  7243.             drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
  7244.             return DRFLAC_FALSE;   /* Never did find that sample... */
  7245.         }
  7246.  
  7247.         runningFrameBytePos = oggbs->currentBytePos - drflac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize;
  7248.         if (oggbs->currentPageHeader.granulePosition >= pcmFrameIndex) {
  7249.             break; /* The sample is somewhere in the previous page. */
  7250.         }
  7251.  
  7252.         /*
  7253.         At this point we know the sample is not in the previous page. It could possibly be in this page. For simplicity we
  7254.         disregard any pages that do not begin a fresh packet.
  7255.         */
  7256.         if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {    /* <-- Is it a fresh page? */
  7257.             if (oggbs->currentPageHeader.segmentTable[0] >= 2) {
  7258.                 drflac_uint8 firstBytesInPage[2];
  7259.                 firstBytesInPage[0] = oggbs->pageData[0];
  7260.                 firstBytesInPage[1] = oggbs->pageData[1];
  7261.  
  7262.                 if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) {    /* <-- Does the page begin with a frame's sync code? */
  7263.                     runningGranulePosition = oggbs->currentPageHeader.granulePosition;
  7264.                 }
  7265.  
  7266.                 continue;
  7267.             }
  7268.         }
  7269.     }
  7270.  
  7271.     /*
  7272.     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
  7273.     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
  7274.     a new frame. This property means that after we've seeked to the page we can immediately start looping over frames until
  7275.     we find the one containing the target sample.
  7276.     */
  7277.     if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, drflac_seek_origin_start)) {
  7278.         return DRFLAC_FALSE;
  7279.     }
  7280.     if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
  7281.         return DRFLAC_FALSE;
  7282.     }
  7283.  
  7284.     /*
  7285.     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
  7286.     looping over these frames until we find the one containing the sample we're after.
  7287.     */
  7288.     runningPCMFrameCount = runningGranulePosition;
  7289.     for (;;) {
  7290.         /*
  7291.         There are two ways to find the sample and seek past irrelevant frames:
  7292.           1) Use the native FLAC decoder.
  7293.           2) Use Ogg's framing system.
  7294.  
  7295.         Both of these options have their own pros and cons. Using the native FLAC decoder is slower because it needs to
  7296.         do a full decode of the frame. Using Ogg's framing system is faster, but more complicated and involves some code
  7297.         duplication for the decoding of frame headers.
  7298.  
  7299.         Another thing to consider is that using the Ogg framing system will perform direct seeking of the physical Ogg
  7300.         bitstream. This is important to consider because it means we cannot read data from the drflac_bs object using the
  7301.         standard drflac__*() APIs because that will read in extra data for its own internal caching which in turn breaks
  7302.         the positioning of the read pointer of the physical Ogg bitstream. Therefore, anything that would normally be read
  7303.         using the native FLAC decoding APIs, such as drflac__read_next_flac_frame_header(), need to be re-implemented so as to
  7304.         avoid the use of the drflac_bs object.
  7305.  
  7306.         Considering these issues, I have decided to use the slower native FLAC decoding method for the following reasons:
  7307.           1) Seeking is already partially accelerated using Ogg's paging system in the code block above.
  7308.           2) Seeking in an Ogg encapsulated FLAC stream is probably quite uncommon.
  7309.           3) Simplicity.
  7310.         */
  7311.         drflac_uint64 firstPCMFrameInFLACFrame = 0;
  7312.         drflac_uint64 lastPCMFrameInFLACFrame = 0;
  7313.         drflac_uint64 pcmFrameCountInThisFrame;
  7314.  
  7315.         if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  7316.             return DRFLAC_FALSE;
  7317.         }
  7318.  
  7319.         drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
  7320.  
  7321.         pcmFrameCountInThisFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
  7322.  
  7323.         /* If we are seeking to the end of the file and we've just hit it, we're done. */
  7324.         if (pcmFrameIndex == pFlac->totalPCMFrameCount && (runningPCMFrameCount + pcmFrameCountInThisFrame) == pFlac->totalPCMFrameCount) {
  7325.             drflac_result result = drflac__decode_flac_frame(pFlac);
  7326.             if (result == DRFLAC_SUCCESS) {
  7327.                 pFlac->currentPCMFrame = pcmFrameIndex;
  7328.                 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  7329.                 return DRFLAC_TRUE;
  7330.             } else {
  7331.                 return DRFLAC_FALSE;
  7332.             }
  7333.         }
  7334.  
  7335.         if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFrame)) {
  7336.             /*
  7337.             The sample should be in this FLAC frame. We need to fully decode it, however if it's an invalid frame (a CRC mismatch), we need to pretend
  7338.             it never existed and keep iterating.
  7339.             */
  7340.             drflac_result result = drflac__decode_flac_frame(pFlac);
  7341.             if (result == DRFLAC_SUCCESS) {
  7342.                 /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
  7343.                 drflac_uint64 pcmFramesToDecode = (size_t)(pcmFrameIndex - runningPCMFrameCount);    /* <-- Safe cast because the maximum number of samples in a frame is 65535. */
  7344.                 if (pcmFramesToDecode == 0) {
  7345.                     return DRFLAC_TRUE;
  7346.                 }
  7347.  
  7348.                 pFlac->currentPCMFrame = runningPCMFrameCount;
  7349.  
  7350.                 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;  /* <-- If this fails, something bad has happened (it should never fail). */
  7351.             } else {
  7352.                 if (result == DRFLAC_CRC_MISMATCH) {
  7353.                     continue;   /* CRC mismatch. Pretend this frame never existed. */
  7354.                 } else {
  7355.                     return DRFLAC_FALSE;
  7356.                 }
  7357.             }
  7358.         } else {
  7359.             /*
  7360.             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
  7361.             frame never existed and leave the running sample count untouched.
  7362.             */
  7363.             drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
  7364.             if (result == DRFLAC_SUCCESS) {
  7365.                 runningPCMFrameCount += pcmFrameCountInThisFrame;
  7366.             } else {
  7367.                 if (result == DRFLAC_CRC_MISMATCH) {
  7368.                     continue;   /* CRC mismatch. Pretend this frame never existed. */
  7369.                 } else {
  7370.                     return DRFLAC_FALSE;
  7371.                 }
  7372.             }
  7373.         }
  7374.     }
  7375. }
  7376.  
  7377.  
  7378.  
  7379. static 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)
  7380. {
  7381.     drflac_ogg_page_header header;
  7382.     drflac_uint32 crc32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
  7383.     drflac_uint32 bytesRead = 0;
  7384.  
  7385.     /* Pre Condition: The bit stream should be sitting just past the 4-byte OggS capture pattern. */
  7386.     (void)relaxed;
  7387.  
  7388.     pInit->container = drflac_container_ogg;
  7389.     pInit->oggFirstBytePos = 0;
  7390.  
  7391.     /*
  7392.     We'll get here if the first 4 bytes of the stream were the OggS capture pattern, however it doesn't necessarily mean the
  7393.     stream includes FLAC encoded audio. To check for this we need to scan the beginning-of-stream page markers and check if
  7394.     any match the FLAC specification. Important to keep in mind that the stream may be multiplexed.
  7395.     */
  7396.     if (drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
  7397.         return DRFLAC_FALSE;
  7398.     }
  7399.     pInit->runningFilePos += bytesRead;
  7400.  
  7401.     for (;;) {
  7402.         int pageBodySize;
  7403.  
  7404.         /* Break if we're past the beginning of stream page. */
  7405.         if ((header.headerType & 0x02) == 0) {
  7406.             return DRFLAC_FALSE;
  7407.         }
  7408.  
  7409.         /* Check if it's a FLAC header. */
  7410.         pageBodySize = drflac_ogg__get_page_body_size(&header);
  7411.         if (pageBodySize == 51) {   /* 51 = the lacing value of the FLAC header packet. */
  7412.             /* It could be a FLAC page... */
  7413.             drflac_uint32 bytesRemainingInPage = pageBodySize;
  7414.             drflac_uint8 packetType;
  7415.  
  7416.             if (onRead(pUserData, &packetType, 1) != 1) {
  7417.                 return DRFLAC_FALSE;
  7418.             }
  7419.  
  7420.             bytesRemainingInPage -= 1;
  7421.             if (packetType == 0x7F) {
  7422.                 /* Increasingly more likely to be a FLAC page... */
  7423.                 drflac_uint8 sig[4];
  7424.                 if (onRead(pUserData, sig, 4) != 4) {
  7425.                     return DRFLAC_FALSE;
  7426.                 }
  7427.  
  7428.                 bytesRemainingInPage -= 4;
  7429.                 if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') {
  7430.                     /* Almost certainly a FLAC page... */
  7431.                     drflac_uint8 mappingVersion[2];
  7432.                     if (onRead(pUserData, mappingVersion, 2) != 2) {
  7433.                         return DRFLAC_FALSE;
  7434.                     }
  7435.  
  7436.                     if (mappingVersion[0] != 1) {
  7437.                         return DRFLAC_FALSE;   /* Only supporting version 1.x of the Ogg mapping. */
  7438.                     }
  7439.  
  7440.                     /*
  7441.                     The next 2 bytes are the non-audio packets, not including this one. We don't care about this because we're going to
  7442.                     be handling it in a generic way based on the serial number and packet types.
  7443.                     */
  7444.                     if (!onSeek(pUserData, 2, drflac_seek_origin_current)) {
  7445.                         return DRFLAC_FALSE;
  7446.                     }
  7447.  
  7448.                     /* Expecting the native FLAC signature "fLaC". */
  7449.                     if (onRead(pUserData, sig, 4) != 4) {
  7450.                         return DRFLAC_FALSE;
  7451.                     }
  7452.  
  7453.                     if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C') {
  7454.                         /* The remaining data in the page should be the STREAMINFO block. */
  7455.                         drflac_streaminfo streaminfo;
  7456.                         drflac_uint8 isLastBlock;
  7457.                         drflac_uint8 blockType;
  7458.                         drflac_uint32 blockSize;
  7459.                         if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
  7460.                             return DRFLAC_FALSE;
  7461.                         }
  7462.  
  7463.                         if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
  7464.                             return DRFLAC_FALSE;    /* Invalid block type. First block must be the STREAMINFO block. */
  7465.                         }
  7466.  
  7467.                         if (drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
  7468.                             /* Success! */
  7469.                             pInit->hasStreamInfoBlock      = DRFLAC_TRUE;
  7470.                             pInit->sampleRate              = streaminfo.sampleRate;
  7471.                             pInit->channels                = streaminfo.channels;
  7472.                             pInit->bitsPerSample           = streaminfo.bitsPerSample;
  7473.                             pInit->totalPCMFrameCount      = streaminfo.totalPCMFrameCount;
  7474.                             pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames;
  7475.                             pInit->hasMetadataBlocks       = !isLastBlock;
  7476.  
  7477.                             if (onMeta) {
  7478.                                 drflac_metadata metadata;
  7479.                                 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
  7480.                                 metadata.pRawData = NULL;
  7481.                                 metadata.rawDataSize = 0;
  7482.                                 metadata.data.streaminfo = streaminfo;
  7483.                                 onMeta(pUserDataMD, &metadata);
  7484.                             }
  7485.  
  7486.                             pInit->runningFilePos  += pageBodySize;
  7487.                             pInit->oggFirstBytePos  = pInit->runningFilePos - 79;   /* Subtracting 79 will place us right on top of the "OggS" identifier of the FLAC bos page. */
  7488.                             pInit->oggSerial        = header.serialNumber;
  7489.                             pInit->oggBosHeader     = header;
  7490.                             break;
  7491.                         } else {
  7492.                             /* Failed to read STREAMINFO block. Aww, so close... */
  7493.                             return DRFLAC_FALSE;
  7494.                         }
  7495.                     } else {
  7496.                         /* Invalid file. */
  7497.                         return DRFLAC_FALSE;
  7498.                     }
  7499.                 } else {
  7500.                     /* Not a FLAC header. Skip it. */
  7501.                     if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current)) {
  7502.                         return DRFLAC_FALSE;
  7503.                     }
  7504.                 }
  7505.             } else {
  7506.                 /* Not a FLAC header. Seek past the entire page and move on to the next. */
  7507.                 if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current)) {
  7508.                     return DRFLAC_FALSE;
  7509.                 }
  7510.             }
  7511.         } else {
  7512.             if (!onSeek(pUserData, pageBodySize, drflac_seek_origin_current)) {
  7513.                 return DRFLAC_FALSE;
  7514.             }
  7515.         }
  7516.  
  7517.         pInit->runningFilePos += pageBodySize;
  7518.  
  7519.  
  7520.         /* Read the header of the next page. */
  7521.         if (drflac_ogg__read_page_header(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
  7522.             return DRFLAC_FALSE;
  7523.         }
  7524.         pInit->runningFilePos += bytesRead;
  7525.     }
  7526.  
  7527.     /*
  7528.     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
  7529.     packets in the FLAC logical stream contain the metadata. The only thing left to do in the initialization phase for Ogg is to create the
  7530.     Ogg bistream object.
  7531.     */
  7532.     pInit->hasMetadataBlocks = DRFLAC_TRUE;    /* <-- Always have at least VORBIS_COMMENT metadata block. */
  7533.     return DRFLAC_TRUE;
  7534. }
  7535. #endif
  7536.  
  7537. static 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)
  7538. {
  7539.     drflac_bool32 relaxed;
  7540.     drflac_uint8 id[4];
  7541.  
  7542.     if (pInit == NULL || onRead == NULL || onSeek == NULL) {
  7543.         return DRFLAC_FALSE;
  7544.     }
  7545.  
  7546.     DRFLAC_ZERO_MEMORY(pInit, sizeof(*pInit));
  7547.     pInit->onRead       = onRead;
  7548.     pInit->onSeek       = onSeek;
  7549.     pInit->onMeta       = onMeta;
  7550.     pInit->container    = container;
  7551.     pInit->pUserData    = pUserData;
  7552.     pInit->pUserDataMD  = pUserDataMD;
  7553.  
  7554.     pInit->bs.onRead    = onRead;
  7555.     pInit->bs.onSeek    = onSeek;
  7556.     pInit->bs.pUserData = pUserData;
  7557.     drflac__reset_cache(&pInit->bs);
  7558.  
  7559.  
  7560.     /* If the container is explicitly defined then we can try opening in relaxed mode. */
  7561.     relaxed = container != drflac_container_unknown;
  7562.  
  7563.     /* Skip over any ID3 tags. */
  7564.     for (;;) {
  7565.         if (onRead(pUserData, id, 4) != 4) {
  7566.             return DRFLAC_FALSE;    /* Ran out of data. */
  7567.         }
  7568.         pInit->runningFilePos += 4;
  7569.  
  7570.         if (id[0] == 'I' && id[1] == 'D' && id[2] == '3') {
  7571.             drflac_uint8 header[6];
  7572.             drflac_uint8 flags;
  7573.             drflac_uint32 headerSize;
  7574.  
  7575.             if (onRead(pUserData, header, 6) != 6) {
  7576.                 return DRFLAC_FALSE;    /* Ran out of data. */
  7577.             }
  7578.             pInit->runningFilePos += 6;
  7579.  
  7580.             flags = header[1];
  7581.  
  7582.             DRFLAC_COPY_MEMORY(&headerSize, header+2, 4);
  7583.             headerSize = drflac__unsynchsafe_32(drflac__be2host_32(headerSize));
  7584.             if (flags & 0x10) {
  7585.                 headerSize += 10;
  7586.             }
  7587.  
  7588.             if (!onSeek(pUserData, headerSize, drflac_seek_origin_current)) {
  7589.                 return DRFLAC_FALSE;    /* Failed to seek past the tag. */
  7590.             }
  7591.             pInit->runningFilePos += headerSize;
  7592.         } else {
  7593.             break;
  7594.         }
  7595.     }
  7596.  
  7597.     if (id[0] == 'f' && id[1] == 'L' && id[2] == 'a' && id[3] == 'C') {
  7598.         return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  7599.     }
  7600. #ifndef DR_FLAC_NO_OGG
  7601.     if (id[0] == 'O' && id[1] == 'g' && id[2] == 'g' && id[3] == 'S') {
  7602.         return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  7603.     }
  7604. #endif
  7605.  
  7606.     /* If we get here it means we likely don't have a header. Try opening in relaxed mode, if applicable. */
  7607.     if (relaxed) {
  7608.         if (container == drflac_container_native) {
  7609.             return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  7610.         }
  7611. #ifndef DR_FLAC_NO_OGG
  7612.         if (container == drflac_container_ogg) {
  7613.             return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  7614.         }
  7615. #endif
  7616.     }
  7617.  
  7618.     /* Unsupported container. */
  7619.     return DRFLAC_FALSE;
  7620. }
  7621.  
  7622. static void drflac__init_from_info(drflac* pFlac, const drflac_init_info* pInit)
  7623. {
  7624.     DRFLAC_ASSERT(pFlac != NULL);
  7625.     DRFLAC_ASSERT(pInit != NULL);
  7626.  
  7627.     DRFLAC_ZERO_MEMORY(pFlac, sizeof(*pFlac));
  7628.     pFlac->bs                      = pInit->bs;
  7629.     pFlac->onMeta                  = pInit->onMeta;
  7630.     pFlac->pUserDataMD             = pInit->pUserDataMD;
  7631.     pFlac->maxBlockSizeInPCMFrames = pInit->maxBlockSizeInPCMFrames;
  7632.     pFlac->sampleRate              = pInit->sampleRate;
  7633.     pFlac->channels                = (drflac_uint8)pInit->channels;
  7634.     pFlac->bitsPerSample           = (drflac_uint8)pInit->bitsPerSample;
  7635.     pFlac->totalPCMFrameCount      = pInit->totalPCMFrameCount;
  7636.     pFlac->container               = pInit->container;
  7637. }
  7638.  
  7639.  
  7640. static 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, const drflac_allocation_callbacks* pAllocationCallbacks)
  7641. {
  7642.     drflac_init_info init;
  7643.     drflac_uint32 allocationSize;
  7644.     drflac_uint32 wholeSIMDVectorCountPerChannel;
  7645.     drflac_uint32 decodedSamplesAllocationSize;
  7646. #ifndef DR_FLAC_NO_OGG
  7647.     drflac_oggbs oggbs;
  7648. #endif
  7649.     drflac_uint64 firstFramePos;
  7650.     drflac_uint64 seektablePos;
  7651.     drflac_uint32 seektableSize;
  7652.     drflac_allocation_callbacks allocationCallbacks;
  7653.     drflac* pFlac;
  7654.  
  7655.     /* CPU support first. */
  7656.     drflac__init_cpu_caps();
  7657.  
  7658.     if (!drflac__init_private(&init, onRead, onSeek, onMeta, container, pUserData, pUserDataMD)) {
  7659.         return NULL;
  7660.     }
  7661.  
  7662.     if (pAllocationCallbacks != NULL) {
  7663.         allocationCallbacks = *pAllocationCallbacks;
  7664.         if (allocationCallbacks.onFree == NULL || (allocationCallbacks.onMalloc == NULL && allocationCallbacks.onRealloc == NULL)) {
  7665.             return NULL;    /* Invalid allocation callbacks. */
  7666.         }
  7667.     } else {
  7668.         allocationCallbacks.pUserData = NULL;
  7669.         allocationCallbacks.onMalloc  = drflac__malloc_default;
  7670.         allocationCallbacks.onRealloc = drflac__realloc_default;
  7671.         allocationCallbacks.onFree    = drflac__free_default;
  7672.     }
  7673.  
  7674.  
  7675.     /*
  7676.     The size of the allocation for the drflac object needs to be large enough to fit the following:
  7677.       1) The main members of the drflac structure
  7678.       2) A block of memory large enough to store the decoded samples of the largest frame in the stream
  7679.       3) If the container is Ogg, a drflac_oggbs object
  7680.  
  7681.     The complicated part of the allocation is making sure there's enough room the decoded samples, taking into consideration
  7682.     the different SIMD instruction sets.
  7683.     */
  7684.     allocationSize = sizeof(drflac);
  7685.  
  7686.     /*
  7687.     The allocation size for decoded frames depends on the number of 32-bit integers that fit inside the largest SIMD vector
  7688.     we are supporting.
  7689.     */
  7690.     if ((init.maxBlockSizeInPCMFrames % (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) == 0) {
  7691.         wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32)));
  7692.     } else {
  7693.         wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) + 1;
  7694.     }
  7695.  
  7696.     decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * DRFLAC_MAX_SIMD_VECTOR_SIZE * init.channels;
  7697.  
  7698.     allocationSize += decodedSamplesAllocationSize;
  7699.     allocationSize += DRFLAC_MAX_SIMD_VECTOR_SIZE;  /* Allocate extra bytes to ensure we have enough for alignment. */
  7700.  
  7701. #ifndef DR_FLAC_NO_OGG
  7702.     /* There's additional data required for Ogg streams. */
  7703.     if (init.container == drflac_container_ogg) {
  7704.         allocationSize += sizeof(drflac_oggbs);
  7705.     }
  7706.  
  7707.     DRFLAC_ZERO_MEMORY(&oggbs, sizeof(oggbs));
  7708.     if (init.container == drflac_container_ogg) {
  7709.         oggbs.onRead = onRead;
  7710.         oggbs.onSeek = onSeek;
  7711.         oggbs.pUserData = pUserData;
  7712.         oggbs.currentBytePos = init.oggFirstBytePos;
  7713.         oggbs.firstBytePos = init.oggFirstBytePos;
  7714.         oggbs.serialNumber = init.oggSerial;
  7715.         oggbs.bosPageHeader = init.oggBosHeader;
  7716.         oggbs.bytesRemainingInPage = 0;
  7717.     }
  7718. #endif
  7719.  
  7720.     /*
  7721.     This part is a bit awkward. We need to load the seektable so that it can be referenced in-memory, but I want the drflac object to
  7722.     consist of only a single heap allocation. To this, the size of the seek table needs to be known, which we determine when reading
  7723.     and decoding the metadata.
  7724.     */
  7725.     firstFramePos = 42;   /* <-- We know we are at byte 42 at this point. */
  7726.     seektablePos  = 0;
  7727.     seektableSize = 0;
  7728.     if (init.hasMetadataBlocks) {
  7729.         drflac_read_proc onReadOverride = onRead;
  7730.         drflac_seek_proc onSeekOverride = onSeek;
  7731.         void* pUserDataOverride = pUserData;
  7732.  
  7733. #ifndef DR_FLAC_NO_OGG
  7734.         if (init.container == drflac_container_ogg) {
  7735.             onReadOverride = drflac__on_read_ogg;
  7736.             onSeekOverride = drflac__on_seek_ogg;
  7737.             pUserDataOverride = (void*)&oggbs;
  7738.         }
  7739. #endif
  7740.  
  7741.         if (!drflac__read_and_decode_metadata(onReadOverride, onSeekOverride, onMeta, pUserDataOverride, pUserDataMD, &firstFramePos, &seektablePos, &seektableSize, &allocationCallbacks)) {
  7742.             return NULL;
  7743.         }
  7744.  
  7745.         allocationSize += seektableSize;
  7746.     }
  7747.  
  7748.  
  7749.     pFlac = (drflac*)drflac__malloc_from_callbacks(allocationSize, &allocationCallbacks);
  7750.     if (pFlac == NULL) {
  7751.         return NULL;
  7752.     }
  7753.  
  7754.     drflac__init_from_info(pFlac, &init);
  7755.     pFlac->allocationCallbacks = allocationCallbacks;
  7756.     pFlac->pDecodedSamples = (drflac_int32*)drflac_align((size_t)pFlac->pExtraData, DRFLAC_MAX_SIMD_VECTOR_SIZE);
  7757.  
  7758. #ifndef DR_FLAC_NO_OGG
  7759.     if (init.container == drflac_container_ogg) {
  7760.         drflac_oggbs* pInternalOggbs = (drflac_oggbs*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize + seektableSize);
  7761.         *pInternalOggbs = oggbs;
  7762.  
  7763.         /* The Ogg bistream needs to be layered on top of the original bitstream. */
  7764.         pFlac->bs.onRead = drflac__on_read_ogg;
  7765.         pFlac->bs.onSeek = drflac__on_seek_ogg;
  7766.         pFlac->bs.pUserData = (void*)pInternalOggbs;
  7767.         pFlac->_oggbs = (void*)pInternalOggbs;
  7768.     }
  7769. #endif
  7770.  
  7771.     pFlac->firstFLACFramePosInBytes = firstFramePos;
  7772.  
  7773.     /* NOTE: Seektables are not currently compatible with Ogg encapsulation (Ogg has its own accelerated seeking system). I may change this later, so I'm leaving this here for now. */
  7774. #ifndef DR_FLAC_NO_OGG
  7775.     if (init.container == drflac_container_ogg)
  7776.     {
  7777.         pFlac->pSeekpoints = NULL;
  7778.         pFlac->seekpointCount = 0;
  7779.     }
  7780.     else
  7781. #endif
  7782.     {
  7783.         /* If we have a seektable we need to load it now, making sure we move back to where we were previously. */
  7784.         if (seektablePos != 0) {
  7785.             pFlac->seekpointCount = seektableSize / sizeof(*pFlac->pSeekpoints);
  7786.             pFlac->pSeekpoints = (drflac_seekpoint*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize);
  7787.  
  7788.             DRFLAC_ASSERT(pFlac->bs.onSeek != NULL);
  7789.             DRFLAC_ASSERT(pFlac->bs.onRead != NULL);
  7790.  
  7791.             /* Seek to the seektable, then just read directly into our seektable buffer. */
  7792.             if (pFlac->bs.onSeek(pFlac->bs.pUserData, (int)seektablePos, drflac_seek_origin_start)) {
  7793.                 if (pFlac->bs.onRead(pFlac->bs.pUserData, pFlac->pSeekpoints, seektableSize) == seektableSize) {
  7794.                     /* Endian swap. */
  7795.                     drflac_uint32 iSeekpoint;
  7796.                     for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
  7797.                         pFlac->pSeekpoints[iSeekpoint].firstPCMFrame   = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].firstPCMFrame);
  7798.                         pFlac->pSeekpoints[iSeekpoint].flacFrameOffset = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].flacFrameOffset);
  7799.                         pFlac->pSeekpoints[iSeekpoint].pcmFrameCount   = drflac__be2host_16(pFlac->pSeekpoints[iSeekpoint].pcmFrameCount);
  7800.                     }
  7801.                 } else {
  7802.                     /* Failed to read the seektable. Pretend we don't have one. */
  7803.                     pFlac->pSeekpoints = NULL;
  7804.                     pFlac->seekpointCount = 0;
  7805.                 }
  7806.  
  7807.                 /* We need to seek back to where we were. If this fails it's a critical error. */
  7808.                 if (!pFlac->bs.onSeek(pFlac->bs.pUserData, (int)pFlac->firstFLACFramePosInBytes, drflac_seek_origin_start)) {
  7809.                     drflac__free_from_callbacks(pFlac, &allocationCallbacks);
  7810.                     return NULL;
  7811.                 }
  7812.             } else {
  7813.                 /* Failed to seek to the seektable. Ominous sign, but for now we can just pretend we don't have one. */
  7814.                 pFlac->pSeekpoints = NULL;
  7815.                 pFlac->seekpointCount = 0;
  7816.             }
  7817.         }
  7818.     }
  7819.  
  7820.  
  7821.     /*
  7822.     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
  7823.     the first frame.
  7824.     */
  7825.     if (!init.hasStreamInfoBlock) {
  7826.         pFlac->currentFLACFrame.header = init.firstFrameHeader;
  7827.         for (;;) {
  7828.             drflac_result result = drflac__decode_flac_frame(pFlac);
  7829.             if (result == DRFLAC_SUCCESS) {
  7830.                 break;
  7831.             } else {
  7832.                 if (result == DRFLAC_CRC_MISMATCH) {
  7833.                     if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  7834.                         drflac__free_from_callbacks(pFlac, &allocationCallbacks);
  7835.                         return NULL;
  7836.                     }
  7837.                     continue;
  7838.                 } else {
  7839.                     drflac__free_from_callbacks(pFlac, &allocationCallbacks);
  7840.                     return NULL;
  7841.                 }
  7842.             }
  7843.         }
  7844.     }
  7845.  
  7846.     return pFlac;
  7847. }
  7848.  
  7849.  
  7850.  
  7851. #ifndef DR_FLAC_NO_STDIO
  7852. #include <stdio.h>
  7853. #include <wchar.h>      /* For wcslen(), wcsrtombs() */
  7854.  
  7855. /* drflac_result_from_errno() is only used for fopen() and wfopen() so putting it inside DR_WAV_NO_STDIO for now. If something else needs this later we can move it out. */
  7856. #include <errno.h>
  7857. static drflac_result drflac_result_from_errno(int e)
  7858. {
  7859.     switch (e)
  7860.     {
  7861.         case 0: return DRFLAC_SUCCESS;
  7862.     #ifdef EPERM
  7863.         case EPERM: return DRFLAC_INVALID_OPERATION;
  7864.     #endif
  7865.     #ifdef ENOENT
  7866.         case ENOENT: return DRFLAC_DOES_NOT_EXIST;
  7867.     #endif
  7868.     #ifdef ESRCH
  7869.         case ESRCH: return DRFLAC_DOES_NOT_EXIST;
  7870.     #endif
  7871.     #ifdef EINTR
  7872.         case EINTR: return DRFLAC_INTERRUPT;
  7873.     #endif
  7874.     #ifdef EIO
  7875.         case EIO: return DRFLAC_IO_ERROR;
  7876.     #endif
  7877.     #ifdef ENXIO
  7878.         case ENXIO: return DRFLAC_DOES_NOT_EXIST;
  7879.     #endif
  7880.     #ifdef E2BIG
  7881.         case E2BIG: return DRFLAC_INVALID_ARGS;
  7882.     #endif
  7883.     #ifdef ENOEXEC
  7884.         case ENOEXEC: return DRFLAC_INVALID_FILE;
  7885.     #endif
  7886.     #ifdef EBADF
  7887.         case EBADF: return DRFLAC_INVALID_FILE;
  7888.     #endif
  7889.     #ifdef ECHILD
  7890.         case ECHILD: return DRFLAC_ERROR;
  7891.     #endif
  7892.     #ifdef EAGAIN
  7893.         case EAGAIN: return DRFLAC_UNAVAILABLE;
  7894.     #endif
  7895.     #ifdef ENOMEM
  7896.         case ENOMEM: return DRFLAC_OUT_OF_MEMORY;
  7897.     #endif
  7898.     #ifdef EACCES
  7899.         case EACCES: return DRFLAC_ACCESS_DENIED;
  7900.     #endif
  7901.     #ifdef EFAULT
  7902.         case EFAULT: return DRFLAC_BAD_ADDRESS;
  7903.     #endif
  7904.     #ifdef ENOTBLK
  7905.         case ENOTBLK: return DRFLAC_ERROR;
  7906.     #endif
  7907.     #ifdef EBUSY
  7908.         case EBUSY: return DRFLAC_BUSY;
  7909.     #endif
  7910.     #ifdef EEXIST
  7911.         case EEXIST: return DRFLAC_ALREADY_EXISTS;
  7912.     #endif
  7913.     #ifdef EXDEV
  7914.         case EXDEV: return DRFLAC_ERROR;
  7915.     #endif
  7916.     #ifdef ENODEV
  7917.         case ENODEV: return DRFLAC_DOES_NOT_EXIST;
  7918.     #endif
  7919.     #ifdef ENOTDIR
  7920.         case ENOTDIR: return DRFLAC_NOT_DIRECTORY;
  7921.     #endif
  7922.     #ifdef EISDIR
  7923.         case EISDIR: return DRFLAC_IS_DIRECTORY;
  7924.     #endif
  7925.     #ifdef EINVAL
  7926.         case EINVAL: return DRFLAC_INVALID_ARGS;
  7927.     #endif
  7928.     #ifdef ENFILE
  7929.         case ENFILE: return DRFLAC_TOO_MANY_OPEN_FILES;
  7930.     #endif
  7931.     #ifdef EMFILE
  7932.         case EMFILE: return DRFLAC_TOO_MANY_OPEN_FILES;
  7933.     #endif
  7934.     #ifdef ENOTTY
  7935.         case ENOTTY: return DRFLAC_INVALID_OPERATION;
  7936.     #endif
  7937.     #ifdef ETXTBSY
  7938.         case ETXTBSY: return DRFLAC_BUSY;
  7939.     #endif
  7940.     #ifdef EFBIG
  7941.         case EFBIG: return DRFLAC_TOO_BIG;
  7942.     #endif
  7943.     #ifdef ENOSPC
  7944.         case ENOSPC: return DRFLAC_NO_SPACE;
  7945.     #endif
  7946.     #ifdef ESPIPE
  7947.         case ESPIPE: return DRFLAC_BAD_SEEK;
  7948.     #endif
  7949.     #ifdef EROFS
  7950.         case EROFS: return DRFLAC_ACCESS_DENIED;
  7951.     #endif
  7952.     #ifdef EMLINK
  7953.         case EMLINK: return DRFLAC_TOO_MANY_LINKS;
  7954.     #endif
  7955.     #ifdef EPIPE
  7956.         case EPIPE: return DRFLAC_BAD_PIPE;
  7957.     #endif
  7958.     #ifdef EDOM
  7959.         case EDOM: return DRFLAC_OUT_OF_RANGE;
  7960.     #endif
  7961.     #ifdef ERANGE
  7962.         case ERANGE: return DRFLAC_OUT_OF_RANGE;
  7963.     #endif
  7964.     #ifdef EDEADLK
  7965.         case EDEADLK: return DRFLAC_DEADLOCK;
  7966.     #endif
  7967.     #ifdef ENAMETOOLONG
  7968.         case ENAMETOOLONG: return DRFLAC_PATH_TOO_LONG;
  7969.     #endif
  7970.     #ifdef ENOLCK
  7971.         case ENOLCK: return DRFLAC_ERROR;
  7972.     #endif
  7973.     #ifdef ENOSYS
  7974.         case ENOSYS: return DRFLAC_NOT_IMPLEMENTED;
  7975.     #endif
  7976.     #ifdef ENOTEMPTY
  7977.         case ENOTEMPTY: return DRFLAC_DIRECTORY_NOT_EMPTY;
  7978.     #endif
  7979.     #ifdef ELOOP
  7980.         case ELOOP: return DRFLAC_TOO_MANY_LINKS;
  7981.     #endif
  7982.     #ifdef ENOMSG
  7983.         case ENOMSG: return DRFLAC_NO_MESSAGE;
  7984.     #endif
  7985.     #ifdef EIDRM
  7986.         case EIDRM: return DRFLAC_ERROR;
  7987.     #endif
  7988.     #ifdef ECHRNG
  7989.         case ECHRNG: return DRFLAC_ERROR;
  7990.     #endif
  7991.     #ifdef EL2NSYNC
  7992.         case EL2NSYNC: return DRFLAC_ERROR;
  7993.     #endif
  7994.     #ifdef EL3HLT
  7995.         case EL3HLT: return DRFLAC_ERROR;
  7996.     #endif
  7997.     #ifdef EL3RST
  7998.         case EL3RST: return DRFLAC_ERROR;
  7999.     #endif
  8000.     #ifdef ELNRNG
  8001.         case ELNRNG: return DRFLAC_OUT_OF_RANGE;
  8002.     #endif
  8003.     #ifdef EUNATCH
  8004.         case EUNATCH: return DRFLAC_ERROR;
  8005.     #endif
  8006.     #ifdef ENOCSI
  8007.         case ENOCSI: return DRFLAC_ERROR;
  8008.     #endif
  8009.     #ifdef EL2HLT
  8010.         case EL2HLT: return DRFLAC_ERROR;
  8011.     #endif
  8012.     #ifdef EBADE
  8013.         case EBADE: return DRFLAC_ERROR;
  8014.     #endif
  8015.     #ifdef EBADR
  8016.         case EBADR: return DRFLAC_ERROR;
  8017.     #endif
  8018.     #ifdef EXFULL
  8019.         case EXFULL: return DRFLAC_ERROR;
  8020.     #endif
  8021.     #ifdef ENOANO
  8022.         case ENOANO: return DRFLAC_ERROR;
  8023.     #endif
  8024.     #ifdef EBADRQC
  8025.         case EBADRQC: return DRFLAC_ERROR;
  8026.     #endif
  8027.     #ifdef EBADSLT
  8028.         case EBADSLT: return DRFLAC_ERROR;
  8029.     #endif
  8030.     #ifdef EBFONT
  8031.         case EBFONT: return DRFLAC_INVALID_FILE;
  8032.     #endif
  8033.     #ifdef ENOSTR
  8034.         case ENOSTR: return DRFLAC_ERROR;
  8035.     #endif
  8036.     #ifdef ENODATA
  8037.         case ENODATA: return DRFLAC_NO_DATA_AVAILABLE;
  8038.     #endif
  8039.     #ifdef ETIME
  8040.         case ETIME: return DRFLAC_TIMEOUT;
  8041.     #endif
  8042.     #ifdef ENOSR
  8043.         case ENOSR: return DRFLAC_NO_DATA_AVAILABLE;
  8044.     #endif
  8045.     #ifdef ENONET
  8046.         case ENONET: return DRFLAC_NO_NETWORK;
  8047.     #endif
  8048.     #ifdef ENOPKG
  8049.         case ENOPKG: return DRFLAC_ERROR;
  8050.     #endif
  8051.     #ifdef EREMOTE
  8052.         case EREMOTE: return DRFLAC_ERROR;
  8053.     #endif
  8054.     #ifdef ENOLINK
  8055.         case ENOLINK: return DRFLAC_ERROR;
  8056.     #endif
  8057.     #ifdef EADV
  8058.         case EADV: return DRFLAC_ERROR;
  8059.     #endif
  8060.     #ifdef ESRMNT
  8061.         case ESRMNT: return DRFLAC_ERROR;
  8062.     #endif
  8063.     #ifdef ECOMM
  8064.         case ECOMM: return DRFLAC_ERROR;
  8065.     #endif
  8066.     #ifdef EPROTO
  8067.         case EPROTO: return DRFLAC_ERROR;
  8068.     #endif
  8069.     #ifdef EMULTIHOP
  8070.         case EMULTIHOP: return DRFLAC_ERROR;
  8071.     #endif
  8072.     #ifdef EDOTDOT
  8073.         case EDOTDOT: return DRFLAC_ERROR;
  8074.     #endif
  8075.     #ifdef EBADMSG
  8076.         case EBADMSG: return DRFLAC_BAD_MESSAGE;
  8077.     #endif
  8078.     #ifdef EOVERFLOW
  8079.         case EOVERFLOW: return DRFLAC_TOO_BIG;
  8080.     #endif
  8081.     #ifdef ENOTUNIQ
  8082.         case ENOTUNIQ: return DRFLAC_NOT_UNIQUE;
  8083.     #endif
  8084.     #ifdef EBADFD
  8085.         case EBADFD: return DRFLAC_ERROR;
  8086.     #endif
  8087.     #ifdef EREMCHG
  8088.         case EREMCHG: return DRFLAC_ERROR;
  8089.     #endif
  8090.     #ifdef ELIBACC
  8091.         case ELIBACC: return DRFLAC_ACCESS_DENIED;
  8092.     #endif
  8093.     #ifdef ELIBBAD
  8094.         case ELIBBAD: return DRFLAC_INVALID_FILE;
  8095.     #endif
  8096.     #ifdef ELIBSCN
  8097.         case ELIBSCN: return DRFLAC_INVALID_FILE;
  8098.     #endif
  8099.     #ifdef ELIBMAX
  8100.         case ELIBMAX: return DRFLAC_ERROR;
  8101.     #endif
  8102.     #ifdef ELIBEXEC
  8103.         case ELIBEXEC: return DRFLAC_ERROR;
  8104.     #endif
  8105.     #ifdef EILSEQ
  8106.         case EILSEQ: return DRFLAC_INVALID_DATA;
  8107.     #endif
  8108.     #ifdef ERESTART
  8109.         case ERESTART: return DRFLAC_ERROR;
  8110.     #endif
  8111.     #ifdef ESTRPIPE
  8112.         case ESTRPIPE: return DRFLAC_ERROR;
  8113.     #endif
  8114.     #ifdef EUSERS
  8115.         case EUSERS: return DRFLAC_ERROR;
  8116.     #endif
  8117.     #ifdef ENOTSOCK
  8118.         case ENOTSOCK: return DRFLAC_NOT_SOCKET;
  8119.     #endif
  8120.     #ifdef EDESTADDRREQ
  8121.         case EDESTADDRREQ: return DRFLAC_NO_ADDRESS;
  8122.     #endif
  8123.     #ifdef EMSGSIZE
  8124.         case EMSGSIZE: return DRFLAC_TOO_BIG;
  8125.     #endif
  8126.     #ifdef EPROTOTYPE
  8127.         case EPROTOTYPE: return DRFLAC_BAD_PROTOCOL;
  8128.     #endif
  8129.     #ifdef ENOPROTOOPT
  8130.         case ENOPROTOOPT: return DRFLAC_PROTOCOL_UNAVAILABLE;
  8131.     #endif
  8132.     #ifdef EPROTONOSUPPORT
  8133.         case EPROTONOSUPPORT: return DRFLAC_PROTOCOL_NOT_SUPPORTED;
  8134.     #endif
  8135.     #ifdef ESOCKTNOSUPPORT
  8136.         case ESOCKTNOSUPPORT: return DRFLAC_SOCKET_NOT_SUPPORTED;
  8137.     #endif
  8138.     #ifdef EOPNOTSUPP
  8139.         case EOPNOTSUPP: return DRFLAC_INVALID_OPERATION;
  8140.     #endif
  8141.     #ifdef EPFNOSUPPORT
  8142.         case EPFNOSUPPORT: return DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED;
  8143.     #endif
  8144.     #ifdef EAFNOSUPPORT
  8145.         case EAFNOSUPPORT: return DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED;
  8146.     #endif
  8147.     #ifdef EADDRINUSE
  8148.         case EADDRINUSE: return DRFLAC_ALREADY_IN_USE;
  8149.     #endif
  8150.     #ifdef EADDRNOTAVAIL
  8151.         case EADDRNOTAVAIL: return DRFLAC_ERROR;
  8152.     #endif
  8153.     #ifdef ENETDOWN
  8154.         case ENETDOWN: return DRFLAC_NO_NETWORK;
  8155.     #endif
  8156.     #ifdef ENETUNREACH
  8157.         case ENETUNREACH: return DRFLAC_NO_NETWORK;
  8158.     #endif
  8159.     #ifdef ENETRESET
  8160.         case ENETRESET: return DRFLAC_NO_NETWORK;
  8161.     #endif
  8162.     #ifdef ECONNABORTED
  8163.         case ECONNABORTED: return DRFLAC_NO_NETWORK;
  8164.     #endif
  8165.     #ifdef ECONNRESET
  8166.         case ECONNRESET: return DRFLAC_CONNECTION_RESET;
  8167.     #endif
  8168.     #ifdef ENOBUFS
  8169.         case ENOBUFS: return DRFLAC_NO_SPACE;
  8170.     #endif
  8171.     #ifdef EISCONN
  8172.         case EISCONN: return DRFLAC_ALREADY_CONNECTED;
  8173.     #endif
  8174.     #ifdef ENOTCONN
  8175.         case ENOTCONN: return DRFLAC_NOT_CONNECTED;
  8176.     #endif
  8177.     #ifdef ESHUTDOWN
  8178.         case ESHUTDOWN: return DRFLAC_ERROR;
  8179.     #endif
  8180.     #ifdef ETOOMANYREFS
  8181.         case ETOOMANYREFS: return DRFLAC_ERROR;
  8182.     #endif
  8183.     #ifdef ETIMEDOUT
  8184.         case ETIMEDOUT: return DRFLAC_TIMEOUT;
  8185.     #endif
  8186.     #ifdef ECONNREFUSED
  8187.         case ECONNREFUSED: return DRFLAC_CONNECTION_REFUSED;
  8188.     #endif
  8189.     #ifdef EHOSTDOWN
  8190.         case EHOSTDOWN: return DRFLAC_NO_HOST;
  8191.     #endif
  8192.     #ifdef EHOSTUNREACH
  8193.         case EHOSTUNREACH: return DRFLAC_NO_HOST;
  8194.     #endif
  8195.     #ifdef EALREADY
  8196.         case EALREADY: return DRFLAC_IN_PROGRESS;
  8197.     #endif
  8198.     #ifdef EINPROGRESS
  8199.         case EINPROGRESS: return DRFLAC_IN_PROGRESS;
  8200.     #endif
  8201.     #ifdef ESTALE
  8202.         case ESTALE: return DRFLAC_INVALID_FILE;
  8203.     #endif
  8204.     #ifdef EUCLEAN
  8205.         case EUCLEAN: return DRFLAC_ERROR;
  8206.     #endif
  8207.     #ifdef ENOTNAM
  8208.         case ENOTNAM: return DRFLAC_ERROR;
  8209.     #endif
  8210.     #ifdef ENAVAIL
  8211.         case ENAVAIL: return DRFLAC_ERROR;
  8212.     #endif
  8213.     #ifdef EISNAM
  8214.         case EISNAM: return DRFLAC_ERROR;
  8215.     #endif
  8216.     #ifdef EREMOTEIO
  8217.         case EREMOTEIO: return DRFLAC_IO_ERROR;
  8218.     #endif
  8219.     #ifdef EDQUOT
  8220.         case EDQUOT: return DRFLAC_NO_SPACE;
  8221.     #endif
  8222.     #ifdef ENOMEDIUM
  8223.         case ENOMEDIUM: return DRFLAC_DOES_NOT_EXIST;
  8224.     #endif
  8225.     #ifdef EMEDIUMTYPE
  8226.         case EMEDIUMTYPE: return DRFLAC_ERROR;
  8227.     #endif
  8228.     #ifdef ECANCELED
  8229.         case ECANCELED: return DRFLAC_CANCELLED;
  8230.     #endif
  8231.     #ifdef ENOKEY
  8232.         case ENOKEY: return DRFLAC_ERROR;
  8233.     #endif
  8234.     #ifdef EKEYEXPIRED
  8235.         case EKEYEXPIRED: return DRFLAC_ERROR;
  8236.     #endif
  8237.     #ifdef EKEYREVOKED
  8238.         case EKEYREVOKED: return DRFLAC_ERROR;
  8239.     #endif
  8240.     #ifdef EKEYREJECTED
  8241.         case EKEYREJECTED: return DRFLAC_ERROR;
  8242.     #endif
  8243.     #ifdef EOWNERDEAD
  8244.         case EOWNERDEAD: return DRFLAC_ERROR;
  8245.     #endif
  8246.     #ifdef ENOTRECOVERABLE
  8247.         case ENOTRECOVERABLE: return DRFLAC_ERROR;
  8248.     #endif
  8249.     #ifdef ERFKILL
  8250.         case ERFKILL: return DRFLAC_ERROR;
  8251.     #endif
  8252.     #ifdef EHWPOISON
  8253.         case EHWPOISON: return DRFLAC_ERROR;
  8254.     #endif
  8255.         default: return DRFLAC_ERROR;
  8256.     }
  8257. }
  8258.  
  8259. static drflac_result drflac_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
  8260. {
  8261. #if _MSC_VER && _MSC_VER >= 1400
  8262.     errno_t err;
  8263. #endif
  8264.  
  8265.     if (ppFile != NULL) {
  8266.         *ppFile = NULL;  /* Safety. */
  8267.     }
  8268.  
  8269.     if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  8270.         return DRFLAC_INVALID_ARGS;
  8271.     }
  8272.  
  8273. #if _MSC_VER && _MSC_VER >= 1400
  8274.     err = fopen_s(ppFile, pFilePath, pOpenMode);
  8275.     if (err != 0) {
  8276.         return drflac_result_from_errno(err);
  8277.     }
  8278. #else
  8279. #if defined(_WIN32) || defined(__APPLE__)
  8280.     *ppFile = fopen(pFilePath, pOpenMode);
  8281. #else
  8282.     #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
  8283.         *ppFile = fopen64(pFilePath, pOpenMode);
  8284.     #else
  8285.         *ppFile = fopen(pFilePath, pOpenMode);
  8286.     #endif
  8287. #endif
  8288.     if (*ppFile == NULL) {
  8289.         drflac_result result = drflac_result_from_errno(errno);
  8290.         if (result == DRFLAC_SUCCESS) {
  8291.             result = DRFLAC_ERROR;   /* Just a safety check to make sure we never ever return success when pFile == NULL. */
  8292.         }
  8293.  
  8294.         return result;
  8295.     }
  8296. #endif
  8297.  
  8298.     return DRFLAC_SUCCESS;
  8299. }
  8300.  
  8301. /*
  8302. _wfopen() isn't always available in all compilation environments.
  8303.  
  8304.     * Windows only.
  8305.     * MSVC seems to support it universally as far back as VC6 from what I can tell (haven't checked further back).
  8306.     * MinGW-64 (both 32- and 64-bit) seems to support it.
  8307.     * MinGW wraps it in !defined(__STRICT_ANSI__).
  8308.  
  8309. This can be reviewed as compatibility issues arise. The preference is to use _wfopen_s() and _wfopen() as opposed to the wcsrtombs()
  8310. fallback, so if you notice your compiler not detecting this properly I'm happy to look at adding support.
  8311. */
  8312. #if defined(_WIN32)
  8313.     #if defined(_MSC_VER) || defined(__MINGW64__) || !defined(__STRICT_ANSI__)
  8314.         #define DRFLAC_HAS_WFOPEN
  8315.     #endif
  8316. #endif
  8317.  
  8318. static drflac_result drflac_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const drflac_allocation_callbacks* pAllocationCallbacks)
  8319. {
  8320.     if (ppFile != NULL) {
  8321.         *ppFile = NULL;  /* Safety. */
  8322.     }
  8323.  
  8324.     if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  8325.         return DRFLAC_INVALID_ARGS;
  8326.     }
  8327.  
  8328. #if defined(DRFLAC_HAS_WFOPEN)
  8329.     {
  8330.         /* Use _wfopen() on Windows. */
  8331.     #if defined(_MSC_VER) && _MSC_VER >= 1400
  8332.         errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
  8333.         if (err != 0) {
  8334.             return drflac_result_from_errno(err);
  8335.         }
  8336.     #else
  8337.         *ppFile = _wfopen(pFilePath, pOpenMode);
  8338.         if (*ppFile == NULL) {
  8339.             return drflac_result_from_errno(errno);
  8340.         }
  8341.     #endif
  8342.         (void)pAllocationCallbacks;
  8343.     }
  8344. #else
  8345.     /*
  8346.     Use fopen() on anything other than Windows. Requires a conversion. This is annoying because fopen() is locale specific. The only real way I can
  8347.     think of to do this is with wcsrtombs(). Note that wcstombs() is apparently not thread-safe because it uses a static global mbstate_t object for
  8348.     maintaining state. I've checked this with -std=c89 and it works, but if somebody get's a compiler error I'll look into improving compatibility.
  8349.     */
  8350.     {
  8351.         mbstate_t mbs;
  8352.         size_t lenMB;
  8353.         const wchar_t* pFilePathTemp = pFilePath;
  8354.         char* pFilePathMB = NULL;
  8355.         char pOpenModeMB[32] = {0};
  8356.  
  8357.         /* Get the length first. */
  8358.         DRFLAC_ZERO_OBJECT(&mbs);
  8359.         lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
  8360.         if (lenMB == (size_t)-1) {
  8361.             return drflac_result_from_errno(errno);
  8362.         }
  8363.  
  8364.         pFilePathMB = (char*)drflac__malloc_from_callbacks(lenMB + 1, pAllocationCallbacks);
  8365.         if (pFilePathMB == NULL) {
  8366.             return DRFLAC_OUT_OF_MEMORY;
  8367.         }
  8368.  
  8369.         pFilePathTemp = pFilePath;
  8370.         DRFLAC_ZERO_OBJECT(&mbs);
  8371.         wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
  8372.  
  8373.         /* The open mode should always consist of ASCII characters so we should be able to do a trivial conversion. */
  8374.         {
  8375.             size_t i = 0;
  8376.             for (;;) {
  8377.                 if (pOpenMode[i] == 0) {
  8378.                     pOpenModeMB[i] = '\0';
  8379.                     break;
  8380.                 }
  8381.  
  8382.                 pOpenModeMB[i] = (char)pOpenMode[i];
  8383.                 i += 1;
  8384.             }
  8385.         }
  8386.  
  8387.         *ppFile = fopen(pFilePathMB, pOpenModeMB);
  8388.  
  8389.         drflac__free_from_callbacks(pFilePathMB, pAllocationCallbacks);
  8390.     }
  8391.  
  8392.     if (*ppFile == NULL) {
  8393.         return DRFLAC_ERROR;
  8394.     }
  8395. #endif
  8396.  
  8397.     return DRFLAC_SUCCESS;
  8398. }
  8399.  
  8400. static size_t drflac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead)
  8401. {
  8402.     return fread(bufferOut, 1, bytesToRead, (FILE*)pUserData);
  8403. }
  8404.  
  8405. static drflac_bool32 drflac__on_seek_stdio(void* pUserData, int offset, drflac_seek_origin origin)
  8406. {
  8407.     DRFLAC_ASSERT(offset >= 0);  /* <-- Never seek backwards. */
  8408.  
  8409.     return fseek((FILE*)pUserData, offset, (origin == drflac_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
  8410. }
  8411.  
  8412.  
  8413. DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks)
  8414. {
  8415.     drflac* pFlac;
  8416.     FILE* pFile;
  8417.  
  8418.     if (drflac_fopen(&pFile, pFileName, "rb") != DRFLAC_SUCCESS) {
  8419.         return NULL;
  8420.     }
  8421.  
  8422.     pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  8423.     if (pFlac == NULL) {
  8424.         fclose(pFile);
  8425.         return NULL;
  8426.     }
  8427.  
  8428.     return pFlac;
  8429. }
  8430.  
  8431. DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks)
  8432. {
  8433.     drflac* pFlac;
  8434.     FILE* pFile;
  8435.  
  8436.     if (drflac_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != DRFLAC_SUCCESS) {
  8437.         return NULL;
  8438.     }
  8439.  
  8440.     pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  8441.     if (pFlac == NULL) {
  8442.         fclose(pFile);
  8443.         return NULL;
  8444.     }
  8445.  
  8446.     return pFlac;
  8447. }
  8448.  
  8449. DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  8450. {
  8451.     drflac* pFlac;
  8452.     FILE* pFile;
  8453.  
  8454.     if (drflac_fopen(&pFile, pFileName, "rb") != DRFLAC_SUCCESS) {
  8455.         return NULL;
  8456.     }
  8457.  
  8458.     pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, onMeta, drflac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks);
  8459.     if (pFlac == NULL) {
  8460.         fclose(pFile);
  8461.         return pFlac;
  8462.     }
  8463.  
  8464.     return pFlac;
  8465. }
  8466.  
  8467. DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  8468. {
  8469.     drflac* pFlac;
  8470.     FILE* pFile;
  8471.  
  8472.     if (drflac_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != DRFLAC_SUCCESS) {
  8473.         return NULL;
  8474.     }
  8475.  
  8476.     pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, onMeta, drflac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks);
  8477.     if (pFlac == NULL) {
  8478.         fclose(pFile);
  8479.         return pFlac;
  8480.     }
  8481.  
  8482.     return pFlac;
  8483. }
  8484. #endif  /* DR_FLAC_NO_STDIO */
  8485.  
  8486. static size_t drflac__on_read_memory(void* pUserData, void* bufferOut, size_t bytesToRead)
  8487. {
  8488.     drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
  8489.     size_t bytesRemaining;
  8490.  
  8491.     DRFLAC_ASSERT(memoryStream != NULL);
  8492.     DRFLAC_ASSERT(memoryStream->dataSize >= memoryStream->currentReadPos);
  8493.  
  8494.     bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos;
  8495.     if (bytesToRead > bytesRemaining) {
  8496.         bytesToRead = bytesRemaining;
  8497.     }
  8498.  
  8499.     if (bytesToRead > 0) {
  8500.         DRFLAC_COPY_MEMORY(bufferOut, memoryStream->data + memoryStream->currentReadPos, bytesToRead);
  8501.         memoryStream->currentReadPos += bytesToRead;
  8502.     }
  8503.  
  8504.     return bytesToRead;
  8505. }
  8506.  
  8507. static drflac_bool32 drflac__on_seek_memory(void* pUserData, int offset, drflac_seek_origin origin)
  8508. {
  8509.     drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
  8510.  
  8511.     DRFLAC_ASSERT(memoryStream != NULL);
  8512.     DRFLAC_ASSERT(offset >= 0); /* <-- Never seek backwards. */
  8513.  
  8514.     if (offset > (drflac_int64)memoryStream->dataSize) {
  8515.         return DRFLAC_FALSE;
  8516.     }
  8517.  
  8518.     if (origin == drflac_seek_origin_current) {
  8519.         if (memoryStream->currentReadPos + offset <= memoryStream->dataSize) {
  8520.             memoryStream->currentReadPos += offset;
  8521.         } else {
  8522.             return DRFLAC_FALSE;  /* Trying to seek too far forward. */
  8523.         }
  8524.     } else {
  8525.         if ((drflac_uint32)offset <= memoryStream->dataSize) {
  8526.             memoryStream->currentReadPos = offset;
  8527.         } else {
  8528.             return DRFLAC_FALSE;  /* Trying to seek too far forward. */
  8529.         }
  8530.     }
  8531.  
  8532.     return DRFLAC_TRUE;
  8533. }
  8534.  
  8535. DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks)
  8536. {
  8537.     drflac__memory_stream memoryStream;
  8538.     drflac* pFlac;
  8539.  
  8540.     memoryStream.data = (const drflac_uint8*)pData;
  8541.     memoryStream.dataSize = dataSize;
  8542.     memoryStream.currentReadPos = 0;
  8543.     pFlac = drflac_open(drflac__on_read_memory, drflac__on_seek_memory, &memoryStream, pAllocationCallbacks);
  8544.     if (pFlac == NULL) {
  8545.         return NULL;
  8546.     }
  8547.  
  8548.     pFlac->memoryStream = memoryStream;
  8549.  
  8550.     /* This is an awful hack... */
  8551. #ifndef DR_FLAC_NO_OGG
  8552.     if (pFlac->container == drflac_container_ogg)
  8553.     {
  8554.         drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
  8555.         oggbs->pUserData = &pFlac->memoryStream;
  8556.     }
  8557.     else
  8558. #endif
  8559.     {
  8560.         pFlac->bs.pUserData = &pFlac->memoryStream;
  8561.     }
  8562.  
  8563.     return pFlac;
  8564. }
  8565.  
  8566. DRFLAC_API drflac* drflac_open_memory_with_metadata(const void* pData, size_t dataSize, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  8567. {
  8568.     drflac__memory_stream memoryStream;
  8569.     drflac* pFlac;
  8570.  
  8571.     memoryStream.data = (const drflac_uint8*)pData;
  8572.     memoryStream.dataSize = dataSize;
  8573.     memoryStream.currentReadPos = 0;
  8574.     pFlac = drflac_open_with_metadata_private(drflac__on_read_memory, drflac__on_seek_memory, onMeta, drflac_container_unknown, &memoryStream, pUserData, pAllocationCallbacks);
  8575.     if (pFlac == NULL) {
  8576.         return NULL;
  8577.     }
  8578.  
  8579.     pFlac->memoryStream = memoryStream;
  8580.  
  8581.     /* This is an awful hack... */
  8582. #ifndef DR_FLAC_NO_OGG
  8583.     if (pFlac->container == drflac_container_ogg)
  8584.     {
  8585.         drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
  8586.         oggbs->pUserData = &pFlac->memoryStream;
  8587.     }
  8588.     else
  8589. #endif
  8590.     {
  8591.         pFlac->bs.pUserData = &pFlac->memoryStream;
  8592.     }
  8593.  
  8594.     return pFlac;
  8595. }
  8596.  
  8597.  
  8598.  
  8599. DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  8600. {
  8601.     return drflac_open_with_metadata_private(onRead, onSeek, NULL, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
  8602. }
  8603. DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  8604. {
  8605.     return drflac_open_with_metadata_private(onRead, onSeek, NULL, container, pUserData, pUserData, pAllocationCallbacks);
  8606. }
  8607.  
  8608. DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  8609. {
  8610.     return drflac_open_with_metadata_private(onRead, onSeek, onMeta, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
  8611. }
  8612. DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  8613. {
  8614.     return drflac_open_with_metadata_private(onRead, onSeek, onMeta, container, pUserData, pUserData, pAllocationCallbacks);
  8615. }
  8616.  
  8617. DRFLAC_API void drflac_close(drflac* pFlac)
  8618. {
  8619.     if (pFlac == NULL) {
  8620.         return;
  8621.     }
  8622.  
  8623. #ifndef DR_FLAC_NO_STDIO
  8624.     /*
  8625.     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()
  8626.     was used by looking at the callbacks.
  8627.     */
  8628.     if (pFlac->bs.onRead == drflac__on_read_stdio) {
  8629.         fclose((FILE*)pFlac->bs.pUserData);
  8630.     }
  8631.  
  8632. #ifndef DR_FLAC_NO_OGG
  8633.     /* Need to clean up Ogg streams a bit differently due to the way the bit streaming is chained. */
  8634.     if (pFlac->container == drflac_container_ogg) {
  8635.         drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
  8636.         DRFLAC_ASSERT(pFlac->bs.onRead == drflac__on_read_ogg);
  8637.  
  8638.         if (oggbs->onRead == drflac__on_read_stdio) {
  8639.             fclose((FILE*)oggbs->pUserData);
  8640.         }
  8641.     }
  8642. #endif
  8643. #endif
  8644.  
  8645.     drflac__free_from_callbacks(pFlac, &pFlac->allocationCallbacks);
  8646. }
  8647.  
  8648.  
  8649. #if 0
  8650. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  8651. {
  8652.     drflac_uint64 i;
  8653.     for (i = 0; i < frameCount; ++i) {
  8654.         drflac_uint32 left  = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  8655.         drflac_uint32 side  = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  8656.         drflac_uint32 right = left - side;
  8657.  
  8658.         pOutputSamples[i*2+0] = (drflac_int32)left;
  8659.         pOutputSamples[i*2+1] = (drflac_int32)right;
  8660.     }
  8661. }
  8662. #endif
  8663.  
  8664. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  8665. {
  8666.     drflac_uint64 i;
  8667.     drflac_uint64 frameCount4 = frameCount >> 2;
  8668.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  8669.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  8670.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  8671.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  8672.  
  8673.     for (i = 0; i < frameCount4; ++i) {
  8674.         drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
  8675.         drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
  8676.         drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
  8677.         drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
  8678.  
  8679.         drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
  8680.         drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
  8681.         drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
  8682.         drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
  8683.  
  8684.         drflac_uint32 right0 = left0 - side0;
  8685.         drflac_uint32 right1 = left1 - side1;
  8686.         drflac_uint32 right2 = left2 - side2;
  8687.         drflac_uint32 right3 = left3 - side3;
  8688.  
  8689.         pOutputSamples[i*8+0] = (drflac_int32)left0;
  8690.         pOutputSamples[i*8+1] = (drflac_int32)right0;
  8691.         pOutputSamples[i*8+2] = (drflac_int32)left1;
  8692.         pOutputSamples[i*8+3] = (drflac_int32)right1;
  8693.         pOutputSamples[i*8+4] = (drflac_int32)left2;
  8694.         pOutputSamples[i*8+5] = (drflac_int32)right2;
  8695.         pOutputSamples[i*8+6] = (drflac_int32)left3;
  8696.         pOutputSamples[i*8+7] = (drflac_int32)right3;
  8697.     }
  8698.  
  8699.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  8700.         drflac_uint32 left  = pInputSamples0U32[i] << shift0;
  8701.         drflac_uint32 side  = pInputSamples1U32[i] << shift1;
  8702.         drflac_uint32 right = left - side;
  8703.  
  8704.         pOutputSamples[i*2+0] = (drflac_int32)left;
  8705.         pOutputSamples[i*2+1] = (drflac_int32)right;
  8706.     }
  8707. }
  8708.  
  8709. #if defined(DRFLAC_SUPPORT_SSE2)
  8710. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  8711. {
  8712.     drflac_uint64 i;
  8713.     drflac_uint64 frameCount4 = frameCount >> 2;
  8714.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  8715.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  8716.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  8717.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  8718.  
  8719.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  8720.  
  8721.     for (i = 0; i < frameCount4; ++i) {
  8722.         __m128i left  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  8723.         __m128i side  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  8724.         __m128i right = _mm_sub_epi32(left, side);
  8725.  
  8726.         _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  8727.         _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  8728.     }
  8729.  
  8730.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  8731.         drflac_uint32 left  = pInputSamples0U32[i] << shift0;
  8732.         drflac_uint32 side  = pInputSamples1U32[i] << shift1;
  8733.         drflac_uint32 right = left - side;
  8734.  
  8735.         pOutputSamples[i*2+0] = (drflac_int32)left;
  8736.         pOutputSamples[i*2+1] = (drflac_int32)right;
  8737.     }
  8738. }
  8739. #endif
  8740.  
  8741. #if defined(DRFLAC_SUPPORT_NEON)
  8742. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  8743. {
  8744.     drflac_uint64 i;
  8745.     drflac_uint64 frameCount4 = frameCount >> 2;
  8746.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  8747.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  8748.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  8749.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  8750.     int32x4_t shift0_4;
  8751.     int32x4_t shift1_4;
  8752.  
  8753.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  8754.  
  8755.     shift0_4 = vdupq_n_s32(shift0);
  8756.     shift1_4 = vdupq_n_s32(shift1);
  8757.  
  8758.     for (i = 0; i < frameCount4; ++i) {
  8759.         uint32x4_t left;
  8760.         uint32x4_t side;
  8761.         uint32x4_t right;
  8762.  
  8763.         left  = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  8764.         side  = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  8765.         right = vsubq_u32(left, side);
  8766.  
  8767.         drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
  8768.     }
  8769.  
  8770.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  8771.         drflac_uint32 left  = pInputSamples0U32[i] << shift0;
  8772.         drflac_uint32 side  = pInputSamples1U32[i] << shift1;
  8773.         drflac_uint32 right = left - side;
  8774.  
  8775.         pOutputSamples[i*2+0] = (drflac_int32)left;
  8776.         pOutputSamples[i*2+1] = (drflac_int32)right;
  8777.     }
  8778. }
  8779. #endif
  8780.  
  8781. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  8782. {
  8783. #if defined(DRFLAC_SUPPORT_SSE2)
  8784.     if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  8785.         drflac_read_pcm_frames_s32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  8786.     } else
  8787. #elif defined(DRFLAC_SUPPORT_NEON)
  8788.     if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  8789.         drflac_read_pcm_frames_s32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  8790.     } else
  8791. #endif
  8792.     {
  8793.         /* Scalar fallback. */
  8794. #if 0
  8795.         drflac_read_pcm_frames_s32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  8796. #else
  8797.         drflac_read_pcm_frames_s32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  8798. #endif
  8799.     }
  8800. }
  8801.  
  8802.  
  8803. #if 0
  8804. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  8805. {
  8806.     drflac_uint64 i;
  8807.     for (i = 0; i < frameCount; ++i) {
  8808.         drflac_uint32 side  = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  8809.         drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  8810.         drflac_uint32 left  = right + side;
  8811.  
  8812.         pOutputSamples[i*2+0] = (drflac_int32)left;
  8813.         pOutputSamples[i*2+1] = (drflac_int32)right;
  8814.     }
  8815. }
  8816. #endif
  8817.  
  8818. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  8819. {
  8820.     drflac_uint64 i;
  8821.     drflac_uint64 frameCount4 = frameCount >> 2;
  8822.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  8823.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  8824.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  8825.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  8826.  
  8827.     for (i = 0; i < frameCount4; ++i) {
  8828.         drflac_uint32 side0  = pInputSamples0U32[i*4+0] << shift0;
  8829.         drflac_uint32 side1  = pInputSamples0U32[i*4+1] << shift0;
  8830.         drflac_uint32 side2  = pInputSamples0U32[i*4+2] << shift0;
  8831.         drflac_uint32 side3  = pInputSamples0U32[i*4+3] << shift0;
  8832.  
  8833.         drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
  8834.         drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
  8835.         drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
  8836.         drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
  8837.  
  8838.         drflac_uint32 left0 = right0 + side0;
  8839.         drflac_uint32 left1 = right1 + side1;
  8840.         drflac_uint32 left2 = right2 + side2;
  8841.         drflac_uint32 left3 = right3 + side3;
  8842.  
  8843.         pOutputSamples[i*8+0] = (drflac_int32)left0;
  8844.         pOutputSamples[i*8+1] = (drflac_int32)right0;
  8845.         pOutputSamples[i*8+2] = (drflac_int32)left1;
  8846.         pOutputSamples[i*8+3] = (drflac_int32)right1;
  8847.         pOutputSamples[i*8+4] = (drflac_int32)left2;
  8848.         pOutputSamples[i*8+5] = (drflac_int32)right2;
  8849.         pOutputSamples[i*8+6] = (drflac_int32)left3;
  8850.         pOutputSamples[i*8+7] = (drflac_int32)right3;
  8851.     }
  8852.  
  8853.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  8854.         drflac_uint32 side  = pInputSamples0U32[i] << shift0;
  8855.         drflac_uint32 right = pInputSamples1U32[i] << shift1;
  8856.         drflac_uint32 left  = right + side;
  8857.  
  8858.         pOutputSamples[i*2+0] = (drflac_int32)left;
  8859.         pOutputSamples[i*2+1] = (drflac_int32)right;
  8860.     }
  8861. }
  8862.  
  8863. #if defined(DRFLAC_SUPPORT_SSE2)
  8864. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  8865. {
  8866.     drflac_uint64 i;
  8867.     drflac_uint64 frameCount4 = frameCount >> 2;
  8868.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  8869.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  8870.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  8871.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  8872.  
  8873.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  8874.  
  8875.     for (i = 0; i < frameCount4; ++i) {
  8876.         __m128i side  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  8877.         __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  8878.         __m128i left  = _mm_add_epi32(right, side);
  8879.  
  8880.         _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  8881.         _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  8882.     }
  8883.  
  8884.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  8885.         drflac_uint32 side  = pInputSamples0U32[i] << shift0;
  8886.         drflac_uint32 right = pInputSamples1U32[i] << shift1;
  8887.         drflac_uint32 left  = right + side;
  8888.  
  8889.         pOutputSamples[i*2+0] = (drflac_int32)left;
  8890.         pOutputSamples[i*2+1] = (drflac_int32)right;
  8891.     }
  8892. }
  8893. #endif
  8894.  
  8895. #if defined(DRFLAC_SUPPORT_NEON)
  8896. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  8897. {
  8898.     drflac_uint64 i;
  8899.     drflac_uint64 frameCount4 = frameCount >> 2;
  8900.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  8901.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  8902.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  8903.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  8904.     int32x4_t shift0_4;
  8905.     int32x4_t shift1_4;
  8906.  
  8907.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  8908.  
  8909.     shift0_4 = vdupq_n_s32(shift0);
  8910.     shift1_4 = vdupq_n_s32(shift1);
  8911.  
  8912.     for (i = 0; i < frameCount4; ++i) {
  8913.         uint32x4_t side;
  8914.         uint32x4_t right;
  8915.         uint32x4_t left;
  8916.  
  8917.         side  = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  8918.         right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  8919.         left  = vaddq_u32(right, side);
  8920.  
  8921.         drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
  8922.     }
  8923.  
  8924.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  8925.         drflac_uint32 side  = pInputSamples0U32[i] << shift0;
  8926.         drflac_uint32 right = pInputSamples1U32[i] << shift1;
  8927.         drflac_uint32 left  = right + side;
  8928.  
  8929.         pOutputSamples[i*2+0] = (drflac_int32)left;
  8930.         pOutputSamples[i*2+1] = (drflac_int32)right;
  8931.     }
  8932. }
  8933. #endif
  8934.  
  8935. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  8936. {
  8937. #if defined(DRFLAC_SUPPORT_SSE2)
  8938.     if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  8939.         drflac_read_pcm_frames_s32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  8940.     } else
  8941. #elif defined(DRFLAC_SUPPORT_NEON)
  8942.     if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  8943.         drflac_read_pcm_frames_s32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  8944.     } else
  8945. #endif
  8946.     {
  8947.         /* Scalar fallback. */
  8948. #if 0
  8949.         drflac_read_pcm_frames_s32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  8950. #else
  8951.         drflac_read_pcm_frames_s32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  8952. #endif
  8953.     }
  8954. }
  8955.  
  8956.  
  8957. #if 0
  8958. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  8959. {
  8960.     for (drflac_uint64 i = 0; i < frameCount; ++i) {
  8961.         drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  8962.         drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  8963.  
  8964.         mid = (mid << 1) | (side & 0x01);
  8965.  
  8966.         pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
  8967.         pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
  8968.     }
  8969. }
  8970. #endif
  8971.  
  8972. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  8973. {
  8974.     drflac_uint64 i;
  8975.     drflac_uint64 frameCount4 = frameCount >> 2;
  8976.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  8977.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  8978.     drflac_int32 shift = unusedBitsPerSample;
  8979.  
  8980.     if (shift > 0) {
  8981.         shift -= 1;
  8982.         for (i = 0; i < frameCount4; ++i) {
  8983.             drflac_uint32 temp0L;
  8984.             drflac_uint32 temp1L;
  8985.             drflac_uint32 temp2L;
  8986.             drflac_uint32 temp3L;
  8987.             drflac_uint32 temp0R;
  8988.             drflac_uint32 temp1R;
  8989.             drflac_uint32 temp2R;
  8990.             drflac_uint32 temp3R;
  8991.  
  8992.             drflac_uint32 mid0  = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  8993.             drflac_uint32 mid1  = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  8994.             drflac_uint32 mid2  = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  8995.             drflac_uint32 mid3  = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  8996.  
  8997.             drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  8998.             drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  8999.             drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9000.             drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9001.  
  9002.             mid0 = (mid0 << 1) | (side0 & 0x01);
  9003.             mid1 = (mid1 << 1) | (side1 & 0x01);
  9004.             mid2 = (mid2 << 1) | (side2 & 0x01);
  9005.             mid3 = (mid3 << 1) | (side3 & 0x01);
  9006.  
  9007.             temp0L = (mid0 + side0) << shift;
  9008.             temp1L = (mid1 + side1) << shift;
  9009.             temp2L = (mid2 + side2) << shift;
  9010.             temp3L = (mid3 + side3) << shift;
  9011.  
  9012.             temp0R = (mid0 - side0) << shift;
  9013.             temp1R = (mid1 - side1) << shift;
  9014.             temp2R = (mid2 - side2) << shift;
  9015.             temp3R = (mid3 - side3) << shift;
  9016.  
  9017.             pOutputSamples[i*8+0] = (drflac_int32)temp0L;
  9018.             pOutputSamples[i*8+1] = (drflac_int32)temp0R;
  9019.             pOutputSamples[i*8+2] = (drflac_int32)temp1L;
  9020.             pOutputSamples[i*8+3] = (drflac_int32)temp1R;
  9021.             pOutputSamples[i*8+4] = (drflac_int32)temp2L;
  9022.             pOutputSamples[i*8+5] = (drflac_int32)temp2R;
  9023.             pOutputSamples[i*8+6] = (drflac_int32)temp3L;
  9024.             pOutputSamples[i*8+7] = (drflac_int32)temp3R;
  9025.         }
  9026.     } else {
  9027.         for (i = 0; i < frameCount4; ++i) {
  9028.             drflac_uint32 temp0L;
  9029.             drflac_uint32 temp1L;
  9030.             drflac_uint32 temp2L;
  9031.             drflac_uint32 temp3L;
  9032.             drflac_uint32 temp0R;
  9033.             drflac_uint32 temp1R;
  9034.             drflac_uint32 temp2R;
  9035.             drflac_uint32 temp3R;
  9036.  
  9037.             drflac_uint32 mid0  = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9038.             drflac_uint32 mid1  = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9039.             drflac_uint32 mid2  = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9040.             drflac_uint32 mid3  = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9041.  
  9042.             drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9043.             drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9044.             drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9045.             drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9046.  
  9047.             mid0 = (mid0 << 1) | (side0 & 0x01);
  9048.             mid1 = (mid1 << 1) | (side1 & 0x01);
  9049.             mid2 = (mid2 << 1) | (side2 & 0x01);
  9050.             mid3 = (mid3 << 1) | (side3 & 0x01);
  9051.  
  9052.             temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
  9053.             temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
  9054.             temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
  9055.             temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
  9056.  
  9057.             temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
  9058.             temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
  9059.             temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
  9060.             temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
  9061.  
  9062.             pOutputSamples[i*8+0] = (drflac_int32)temp0L;
  9063.             pOutputSamples[i*8+1] = (drflac_int32)temp0R;
  9064.             pOutputSamples[i*8+2] = (drflac_int32)temp1L;
  9065.             pOutputSamples[i*8+3] = (drflac_int32)temp1R;
  9066.             pOutputSamples[i*8+4] = (drflac_int32)temp2L;
  9067.             pOutputSamples[i*8+5] = (drflac_int32)temp2R;
  9068.             pOutputSamples[i*8+6] = (drflac_int32)temp3L;
  9069.             pOutputSamples[i*8+7] = (drflac_int32)temp3R;
  9070.         }
  9071.     }
  9072.  
  9073.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9074.         drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9075.         drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9076.  
  9077.         mid = (mid << 1) | (side & 0x01);
  9078.  
  9079.         pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
  9080.         pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
  9081.     }
  9082. }
  9083.  
  9084. #if defined(DRFLAC_SUPPORT_SSE2)
  9085. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  9086. {
  9087.     drflac_uint64 i;
  9088.     drflac_uint64 frameCount4 = frameCount >> 2;
  9089.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9090.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9091.     drflac_int32 shift = unusedBitsPerSample;
  9092.  
  9093.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  9094.  
  9095.     if (shift == 0) {
  9096.         for (i = 0; i < frameCount4; ++i) {
  9097.             __m128i mid;
  9098.             __m128i side;
  9099.             __m128i left;
  9100.             __m128i right;
  9101.  
  9102.             mid   = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  9103.             side  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  9104.  
  9105.             mid   = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  9106.  
  9107.             left  = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
  9108.             right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
  9109.  
  9110.             _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  9111.             _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  9112.         }
  9113.  
  9114.         for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9115.             drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9116.             drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9117.  
  9118.             mid = (mid << 1) | (side & 0x01);
  9119.  
  9120.             pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
  9121.             pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
  9122.         }
  9123.     } else {
  9124.         shift -= 1;
  9125.         for (i = 0; i < frameCount4; ++i) {
  9126.             __m128i mid;
  9127.             __m128i side;
  9128.             __m128i left;
  9129.             __m128i right;
  9130.  
  9131.             mid   = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  9132.             side  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  9133.  
  9134.             mid   = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  9135.  
  9136.             left  = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
  9137.             right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
  9138.  
  9139.             _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  9140.             _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  9141.         }
  9142.  
  9143.         for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9144.             drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9145.             drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9146.  
  9147.             mid = (mid << 1) | (side & 0x01);
  9148.  
  9149.             pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
  9150.             pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
  9151.         }
  9152.     }
  9153. }
  9154. #endif
  9155.  
  9156. #if defined(DRFLAC_SUPPORT_NEON)
  9157. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  9158. {
  9159.     drflac_uint64 i;
  9160.     drflac_uint64 frameCount4 = frameCount >> 2;
  9161.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9162.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9163.     drflac_int32 shift = unusedBitsPerSample;
  9164.     int32x4_t  wbpsShift0_4; /* wbps = Wasted Bits Per Sample */
  9165.     int32x4_t  wbpsShift1_4; /* wbps = Wasted Bits Per Sample */
  9166.     uint32x4_t one4;
  9167.  
  9168.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  9169.  
  9170.     wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  9171.     wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  9172.     one4         = vdupq_n_u32(1);
  9173.  
  9174.     if (shift == 0) {
  9175.         for (i = 0; i < frameCount4; ++i) {
  9176.             uint32x4_t mid;
  9177.             uint32x4_t side;
  9178.             int32x4_t left;
  9179.             int32x4_t right;
  9180.  
  9181.             mid   = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  9182.             side  = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  9183.  
  9184.             mid   = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
  9185.  
  9186.             left  = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
  9187.             right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
  9188.  
  9189.             drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
  9190.         }
  9191.  
  9192.         for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9193.             drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9194.             drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9195.  
  9196.             mid = (mid << 1) | (side & 0x01);
  9197.  
  9198.             pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
  9199.             pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
  9200.         }
  9201.     } else {
  9202.         int32x4_t shift4;
  9203.  
  9204.         shift -= 1;
  9205.         shift4 = vdupq_n_s32(shift);
  9206.  
  9207.         for (i = 0; i < frameCount4; ++i) {
  9208.             uint32x4_t mid;
  9209.             uint32x4_t side;
  9210.             int32x4_t left;
  9211.             int32x4_t right;
  9212.  
  9213.             mid   = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  9214.             side  = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  9215.  
  9216.             mid   = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
  9217.  
  9218.             left  = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
  9219.             right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
  9220.  
  9221.             drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
  9222.         }
  9223.  
  9224.         for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9225.             drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9226.             drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9227.  
  9228.             mid = (mid << 1) | (side & 0x01);
  9229.  
  9230.             pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
  9231.             pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
  9232.         }
  9233.     }
  9234. }
  9235. #endif
  9236.  
  9237. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  9238. {
  9239. #if defined(DRFLAC_SUPPORT_SSE2)
  9240.     if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  9241.         drflac_read_pcm_frames_s32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9242.     } else
  9243. #elif defined(DRFLAC_SUPPORT_NEON)
  9244.     if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  9245.         drflac_read_pcm_frames_s32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9246.     } else
  9247. #endif
  9248.     {
  9249.         /* Scalar fallback. */
  9250. #if 0
  9251.         drflac_read_pcm_frames_s32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9252. #else
  9253.         drflac_read_pcm_frames_s32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9254. #endif
  9255.     }
  9256. }
  9257.  
  9258.  
  9259. #if 0
  9260. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  9261. {
  9262.     for (drflac_uint64 i = 0; i < frameCount; ++i) {
  9263.         pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample));
  9264.         pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample));
  9265.     }
  9266. }
  9267. #endif
  9268.  
  9269. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  9270. {
  9271.     drflac_uint64 i;
  9272.     drflac_uint64 frameCount4 = frameCount >> 2;
  9273.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9274.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9275.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9276.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9277.  
  9278.     for (i = 0; i < frameCount4; ++i) {
  9279.         drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
  9280.         drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
  9281.         drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
  9282.         drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
  9283.  
  9284.         drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
  9285.         drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
  9286.         drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
  9287.         drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
  9288.  
  9289.         pOutputSamples[i*8+0] = (drflac_int32)tempL0;
  9290.         pOutputSamples[i*8+1] = (drflac_int32)tempR0;
  9291.         pOutputSamples[i*8+2] = (drflac_int32)tempL1;
  9292.         pOutputSamples[i*8+3] = (drflac_int32)tempR1;
  9293.         pOutputSamples[i*8+4] = (drflac_int32)tempL2;
  9294.         pOutputSamples[i*8+5] = (drflac_int32)tempR2;
  9295.         pOutputSamples[i*8+6] = (drflac_int32)tempL3;
  9296.         pOutputSamples[i*8+7] = (drflac_int32)tempR3;
  9297.     }
  9298.  
  9299.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9300.         pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
  9301.         pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
  9302.     }
  9303. }
  9304.  
  9305. #if defined(DRFLAC_SUPPORT_SSE2)
  9306. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  9307. {
  9308.     drflac_uint64 i;
  9309.     drflac_uint64 frameCount4 = frameCount >> 2;
  9310.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9311.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9312.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9313.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9314.  
  9315.     for (i = 0; i < frameCount4; ++i) {
  9316.         __m128i left  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  9317.         __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  9318.  
  9319.         _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  9320.         _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  9321.     }
  9322.  
  9323.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9324.         pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
  9325.         pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
  9326.     }
  9327. }
  9328. #endif
  9329.  
  9330. #if defined(DRFLAC_SUPPORT_NEON)
  9331. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  9332. {
  9333.     drflac_uint64 i;
  9334.     drflac_uint64 frameCount4 = frameCount >> 2;
  9335.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9336.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9337.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9338.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9339.  
  9340.     int32x4_t shift4_0 = vdupq_n_s32(shift0);
  9341.     int32x4_t shift4_1 = vdupq_n_s32(shift1);
  9342.  
  9343.     for (i = 0; i < frameCount4; ++i) {
  9344.         int32x4_t left;
  9345.         int32x4_t right;
  9346.  
  9347.         left  = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift4_0));
  9348.         right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift4_1));
  9349.  
  9350.         drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
  9351.     }
  9352.  
  9353.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9354.         pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
  9355.         pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
  9356.     }
  9357. }
  9358. #endif
  9359.  
  9360. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  9361. {
  9362. #if defined(DRFLAC_SUPPORT_SSE2)
  9363.     if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  9364.         drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9365.     } else
  9366. #elif defined(DRFLAC_SUPPORT_NEON)
  9367.     if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  9368.         drflac_read_pcm_frames_s32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9369.     } else
  9370. #endif
  9371.     {
  9372.         /* Scalar fallback. */
  9373. #if 0
  9374.         drflac_read_pcm_frames_s32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9375. #else
  9376.         drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9377. #endif
  9378.     }
  9379. }
  9380.  
  9381.  
  9382. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut)
  9383. {
  9384.     drflac_uint64 framesRead;
  9385.     drflac_uint32 unusedBitsPerSample;
  9386.  
  9387.     if (pFlac == NULL || framesToRead == 0) {
  9388.         return 0;
  9389.     }
  9390.  
  9391.     if (pBufferOut == NULL) {
  9392.         return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
  9393.     }
  9394.  
  9395.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
  9396.     unusedBitsPerSample = 32 - pFlac->bitsPerSample;
  9397.  
  9398.     framesRead = 0;
  9399.     while (framesToRead > 0) {
  9400.         /* If we've run out of samples in this frame, go to the next. */
  9401.         if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  9402.             if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  9403.                 break;  /* Couldn't read the next frame, so just break from the loop and return. */
  9404.             }
  9405.         } else {
  9406.             unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  9407.             drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
  9408.             drflac_uint64 frameCountThisIteration = framesToRead;
  9409.  
  9410.             if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
  9411.                 frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
  9412.             }
  9413.  
  9414.             if (channelCount == 2) {
  9415.                 const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
  9416.                 const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
  9417.  
  9418.                 switch (pFlac->currentFLACFrame.header.channelAssignment)
  9419.                 {
  9420.                     case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
  9421.                     {
  9422.                         drflac_read_pcm_frames_s32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  9423.                     } break;
  9424.  
  9425.                     case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  9426.                     {
  9427.                         drflac_read_pcm_frames_s32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  9428.                     } break;
  9429.  
  9430.                     case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
  9431.                     {
  9432.                         drflac_read_pcm_frames_s32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  9433.                     } break;
  9434.  
  9435.                     case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
  9436.                     default:
  9437.                     {
  9438.                         drflac_read_pcm_frames_s32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  9439.                     } break;
  9440.                 }
  9441.             } else {
  9442.                 /* Generic interleaving. */
  9443.                 drflac_uint64 i;
  9444.                 for (i = 0; i < frameCountThisIteration; ++i) {
  9445.                     unsigned int j;
  9446.                     for (j = 0; j < channelCount; ++j) {
  9447.                         pBufferOut[(i*channelCount)+j] = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
  9448.                     }
  9449.                 }
  9450.             }
  9451.  
  9452.             framesRead                += frameCountThisIteration;
  9453.             pBufferOut                += frameCountThisIteration * channelCount;
  9454.             framesToRead              -= frameCountThisIteration;
  9455.             pFlac->currentPCMFrame    += frameCountThisIteration;
  9456.             pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
  9457.         }
  9458.     }
  9459.  
  9460.     return framesRead;
  9461. }
  9462.  
  9463.  
  9464. #if 0
  9465. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9466. {
  9467.     drflac_uint64 i;
  9468.     for (i = 0; i < frameCount; ++i) {
  9469.         drflac_uint32 left  = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  9470.         drflac_uint32 side  = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  9471.         drflac_uint32 right = left - side;
  9472.  
  9473.         left  >>= 16;
  9474.         right >>= 16;
  9475.  
  9476.         pOutputSamples[i*2+0] = (drflac_int16)left;
  9477.         pOutputSamples[i*2+1] = (drflac_int16)right;
  9478.     }
  9479. }
  9480. #endif
  9481.  
  9482. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9483. {
  9484.     drflac_uint64 i;
  9485.     drflac_uint64 frameCount4 = frameCount >> 2;
  9486.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9487.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9488.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9489.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9490.  
  9491.     for (i = 0; i < frameCount4; ++i) {
  9492.         drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
  9493.         drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
  9494.         drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
  9495.         drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
  9496.  
  9497.         drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
  9498.         drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
  9499.         drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
  9500.         drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
  9501.  
  9502.         drflac_uint32 right0 = left0 - side0;
  9503.         drflac_uint32 right1 = left1 - side1;
  9504.         drflac_uint32 right2 = left2 - side2;
  9505.         drflac_uint32 right3 = left3 - side3;
  9506.  
  9507.         left0  >>= 16;
  9508.         left1  >>= 16;
  9509.         left2  >>= 16;
  9510.         left3  >>= 16;
  9511.  
  9512.         right0 >>= 16;
  9513.         right1 >>= 16;
  9514.         right2 >>= 16;
  9515.         right3 >>= 16;
  9516.  
  9517.         pOutputSamples[i*8+0] = (drflac_int16)left0;
  9518.         pOutputSamples[i*8+1] = (drflac_int16)right0;
  9519.         pOutputSamples[i*8+2] = (drflac_int16)left1;
  9520.         pOutputSamples[i*8+3] = (drflac_int16)right1;
  9521.         pOutputSamples[i*8+4] = (drflac_int16)left2;
  9522.         pOutputSamples[i*8+5] = (drflac_int16)right2;
  9523.         pOutputSamples[i*8+6] = (drflac_int16)left3;
  9524.         pOutputSamples[i*8+7] = (drflac_int16)right3;
  9525.     }
  9526.  
  9527.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9528.         drflac_uint32 left  = pInputSamples0U32[i] << shift0;
  9529.         drflac_uint32 side  = pInputSamples1U32[i] << shift1;
  9530.         drflac_uint32 right = left - side;
  9531.  
  9532.         left  >>= 16;
  9533.         right >>= 16;
  9534.  
  9535.         pOutputSamples[i*2+0] = (drflac_int16)left;
  9536.         pOutputSamples[i*2+1] = (drflac_int16)right;
  9537.     }
  9538. }
  9539.  
  9540. #if defined(DRFLAC_SUPPORT_SSE2)
  9541. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9542. {
  9543.     drflac_uint64 i;
  9544.     drflac_uint64 frameCount4 = frameCount >> 2;
  9545.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9546.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9547.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9548.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9549.  
  9550.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  9551.  
  9552.     for (i = 0; i < frameCount4; ++i) {
  9553.         __m128i left  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  9554.         __m128i side  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  9555.         __m128i right = _mm_sub_epi32(left, side);
  9556.  
  9557.         left  = _mm_srai_epi32(left,  16);
  9558.         right = _mm_srai_epi32(right, 16);
  9559.  
  9560.         _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  9561.     }
  9562.  
  9563.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9564.         drflac_uint32 left  = pInputSamples0U32[i] << shift0;
  9565.         drflac_uint32 side  = pInputSamples1U32[i] << shift1;
  9566.         drflac_uint32 right = left - side;
  9567.  
  9568.         left  >>= 16;
  9569.         right >>= 16;
  9570.  
  9571.         pOutputSamples[i*2+0] = (drflac_int16)left;
  9572.         pOutputSamples[i*2+1] = (drflac_int16)right;
  9573.     }
  9574. }
  9575. #endif
  9576.  
  9577. #if defined(DRFLAC_SUPPORT_NEON)
  9578. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9579. {
  9580.     drflac_uint64 i;
  9581.     drflac_uint64 frameCount4 = frameCount >> 2;
  9582.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9583.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9584.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9585.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9586.     int32x4_t shift0_4;
  9587.     int32x4_t shift1_4;
  9588.  
  9589.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  9590.  
  9591.     shift0_4 = vdupq_n_s32(shift0);
  9592.     shift1_4 = vdupq_n_s32(shift1);
  9593.  
  9594.     for (i = 0; i < frameCount4; ++i) {
  9595.         uint32x4_t left;
  9596.         uint32x4_t side;
  9597.         uint32x4_t right;
  9598.  
  9599.         left  = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  9600.         side  = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  9601.         right = vsubq_u32(left, side);
  9602.  
  9603.         left  = vshrq_n_u32(left,  16);
  9604.         right = vshrq_n_u32(right, 16);
  9605.  
  9606.         drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
  9607.     }
  9608.  
  9609.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9610.         drflac_uint32 left  = pInputSamples0U32[i] << shift0;
  9611.         drflac_uint32 side  = pInputSamples1U32[i] << shift1;
  9612.         drflac_uint32 right = left - side;
  9613.  
  9614.         left  >>= 16;
  9615.         right >>= 16;
  9616.  
  9617.         pOutputSamples[i*2+0] = (drflac_int16)left;
  9618.         pOutputSamples[i*2+1] = (drflac_int16)right;
  9619.     }
  9620. }
  9621. #endif
  9622.  
  9623. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9624. {
  9625. #if defined(DRFLAC_SUPPORT_SSE2)
  9626.     if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  9627.         drflac_read_pcm_frames_s16__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9628.     } else
  9629. #elif defined(DRFLAC_SUPPORT_NEON)
  9630.     if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  9631.         drflac_read_pcm_frames_s16__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9632.     } else
  9633. #endif
  9634.     {
  9635.         /* Scalar fallback. */
  9636. #if 0
  9637.         drflac_read_pcm_frames_s16__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9638. #else
  9639.         drflac_read_pcm_frames_s16__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9640. #endif
  9641.     }
  9642. }
  9643.  
  9644.  
  9645. #if 0
  9646. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9647. {
  9648.     drflac_uint64 i;
  9649.     for (i = 0; i < frameCount; ++i) {
  9650.         drflac_uint32 side  = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  9651.         drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  9652.         drflac_uint32 left  = right + side;
  9653.  
  9654.         left  >>= 16;
  9655.         right >>= 16;
  9656.  
  9657.         pOutputSamples[i*2+0] = (drflac_int16)left;
  9658.         pOutputSamples[i*2+1] = (drflac_int16)right;
  9659.     }
  9660. }
  9661. #endif
  9662.  
  9663. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9664. {
  9665.     drflac_uint64 i;
  9666.     drflac_uint64 frameCount4 = frameCount >> 2;
  9667.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9668.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9669.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9670.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9671.  
  9672.     for (i = 0; i < frameCount4; ++i) {
  9673.         drflac_uint32 side0  = pInputSamples0U32[i*4+0] << shift0;
  9674.         drflac_uint32 side1  = pInputSamples0U32[i*4+1] << shift0;
  9675.         drflac_uint32 side2  = pInputSamples0U32[i*4+2] << shift0;
  9676.         drflac_uint32 side3  = pInputSamples0U32[i*4+3] << shift0;
  9677.  
  9678.         drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
  9679.         drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
  9680.         drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
  9681.         drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
  9682.  
  9683.         drflac_uint32 left0 = right0 + side0;
  9684.         drflac_uint32 left1 = right1 + side1;
  9685.         drflac_uint32 left2 = right2 + side2;
  9686.         drflac_uint32 left3 = right3 + side3;
  9687.  
  9688.         left0  >>= 16;
  9689.         left1  >>= 16;
  9690.         left2  >>= 16;
  9691.         left3  >>= 16;
  9692.  
  9693.         right0 >>= 16;
  9694.         right1 >>= 16;
  9695.         right2 >>= 16;
  9696.         right3 >>= 16;
  9697.  
  9698.         pOutputSamples[i*8+0] = (drflac_int16)left0;
  9699.         pOutputSamples[i*8+1] = (drflac_int16)right0;
  9700.         pOutputSamples[i*8+2] = (drflac_int16)left1;
  9701.         pOutputSamples[i*8+3] = (drflac_int16)right1;
  9702.         pOutputSamples[i*8+4] = (drflac_int16)left2;
  9703.         pOutputSamples[i*8+5] = (drflac_int16)right2;
  9704.         pOutputSamples[i*8+6] = (drflac_int16)left3;
  9705.         pOutputSamples[i*8+7] = (drflac_int16)right3;
  9706.     }
  9707.  
  9708.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9709.         drflac_uint32 side  = pInputSamples0U32[i] << shift0;
  9710.         drflac_uint32 right = pInputSamples1U32[i] << shift1;
  9711.         drflac_uint32 left  = right + side;
  9712.  
  9713.         left  >>= 16;
  9714.         right >>= 16;
  9715.  
  9716.         pOutputSamples[i*2+0] = (drflac_int16)left;
  9717.         pOutputSamples[i*2+1] = (drflac_int16)right;
  9718.     }
  9719. }
  9720.  
  9721. #if defined(DRFLAC_SUPPORT_SSE2)
  9722. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9723. {
  9724.     drflac_uint64 i;
  9725.     drflac_uint64 frameCount4 = frameCount >> 2;
  9726.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9727.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9728.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9729.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9730.  
  9731.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  9732.  
  9733.     for (i = 0; i < frameCount4; ++i) {
  9734.         __m128i side  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  9735.         __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  9736.         __m128i left  = _mm_add_epi32(right, side);
  9737.  
  9738.         left  = _mm_srai_epi32(left,  16);
  9739.         right = _mm_srai_epi32(right, 16);
  9740.  
  9741.         _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  9742.     }
  9743.  
  9744.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9745.         drflac_uint32 side  = pInputSamples0U32[i] << shift0;
  9746.         drflac_uint32 right = pInputSamples1U32[i] << shift1;
  9747.         drflac_uint32 left  = right + side;
  9748.  
  9749.         left  >>= 16;
  9750.         right >>= 16;
  9751.  
  9752.         pOutputSamples[i*2+0] = (drflac_int16)left;
  9753.         pOutputSamples[i*2+1] = (drflac_int16)right;
  9754.     }
  9755. }
  9756. #endif
  9757.  
  9758. #if defined(DRFLAC_SUPPORT_NEON)
  9759. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9760. {
  9761.     drflac_uint64 i;
  9762.     drflac_uint64 frameCount4 = frameCount >> 2;
  9763.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9764.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9765.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9766.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9767.     int32x4_t shift0_4;
  9768.     int32x4_t shift1_4;
  9769.  
  9770.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  9771.  
  9772.     shift0_4 = vdupq_n_s32(shift0);
  9773.     shift1_4 = vdupq_n_s32(shift1);
  9774.  
  9775.     for (i = 0; i < frameCount4; ++i) {
  9776.         uint32x4_t side;
  9777.         uint32x4_t right;
  9778.         uint32x4_t left;
  9779.  
  9780.         side  = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  9781.         right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  9782.         left  = vaddq_u32(right, side);
  9783.  
  9784.         left  = vshrq_n_u32(left,  16);
  9785.         right = vshrq_n_u32(right, 16);
  9786.  
  9787.         drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
  9788.     }
  9789.  
  9790.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9791.         drflac_uint32 side  = pInputSamples0U32[i] << shift0;
  9792.         drflac_uint32 right = pInputSamples1U32[i] << shift1;
  9793.         drflac_uint32 left  = right + side;
  9794.  
  9795.         left  >>= 16;
  9796.         right >>= 16;
  9797.  
  9798.         pOutputSamples[i*2+0] = (drflac_int16)left;
  9799.         pOutputSamples[i*2+1] = (drflac_int16)right;
  9800.     }
  9801. }
  9802. #endif
  9803.  
  9804. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9805. {
  9806. #if defined(DRFLAC_SUPPORT_SSE2)
  9807.     if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  9808.         drflac_read_pcm_frames_s16__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9809.     } else
  9810. #elif defined(DRFLAC_SUPPORT_NEON)
  9811.     if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  9812.         drflac_read_pcm_frames_s16__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9813.     } else
  9814. #endif
  9815.     {
  9816.         /* Scalar fallback. */
  9817. #if 0
  9818.         drflac_read_pcm_frames_s16__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9819. #else
  9820.         drflac_read_pcm_frames_s16__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  9821. #endif
  9822.     }
  9823. }
  9824.  
  9825.  
  9826. #if 0
  9827. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9828. {
  9829.     for (drflac_uint64 i = 0; i < frameCount; ++i) {
  9830.         drflac_uint32 mid  = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9831.         drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9832.  
  9833.         mid = (mid << 1) | (side & 0x01);
  9834.  
  9835.         pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
  9836.         pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
  9837.     }
  9838. }
  9839. #endif
  9840.  
  9841. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9842. {
  9843.     drflac_uint64 i;
  9844.     drflac_uint64 frameCount4 = frameCount >> 2;
  9845.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9846.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9847.     drflac_uint32 shift = unusedBitsPerSample;
  9848.  
  9849.     if (shift > 0) {
  9850.         shift -= 1;
  9851.         for (i = 0; i < frameCount4; ++i) {
  9852.             drflac_uint32 temp0L;
  9853.             drflac_uint32 temp1L;
  9854.             drflac_uint32 temp2L;
  9855.             drflac_uint32 temp3L;
  9856.             drflac_uint32 temp0R;
  9857.             drflac_uint32 temp1R;
  9858.             drflac_uint32 temp2R;
  9859.             drflac_uint32 temp3R;
  9860.  
  9861.             drflac_uint32 mid0  = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9862.             drflac_uint32 mid1  = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9863.             drflac_uint32 mid2  = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9864.             drflac_uint32 mid3  = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9865.  
  9866.             drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9867.             drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9868.             drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9869.             drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9870.  
  9871.             mid0 = (mid0 << 1) | (side0 & 0x01);
  9872.             mid1 = (mid1 << 1) | (side1 & 0x01);
  9873.             mid2 = (mid2 << 1) | (side2 & 0x01);
  9874.             mid3 = (mid3 << 1) | (side3 & 0x01);
  9875.  
  9876.             temp0L = (mid0 + side0) << shift;
  9877.             temp1L = (mid1 + side1) << shift;
  9878.             temp2L = (mid2 + side2) << shift;
  9879.             temp3L = (mid3 + side3) << shift;
  9880.  
  9881.             temp0R = (mid0 - side0) << shift;
  9882.             temp1R = (mid1 - side1) << shift;
  9883.             temp2R = (mid2 - side2) << shift;
  9884.             temp3R = (mid3 - side3) << shift;
  9885.  
  9886.             temp0L >>= 16;
  9887.             temp1L >>= 16;
  9888.             temp2L >>= 16;
  9889.             temp3L >>= 16;
  9890.  
  9891.             temp0R >>= 16;
  9892.             temp1R >>= 16;
  9893.             temp2R >>= 16;
  9894.             temp3R >>= 16;
  9895.  
  9896.             pOutputSamples[i*8+0] = (drflac_int16)temp0L;
  9897.             pOutputSamples[i*8+1] = (drflac_int16)temp0R;
  9898.             pOutputSamples[i*8+2] = (drflac_int16)temp1L;
  9899.             pOutputSamples[i*8+3] = (drflac_int16)temp1R;
  9900.             pOutputSamples[i*8+4] = (drflac_int16)temp2L;
  9901.             pOutputSamples[i*8+5] = (drflac_int16)temp2R;
  9902.             pOutputSamples[i*8+6] = (drflac_int16)temp3L;
  9903.             pOutputSamples[i*8+7] = (drflac_int16)temp3R;
  9904.         }
  9905.     } else {
  9906.         for (i = 0; i < frameCount4; ++i) {
  9907.             drflac_uint32 temp0L;
  9908.             drflac_uint32 temp1L;
  9909.             drflac_uint32 temp2L;
  9910.             drflac_uint32 temp3L;
  9911.             drflac_uint32 temp0R;
  9912.             drflac_uint32 temp1R;
  9913.             drflac_uint32 temp2R;
  9914.             drflac_uint32 temp3R;
  9915.  
  9916.             drflac_uint32 mid0  = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9917.             drflac_uint32 mid1  = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9918.             drflac_uint32 mid2  = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9919.             drflac_uint32 mid3  = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9920.  
  9921.             drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9922.             drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9923.             drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9924.             drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9925.  
  9926.             mid0 = (mid0 << 1) | (side0 & 0x01);
  9927.             mid1 = (mid1 << 1) | (side1 & 0x01);
  9928.             mid2 = (mid2 << 1) | (side2 & 0x01);
  9929.             mid3 = (mid3 << 1) | (side3 & 0x01);
  9930.  
  9931.             temp0L = ((drflac_int32)(mid0 + side0) >> 1);
  9932.             temp1L = ((drflac_int32)(mid1 + side1) >> 1);
  9933.             temp2L = ((drflac_int32)(mid2 + side2) >> 1);
  9934.             temp3L = ((drflac_int32)(mid3 + side3) >> 1);
  9935.  
  9936.             temp0R = ((drflac_int32)(mid0 - side0) >> 1);
  9937.             temp1R = ((drflac_int32)(mid1 - side1) >> 1);
  9938.             temp2R = ((drflac_int32)(mid2 - side2) >> 1);
  9939.             temp3R = ((drflac_int32)(mid3 - side3) >> 1);
  9940.  
  9941.             temp0L >>= 16;
  9942.             temp1L >>= 16;
  9943.             temp2L >>= 16;
  9944.             temp3L >>= 16;
  9945.  
  9946.             temp0R >>= 16;
  9947.             temp1R >>= 16;
  9948.             temp2R >>= 16;
  9949.             temp3R >>= 16;
  9950.  
  9951.             pOutputSamples[i*8+0] = (drflac_int16)temp0L;
  9952.             pOutputSamples[i*8+1] = (drflac_int16)temp0R;
  9953.             pOutputSamples[i*8+2] = (drflac_int16)temp1L;
  9954.             pOutputSamples[i*8+3] = (drflac_int16)temp1R;
  9955.             pOutputSamples[i*8+4] = (drflac_int16)temp2L;
  9956.             pOutputSamples[i*8+5] = (drflac_int16)temp2R;
  9957.             pOutputSamples[i*8+6] = (drflac_int16)temp3L;
  9958.             pOutputSamples[i*8+7] = (drflac_int16)temp3R;
  9959.         }
  9960.     }
  9961.  
  9962.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  9963.         drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  9964.         drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  9965.  
  9966.         mid = (mid << 1) | (side & 0x01);
  9967.  
  9968.         pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
  9969.         pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
  9970.     }
  9971. }
  9972.  
  9973. #if defined(DRFLAC_SUPPORT_SSE2)
  9974. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  9975. {
  9976.     drflac_uint64 i;
  9977.     drflac_uint64 frameCount4 = frameCount >> 2;
  9978.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  9979.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  9980.     drflac_uint32 shift = unusedBitsPerSample;
  9981.  
  9982.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  9983.  
  9984.     if (shift == 0) {
  9985.         for (i = 0; i < frameCount4; ++i) {
  9986.             __m128i mid;
  9987.             __m128i side;
  9988.             __m128i left;
  9989.             __m128i right;
  9990.  
  9991.             mid   = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  9992.             side  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  9993.  
  9994.             mid   = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  9995.  
  9996.             left  = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
  9997.             right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
  9998.  
  9999.             left  = _mm_srai_epi32(left,  16);
  10000.             right = _mm_srai_epi32(right, 16);
  10001.  
  10002.             _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  10003.         }
  10004.  
  10005.         for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10006.             drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10007.             drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10008.  
  10009.             mid = (mid << 1) | (side & 0x01);
  10010.  
  10011.             pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
  10012.             pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
  10013.         }
  10014.     } else {
  10015.         shift -= 1;
  10016.         for (i = 0; i < frameCount4; ++i) {
  10017.             __m128i mid;
  10018.             __m128i side;
  10019.             __m128i left;
  10020.             __m128i right;
  10021.  
  10022.             mid   = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  10023.             side  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  10024.  
  10025.             mid   = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  10026.  
  10027.             left  = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
  10028.             right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
  10029.  
  10030.             left  = _mm_srai_epi32(left,  16);
  10031.             right = _mm_srai_epi32(right, 16);
  10032.  
  10033.             _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  10034.         }
  10035.  
  10036.         for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10037.             drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10038.             drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10039.  
  10040.             mid = (mid << 1) | (side & 0x01);
  10041.  
  10042.             pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
  10043.             pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
  10044.         }
  10045.     }
  10046. }
  10047. #endif
  10048.  
  10049. #if defined(DRFLAC_SUPPORT_NEON)
  10050. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  10051. {
  10052.     drflac_uint64 i;
  10053.     drflac_uint64 frameCount4 = frameCount >> 2;
  10054.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10055.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10056.     drflac_uint32 shift = unusedBitsPerSample;
  10057.     int32x4_t wbpsShift0_4; /* wbps = Wasted Bits Per Sample */
  10058.     int32x4_t wbpsShift1_4; /* wbps = Wasted Bits Per Sample */
  10059.  
  10060.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  10061.  
  10062.     wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  10063.     wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  10064.  
  10065.     if (shift == 0) {
  10066.         for (i = 0; i < frameCount4; ++i) {
  10067.             uint32x4_t mid;
  10068.             uint32x4_t side;
  10069.             int32x4_t left;
  10070.             int32x4_t right;
  10071.  
  10072.             mid   = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  10073.             side  = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  10074.  
  10075.             mid   = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  10076.  
  10077.             left  = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
  10078.             right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
  10079.  
  10080.             left  = vshrq_n_s32(left,  16);
  10081.             right = vshrq_n_s32(right, 16);
  10082.  
  10083.             drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
  10084.         }
  10085.  
  10086.         for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10087.             drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10088.             drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10089.  
  10090.             mid = (mid << 1) | (side & 0x01);
  10091.  
  10092.             pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
  10093.             pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
  10094.         }
  10095.     } else {
  10096.         int32x4_t shift4;
  10097.  
  10098.         shift -= 1;
  10099.         shift4 = vdupq_n_s32(shift);
  10100.  
  10101.         for (i = 0; i < frameCount4; ++i) {
  10102.             uint32x4_t mid;
  10103.             uint32x4_t side;
  10104.             int32x4_t left;
  10105.             int32x4_t right;
  10106.  
  10107.             mid   = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  10108.             side  = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  10109.  
  10110.             mid   = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  10111.  
  10112.             left  = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
  10113.             right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
  10114.  
  10115.             left  = vshrq_n_s32(left,  16);
  10116.             right = vshrq_n_s32(right, 16);
  10117.  
  10118.             drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
  10119.         }
  10120.  
  10121.         for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10122.             drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10123.             drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10124.  
  10125.             mid = (mid << 1) | (side & 0x01);
  10126.  
  10127.             pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
  10128.             pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
  10129.         }
  10130.     }
  10131. }
  10132. #endif
  10133.  
  10134. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  10135. {
  10136. #if defined(DRFLAC_SUPPORT_SSE2)
  10137.     if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  10138.         drflac_read_pcm_frames_s16__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10139.     } else
  10140. #elif defined(DRFLAC_SUPPORT_NEON)
  10141.     if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  10142.         drflac_read_pcm_frames_s16__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10143.     } else
  10144. #endif
  10145.     {
  10146.         /* Scalar fallback. */
  10147. #if 0
  10148.         drflac_read_pcm_frames_s16__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10149. #else
  10150.         drflac_read_pcm_frames_s16__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10151. #endif
  10152.     }
  10153. }
  10154.  
  10155.  
  10156. #if 0
  10157. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  10158. {
  10159.     for (drflac_uint64 i = 0; i < frameCount; ++i) {
  10160.         pOutputSamples[i*2+0] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) >> 16);
  10161.         pOutputSamples[i*2+1] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) >> 16);
  10162.     }
  10163. }
  10164. #endif
  10165.  
  10166. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  10167. {
  10168.     drflac_uint64 i;
  10169.     drflac_uint64 frameCount4 = frameCount >> 2;
  10170.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10171.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10172.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10173.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10174.  
  10175.     for (i = 0; i < frameCount4; ++i) {
  10176.         drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
  10177.         drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
  10178.         drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
  10179.         drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
  10180.  
  10181.         drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
  10182.         drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
  10183.         drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
  10184.         drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
  10185.  
  10186.         tempL0 >>= 16;
  10187.         tempL1 >>= 16;
  10188.         tempL2 >>= 16;
  10189.         tempL3 >>= 16;
  10190.  
  10191.         tempR0 >>= 16;
  10192.         tempR1 >>= 16;
  10193.         tempR2 >>= 16;
  10194.         tempR3 >>= 16;
  10195.  
  10196.         pOutputSamples[i*8+0] = (drflac_int16)tempL0;
  10197.         pOutputSamples[i*8+1] = (drflac_int16)tempR0;
  10198.         pOutputSamples[i*8+2] = (drflac_int16)tempL1;
  10199.         pOutputSamples[i*8+3] = (drflac_int16)tempR1;
  10200.         pOutputSamples[i*8+4] = (drflac_int16)tempL2;
  10201.         pOutputSamples[i*8+5] = (drflac_int16)tempR2;
  10202.         pOutputSamples[i*8+6] = (drflac_int16)tempL3;
  10203.         pOutputSamples[i*8+7] = (drflac_int16)tempR3;
  10204.     }
  10205.  
  10206.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10207.         pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
  10208.         pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
  10209.     }
  10210. }
  10211.  
  10212. #if defined(DRFLAC_SUPPORT_SSE2)
  10213. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  10214. {
  10215.     drflac_uint64 i;
  10216.     drflac_uint64 frameCount4 = frameCount >> 2;
  10217.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10218.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10219.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10220.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10221.  
  10222.     for (i = 0; i < frameCount4; ++i) {
  10223.         __m128i left  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  10224.         __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  10225.  
  10226.         left  = _mm_srai_epi32(left,  16);
  10227.         right = _mm_srai_epi32(right, 16);
  10228.  
  10229.         /* At this point we have results. We can now pack and interleave these into a single __m128i object and then store the in the output buffer. */
  10230.         _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  10231.     }
  10232.  
  10233.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10234.         pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
  10235.         pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
  10236.     }
  10237. }
  10238. #endif
  10239.  
  10240. #if defined(DRFLAC_SUPPORT_NEON)
  10241. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  10242. {
  10243.     drflac_uint64 i;
  10244.     drflac_uint64 frameCount4 = frameCount >> 2;
  10245.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10246.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10247.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10248.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10249.  
  10250.     int32x4_t shift0_4 = vdupq_n_s32(shift0);
  10251.     int32x4_t shift1_4 = vdupq_n_s32(shift1);
  10252.  
  10253.     for (i = 0; i < frameCount4; ++i) {
  10254.         int32x4_t left;
  10255.         int32x4_t right;
  10256.  
  10257.         left  = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
  10258.         right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
  10259.  
  10260.         left  = vshrq_n_s32(left,  16);
  10261.         right = vshrq_n_s32(right, 16);
  10262.  
  10263.         drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
  10264.     }
  10265.  
  10266.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10267.         pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
  10268.         pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
  10269.     }
  10270. }
  10271. #endif
  10272.  
  10273. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  10274. {
  10275. #if defined(DRFLAC_SUPPORT_SSE2)
  10276.     if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  10277.         drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10278.     } else
  10279. #elif defined(DRFLAC_SUPPORT_NEON)
  10280.     if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  10281.         drflac_read_pcm_frames_s16__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10282.     } else
  10283. #endif
  10284.     {
  10285.         /* Scalar fallback. */
  10286. #if 0
  10287.         drflac_read_pcm_frames_s16__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10288. #else
  10289.         drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10290. #endif
  10291.     }
  10292. }
  10293.  
  10294. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut)
  10295. {
  10296.     drflac_uint64 framesRead;
  10297.     drflac_uint32 unusedBitsPerSample;
  10298.  
  10299.     if (pFlac == NULL || framesToRead == 0) {
  10300.         return 0;
  10301.     }
  10302.  
  10303.     if (pBufferOut == NULL) {
  10304.         return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
  10305.     }
  10306.  
  10307.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
  10308.     unusedBitsPerSample = 32 - pFlac->bitsPerSample;
  10309.  
  10310.     framesRead = 0;
  10311.     while (framesToRead > 0) {
  10312.         /* If we've run out of samples in this frame, go to the next. */
  10313.         if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  10314.             if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  10315.                 break;  /* Couldn't read the next frame, so just break from the loop and return. */
  10316.             }
  10317.         } else {
  10318.             unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  10319.             drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
  10320.             drflac_uint64 frameCountThisIteration = framesToRead;
  10321.  
  10322.             if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
  10323.                 frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
  10324.             }
  10325.  
  10326.             if (channelCount == 2) {
  10327.                 const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
  10328.                 const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
  10329.  
  10330.                 switch (pFlac->currentFLACFrame.header.channelAssignment)
  10331.                 {
  10332.                     case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
  10333.                     {
  10334.                         drflac_read_pcm_frames_s16__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  10335.                     } break;
  10336.  
  10337.                     case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  10338.                     {
  10339.                         drflac_read_pcm_frames_s16__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  10340.                     } break;
  10341.  
  10342.                     case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
  10343.                     {
  10344.                         drflac_read_pcm_frames_s16__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  10345.                     } break;
  10346.  
  10347.                     case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
  10348.                     default:
  10349.                     {
  10350.                         drflac_read_pcm_frames_s16__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  10351.                     } break;
  10352.                 }
  10353.             } else {
  10354.                 /* Generic interleaving. */
  10355.                 drflac_uint64 i;
  10356.                 for (i = 0; i < frameCountThisIteration; ++i) {
  10357.                     unsigned int j;
  10358.                     for (j = 0; j < channelCount; ++j) {
  10359.                         drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
  10360.                         pBufferOut[(i*channelCount)+j] = (drflac_int16)(sampleS32 >> 16);
  10361.                     }
  10362.                 }
  10363.             }
  10364.  
  10365.             framesRead                += frameCountThisIteration;
  10366.             pBufferOut                += frameCountThisIteration * channelCount;
  10367.             framesToRead              -= frameCountThisIteration;
  10368.             pFlac->currentPCMFrame    += frameCountThisIteration;
  10369.             pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
  10370.         }
  10371.     }
  10372.  
  10373.     return framesRead;
  10374. }
  10375.  
  10376.  
  10377. #if 0
  10378. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10379. {
  10380.     drflac_uint64 i;
  10381.     for (i = 0; i < frameCount; ++i) {
  10382.         drflac_uint32 left  = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  10383.         drflac_uint32 side  = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  10384.         drflac_uint32 right = left - side;
  10385.  
  10386.         pOutputSamples[i*2+0] = (float)((drflac_int32)left  / 2147483648.0);
  10387.         pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
  10388.     }
  10389. }
  10390. #endif
  10391.  
  10392. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10393. {
  10394.     drflac_uint64 i;
  10395.     drflac_uint64 frameCount4 = frameCount >> 2;
  10396.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10397.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10398.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10399.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10400.  
  10401.     float factor = 1 / 2147483648.0;
  10402.  
  10403.     for (i = 0; i < frameCount4; ++i) {
  10404.         drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
  10405.         drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
  10406.         drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
  10407.         drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
  10408.  
  10409.         drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
  10410.         drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
  10411.         drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
  10412.         drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
  10413.  
  10414.         drflac_uint32 right0 = left0 - side0;
  10415.         drflac_uint32 right1 = left1 - side1;
  10416.         drflac_uint32 right2 = left2 - side2;
  10417.         drflac_uint32 right3 = left3 - side3;
  10418.  
  10419.         pOutputSamples[i*8+0] = (drflac_int32)left0  * factor;
  10420.         pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
  10421.         pOutputSamples[i*8+2] = (drflac_int32)left1  * factor;
  10422.         pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
  10423.         pOutputSamples[i*8+4] = (drflac_int32)left2  * factor;
  10424.         pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
  10425.         pOutputSamples[i*8+6] = (drflac_int32)left3  * factor;
  10426.         pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
  10427.     }
  10428.  
  10429.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10430.         drflac_uint32 left  = pInputSamples0U32[i] << shift0;
  10431.         drflac_uint32 side  = pInputSamples1U32[i] << shift1;
  10432.         drflac_uint32 right = left - side;
  10433.  
  10434.         pOutputSamples[i*2+0] = (drflac_int32)left  * factor;
  10435.         pOutputSamples[i*2+1] = (drflac_int32)right * factor;
  10436.     }
  10437. }
  10438.  
  10439. #if defined(DRFLAC_SUPPORT_SSE2)
  10440. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10441. {
  10442.     drflac_uint64 i;
  10443.     drflac_uint64 frameCount4 = frameCount >> 2;
  10444.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10445.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10446.     drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  10447.     drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  10448.     __m128 factor;
  10449.  
  10450.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  10451.  
  10452.     factor = _mm_set1_ps(1.0f / 8388608.0f);
  10453.  
  10454.     for (i = 0; i < frameCount4; ++i) {
  10455.         __m128i left  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  10456.         __m128i side  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  10457.         __m128i right = _mm_sub_epi32(left, side);
  10458.         __m128 leftf  = _mm_mul_ps(_mm_cvtepi32_ps(left),  factor);
  10459.         __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
  10460.  
  10461.         _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  10462.         _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  10463.     }
  10464.  
  10465.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10466.         drflac_uint32 left  = pInputSamples0U32[i] << shift0;
  10467.         drflac_uint32 side  = pInputSamples1U32[i] << shift1;
  10468.         drflac_uint32 right = left - side;
  10469.  
  10470.         pOutputSamples[i*2+0] = (drflac_int32)left  / 8388608.0f;
  10471.         pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
  10472.     }
  10473. }
  10474. #endif
  10475.  
  10476. #if defined(DRFLAC_SUPPORT_NEON)
  10477. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10478. {
  10479.     drflac_uint64 i;
  10480.     drflac_uint64 frameCount4 = frameCount >> 2;
  10481.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10482.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10483.     drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  10484.     drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  10485.     float32x4_t factor4;
  10486.     int32x4_t shift0_4;
  10487.     int32x4_t shift1_4;
  10488.  
  10489.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  10490.  
  10491.     factor4  = vdupq_n_f32(1.0f / 8388608.0f);
  10492.     shift0_4 = vdupq_n_s32(shift0);
  10493.     shift1_4 = vdupq_n_s32(shift1);
  10494.  
  10495.     for (i = 0; i < frameCount4; ++i) {
  10496.         uint32x4_t left;
  10497.         uint32x4_t side;
  10498.         uint32x4_t right;
  10499.         float32x4_t leftf;
  10500.         float32x4_t rightf;
  10501.  
  10502.         left   = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  10503.         side   = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  10504.         right  = vsubq_u32(left, side);
  10505.         leftf  = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)),  factor4);
  10506.         rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
  10507.  
  10508.         drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  10509.     }
  10510.  
  10511.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10512.         drflac_uint32 left  = pInputSamples0U32[i] << shift0;
  10513.         drflac_uint32 side  = pInputSamples1U32[i] << shift1;
  10514.         drflac_uint32 right = left - side;
  10515.  
  10516.         pOutputSamples[i*2+0] = (drflac_int32)left  / 8388608.0f;
  10517.         pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
  10518.     }
  10519. }
  10520. #endif
  10521.  
  10522. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10523. {
  10524. #if defined(DRFLAC_SUPPORT_SSE2)
  10525.     if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  10526.         drflac_read_pcm_frames_f32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10527.     } else
  10528. #elif defined(DRFLAC_SUPPORT_NEON)
  10529.     if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  10530.         drflac_read_pcm_frames_f32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10531.     } else
  10532. #endif
  10533.     {
  10534.         /* Scalar fallback. */
  10535. #if 0
  10536.         drflac_read_pcm_frames_f32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10537. #else
  10538.         drflac_read_pcm_frames_f32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10539. #endif
  10540.     }
  10541. }
  10542.  
  10543.  
  10544. #if 0
  10545. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10546. {
  10547.     drflac_uint64 i;
  10548.     for (i = 0; i < frameCount; ++i) {
  10549.         drflac_uint32 side  = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  10550.         drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  10551.         drflac_uint32 left  = right + side;
  10552.  
  10553.         pOutputSamples[i*2+0] = (float)((drflac_int32)left  / 2147483648.0);
  10554.         pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
  10555.     }
  10556. }
  10557. #endif
  10558.  
  10559. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10560. {
  10561.     drflac_uint64 i;
  10562.     drflac_uint64 frameCount4 = frameCount >> 2;
  10563.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10564.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10565.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10566.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10567.     float factor = 1 / 2147483648.0;
  10568.  
  10569.     for (i = 0; i < frameCount4; ++i) {
  10570.         drflac_uint32 side0  = pInputSamples0U32[i*4+0] << shift0;
  10571.         drflac_uint32 side1  = pInputSamples0U32[i*4+1] << shift0;
  10572.         drflac_uint32 side2  = pInputSamples0U32[i*4+2] << shift0;
  10573.         drflac_uint32 side3  = pInputSamples0U32[i*4+3] << shift0;
  10574.  
  10575.         drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
  10576.         drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
  10577.         drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
  10578.         drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
  10579.  
  10580.         drflac_uint32 left0 = right0 + side0;
  10581.         drflac_uint32 left1 = right1 + side1;
  10582.         drflac_uint32 left2 = right2 + side2;
  10583.         drflac_uint32 left3 = right3 + side3;
  10584.  
  10585.         pOutputSamples[i*8+0] = (drflac_int32)left0  * factor;
  10586.         pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
  10587.         pOutputSamples[i*8+2] = (drflac_int32)left1  * factor;
  10588.         pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
  10589.         pOutputSamples[i*8+4] = (drflac_int32)left2  * factor;
  10590.         pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
  10591.         pOutputSamples[i*8+6] = (drflac_int32)left3  * factor;
  10592.         pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
  10593.     }
  10594.  
  10595.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10596.         drflac_uint32 side  = pInputSamples0U32[i] << shift0;
  10597.         drflac_uint32 right = pInputSamples1U32[i] << shift1;
  10598.         drflac_uint32 left  = right + side;
  10599.  
  10600.         pOutputSamples[i*2+0] = (drflac_int32)left  * factor;
  10601.         pOutputSamples[i*2+1] = (drflac_int32)right * factor;
  10602.     }
  10603. }
  10604.  
  10605. #if defined(DRFLAC_SUPPORT_SSE2)
  10606. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10607. {
  10608.     drflac_uint64 i;
  10609.     drflac_uint64 frameCount4 = frameCount >> 2;
  10610.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10611.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10612.     drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  10613.     drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  10614.     __m128 factor;
  10615.  
  10616.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  10617.  
  10618.     factor = _mm_set1_ps(1.0f / 8388608.0f);
  10619.  
  10620.     for (i = 0; i < frameCount4; ++i) {
  10621.         __m128i side  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  10622.         __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  10623.         __m128i left  = _mm_add_epi32(right, side);
  10624.         __m128 leftf  = _mm_mul_ps(_mm_cvtepi32_ps(left),  factor);
  10625.         __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
  10626.  
  10627.         _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  10628.         _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  10629.     }
  10630.  
  10631.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10632.         drflac_uint32 side  = pInputSamples0U32[i] << shift0;
  10633.         drflac_uint32 right = pInputSamples1U32[i] << shift1;
  10634.         drflac_uint32 left  = right + side;
  10635.  
  10636.         pOutputSamples[i*2+0] = (drflac_int32)left  / 8388608.0f;
  10637.         pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
  10638.     }
  10639. }
  10640. #endif
  10641.  
  10642. #if defined(DRFLAC_SUPPORT_NEON)
  10643. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10644. {
  10645.     drflac_uint64 i;
  10646.     drflac_uint64 frameCount4 = frameCount >> 2;
  10647.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10648.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10649.     drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  10650.     drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  10651.     float32x4_t factor4;
  10652.     int32x4_t shift0_4;
  10653.     int32x4_t shift1_4;
  10654.  
  10655.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  10656.  
  10657.     factor4  = vdupq_n_f32(1.0f / 8388608.0f);
  10658.     shift0_4 = vdupq_n_s32(shift0);
  10659.     shift1_4 = vdupq_n_s32(shift1);
  10660.  
  10661.     for (i = 0; i < frameCount4; ++i) {
  10662.         uint32x4_t side;
  10663.         uint32x4_t right;
  10664.         uint32x4_t left;
  10665.         float32x4_t leftf;
  10666.         float32x4_t rightf;
  10667.  
  10668.         side   = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  10669.         right  = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  10670.         left   = vaddq_u32(right, side);
  10671.         leftf  = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)),  factor4);
  10672.         rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
  10673.  
  10674.         drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  10675.     }
  10676.  
  10677.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10678.         drflac_uint32 side  = pInputSamples0U32[i] << shift0;
  10679.         drflac_uint32 right = pInputSamples1U32[i] << shift1;
  10680.         drflac_uint32 left  = right + side;
  10681.  
  10682.         pOutputSamples[i*2+0] = (drflac_int32)left  / 8388608.0f;
  10683.         pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
  10684.     }
  10685. }
  10686. #endif
  10687.  
  10688. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10689. {
  10690. #if defined(DRFLAC_SUPPORT_SSE2)
  10691.     if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  10692.         drflac_read_pcm_frames_f32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10693.     } else
  10694. #elif defined(DRFLAC_SUPPORT_NEON)
  10695.     if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  10696.         drflac_read_pcm_frames_f32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10697.     } else
  10698. #endif
  10699.     {
  10700.         /* Scalar fallback. */
  10701. #if 0
  10702.         drflac_read_pcm_frames_f32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10703. #else
  10704.         drflac_read_pcm_frames_f32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  10705. #endif
  10706.     }
  10707. }
  10708.  
  10709.  
  10710. #if 0
  10711. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10712. {
  10713.     for (drflac_uint64 i = 0; i < frameCount; ++i) {
  10714.         drflac_uint32 mid  = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10715.         drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10716.  
  10717.         mid = (mid << 1) | (side & 0x01);
  10718.  
  10719.         pOutputSamples[i*2+0] = (float)((((drflac_int32)(mid + side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
  10720.         pOutputSamples[i*2+1] = (float)((((drflac_int32)(mid - side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
  10721.     }
  10722. }
  10723. #endif
  10724.  
  10725. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10726. {
  10727.     drflac_uint64 i;
  10728.     drflac_uint64 frameCount4 = frameCount >> 2;
  10729.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10730.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10731.     drflac_uint32 shift = unusedBitsPerSample;
  10732.     float factor = 1 / 2147483648.0;
  10733.  
  10734.     if (shift > 0) {
  10735.         shift -= 1;
  10736.         for (i = 0; i < frameCount4; ++i) {
  10737.             drflac_uint32 temp0L;
  10738.             drflac_uint32 temp1L;
  10739.             drflac_uint32 temp2L;
  10740.             drflac_uint32 temp3L;
  10741.             drflac_uint32 temp0R;
  10742.             drflac_uint32 temp1R;
  10743.             drflac_uint32 temp2R;
  10744.             drflac_uint32 temp3R;
  10745.  
  10746.             drflac_uint32 mid0  = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10747.             drflac_uint32 mid1  = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10748.             drflac_uint32 mid2  = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10749.             drflac_uint32 mid3  = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10750.  
  10751.             drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10752.             drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10753.             drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10754.             drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10755.  
  10756.             mid0 = (mid0 << 1) | (side0 & 0x01);
  10757.             mid1 = (mid1 << 1) | (side1 & 0x01);
  10758.             mid2 = (mid2 << 1) | (side2 & 0x01);
  10759.             mid3 = (mid3 << 1) | (side3 & 0x01);
  10760.  
  10761.             temp0L = (mid0 + side0) << shift;
  10762.             temp1L = (mid1 + side1) << shift;
  10763.             temp2L = (mid2 + side2) << shift;
  10764.             temp3L = (mid3 + side3) << shift;
  10765.  
  10766.             temp0R = (mid0 - side0) << shift;
  10767.             temp1R = (mid1 - side1) << shift;
  10768.             temp2R = (mid2 - side2) << shift;
  10769.             temp3R = (mid3 - side3) << shift;
  10770.  
  10771.             pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
  10772.             pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
  10773.             pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
  10774.             pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
  10775.             pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
  10776.             pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
  10777.             pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
  10778.             pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
  10779.         }
  10780.     } else {
  10781.         for (i = 0; i < frameCount4; ++i) {
  10782.             drflac_uint32 temp0L;
  10783.             drflac_uint32 temp1L;
  10784.             drflac_uint32 temp2L;
  10785.             drflac_uint32 temp3L;
  10786.             drflac_uint32 temp0R;
  10787.             drflac_uint32 temp1R;
  10788.             drflac_uint32 temp2R;
  10789.             drflac_uint32 temp3R;
  10790.  
  10791.             drflac_uint32 mid0  = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10792.             drflac_uint32 mid1  = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10793.             drflac_uint32 mid2  = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10794.             drflac_uint32 mid3  = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10795.  
  10796.             drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10797.             drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10798.             drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10799.             drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10800.  
  10801.             mid0 = (mid0 << 1) | (side0 & 0x01);
  10802.             mid1 = (mid1 << 1) | (side1 & 0x01);
  10803.             mid2 = (mid2 << 1) | (side2 & 0x01);
  10804.             mid3 = (mid3 << 1) | (side3 & 0x01);
  10805.  
  10806.             temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
  10807.             temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
  10808.             temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
  10809.             temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
  10810.  
  10811.             temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
  10812.             temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
  10813.             temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
  10814.             temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
  10815.  
  10816.             pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
  10817.             pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
  10818.             pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
  10819.             pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
  10820.             pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
  10821.             pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
  10822.             pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
  10823.             pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
  10824.         }
  10825.     }
  10826.  
  10827.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10828.         drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10829.         drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10830.  
  10831.         mid = (mid << 1) | (side & 0x01);
  10832.  
  10833.         pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) * factor;
  10834.         pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) * factor;
  10835.     }
  10836. }
  10837.  
  10838. #if defined(DRFLAC_SUPPORT_SSE2)
  10839. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10840. {
  10841.     drflac_uint64 i;
  10842.     drflac_uint64 frameCount4 = frameCount >> 2;
  10843.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10844.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10845.     drflac_uint32 shift = unusedBitsPerSample - 8;
  10846.     float factor;
  10847.     __m128 factor128;
  10848.  
  10849.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  10850.  
  10851.     factor = 1.0f / 8388608.0f;
  10852.     factor128 = _mm_set1_ps(factor);
  10853.  
  10854.     if (shift == 0) {
  10855.         for (i = 0; i < frameCount4; ++i) {
  10856.             __m128i mid;
  10857.             __m128i side;
  10858.             __m128i tempL;
  10859.             __m128i tempR;
  10860.             __m128  leftf;
  10861.             __m128  rightf;
  10862.  
  10863.             mid    = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  10864.             side   = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  10865.  
  10866.             mid    = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  10867.  
  10868.             tempL  = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
  10869.             tempR  = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
  10870.  
  10871.             leftf  = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
  10872.             rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
  10873.  
  10874.             _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  10875.             _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  10876.         }
  10877.  
  10878.         for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10879.             drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10880.             drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10881.  
  10882.             mid = (mid << 1) | (side & 0x01);
  10883.  
  10884.             pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
  10885.             pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
  10886.         }
  10887.     } else {
  10888.         shift -= 1;
  10889.         for (i = 0; i < frameCount4; ++i) {
  10890.             __m128i mid;
  10891.             __m128i side;
  10892.             __m128i tempL;
  10893.             __m128i tempR;
  10894.             __m128 leftf;
  10895.             __m128 rightf;
  10896.  
  10897.             mid    = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  10898.             side   = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  10899.  
  10900.             mid    = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  10901.  
  10902.             tempL  = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
  10903.             tempR  = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
  10904.  
  10905.             leftf  = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
  10906.             rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
  10907.  
  10908.             _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  10909.             _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  10910.         }
  10911.  
  10912.         for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10913.             drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10914.             drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10915.  
  10916.             mid = (mid << 1) | (side & 0x01);
  10917.  
  10918.             pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
  10919.             pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
  10920.         }
  10921.     }
  10922. }
  10923. #endif
  10924.  
  10925. #if defined(DRFLAC_SUPPORT_NEON)
  10926. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  10927. {
  10928.     drflac_uint64 i;
  10929.     drflac_uint64 frameCount4 = frameCount >> 2;
  10930.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  10931.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  10932.     drflac_uint32 shift = unusedBitsPerSample - 8;
  10933.     float factor;
  10934.     float32x4_t factor4;
  10935.     int32x4_t shift4;
  10936.     int32x4_t wbps0_4;  /* Wasted Bits Per Sample */
  10937.     int32x4_t wbps1_4;  /* Wasted Bits Per Sample */
  10938.  
  10939.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  10940.  
  10941.     factor  = 1.0f / 8388608.0f;
  10942.     factor4 = vdupq_n_f32(factor);
  10943.     wbps0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  10944.     wbps1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  10945.  
  10946.     if (shift == 0) {
  10947.         for (i = 0; i < frameCount4; ++i) {
  10948.             int32x4_t lefti;
  10949.             int32x4_t righti;
  10950.             float32x4_t leftf;
  10951.             float32x4_t rightf;
  10952.  
  10953.             uint32x4_t mid  = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
  10954.             uint32x4_t side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
  10955.  
  10956.             mid    = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  10957.  
  10958.             lefti  = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
  10959.             righti = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
  10960.  
  10961.             leftf  = vmulq_f32(vcvtq_f32_s32(lefti),  factor4);
  10962.             rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
  10963.  
  10964.             drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  10965.         }
  10966.  
  10967.         for (i = (frameCount4 << 2); i < frameCount; ++i) {
  10968.             drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  10969.             drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  10970.  
  10971.             mid = (mid << 1) | (side & 0x01);
  10972.  
  10973.             pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
  10974.             pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
  10975.         }
  10976.     } else {
  10977.         shift -= 1;
  10978.         shift4 = vdupq_n_s32(shift);
  10979.         for (i = 0; i < frameCount4; ++i) {
  10980.             uint32x4_t mid;
  10981.             uint32x4_t side;
  10982.             int32x4_t lefti;
  10983.             int32x4_t righti;
  10984.             float32x4_t leftf;
  10985.             float32x4_t rightf;
  10986.  
  10987.             mid    = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
  10988.             side   = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
  10989.  
  10990.             mid    = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  10991.  
  10992.             lefti  = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
  10993.             righti = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
  10994.  
  10995.             leftf  = vmulq_f32(vcvtq_f32_s32(lefti),  factor4);
  10996.             rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
  10997.  
  10998.             drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  10999.         }
  11000.  
  11001.         for (i = (frameCount4 << 2); i < frameCount; ++i) {
  11002.             drflac_uint32 mid  = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  11003.             drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  11004.  
  11005.             mid = (mid << 1) | (side & 0x01);
  11006.  
  11007.             pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
  11008.             pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
  11009.         }
  11010.     }
  11011. }
  11012. #endif
  11013.  
  11014. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  11015. {
  11016. #if defined(DRFLAC_SUPPORT_SSE2)
  11017.     if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  11018.         drflac_read_pcm_frames_f32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  11019.     } else
  11020. #elif defined(DRFLAC_SUPPORT_NEON)
  11021.     if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  11022.         drflac_read_pcm_frames_f32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  11023.     } else
  11024. #endif
  11025.     {
  11026.         /* Scalar fallback. */
  11027. #if 0
  11028.         drflac_read_pcm_frames_f32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  11029. #else
  11030.         drflac_read_pcm_frames_f32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  11031. #endif
  11032.     }
  11033. }
  11034.  
  11035. #if 0
  11036. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  11037. {
  11038.     for (drflac_uint64 i = 0; i < frameCount; ++i) {
  11039.         pOutputSamples[i*2+0] = (float)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) / 2147483648.0);
  11040.         pOutputSamples[i*2+1] = (float)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) / 2147483648.0);
  11041.     }
  11042. }
  11043. #endif
  11044.  
  11045. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  11046. {
  11047.     drflac_uint64 i;
  11048.     drflac_uint64 frameCount4 = frameCount >> 2;
  11049.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  11050.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  11051.     drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  11052.     drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  11053.     float factor = 1 / 2147483648.0;
  11054.  
  11055.     for (i = 0; i < frameCount4; ++i) {
  11056.         drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
  11057.         drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
  11058.         drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
  11059.         drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
  11060.  
  11061.         drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
  11062.         drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
  11063.         drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
  11064.         drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
  11065.  
  11066.         pOutputSamples[i*8+0] = (drflac_int32)tempL0 * factor;
  11067.         pOutputSamples[i*8+1] = (drflac_int32)tempR0 * factor;
  11068.         pOutputSamples[i*8+2] = (drflac_int32)tempL1 * factor;
  11069.         pOutputSamples[i*8+3] = (drflac_int32)tempR1 * factor;
  11070.         pOutputSamples[i*8+4] = (drflac_int32)tempL2 * factor;
  11071.         pOutputSamples[i*8+5] = (drflac_int32)tempR2 * factor;
  11072.         pOutputSamples[i*8+6] = (drflac_int32)tempL3 * factor;
  11073.         pOutputSamples[i*8+7] = (drflac_int32)tempR3 * factor;
  11074.     }
  11075.  
  11076.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  11077.         pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
  11078.         pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
  11079.     }
  11080. }
  11081.  
  11082. #if defined(DRFLAC_SUPPORT_SSE2)
  11083. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  11084. {
  11085.     drflac_uint64 i;
  11086.     drflac_uint64 frameCount4 = frameCount >> 2;
  11087.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  11088.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  11089.     drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  11090.     drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  11091.  
  11092.     float factor = 1.0f / 8388608.0f;
  11093.     __m128 factor128 = _mm_set1_ps(factor);
  11094.  
  11095.     for (i = 0; i < frameCount4; ++i) {
  11096.         __m128i lefti;
  11097.         __m128i righti;
  11098.         __m128 leftf;
  11099.         __m128 rightf;
  11100.  
  11101.         lefti  = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  11102.         righti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  11103.  
  11104.         leftf  = _mm_mul_ps(_mm_cvtepi32_ps(lefti),  factor128);
  11105.         rightf = _mm_mul_ps(_mm_cvtepi32_ps(righti), factor128);
  11106.  
  11107.         _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  11108.         _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  11109.     }
  11110.  
  11111.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  11112.         pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
  11113.         pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
  11114.     }
  11115. }
  11116. #endif
  11117.  
  11118. #if defined(DRFLAC_SUPPORT_NEON)
  11119. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  11120. {
  11121.     drflac_uint64 i;
  11122.     drflac_uint64 frameCount4 = frameCount >> 2;
  11123.     const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  11124.     const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  11125.     drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  11126.     drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  11127.  
  11128.     float factor = 1.0f / 8388608.0f;
  11129.     float32x4_t factor4 = vdupq_n_f32(factor);
  11130.     int32x4_t shift0_4  = vdupq_n_s32(shift0);
  11131.     int32x4_t shift1_4  = vdupq_n_s32(shift1);
  11132.  
  11133.     for (i = 0; i < frameCount4; ++i) {
  11134.         int32x4_t lefti;
  11135.         int32x4_t righti;
  11136.         float32x4_t leftf;
  11137.         float32x4_t rightf;
  11138.  
  11139.         lefti  = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
  11140.         righti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
  11141.  
  11142.         leftf  = vmulq_f32(vcvtq_f32_s32(lefti),  factor4);
  11143.         rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
  11144.  
  11145.         drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  11146.     }
  11147.  
  11148.     for (i = (frameCount4 << 2); i < frameCount; ++i) {
  11149.         pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
  11150.         pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
  11151.     }
  11152. }
  11153. #endif
  11154.  
  11155. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  11156. {
  11157. #if defined(DRFLAC_SUPPORT_SSE2)
  11158.     if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  11159.         drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  11160.     } else
  11161. #elif defined(DRFLAC_SUPPORT_NEON)
  11162.     if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  11163.         drflac_read_pcm_frames_f32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  11164.     } else
  11165. #endif
  11166.     {
  11167.         /* Scalar fallback. */
  11168. #if 0
  11169.         drflac_read_pcm_frames_f32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  11170. #else
  11171.         drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  11172. #endif
  11173.     }
  11174. }
  11175.  
  11176. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut)
  11177. {
  11178.     drflac_uint64 framesRead;
  11179.     drflac_uint32 unusedBitsPerSample;
  11180.  
  11181.     if (pFlac == NULL || framesToRead == 0) {
  11182.         return 0;
  11183.     }
  11184.  
  11185.     if (pBufferOut == NULL) {
  11186.         return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
  11187.     }
  11188.  
  11189.     DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
  11190.     unusedBitsPerSample = 32 - pFlac->bitsPerSample;
  11191.  
  11192.     framesRead = 0;
  11193.     while (framesToRead > 0) {
  11194.         /* If we've run out of samples in this frame, go to the next. */
  11195.         if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  11196.             if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  11197.                 break;  /* Couldn't read the next frame, so just break from the loop and return. */
  11198.             }
  11199.         } else {
  11200.             unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  11201.             drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
  11202.             drflac_uint64 frameCountThisIteration = framesToRead;
  11203.  
  11204.             if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
  11205.                 frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
  11206.             }
  11207.  
  11208.             if (channelCount == 2) {
  11209.                 const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
  11210.                 const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
  11211.  
  11212.                 switch (pFlac->currentFLACFrame.header.channelAssignment)
  11213.                 {
  11214.                     case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
  11215.                     {
  11216.                         drflac_read_pcm_frames_f32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  11217.                     } break;
  11218.  
  11219.                     case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  11220.                     {
  11221.                         drflac_read_pcm_frames_f32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  11222.                     } break;
  11223.  
  11224.                     case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
  11225.                     {
  11226.                         drflac_read_pcm_frames_f32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  11227.                     } break;
  11228.  
  11229.                     case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
  11230.                     default:
  11231.                     {
  11232.                         drflac_read_pcm_frames_f32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  11233.                     } break;
  11234.                 }
  11235.             } else {
  11236.                 /* Generic interleaving. */
  11237.                 drflac_uint64 i;
  11238.                 for (i = 0; i < frameCountThisIteration; ++i) {
  11239.                     unsigned int j;
  11240.                     for (j = 0; j < channelCount; ++j) {
  11241.                         drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
  11242.                         pBufferOut[(i*channelCount)+j] = (float)(sampleS32 / 2147483648.0);
  11243.                     }
  11244.                 }
  11245.             }
  11246.  
  11247.             framesRead                += frameCountThisIteration;
  11248.             pBufferOut                += frameCountThisIteration * channelCount;
  11249.             framesToRead              -= frameCountThisIteration;
  11250.             pFlac->currentPCMFrame    += frameCountThisIteration;
  11251.             pFlac->currentFLACFrame.pcmFramesRemaining -= (unsigned int)frameCountThisIteration;
  11252.         }
  11253.     }
  11254.  
  11255.     return framesRead;
  11256. }
  11257.  
  11258.  
  11259. DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  11260. {
  11261.     if (pFlac == NULL) {
  11262.         return DRFLAC_FALSE;
  11263.     }
  11264.  
  11265.     /* Don't do anything if we're already on the seek point. */
  11266.     if (pFlac->currentPCMFrame == pcmFrameIndex) {
  11267.         return DRFLAC_TRUE;
  11268.     }
  11269.  
  11270.     /*
  11271.     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
  11272.     when the decoder was opened.
  11273.     */
  11274.     if (pFlac->firstFLACFramePosInBytes == 0) {
  11275.         return DRFLAC_FALSE;
  11276.     }
  11277.  
  11278.     if (pcmFrameIndex == 0) {
  11279.         pFlac->currentPCMFrame = 0;
  11280.         return drflac__seek_to_first_frame(pFlac);
  11281.     } else {
  11282.         drflac_bool32 wasSuccessful = DRFLAC_FALSE;
  11283.  
  11284.         /* Clamp the sample to the end. */
  11285.         if (pcmFrameIndex > pFlac->totalPCMFrameCount) {
  11286.             pcmFrameIndex = pFlac->totalPCMFrameCount;
  11287.         }
  11288.  
  11289.         /* If the target sample and the current sample are in the same frame we just move the position forward. */
  11290.         if (pcmFrameIndex > pFlac->currentPCMFrame) {
  11291.             /* Forward. */
  11292.             drflac_uint32 offset = (drflac_uint32)(pcmFrameIndex - pFlac->currentPCMFrame);
  11293.             if (pFlac->currentFLACFrame.pcmFramesRemaining >  offset) {
  11294.                 pFlac->currentFLACFrame.pcmFramesRemaining -= offset;
  11295.                 pFlac->currentPCMFrame = pcmFrameIndex;
  11296.                 return DRFLAC_TRUE;
  11297.             }
  11298.         } else {
  11299.             /* Backward. */
  11300.             drflac_uint32 offsetAbs = (drflac_uint32)(pFlac->currentPCMFrame - pcmFrameIndex);
  11301.             drflac_uint32 currentFLACFramePCMFrameCount = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
  11302.             drflac_uint32 currentFLACFramePCMFramesConsumed = currentFLACFramePCMFrameCount - pFlac->currentFLACFrame.pcmFramesRemaining;
  11303.             if (currentFLACFramePCMFramesConsumed > offsetAbs) {
  11304.                 pFlac->currentFLACFrame.pcmFramesRemaining += offsetAbs;
  11305.                 pFlac->currentPCMFrame = pcmFrameIndex;
  11306.                 return DRFLAC_TRUE;
  11307.             }
  11308.         }
  11309.  
  11310.         /*
  11311.         Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so
  11312.         we'll instead use Ogg's natural seeking facility.
  11313.         */
  11314. #ifndef DR_FLAC_NO_OGG
  11315.         if (pFlac->container == drflac_container_ogg)
  11316.         {
  11317.             wasSuccessful = drflac_ogg__seek_to_pcm_frame(pFlac, pcmFrameIndex);
  11318.         }
  11319.         else
  11320. #endif
  11321.         {
  11322.             /* First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower. */
  11323.             if (/*!wasSuccessful && */!pFlac->_noSeekTableSeek) {
  11324.                 wasSuccessful = drflac__seek_to_pcm_frame__seek_table(pFlac, pcmFrameIndex);
  11325.             }
  11326.  
  11327. #if !defined(DR_FLAC_NO_CRC)
  11328.             /* Fall back to binary search if seek table seeking fails. This requires the length of the stream to be known. */
  11329.             if (!wasSuccessful && !pFlac->_noBinarySearchSeek && pFlac->totalPCMFrameCount > 0) {
  11330.                 wasSuccessful = drflac__seek_to_pcm_frame__binary_search(pFlac, pcmFrameIndex);
  11331.             }
  11332. #endif
  11333.  
  11334.             /* Fall back to brute force if all else fails. */
  11335.             if (!wasSuccessful && !pFlac->_noBruteForceSeek) {
  11336.                 wasSuccessful = drflac__seek_to_pcm_frame__brute_force(pFlac, pcmFrameIndex);
  11337.             }
  11338.         }
  11339.  
  11340.         pFlac->currentPCMFrame = pcmFrameIndex;
  11341.         return wasSuccessful;
  11342.     }
  11343. }
  11344.  
  11345.  
  11346.  
  11347. /* High Level APIs */
  11348.  
  11349. #if defined(SIZE_MAX)
  11350.     #define DRFLAC_SIZE_MAX  SIZE_MAX
  11351. #else
  11352.     #if defined(DRFLAC_64BIT)
  11353.         #define DRFLAC_SIZE_MAX  ((drflac_uint64)0xFFFFFFFFFFFFFFFF)
  11354.     #else
  11355.         #define DRFLAC_SIZE_MAX  0xFFFFFFFF
  11356.     #endif
  11357. #endif
  11358.  
  11359.  
  11360. /* Using a macro as the definition of the drflac__full_decode_and_close_*() API family. Sue me. */
  11361. #define DRFLAC_DEFINE_FULL_READ_AND_CLOSE(extension, type) \
  11362. static type* drflac__full_read_and_close_ ## extension (drflac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut)\
  11363. {                                                                                                                                                                   \
  11364.     type* pSampleData = NULL;                                                                                                                                       \
  11365.     drflac_uint64 totalPCMFrameCount;                                                                                                                               \
  11366.                                                                                                                                                                     \
  11367.     DRFLAC_ASSERT(pFlac != NULL);                                                                                                                                   \
  11368.                                                                                                                                                                     \
  11369.     totalPCMFrameCount = pFlac->totalPCMFrameCount;                                                                                                                 \
  11370.                                                                                                                                                                     \
  11371.     if (totalPCMFrameCount == 0) {                                                                                                                                  \
  11372.         type buffer[4096];                                                                                                                                          \
  11373.         drflac_uint64 pcmFramesRead;                                                                                                                                \
  11374.         size_t sampleDataBufferSize = sizeof(buffer);                                                                                                               \
  11375.                                                                                                                                                                     \
  11376.         pSampleData = (type*)drflac__malloc_from_callbacks(sampleDataBufferSize, &pFlac->allocationCallbacks);                                                      \
  11377.         if (pSampleData == NULL) {                                                                                                                                  \
  11378.             goto on_error;                                                                                                                                          \
  11379.         }                                                                                                                                                           \
  11380.                                                                                                                                                                     \
  11381.         while ((pcmFramesRead = (drflac_uint64)drflac_read_pcm_frames_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0])/pFlac->channels, buffer)) > 0) {          \
  11382.             if (((totalPCMFrameCount + pcmFramesRead) * pFlac->channels * sizeof(type)) > sampleDataBufferSize) {                                                   \
  11383.                 type* pNewSampleData;                                                                                                                               \
  11384.                 size_t newSampleDataBufferSize;                                                                                                                     \
  11385.                                                                                                                                                                     \
  11386.                 newSampleDataBufferSize = sampleDataBufferSize * 2;                                                                                                 \
  11387.                 pNewSampleData = (type*)drflac__realloc_from_callbacks(pSampleData, newSampleDataBufferSize, sampleDataBufferSize, &pFlac->allocationCallbacks);    \
  11388.                 if (pNewSampleData == NULL) {                                                                                                                       \
  11389.                     drflac__free_from_callbacks(pSampleData, &pFlac->allocationCallbacks);                                                                          \
  11390.                     goto on_error;                                                                                                                                  \
  11391.                 }                                                                                                                                                   \
  11392.                                                                                                                                                                     \
  11393.                 sampleDataBufferSize = newSampleDataBufferSize;                                                                                                     \
  11394.                 pSampleData = pNewSampleData;                                                                                                                       \
  11395.             }                                                                                                                                                       \
  11396.                                                                                                                                                                     \
  11397.             DRFLAC_COPY_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), buffer, (size_t)(pcmFramesRead*pFlac->channels*sizeof(type)));                   \
  11398.             totalPCMFrameCount += pcmFramesRead;                                                                                                                    \
  11399.         }                                                                                                                                                           \
  11400.                                                                                                                                                                     \
  11401.         /* At this point everything should be decoded, but we just want to fill the unused part buffer with silence - need to                                       \
  11402.            protect those ears from random noise! */                                                                                                                 \
  11403.         DRFLAC_ZERO_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), (size_t)(sampleDataBufferSize - totalPCMFrameCount*pFlac->channels*sizeof(type)));   \
  11404.     } else {                                                                                                                                                        \
  11405.         drflac_uint64 dataSize = totalPCMFrameCount*pFlac->channels*sizeof(type);                                                                                   \
  11406.         if (dataSize > DRFLAC_SIZE_MAX) {                                                                                                                           \
  11407.             goto on_error;  /* The decoded data is too big. */                                                                                                      \
  11408.         }                                                                                                                                                           \
  11409.                                                                                                                                                                     \
  11410.         pSampleData = (type*)drflac__malloc_from_callbacks((size_t)dataSize, &pFlac->allocationCallbacks);    /* <-- Safe cast as per the check above. */           \
  11411.         if (pSampleData == NULL) {                                                                                                                                  \
  11412.             goto on_error;                                                                                                                                          \
  11413.         }                                                                                                                                                           \
  11414.                                                                                                                                                                     \
  11415.         totalPCMFrameCount = drflac_read_pcm_frames_##extension(pFlac, pFlac->totalPCMFrameCount, pSampleData);                                                     \
  11416.     }                                                                                                                                                               \
  11417.                                                                                                                                                                     \
  11418.     if (sampleRateOut) *sampleRateOut = pFlac->sampleRate;                                                                                                          \
  11419.     if (channelsOut) *channelsOut = pFlac->channels;                                                                                                                \
  11420.     if (totalPCMFrameCountOut) *totalPCMFrameCountOut = totalPCMFrameCount;                                                                                         \
  11421.                                                                                                                                                                     \
  11422.     drflac_close(pFlac);                                                                                                                                            \
  11423.     return pSampleData;                                                                                                                                             \
  11424.                                                                                                                                                                     \
  11425. on_error:                                                                                                                                                           \
  11426.     drflac_close(pFlac);                                                                                                                                            \
  11427.     return NULL;                                                                                                                                                    \
  11428. }
  11429.  
  11430. DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s32, drflac_int32)
  11431. DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s16, drflac_int16)
  11432. DRFLAC_DEFINE_FULL_READ_AND_CLOSE(f32, float)
  11433.  
  11434. DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
  11435. {
  11436.     drflac* pFlac;
  11437.  
  11438.     if (channelsOut) {
  11439.         *channelsOut = 0;
  11440.     }
  11441.     if (sampleRateOut) {
  11442.         *sampleRateOut = 0;
  11443.     }
  11444.     if (totalPCMFrameCountOut) {
  11445.         *totalPCMFrameCountOut = 0;
  11446.     }
  11447.  
  11448.     pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
  11449.     if (pFlac == NULL) {
  11450.         return NULL;
  11451.     }
  11452.  
  11453.     return drflac__full_read_and_close_s32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
  11454. }
  11455.  
  11456. DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
  11457. {
  11458.     drflac* pFlac;
  11459.  
  11460.     if (channelsOut) {
  11461.         *channelsOut = 0;
  11462.     }
  11463.     if (sampleRateOut) {
  11464.         *sampleRateOut = 0;
  11465.     }
  11466.     if (totalPCMFrameCountOut) {
  11467.         *totalPCMFrameCountOut = 0;
  11468.     }
  11469.  
  11470.     pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
  11471.     if (pFlac == NULL) {
  11472.         return NULL;
  11473.     }
  11474.  
  11475.     return drflac__full_read_and_close_s16(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
  11476. }
  11477.  
  11478. DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
  11479. {
  11480.     drflac* pFlac;
  11481.  
  11482.     if (channelsOut) {
  11483.         *channelsOut = 0;
  11484.     }
  11485.     if (sampleRateOut) {
  11486.         *sampleRateOut = 0;
  11487.     }
  11488.     if (totalPCMFrameCountOut) {
  11489.         *totalPCMFrameCountOut = 0;
  11490.     }
  11491.  
  11492.     pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
  11493.     if (pFlac == NULL) {
  11494.         return NULL;
  11495.     }
  11496.  
  11497.     return drflac__full_read_and_close_f32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
  11498. }
  11499.  
  11500. #ifndef DR_FLAC_NO_STDIO
  11501. DRFLAC_API drflac_int32* drflac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  11502. {
  11503.     drflac* pFlac;
  11504.  
  11505.     if (sampleRate) {
  11506.         *sampleRate = 0;
  11507.     }
  11508.     if (channels) {
  11509.         *channels = 0;
  11510.     }
  11511.     if (totalPCMFrameCount) {
  11512.         *totalPCMFrameCount = 0;
  11513.     }
  11514.  
  11515.     pFlac = drflac_open_file(filename, pAllocationCallbacks);
  11516.     if (pFlac == NULL) {
  11517.         return NULL;
  11518.     }
  11519.  
  11520.     return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
  11521. }
  11522.  
  11523. DRFLAC_API drflac_int16* drflac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  11524. {
  11525.     drflac* pFlac;
  11526.  
  11527.     if (sampleRate) {
  11528.         *sampleRate = 0;
  11529.     }
  11530.     if (channels) {
  11531.         *channels = 0;
  11532.     }
  11533.     if (totalPCMFrameCount) {
  11534.         *totalPCMFrameCount = 0;
  11535.     }
  11536.  
  11537.     pFlac = drflac_open_file(filename, pAllocationCallbacks);
  11538.     if (pFlac == NULL) {
  11539.         return NULL;
  11540.     }
  11541.  
  11542.     return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
  11543. }
  11544.  
  11545. DRFLAC_API float* drflac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  11546. {
  11547.     drflac* pFlac;
  11548.  
  11549.     if (sampleRate) {
  11550.         *sampleRate = 0;
  11551.     }
  11552.     if (channels) {
  11553.         *channels = 0;
  11554.     }
  11555.     if (totalPCMFrameCount) {
  11556.         *totalPCMFrameCount = 0;
  11557.     }
  11558.  
  11559.     pFlac = drflac_open_file(filename, pAllocationCallbacks);
  11560.     if (pFlac == NULL) {
  11561.         return NULL;
  11562.     }
  11563.  
  11564.     return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
  11565. }
  11566. #endif
  11567.  
  11568. DRFLAC_API drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  11569. {
  11570.     drflac* pFlac;
  11571.  
  11572.     if (sampleRate) {
  11573.         *sampleRate = 0;
  11574.     }
  11575.     if (channels) {
  11576.         *channels = 0;
  11577.     }
  11578.     if (totalPCMFrameCount) {
  11579.         *totalPCMFrameCount = 0;
  11580.     }
  11581.  
  11582.     pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
  11583.     if (pFlac == NULL) {
  11584.         return NULL;
  11585.     }
  11586.  
  11587.     return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
  11588. }
  11589.  
  11590. DRFLAC_API drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  11591. {
  11592.     drflac* pFlac;
  11593.  
  11594.     if (sampleRate) {
  11595.         *sampleRate = 0;
  11596.     }
  11597.     if (channels) {
  11598.         *channels = 0;
  11599.     }
  11600.     if (totalPCMFrameCount) {
  11601.         *totalPCMFrameCount = 0;
  11602.     }
  11603.  
  11604.     pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
  11605.     if (pFlac == NULL) {
  11606.         return NULL;
  11607.     }
  11608.  
  11609.     return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
  11610. }
  11611.  
  11612. DRFLAC_API float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  11613. {
  11614.     drflac* pFlac;
  11615.  
  11616.     if (sampleRate) {
  11617.         *sampleRate = 0;
  11618.     }
  11619.     if (channels) {
  11620.         *channels = 0;
  11621.     }
  11622.     if (totalPCMFrameCount) {
  11623.         *totalPCMFrameCount = 0;
  11624.     }
  11625.  
  11626.     pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
  11627.     if (pFlac == NULL) {
  11628.         return NULL;
  11629.     }
  11630.  
  11631.     return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
  11632. }
  11633.  
  11634.  
  11635. DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
  11636. {
  11637.     if (pAllocationCallbacks != NULL) {
  11638.         drflac__free_from_callbacks(p, pAllocationCallbacks);
  11639.     } else {
  11640.         drflac__free_default(p, NULL);
  11641.     }
  11642. }
  11643.  
  11644.  
  11645.  
  11646.  
  11647. DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments)
  11648. {
  11649.     if (pIter == NULL) {
  11650.         return;
  11651.     }
  11652.  
  11653.     pIter->countRemaining = commentCount;
  11654.     pIter->pRunningData   = (const char*)pComments;
  11655. }
  11656.  
  11657. DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut)
  11658. {
  11659.     drflac_int32 length;
  11660.     const char* pComment;
  11661.  
  11662.     /* Safety. */
  11663.     if (pCommentLengthOut) {
  11664.         *pCommentLengthOut = 0;
  11665.     }
  11666.  
  11667.     if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
  11668.         return NULL;
  11669.     }
  11670.  
  11671.     length = drflac__le2host_32(*(const drflac_uint32*)pIter->pRunningData);
  11672.     pIter->pRunningData += 4;
  11673.  
  11674.     pComment = pIter->pRunningData;
  11675.     pIter->pRunningData += length;
  11676.     pIter->countRemaining -= 1;
  11677.  
  11678.     if (pCommentLengthOut) {
  11679.         *pCommentLengthOut = length;
  11680.     }
  11681.  
  11682.     return pComment;
  11683. }
  11684.  
  11685.  
  11686.  
  11687.  
  11688. DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData)
  11689. {
  11690.     if (pIter == NULL) {
  11691.         return;
  11692.     }
  11693.  
  11694.     pIter->countRemaining = trackCount;
  11695.     pIter->pRunningData   = (const char*)pTrackData;
  11696. }
  11697.  
  11698. DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack)
  11699. {
  11700.     drflac_cuesheet_track cuesheetTrack;
  11701.     const char* pRunningData;
  11702.     drflac_uint64 offsetHi;
  11703.     drflac_uint64 offsetLo;
  11704.  
  11705.     if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
  11706.         return DRFLAC_FALSE;
  11707.     }
  11708.  
  11709.     pRunningData = pIter->pRunningData;
  11710.  
  11711.     offsetHi                   = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  11712.     offsetLo                   = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  11713.     cuesheetTrack.offset       = offsetLo | (offsetHi << 32);
  11714.     cuesheetTrack.trackNumber  = pRunningData[0];                                         pRunningData += 1;
  11715.     DRFLAC_COPY_MEMORY(cuesheetTrack.ISRC, pRunningData, sizeof(cuesheetTrack.ISRC));     pRunningData += 12;
  11716.     cuesheetTrack.isAudio      = (pRunningData[0] & 0x80) != 0;
  11717.     cuesheetTrack.preEmphasis  = (pRunningData[0] & 0x40) != 0;                           pRunningData += 14;
  11718.     cuesheetTrack.indexCount   = pRunningData[0];                                         pRunningData += 1;
  11719.     cuesheetTrack.pIndexPoints = (const drflac_cuesheet_track_index*)pRunningData;        pRunningData += cuesheetTrack.indexCount * sizeof(drflac_cuesheet_track_index);
  11720.  
  11721.     pIter->pRunningData = pRunningData;
  11722.     pIter->countRemaining -= 1;
  11723.  
  11724.     if (pCuesheetTrack) {
  11725.         *pCuesheetTrack = cuesheetTrack;
  11726.     }
  11727.  
  11728.     return DRFLAC_TRUE;
  11729. }
  11730.  
  11731. #if defined(__GNUC__)
  11732.     #pragma GCC diagnostic pop
  11733. #endif
  11734. #endif  /* DR_FLAC_IMPLEMENTATION */
  11735.  
  11736.  
  11737. /*
  11738. REVISION HISTORY
  11739. ================
  11740. v0.12.13 - 2020-05-16
  11741.   - Add compile-time and run-time version querying.
  11742.     - DRFLAC_VERSION_MINOR
  11743.     - DRFLAC_VERSION_MAJOR
  11744.     - DRFLAC_VERSION_REVISION
  11745.     - DRFLAC_VERSION_STRING
  11746.     - drflac_version()
  11747.     - drflac_version_string()
  11748.  
  11749. v0.12.12 - 2020-04-30
  11750.   - Fix compilation errors with VC6.
  11751.  
  11752. v0.12.11 - 2020-04-19
  11753.   - Fix some pedantic warnings.
  11754.   - Fix some undefined behaviour warnings.
  11755.  
  11756. v0.12.10 - 2020-04-10
  11757.   - Fix some bugs when trying to seek with an invalid seek table.
  11758.  
  11759. v0.12.9 - 2020-04-05
  11760.   - Fix warnings.
  11761.  
  11762. v0.12.8 - 2020-04-04
  11763.   - Add drflac_open_file_w() and drflac_open_file_with_metadata_w().
  11764.   - Fix some static analysis warnings.
  11765.   - Minor documentation updates.
  11766.  
  11767. v0.12.7 - 2020-03-14
  11768.   - Fix compilation errors with VC6.
  11769.  
  11770. v0.12.6 - 2020-03-07
  11771.   - Fix compilation error with Visual Studio .NET 2003.
  11772.  
  11773. v0.12.5 - 2020-01-30
  11774.   - Silence some static analysis warnings.
  11775.  
  11776. v0.12.4 - 2020-01-29
  11777.   - Silence some static analysis warnings.
  11778.  
  11779. v0.12.3 - 2019-12-02
  11780.   - Fix some warnings when compiling with GCC and the -Og flag.
  11781.   - Fix a crash in out-of-memory situations.
  11782.   - Fix potential integer overflow bug.
  11783.   - Fix some static analysis warnings.
  11784.   - Fix a possible crash when using custom memory allocators without a custom realloc() implementation.
  11785.   - Fix a bug with binary search seeking where the bits per sample is not a multiple of 8.
  11786.  
  11787. v0.12.2 - 2019-10-07
  11788.   - Internal code clean up.
  11789.  
  11790. v0.12.1 - 2019-09-29
  11791.   - Fix some Clang Static Analyzer warnings.
  11792.   - Fix an unused variable warning.
  11793.  
  11794. v0.12.0 - 2019-09-23
  11795.   - API CHANGE: Add support for user defined memory allocation routines. This system allows the program to specify their own memory allocation
  11796.     routines with a user data pointer for client-specific contextual data. This adds an extra parameter to the end of the following APIs:
  11797.     - drflac_open()
  11798.     - drflac_open_relaxed()
  11799.     - drflac_open_with_metadata()
  11800.     - drflac_open_with_metadata_relaxed()
  11801.     - drflac_open_file()
  11802.     - drflac_open_file_with_metadata()
  11803.     - drflac_open_memory()
  11804.     - drflac_open_memory_with_metadata()
  11805.     - drflac_open_and_read_pcm_frames_s32()
  11806.     - drflac_open_and_read_pcm_frames_s16()
  11807.     - drflac_open_and_read_pcm_frames_f32()
  11808.     - drflac_open_file_and_read_pcm_frames_s32()
  11809.     - drflac_open_file_and_read_pcm_frames_s16()
  11810.     - drflac_open_file_and_read_pcm_frames_f32()
  11811.     - drflac_open_memory_and_read_pcm_frames_s32()
  11812.     - drflac_open_memory_and_read_pcm_frames_s16()
  11813.     - drflac_open_memory_and_read_pcm_frames_f32()
  11814.     Set this extra parameter to NULL to use defaults which is the same as the previous behaviour. Setting this NULL will use
  11815.     DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE.
  11816.   - Remove deprecated APIs:
  11817.     - drflac_read_s32()
  11818.     - drflac_read_s16()
  11819.     - drflac_read_f32()
  11820.     - drflac_seek_to_sample()
  11821.     - drflac_open_and_decode_s32()
  11822.     - drflac_open_and_decode_s16()
  11823.     - drflac_open_and_decode_f32()
  11824.     - drflac_open_and_decode_file_s32()
  11825.     - drflac_open_and_decode_file_s16()
  11826.     - drflac_open_and_decode_file_f32()
  11827.     - drflac_open_and_decode_memory_s32()
  11828.     - drflac_open_and_decode_memory_s16()
  11829.     - drflac_open_and_decode_memory_f32()
  11830.   - Remove drflac.totalSampleCount which is now replaced with drflac.totalPCMFrameCount. You can emulate drflac.totalSampleCount
  11831.     by doing pFlac->totalPCMFrameCount*pFlac->channels.
  11832.   - Rename drflac.currentFrame to drflac.currentFLACFrame to remove ambiguity with PCM frames.
  11833.   - Fix errors when seeking to the end of a stream.
  11834.   - Optimizations to seeking.
  11835.   - SSE improvements and optimizations.
  11836.   - ARM NEON optimizations.
  11837.   - Optimizations to drflac_read_pcm_frames_s16().
  11838.   - Optimizations to drflac_read_pcm_frames_s32().
  11839.  
  11840. v0.11.10 - 2019-06-26
  11841.   - Fix a compiler error.
  11842.  
  11843. v0.11.9 - 2019-06-16
  11844.   - Silence some ThreadSanitizer warnings.
  11845.  
  11846. v0.11.8 - 2019-05-21
  11847.   - Fix warnings.
  11848.  
  11849. v0.11.7 - 2019-05-06
  11850.   - C89 fixes.
  11851.  
  11852. v0.11.6 - 2019-05-05
  11853.   - Add support for C89.
  11854.   - Fix a compiler warning when CRC is disabled.
  11855.   - Change license to choice of public domain or MIT-0.
  11856.  
  11857. v0.11.5 - 2019-04-19
  11858.   - Fix a compiler error with GCC.
  11859.  
  11860. v0.11.4 - 2019-04-17
  11861.   - Fix some warnings with GCC when compiling with -std=c99.
  11862.  
  11863. v0.11.3 - 2019-04-07
  11864.   - Silence warnings with GCC.
  11865.  
  11866. v0.11.2 - 2019-03-10
  11867.   - Fix a warning.
  11868.  
  11869. v0.11.1 - 2019-02-17
  11870.   - Fix a potential bug with seeking.
  11871.  
  11872. v0.11.0 - 2018-12-16
  11873.   - API CHANGE: Deprecated drflac_read_s32(), drflac_read_s16() and drflac_read_f32() and replaced them with
  11874.     drflac_read_pcm_frames_s32(), drflac_read_pcm_frames_s16() and drflac_read_pcm_frames_f32(). The new APIs take
  11875.     and return PCM frame counts instead of sample counts. To upgrade you will need to change the input count by
  11876.     dividing it by the channel count, and then do the same with the return value.
  11877.   - API_CHANGE: Deprecated drflac_seek_to_sample() and replaced with drflac_seek_to_pcm_frame(). Same rules as
  11878.     the changes to drflac_read_*() apply.
  11879.   - API CHANGE: Deprecated drflac_open_and_decode_*() and replaced with drflac_open_*_and_read_*(). Same rules as
  11880.     the changes to drflac_read_*() apply.
  11881.   - Optimizations.
  11882.  
  11883. v0.10.0 - 2018-09-11
  11884.   - Remove the DR_FLAC_NO_WIN32_IO option and the Win32 file IO functionality. If you need to use Win32 file IO you
  11885.     need to do it yourself via the callback API.
  11886.   - Fix the clang build.
  11887.   - Fix undefined behavior.
  11888.   - Fix errors with CUESHEET metdata blocks.
  11889.   - Add an API for iterating over each cuesheet track in the CUESHEET metadata block. This works the same way as the
  11890.     Vorbis comment API.
  11891.   - Other miscellaneous bug fixes, mostly relating to invalid FLAC streams.
  11892.   - Minor optimizations.
  11893.  
  11894. v0.9.11 - 2018-08-29
  11895.   - Fix a bug with sample reconstruction.
  11896.  
  11897. v0.9.10 - 2018-08-07
  11898.   - Improve 64-bit detection.
  11899.  
  11900. v0.9.9 - 2018-08-05
  11901.   - Fix C++ build on older versions of GCC.
  11902.  
  11903. v0.9.8 - 2018-07-24
  11904.   - Fix compilation errors.
  11905.  
  11906. v0.9.7 - 2018-07-05
  11907.   - Fix a warning.
  11908.  
  11909. v0.9.6 - 2018-06-29
  11910.   - Fix some typos.
  11911.  
  11912. v0.9.5 - 2018-06-23
  11913.   - Fix some warnings.
  11914.  
  11915. v0.9.4 - 2018-06-14
  11916.   - Optimizations to seeking.
  11917.   - Clean up.
  11918.  
  11919. v0.9.3 - 2018-05-22
  11920.   - Bug fix.
  11921.  
  11922. v0.9.2 - 2018-05-12
  11923.   - Fix a compilation error due to a missing break statement.
  11924.  
  11925. v0.9.1 - 2018-04-29
  11926.   - Fix compilation error with Clang.
  11927.  
  11928. v0.9 - 2018-04-24
  11929.   - Fix Clang build.
  11930.   - Start using major.minor.revision versioning.
  11931.  
  11932. v0.8g - 2018-04-19
  11933.   - Fix build on non-x86/x64 architectures.
  11934.  
  11935. v0.8f - 2018-02-02
  11936.   - Stop pretending to support changing rate/channels mid stream.
  11937.  
  11938. v0.8e - 2018-02-01
  11939.   - Fix a crash when the block size of a frame is larger than the maximum block size defined by the FLAC stream.
  11940.   - Fix a crash the the Rice partition order is invalid.
  11941.  
  11942. v0.8d - 2017-09-22
  11943.   - Add support for decoding streams with ID3 tags. ID3 tags are just skipped.
  11944.  
  11945. v0.8c - 2017-09-07
  11946.   - Fix warning on non-x86/x64 architectures.
  11947.  
  11948. v0.8b - 2017-08-19
  11949.   - Fix build on non-x86/x64 architectures.
  11950.  
  11951. v0.8a - 2017-08-13
  11952.   - A small optimization for the Clang build.
  11953.  
  11954. v0.8 - 2017-08-12
  11955.   - API CHANGE: Rename dr_* types to drflac_*.
  11956.   - Optimizations. This brings dr_flac back to about the same class of efficiency as the reference implementation.
  11957.   - Add support for custom implementations of malloc(), realloc(), etc.
  11958.   - Add CRC checking to Ogg encapsulated streams.
  11959.   - Fix VC++ 6 build. This is only for the C++ compiler. The C compiler is not currently supported.
  11960.   - Bug fixes.
  11961.  
  11962. v0.7 - 2017-07-23
  11963.   - Add support for opening a stream without a header block. To do this, use drflac_open_relaxed() / drflac_open_with_metadata_relaxed().
  11964.  
  11965. v0.6 - 2017-07-22
  11966.   - Add support for recovering from invalid frames. With this change, dr_flac will simply skip over invalid frames as if they
  11967.     never existed. Frames are checked against their sync code, the CRC-8 of the frame header and the CRC-16 of the whole frame.
  11968.  
  11969. v0.5 - 2017-07-16
  11970.   - Fix typos.
  11971.   - Change drflac_bool* types to unsigned.
  11972.   - Add CRC checking. This makes dr_flac slower, but can be disabled with #define DR_FLAC_NO_CRC.
  11973.  
  11974. v0.4f - 2017-03-10
  11975.   - Fix a couple of bugs with the bitstreaming code.
  11976.  
  11977. v0.4e - 2017-02-17
  11978.   - Fix some warnings.
  11979.  
  11980. v0.4d - 2016-12-26
  11981.   - Add support for 32-bit floating-point PCM decoding.
  11982.   - Use drflac_int* and drflac_uint* sized types to improve compiler support.
  11983.   - Minor improvements to documentation.
  11984.  
  11985. v0.4c - 2016-12-26
  11986.   - Add support for signed 16-bit integer PCM decoding.
  11987.  
  11988. v0.4b - 2016-10-23
  11989.   - A minor change to drflac_bool8 and drflac_bool32 types.
  11990.  
  11991. v0.4a - 2016-10-11
  11992.   - Rename drBool32 to drflac_bool32 for styling consistency.
  11993.  
  11994. v0.4 - 2016-09-29
  11995.   - API/ABI CHANGE: Use fixed size 32-bit booleans instead of the built-in bool type.
  11996.   - API CHANGE: Rename drflac_open_and_decode*() to drflac_open_and_decode*_s32().
  11997.   - API CHANGE: Swap the order of "channels" and "sampleRate" parameters in drflac_open_and_decode*(). Rationale for this is to
  11998.     keep it consistent with drflac_audio.
  11999.  
  12000. v0.3f - 2016-09-21
  12001.   - Fix a warning with GCC.
  12002.  
  12003. v0.3e - 2016-09-18
  12004.   - Fixed a bug where GCC 4.3+ was not getting properly identified.
  12005.   - Fixed a few typos.
  12006.   - Changed date formats to ISO 8601 (YYYY-MM-DD).
  12007.  
  12008. v0.3d - 2016-06-11
  12009.   - Minor clean up.
  12010.  
  12011. v0.3c - 2016-05-28
  12012.   - Fixed compilation error.
  12013.  
  12014. v0.3b - 2016-05-16
  12015.   - Fixed Linux/GCC build.
  12016.   - Updated documentation.
  12017.  
  12018. v0.3a - 2016-05-15
  12019.   - Minor fixes to documentation.
  12020.  
  12021. v0.3 - 2016-05-11
  12022.   - Optimizations. Now at about parity with the reference implementation on 32-bit builds.
  12023.   - Lots of clean up.
  12024.  
  12025. v0.2b - 2016-05-10
  12026.   - Bug fixes.
  12027.  
  12028. v0.2a - 2016-05-10
  12029.   - Made drflac_open_and_decode() more robust.
  12030.   - Removed an unused debugging variable
  12031.  
  12032. v0.2 - 2016-05-09
  12033.   - Added support for Ogg encapsulation.
  12034.   - API CHANGE. Have the onSeek callback take a third argument which specifies whether or not the seek
  12035.     should be relative to the start or the current position. Also changes the seeking rules such that
  12036.     seeking offsets will never be negative.
  12037.   - Have drflac_open_and_decode() fail gracefully if the stream has an unknown total sample count.
  12038.  
  12039. v0.1b - 2016-05-07
  12040.   - Properly close the file handle in drflac_open_file() and family when the decoder fails to initialize.
  12041.   - Removed a stale comment.
  12042.  
  12043. v0.1a - 2016-05-05
  12044.   - Minor formatting changes.
  12045.   - Fixed a warning on the GCC build.
  12046.  
  12047. v0.1 - 2016-05-03
  12048.   - Initial versioned release.
  12049. */
  12050.  
  12051. /*
  12052. This software is available as a choice of the following licenses. Choose
  12053. whichever you prefer.
  12054.  
  12055. ===============================================================================
  12056. ALTERNATIVE 1 - Public Domain (www.unlicense.org)
  12057. ===============================================================================
  12058. This is free and unencumbered software released into the public domain.
  12059.  
  12060. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  12061. software, either in source code form or as a compiled binary, for any purpose,
  12062. commercial or non-commercial, and by any means.
  12063.  
  12064. In jurisdictions that recognize copyright laws, the author or authors of this
  12065. software dedicate any and all copyright interest in the software to the public
  12066. domain. We make this dedication for the benefit of the public at large and to
  12067. the detriment of our heirs and successors. We intend this dedication to be an
  12068. overt act of relinquishment in perpetuity of all present and future rights to
  12069. this software under copyright law.
  12070.  
  12071. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12072. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12073. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  12074. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  12075. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  12076. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  12077.  
  12078. For more information, please refer to <http://unlicense.org/>
  12079.  
  12080. ===============================================================================
  12081. ALTERNATIVE 2 - MIT No Attribution
  12082. ===============================================================================
  12083. Copyright 2020 David Reid
  12084.  
  12085. Permission is hereby granted, free of charge, to any person obtaining a copy of
  12086. this software and associated documentation files (the "Software"), to deal in
  12087. the Software without restriction, including without limitation the rights to
  12088. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  12089. of the Software, and to permit persons to whom the Software is furnished to do
  12090. so.
  12091.  
  12092. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  12093. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  12094. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  12095. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  12096. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  12097. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  12098. SOFTWARE.
  12099. */
  12100.