Debian Codegraph @

src/external/dr_flac.h

raw symbols SCIP
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.13.3 - 2026-01-17
4
5 David Reid - [email protected]
6
7 GitHub: https://github.com/mackron/dr_libs
8 */
9
10 /*
11 Introduction
12 ============
13 dr_flac is a single file library. To use it, do something like the following in one .c file.
14
15 ```c
16 #define DR_FLAC_IMPLEMENTATION
17 #include "dr_flac.h"
18 ```
19
20 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:
21
22 ```c
23 drflac* pFlac = drflac_open_file("MySong.flac", NULL);
24 if (pFlac == NULL) {
25 // Failed to open FLAC file
26 }
27
28 drflac_int32* pSamples = malloc(pFlac->totalPCMFrameCount * pFlac->channels * sizeof(drflac_int32));
29 drflac_uint64 numberOfInterleavedSamplesActuallyRead = drflac_read_pcm_frames_s32(pFlac, pFlac->totalPCMFrameCount, pSamples);
30 ```
31
32 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,
33 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
34 a native FLAC stream was opened, however dr_flac has seamless support for Ogg encapsulated FLAC streams as well.
35
36 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
37 samples as it can, up to the amount requested. Later on when you need the next batch of samples, just call it again. Example:
38
39 ```c
40 while (drflac_read_pcm_frames_s32(pFlac, chunkSizeInPCMFrames, pChunkSamples) > 0) {
41 do_something();
42 }
43 ```
44
45 You can seek to a specific PCM frame with `drflac_seek_to_pcm_frame()`.
46
47 If you just want to quickly decode an entire FLAC file in one go you can do something like this:
48
49 ```c
50 unsigned int channels;
51 unsigned int sampleRate;
52 drflac_uint64 totalPCMFrameCount;
53 drflac_int32* pSampleData = drflac_open_file_and_read_pcm_frames_s32("MySong.flac", &channels, &sampleRate, &totalPCMFrameCount, NULL);
54 if (pSampleData == NULL) {
55 // Failed to open and decode FLAC file.
56 }
57
58 ...
59
60 drflac_free(pSampleData, NULL);
61 ```
62
63 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
64 should be considered lossy.
65
66
67 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()`.
68 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
69 reports metadata to the application through the use of a callback, and every metadata block is reported before `drflac_open_with_metdata()` returns.
70
71 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
72 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:
73
74 `drflac_open_relaxed()`
75 `drflac_open_with_metadata_relaxed()`
76
77 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
78 APIs can take a long time to initialize because they may need to spend a lot of time finding the first frame.
79
80
81
82 Build Options
83 =============
84 #define these options before including this file.
85
86 #define DR_FLAC_NO_STDIO
87 Disable `drflac_open_file()` and family.
88
89 #define DR_FLAC_NO_OGG
90 Disables support for Ogg/FLAC streams.
91
92 #define DR_FLAC_BUFFER_SIZE <number>
93 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.
94 Larger values means more memory, but better performance. My tests show diminishing returns after about 4KB (which is the default). Consider reducing this if
95 you have a very efficient implementation of onRead(), or increase it if it's very inefficient. Must be a multiple of 8.
96
97 #define DR_FLAC_NO_CRC
98 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
99 be used if available. Otherwise the seek will be performed using brute force.
100
101 #define DR_FLAC_NO_SIMD
102 Disables SIMD optimizations (SSE on x86/x64 architectures, NEON on ARM architectures). Use this if you are having compatibility issues with your compiler.
103
104 #define DR_FLAC_NO_WCHAR
105 Disables all functions ending with `_w`. Use this if your compiler does not provide wchar.h. Not required if DR_FLAC_NO_STDIO is also defined.
106
107
108
109 Notes
110 =====
111 - dr_flac does not support changing the sample rate nor channel count mid stream.
112 - dr_flac is not thread-safe, but its APIs can be called from any thread so long as you do your own synchronization.
113 - When using Ogg encapsulation, a corrupted metadata block will result in `drflac_open_with_metadata()` and `drflac_open()` returning inconsistent samples due
114 to differences in corrupted stream recorvery logic between the two APIs.
115 */
116
117 #ifndef dr_flac_h
118 #define dr_flac_h
119
120 #ifdef __cplusplus
121 extern "C" {
122 #endif
123
124 #define DRFLAC_STRINGIFY(x) #x
125 #define DRFLAC_XSTRINGIFY(x) DRFLAC_STRINGIFY(x)
126
127 #define DRFLAC_VERSION_MAJOR 0
128 #define DRFLAC_VERSION_MINOR 13
129 #define DRFLAC_VERSION_REVISION 3
130 #define DRFLAC_VERSION_STRING DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MAJOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MINOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_REVISION)
131
132 #include <stddef.h> /* For size_t. */
133
134 /* Sized Types */
135 typedef signed char drflac_int8;
136 typedef unsigned char drflac_uint8;
137 typedef signed short drflac_int16;
138 typedef unsigned short drflac_uint16;
139 typedef signed int drflac_int32;
140 typedef unsigned int drflac_uint32;
141 #if defined(_MSC_VER) && !defined(__clang__)
142 typedef signed __int64 drflac_int64;
143 typedef unsigned __int64 drflac_uint64;
144 #else
145 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
146 #pragma GCC diagnostic push
147 #pragma GCC diagnostic ignored "-Wlong-long"
148 #if defined(__clang__)
149 #pragma GCC diagnostic ignored "-Wc++11-long-long"
150 #endif
151 #endif
152 typedef signed long long drflac_int64;
153 typedef unsigned long long drflac_uint64;
154 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
155 #pragma GCC diagnostic pop
156 #endif
157 #endif
158 #if defined(__LP64__) || defined(_WIN64) || (defined(__x86_64__) && !defined(__ILP32__)) || defined(_M_X64) || defined(__ia64) || defined(_M_IA64) || defined(__aarch64__) || defined(_M_ARM64) || defined(__powerpc64__)
159 typedef drflac_uint64 drflac_uintptr;
160 #else
161 typedef drflac_uint32 drflac_uintptr;
162 #endif
163 typedef drflac_uint8 drflac_bool8;
164 typedef drflac_uint32 drflac_bool32;
165 #define DRFLAC_TRUE 1
166 #define DRFLAC_FALSE 0
167 /* End Sized Types */
168
169 /* Decorations */
170 #if !defined(DRFLAC_API)
171 #if defined(DRFLAC_DLL)
172 #if defined(_WIN32)
173 #define DRFLAC_DLL_IMPORT __declspec(dllimport)
174 #define DRFLAC_DLL_EXPORT __declspec(dllexport)
175 #define DRFLAC_DLL_PRIVATE static
176 #else
177 #if defined(__GNUC__) && __GNUC__ >= 4
178 #define DRFLAC_DLL_IMPORT __attribute__((visibility("default")))
179 #define DRFLAC_DLL_EXPORT __attribute__((visibility("default")))
180 #define DRFLAC_DLL_PRIVATE __attribute__((visibility("hidden")))
181 #else
182 #define DRFLAC_DLL_IMPORT
183 #define DRFLAC_DLL_EXPORT
184 #define DRFLAC_DLL_PRIVATE static
185 #endif
186 #endif
187
188 #if defined(DR_FLAC_IMPLEMENTATION) || defined(DRFLAC_IMPLEMENTATION)
189 #define DRFLAC_API DRFLAC_DLL_EXPORT
190 #else
191 #define DRFLAC_API DRFLAC_DLL_IMPORT
192 #endif
193 #define DRFLAC_PRIVATE DRFLAC_DLL_PRIVATE
194 #else
195 #define DRFLAC_API extern
196 #define DRFLAC_PRIVATE static
197 #endif
198 #endif
199 /* End Decorations */
200
201 #if defined(_MSC_VER) && _MSC_VER >= 1700 /* Visual Studio 2012 */
202 #define DRFLAC_DEPRECATED __declspec(deprecated)
203 #elif (defined(__GNUC__) && __GNUC__ >= 4) /* GCC 4 */
204 #define DRFLAC_DEPRECATED __attribute__((deprecated))
205 #elif defined(__has_feature) /* Clang */
206 #if __has_feature(attribute_deprecated)
207 #define DRFLAC_DEPRECATED __attribute__((deprecated))
208 #else
209 #define DRFLAC_DEPRECATED
210 #endif
211 #else
212 #define DRFLAC_DEPRECATED
213 #endif
214
215 DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision);
216 DRFLAC_API const char* drflac_version_string(void);
217
218 /* Allocation Callbacks */
219 typedef struct
220 {
221 void* pUserData;
222 void* (* onMalloc)(size_t sz, void* pUserData);
223 void* (* onRealloc)(void* p, size_t sz, void* pUserData);
224 void (* onFree)(void* p, void* pUserData);
225 } drflac_allocation_callbacks;
226 /* End Allocation Callbacks */
227
228 /*
229 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,
230 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.
231 */
232 #ifndef DR_FLAC_BUFFER_SIZE
233 #define DR_FLAC_BUFFER_SIZE 4096
234 #endif
235
236
237 /* Architecture Detection */
238 #if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
239 #define DRFLAC_64BIT
240 #endif
241
242 #if defined(__x86_64__) || (defined(_M_X64) && !defined(_M_ARM64EC))
243 #define DRFLAC_X64
244 #elif defined(__i386) || defined(_M_IX86)
245 #define DRFLAC_X86
246 #elif defined(__arm__) || defined(_M_ARM) || defined(__arm64) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC)
247 #define DRFLAC_ARM
248 #endif
249 /* End Architecture Detection */
250
251
252 #ifdef DRFLAC_64BIT
253 typedef drflac_uint64 drflac_cache_t;
254 #else
255 typedef drflac_uint32 drflac_cache_t;
256 #endif
257
258 /* The various metadata block types. */
259 #define DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO 0
260 #define DRFLAC_METADATA_BLOCK_TYPE_PADDING 1
261 #define DRFLAC_METADATA_BLOCK_TYPE_APPLICATION 2
262 #define DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE 3
263 #define DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT 4
264 #define DRFLAC_METADATA_BLOCK_TYPE_CUESHEET 5
265 #define DRFLAC_METADATA_BLOCK_TYPE_PICTURE 6
266 #define DRFLAC_METADATA_BLOCK_TYPE_INVALID 127
267
268 /* The various picture types specified in the PICTURE block. */
269 #define DRFLAC_PICTURE_TYPE_OTHER 0
270 #define DRFLAC_PICTURE_TYPE_FILE_ICON 1
271 #define DRFLAC_PICTURE_TYPE_OTHER_FILE_ICON 2
272 #define DRFLAC_PICTURE_TYPE_COVER_FRONT 3
273 #define DRFLAC_PICTURE_TYPE_COVER_BACK 4
274 #define DRFLAC_PICTURE_TYPE_LEAFLET_PAGE 5
275 #define DRFLAC_PICTURE_TYPE_MEDIA 6
276 #define DRFLAC_PICTURE_TYPE_LEAD_ARTIST 7
277 #define DRFLAC_PICTURE_TYPE_ARTIST 8
278 #define DRFLAC_PICTURE_TYPE_CONDUCTOR 9
279 #define DRFLAC_PICTURE_TYPE_BAND 10
280 #define DRFLAC_PICTURE_TYPE_COMPOSER 11
281 #define DRFLAC_PICTURE_TYPE_LYRICIST 12
282 #define DRFLAC_PICTURE_TYPE_RECORDING_LOCATION 13
283 #define DRFLAC_PICTURE_TYPE_DURING_RECORDING 14
284 #define DRFLAC_PICTURE_TYPE_DURING_PERFORMANCE 15
285 #define DRFLAC_PICTURE_TYPE_SCREEN_CAPTURE 16
286 #define DRFLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH 17
287 #define DRFLAC_PICTURE_TYPE_ILLUSTRATION 18
288 #define DRFLAC_PICTURE_TYPE_BAND_LOGOTYPE 19
289 #define DRFLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE 20
290
291 typedef enum
292 {
293 drflac_container_native,
294 drflac_container_ogg,
295 drflac_container_unknown
296 } drflac_container;
297
298 typedef enum
299 {
300 DRFLAC_SEEK_SET,
301 DRFLAC_SEEK_CUR,
302 DRFLAC_SEEK_END
303 } drflac_seek_origin;
304
305 /* The order of members in this structure is important because we map this directly to the raw data within the SEEKTABLE metadata block. */
306 typedef struct
307 {
308 drflac_uint64 firstPCMFrame;
309 drflac_uint64 flacFrameOffset; /* The offset from the first byte of the header of the first frame. */
310 drflac_uint16 pcmFrameCount;
311 } drflac_seekpoint;
312
313 typedef struct
314 {
315 drflac_uint16 minBlockSizeInPCMFrames;
316 drflac_uint16 maxBlockSizeInPCMFrames;
317 drflac_uint32 minFrameSizeInPCMFrames;
318 drflac_uint32 maxFrameSizeInPCMFrames;
319 drflac_uint32 sampleRate;
320 drflac_uint8 channels;
321 drflac_uint8 bitsPerSample;
322 drflac_uint64 totalPCMFrameCount;
323 drflac_uint8 md5[16];
324 } drflac_streaminfo;
325
326 typedef struct
327 {
328 /*
329 The metadata type. Use this to know how to interpret the data below. Will be set to one of the
330 DRFLAC_METADATA_BLOCK_TYPE_* tokens.
331 */
332 drflac_uint32 type;
333
334 /* The size in bytes of the block and the buffer pointed to by pRawData if it's non-NULL. */
335 drflac_uint32 rawDataSize;
336
337 /* The offset in the stream of the raw data. */
338 drflac_uint64 rawDataOffset;
339
340 /*
341 A pointer to the raw data. This points to a temporary buffer so don't hold on to it. It's best to
342 not modify the contents of this buffer. Use the structures below for more meaningful and structured
343 information about the metadata. It's possible for this to be null.
344 */
345 const void* pRawData;
346
347 union
348 {
349 drflac_streaminfo streaminfo;
350
351 struct
352 {
353 int unused;
354 } padding;
355
356 struct
357 {
358 drflac_uint32 id;
359 const void* pData;
360 drflac_uint32 dataSize;
361 } application;
362
363 struct
364 {
365 drflac_uint32 seekpointCount;
366 const drflac_seekpoint* pSeekpoints;
367 } seektable;
368
369 struct
370 {
371 drflac_uint32 vendorLength;
372 const char* vendor;
373 drflac_uint32 commentCount;
374 const void* pComments;
375 } vorbis_comment;
376
377 struct
378 {
379 char catalog[128];
380 drflac_uint64 leadInSampleCount;
381 drflac_bool32 isCD;
382 drflac_uint8 trackCount;
383 const void* pTrackData;
384 } cuesheet;
385
386 struct
387 {
388 drflac_uint32 type;
389 drflac_uint32 mimeLength;
390 const char* mime;
391 drflac_uint32 descriptionLength;
392 const char* description;
393 drflac_uint32 width;
394 drflac_uint32 height;
395 drflac_uint32 colorDepth;
396 drflac_uint32 indexColorCount;
397 drflac_uint32 pictureDataSize;
398 drflac_uint64 pictureDataOffset; /* Offset from the start of the stream. */
399 const drflac_uint8* pPictureData;
400 } picture;
401 } data;
402 } drflac_metadata;
403
404
405 /*
406 Callback for when data needs to be read from the client.
407
408
409 Parameters
410 ----------
411 pUserData (in)
412 The user data that was passed to drflac_open() and family.
413
414 pBufferOut (out)
415 The output buffer.
416
417 bytesToRead (in)
418 The number of bytes to read.
419
420
421 Return Value
422 ------------
423 The number of bytes actually read.
424
425
426 Remarks
427 -------
428 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
429 you have reached the end of the stream.
430 */
431 typedef size_t (* drflac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
432
433 /*
434 Callback for when data needs to be seeked.
435
436
437 Parameters
438 ----------
439 pUserData (in)
440 The user data that was passed to drflac_open() and family.
441
442 offset (in)
443 The number of bytes to move, relative to the origin. Will never be negative.
444
445 origin (in)
446 The origin of the seek - the current position, the start of the stream, or the end of the stream.
447
448
449 Return Value
450 ------------
451 Whether or not the seek was successful.
452
453
454 Remarks
455 -------
456 Seeking relative to the start and the current position must always be supported. If seeking from the end of the stream is not supported, return DRFLAC_FALSE.
457
458 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
459 and handled by returning DRFLAC_FALSE.
460 */
461 typedef drflac_bool32 (* drflac_seek_proc)(void* pUserData, int offset, drflac_seek_origin origin);
462
463 /*
464 Callback for when the current position in the stream needs to be retrieved.
465
466
467 Parameters
468 ----------
469 pUserData (in)
470 The user data that was passed to drflac_open() and family.
471
472 pCursor (out)
473 A pointer to a variable to receive the current position in the stream.
474
475
476 Return Value
477 ------------
478 Whether or not the operation was successful.
479 */
480 typedef drflac_bool32 (* drflac_tell_proc)(void* pUserData, drflac_int64* pCursor);
481
482 /*
483 Callback for when a metadata block is read.
484
485
486 Parameters
487 ----------
488 pUserData (in)
489 The user data that was passed to drflac_open() and family.
490
491 pMetadata (in)
492 A pointer to a structure containing the data of the metadata block.
493
494
495 Remarks
496 -------
497 Use pMetadata->type to determine which metadata block is being handled and how to read the data. This
498 will be set to one of the DRFLAC_METADATA_BLOCK_TYPE_* tokens.
499 */
500 typedef void (* drflac_meta_proc)(void* pUserData, drflac_metadata* pMetadata);
501
502
503 /* Structure for internal use. Only used for decoders opened with drflac_open_memory. */
504 typedef struct
505 {
506 const drflac_uint8* data;
507 size_t dataSize;
508 size_t currentReadPos;
509 } drflac__memory_stream;
510
511 /* Structure for internal use. Used for bit streaming. */
512 typedef struct
513 {
514 /* The function to call when more data needs to be read. */
515 drflac_read_proc onRead;
516
517 /* The function to call when the current read position needs to be moved. */
518 drflac_seek_proc onSeek;
519
520 /* The function to call when the current read position needs to be retrieved. */
521 drflac_tell_proc onTell;
522
523 /* The user data to pass around to onRead and onSeek. */
524 void* pUserData;
525
526
527 /*
528 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
529 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
530 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).
531 */
532 size_t unalignedByteCount;
533
534 /* The content of the unaligned bytes. */
535 drflac_cache_t unalignedCache;
536
537 /* The index of the next valid cache line in the "L2" cache. */
538 drflac_uint32 nextL2Line;
539
540 /* The number of bits that have been consumed by the cache. This is used to determine how many valid bits are remaining. */
541 drflac_uint32 consumedBits;
542
543 /*
544 The cached data which was most recently read from the client. There are two levels of cache. Data flows as such:
545 Client -> L2 -> L1. The L2 -> L1 movement is aligned and runs on a fast path in just a few instructions.
546 */
547 drflac_cache_t cacheL2[DR_FLAC_BUFFER_SIZE/sizeof(drflac_cache_t)];
548 drflac_cache_t cache;
549
550 /*
551 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
552 is reset to 0 at the beginning of each frame.
553 */
554 drflac_uint16 crc16;
555 drflac_cache_t crc16Cache; /* A cache for optimizing CRC calculations. This is filled when when the L1 cache is reloaded. */
556 drflac_uint32 crc16CacheIgnoredBytes; /* The number of bytes to ignore when updating the CRC-16 from the CRC-16 cache. */
557 } drflac_bs;
558
559 typedef struct
560 {
561 /* The type of the subframe: SUBFRAME_CONSTANT, SUBFRAME_VERBATIM, SUBFRAME_FIXED or SUBFRAME_LPC. */
562 drflac_uint8 subframeType;
563
564 /* The number of wasted bits per sample as specified by the sub-frame header. */
565 drflac_uint8 wastedBitsPerSample;
566
567 /* The order to use for the prediction stage for SUBFRAME_FIXED and SUBFRAME_LPC. */
568 drflac_uint8 lpcOrder;
569
570 /* A pointer to the buffer containing the decoded samples in the subframe. This pointer is an offset from drflac::pExtraData. */
571 drflac_int32* pSamplesS32;
572 } drflac_subframe;
573
574 typedef struct
575 {
576 /*
577 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
578 always be set to 0. This is 64-bit because the decoded PCM frame number will be 36 bits.
579 */
580 drflac_uint64 pcmFrameNumber;
581
582 /*
583 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
584 is 32-bit because in fixed block sizes, the maximum frame number will be 31 bits.
585 */
586 drflac_uint32 flacFrameNumber;
587
588 /* The sample rate of this frame. */
589 drflac_uint32 sampleRate;
590
591 /* The number of PCM frames in each sub-frame within this frame. */
592 drflac_uint16 blockSizeInPCMFrames;
593
594 /*
595 The channel assignment of this frame. This is not always set to the channel count. If interchannel decorrelation is being used this
596 will be set to DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE, DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE or DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE.
597 */
598 drflac_uint8 channelAssignment;
599
600 /* The number of bits per sample within this frame. */
601 drflac_uint8 bitsPerSample;
602
603 /* The frame's CRC. */
604 drflac_uint8 crc8;
605 } drflac_frame_header;
606
607 typedef struct
608 {
609 /* The header. */
610 drflac_frame_header header;
611
612 /*
613 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,
614 this will be decremented. When it reaches 0, the decoder will see this frame as fully consumed and load the next frame.
615 */
616 drflac_uint32 pcmFramesRemaining;
617
618 /* The list of sub-frames within the frame. There is one sub-frame for each channel, and there's a maximum of 8 channels. */
619 drflac_subframe subframes[8];
620 } drflac_frame;
621
622 typedef struct
623 {
624 /* The function to call when a metadata block is read. */
625 drflac_meta_proc onMeta;
626
627 /* The user data posted to the metadata callback function. */
628 void* pUserDataMD;
629
630 /* Memory allocation callbacks. */
631 drflac_allocation_callbacks allocationCallbacks;
632
633
634 /* The sample rate. Will be set to something like 44100. */
635 drflac_uint32 sampleRate;
636
637 /*
638 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
639 value specified in the STREAMINFO block.
640 */
641 drflac_uint8 channels;
642
643 /* The bits per sample. Will be set to something like 16, 24, etc. */
644 drflac_uint8 bitsPerSample;
645
646 /* The maximum block size, in samples. This number represents the number of samples in each channel (not combined). */
647 drflac_uint16 maxBlockSizeInPCMFrames;
648
649 /*
650 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
651 the total PCM frame count is unknown. Likely the case with streams like internet radio.
652 */
653 drflac_uint64 totalPCMFrameCount;
654
655
656 /* The container type. This is set based on whether or not the decoder was opened from a native or Ogg stream. */
657 drflac_container container;
658
659 /* The number of seekpoints in the seektable. */
660 drflac_uint32 seekpointCount;
661
662
663 /* Information about the frame the decoder is currently sitting on. */
664 drflac_frame currentFLACFrame;
665
666
667 /* The index of the PCM frame the decoder is currently sitting on. This is only used for seeking. */
668 drflac_uint64 currentPCMFrame;
669
670 /* The position of the first FLAC frame in the stream. This is only ever used for seeking. */
671 drflac_uint64 firstFLACFramePosInBytes;
672
673
674 /* A hack to avoid a malloc() when opening a decoder with drflac_open_memory(). */
675 drflac__memory_stream memoryStream;
676
677
678 /* A pointer to the decoded sample data. This is an offset of pExtraData. */
679 drflac_int32* pDecodedSamples;
680
681 /* A pointer to the seek table. This is an offset of pExtraData, or NULL if there is no seek table. */
682 drflac_seekpoint* pSeekpoints;
683
684 /* Internal use only. Only used with Ogg containers. Points to a drflac_oggbs object. This is an offset of pExtraData. */
685 void* _oggbs;
686
687 /* Internal use only. Used for profiling and testing different seeking modes. */
688 drflac_bool32 _noSeekTableSeek : 1;
689 drflac_bool32 _noBinarySearchSeek : 1;
690 drflac_bool32 _noBruteForceSeek : 1;
691
692 /* The bit streamer. The raw FLAC data is fed through this object. */
693 drflac_bs bs;
694
695 /* Variable length extra data. We attach this to the end of the object so we can avoid unnecessary mallocs. */
696 drflac_uint8 pExtraData[1];
697 } drflac;
698
699
700 /*
701 Opens a FLAC decoder.
702
703
704 Parameters
705 ----------
706 onRead (in)
707 The function to call when data needs to be read from the client.
708
709 onSeek (in)
710 The function to call when the read position of the client data needs to move.
711
712 pUserData (in, optional)
713 A pointer to application defined data that will be passed to onRead and onSeek.
714
715 pAllocationCallbacks (in, optional)
716 A pointer to application defined callbacks for managing memory allocations.
717
718
719 Return Value
720 ------------
721 Returns a pointer to an object representing the decoder.
722
723
724 Remarks
725 -------
726 Close the decoder with `drflac_close()`.
727
728 `pAllocationCallbacks` can be NULL in which case it will use `DRFLAC_MALLOC`, `DRFLAC_REALLOC` and `DRFLAC_FREE`.
729
730 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
731 without any manual intervention. Ogg encapsulation also works with multiplexed streams which basically means it can play FLAC encoded audio tracks in videos.
732
733 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
734 from a block of memory respectively.
735
736 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.
737
738 Use `drflac_open_with_metadata()` if you need access to metadata.
739
740
741 Seek Also
742 ---------
743 drflac_open_file()
744 drflac_open_memory()
745 drflac_open_with_metadata()
746 drflac_close()
747 */
748 DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
749
750 /*
751 Opens a FLAC stream with relaxed validation of the header block.
752
753
754 Parameters
755 ----------
756 onRead (in)
757 The function to call when data needs to be read from the client.
758
759 onSeek (in)
760 The function to call when the read position of the client data needs to move.
761
762 container (in)
763 Whether or not the FLAC stream is encapsulated using standard FLAC encapsulation or Ogg encapsulation.
764
765 pUserData (in, optional)
766 A pointer to application defined data that will be passed to onRead and onSeek.
767
768 pAllocationCallbacks (in, optional)
769 A pointer to application defined callbacks for managing memory allocations.
770
771
772 Return Value
773 ------------
774 A pointer to an object representing the decoder.
775
776
777 Remarks
778 -------
779 The same as drflac_open(), except attempts to open the stream even when a header block is not present.
780
781 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`
782 as that is for internal use only.
783
784 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,
785 force your `onRead` callback to return 0, which dr_flac will use as an indicator that the end of the stream was found.
786
787 Use `drflac_open_with_metadata_relaxed()` if you need access to metadata.
788 */
789 DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
790
791 /*
792 Opens a FLAC decoder and notifies the caller of the metadata chunks (album art, etc.).
793
794
795 Parameters
796 ----------
797 onRead (in)
798 The function to call when data needs to be read from the client.
799
800 onSeek (in)
801 The function to call when the read position of the client data needs to move.
802
803 onMeta (in)
804 The function to call for every metadata block.
805
806 pUserData (in, optional)
807 A pointer to application defined data that will be passed to onRead, onSeek and onMeta.
808
809 pAllocationCallbacks (in, optional)
810 A pointer to application defined callbacks for managing memory allocations.
811
812
813 Return Value
814 ------------
815 A pointer to an object representing the decoder.
816
817
818 Remarks
819 -------
820 Close the decoder with `drflac_close()`.
821
822 `pAllocationCallbacks` can be NULL in which case it will use `DRFLAC_MALLOC`, `DRFLAC_REALLOC` and `DRFLAC_FREE`.
823
824 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
825 metadata block except for STREAMINFO and PADDING blocks.
826
827 The caller is notified of the metadata via the `onMeta` callback. All metadata blocks will be handled before the function returns. This callback takes a
828 pointer to a `drflac_metadata` object which is a union containing the data of all relevant metadata blocks. Use the `type` member to discriminate against
829 the different metadata types.
830
831 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.
832
833 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
834 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
835 metadata block, whereas `drflac_open()` will simply seek past it (for the sake of efficiency). This inconsistency can result in different samples being
836 returned depending on whether or not the stream is being opened with metadata.
837
838
839 Seek Also
840 ---------
841 drflac_open_file_with_metadata()
842 drflac_open_memory_with_metadata()
843 drflac_open()
844 drflac_close()
845 */
846 DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
847
848 /*
849 The same as drflac_open_with_metadata(), except attempts to open the stream even when a header block is not present.
850
851 See Also
852 --------
853 drflac_open_with_metadata()
854 drflac_open_relaxed()
855 */
856 DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
857
858 /*
859 Closes the given FLAC decoder.
860
861
862 Parameters
863 ----------
864 pFlac (in)
865 The decoder to close.
866
867
868 Remarks
869 -------
870 This will destroy the decoder object.
871
872
873 See Also
874 --------
875 drflac_open()
876 drflac_open_with_metadata()
877 drflac_open_file()
878 drflac_open_file_w()
879 drflac_open_file_with_metadata()
880 drflac_open_file_with_metadata_w()
881 drflac_open_memory()
882 drflac_open_memory_with_metadata()
883 */
884 DRFLAC_API void drflac_close(drflac* pFlac);
885
886
887 /*
888 Reads sample data from the given FLAC decoder, output as interleaved signed 32-bit PCM.
889
890
891 Parameters
892 ----------
893 pFlac (in)
894 The decoder.
895
896 framesToRead (in)
897 The number of PCM frames to read.
898
899 pBufferOut (out, optional)
900 A pointer to the buffer that will receive the decoded samples.
901
902
903 Return Value
904 ------------
905 Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end.
906
907
908 Remarks
909 -------
910 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.
911 */
912 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut);
913
914
915 /*
916 Reads sample data from the given FLAC decoder, output as interleaved signed 16-bit PCM.
917
918
919 Parameters
920 ----------
921 pFlac (in)
922 The decoder.
923
924 framesToRead (in)
925 The number of PCM frames to read.
926
927 pBufferOut (out, optional)
928 A pointer to the buffer that will receive the decoded samples.
929
930
931 Return Value
932 ------------
933 Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end.
934
935
936 Remarks
937 -------
938 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.
939
940 Note that this is lossy for streams where the bits per sample is larger than 16.
941 */
942 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut);
943
944 /*
945 Reads sample data from the given FLAC decoder, output as interleaved 32-bit floating point 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 Note that this should be considered lossy due to the nature of floating point numbers not being able to exactly represent every possible number.
970 */
971 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut);
972
973 /*
974 Seeks to the PCM frame at the given index.
975
976
977 Parameters
978 ----------
979 pFlac (in)
980 The decoder.
981
982 pcmFrameIndex (in)
983 The index of the PCM frame to seek to. See notes below.
984
985
986 Return Value
987 -------------
988 `DRFLAC_TRUE` if successful; `DRFLAC_FALSE` otherwise.
989 */
990 DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex);
991
992
993
994 #ifndef DR_FLAC_NO_STDIO
995 /*
996 Opens a FLAC decoder from the file at the given path.
997
998
999 Parameters
1000 ----------
1001 pFileName (in)
1002 The path of the file to open, either absolute or relative to the current directory.
1003
1004 pAllocationCallbacks (in, optional)
1005 A pointer to application defined callbacks for managing memory allocations.
1006
1007
1008 Return Value
1009 ------------
1010 A pointer to an object representing the decoder.
1011
1012
1013 Remarks
1014 -------
1015 Close the decoder with drflac_close().
1016
1017
1018 Remarks
1019 -------
1020 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
1021 at any given time, so keep this mind if you have many decoders open at the same time.
1022
1023
1024 See Also
1025 --------
1026 drflac_open_file_with_metadata()
1027 drflac_open()
1028 drflac_close()
1029 */
1030 DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
1031 DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
1032
1033 /*
1034 Opens a FLAC decoder from the file at the given path and notifies the caller of the metadata chunks (album art, etc.)
1035
1036
1037 Parameters
1038 ----------
1039 pFileName (in)
1040 The path of the file to open, either absolute or relative to the current directory.
1041
1042 pAllocationCallbacks (in, optional)
1043 A pointer to application defined callbacks for managing memory allocations.
1044
1045 onMeta (in)
1046 The callback to fire for each metadata block.
1047
1048 pUserData (in)
1049 A pointer to the user data to pass to the metadata callback.
1050
1051 pAllocationCallbacks (in)
1052 A pointer to application defined callbacks for managing memory allocations.
1053
1054
1055 Remarks
1056 -------
1057 Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
1058
1059
1060 See Also
1061 --------
1062 drflac_open_with_metadata()
1063 drflac_open()
1064 drflac_close()
1065 */
1066 DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
1067 DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
1068 #endif
1069
1070 /*
1071 Opens a FLAC decoder from a pre-allocated block of memory
1072
1073
1074 Parameters
1075 ----------
1076 pData (in)
1077 A pointer to the raw encoded FLAC data.
1078
1079 dataSize (in)
1080 The size in bytes of `data`.
1081
1082 pAllocationCallbacks (in)
1083 A pointer to application defined callbacks for managing memory allocations.
1084
1085
1086 Return Value
1087 ------------
1088 A pointer to an object representing the decoder.
1089
1090
1091 Remarks
1092 -------
1093 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.
1094
1095
1096 See Also
1097 --------
1098 drflac_open()
1099 drflac_close()
1100 */
1101 DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks);
1102
1103 /*
1104 Opens a FLAC decoder from a pre-allocated block of memory and notifies the caller of the metadata chunks (album art, etc.)
1105
1106
1107 Parameters
1108 ----------
1109 pData (in)
1110 A pointer to the raw encoded FLAC data.
1111
1112 dataSize (in)
1113 The size in bytes of `data`.
1114
1115 onMeta (in)
1116 The callback to fire for each metadata block.
1117
1118 pUserData (in)
1119 A pointer to the user data to pass to the metadata callback.
1120
1121 pAllocationCallbacks (in)
1122 A pointer to application defined callbacks for managing memory allocations.
1123
1124
1125 Remarks
1126 -------
1127 Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
1128
1129
1130 See Also
1131 -------
1132 drflac_open_with_metadata()
1133 drflac_open()
1134 drflac_close()
1135 */
1136 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);
1137
1138
1139
1140 /* High Level APIs */
1141
1142 /*
1143 Opens a FLAC stream from the given callbacks and fully decodes it in a single operation. The return value is a
1144 pointer to the sample data as interleaved signed 32-bit PCM. The returned data must be freed with drflac_free().
1145
1146 You can pass in custom memory allocation callbacks via the pAllocationCallbacks parameter. This can be NULL in which
1147 case it will use DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE.
1148
1149 Sometimes a FLAC file won't keep track of the total sample count. In this situation the function will continuously
1150 read samples into a dynamically sized buffer on the heap until no samples are left.
1151
1152 Do not call this function on a broadcast type of stream (like internet radio streams and whatnot).
1153 */
1154 DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1155
1156 /* Same as drflac_open_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */
1157 DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1158
1159 /* Same as drflac_open_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */
1160 DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1161
1162 #ifndef DR_FLAC_NO_STDIO
1163 /* Same as drflac_open_and_read_pcm_frames_s32() except opens the decoder from a file. */
1164 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);
1165
1166 /* Same as drflac_open_file_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */
1167 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);
1168
1169 /* Same as drflac_open_file_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */
1170 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);
1171 #endif
1172
1173 /* Same as drflac_open_and_read_pcm_frames_s32() except opens the decoder from a block of memory. */
1174 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);
1175
1176 /* Same as drflac_open_memory_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */
1177 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);
1178
1179 /* Same as drflac_open_memory_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */
1180 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);
1181
1182 /*
1183 Frees memory that was allocated internally by dr_flac.
1184
1185 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.
1186 */
1187 DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks);
1188
1189
1190 /* Structure representing an iterator for vorbis comments in a VORBIS_COMMENT metadata block. */
1191 typedef struct
1192 {
1193 drflac_uint32 countRemaining;
1194 const char* pRunningData;
1195 } drflac_vorbis_comment_iterator;
1196
1197 /*
1198 Initializes a vorbis comment iterator. This can be used for iterating over the vorbis comments in a VORBIS_COMMENT
1199 metadata block.
1200 */
1201 DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments);
1202
1203 /*
1204 Goes to the next vorbis comment in the given iterator. If null is returned it means there are no more comments. The
1205 returned string is NOT null terminated.
1206 */
1207 DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut);
1208
1209
1210 /* Structure representing an iterator for cuesheet tracks in a CUESHEET metadata block. */
1211 typedef struct
1212 {
1213 drflac_uint32 countRemaining;
1214 const char* pRunningData;
1215 } drflac_cuesheet_track_iterator;
1216
1217 /* The order of members here is important because we map this directly to the raw data within the CUESHEET metadata block. */
1218 typedef struct
1219 {
1220 drflac_uint64 offset;
1221 drflac_uint8 index;
1222 drflac_uint8 reserved[3];
1223 } drflac_cuesheet_track_index;
1224
1225 typedef struct
1226 {
1227 drflac_uint64 offset;
1228 drflac_uint8 trackNumber;
1229 char ISRC[12];
1230 drflac_bool8 isAudio;
1231 drflac_bool8 preEmphasis;
1232 drflac_uint8 indexCount;
1233 const drflac_cuesheet_track_index* pIndexPoints;
1234 } drflac_cuesheet_track;
1235
1236 /*
1237 Initializes a cuesheet track iterator. This can be used for iterating over the cuesheet tracks in a CUESHEET metadata
1238 block.
1239 */
1240 DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData);
1241
1242 /* Goes to the next cuesheet track in the given iterator. If DRFLAC_FALSE is returned it means there are no more comments. */
1243 DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack);
1244
1245
1246 #ifdef __cplusplus
1247 }
1248 #endif
1249 #endif /* dr_flac_h */
1250
1251
1252 /************************************************************************************************************************************************************
1253 ************************************************************************************************************************************************************
1254
1255 IMPLEMENTATION
1256
1257 ************************************************************************************************************************************************************
1258 ************************************************************************************************************************************************************/
1259 #if defined(DR_FLAC_IMPLEMENTATION) || defined(DRFLAC_IMPLEMENTATION)
1260 #ifndef dr_flac_c
1261 #define dr_flac_c
1262
1263 /* Disable some annoying warnings. */
1264 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
1265 #pragma GCC diagnostic push
1266 #if __GNUC__ >= 7
1267 #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
1268 #endif
1269 #endif
1270
1271 #ifdef __linux__
1272 #ifndef _BSD_SOURCE
1273 #define _BSD_SOURCE
1274 #endif
1275 #ifndef _DEFAULT_SOURCE
1276 #define _DEFAULT_SOURCE
1277 #endif
1278 #ifndef __USE_BSD
1279 #define __USE_BSD
1280 #endif
1281 #include <endian.h>
1282 #endif
1283
1284 #include <stdlib.h>
1285 #include <string.h>
1286
1287 /* Inline */
1288 #ifdef _MSC_VER
1289 #define DRFLAC_INLINE __forceinline
1290 #elif defined(__GNUC__)
1291 /*
1292 I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when
1293 the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some
1294 case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the
1295 command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue
1296 I am using "__inline__" only when we're compiling in strict ANSI mode.
1297 */
1298 #if defined(__STRICT_ANSI__)
1299 #define DRFLAC_GNUC_INLINE_HINT __inline__
1300 #else
1301 #define DRFLAC_GNUC_INLINE_HINT inline
1302 #endif
1303
1304 #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
1305 #define DRFLAC_INLINE DRFLAC_GNUC_INLINE_HINT __attribute__((always_inline))
1306 #else
1307 #define DRFLAC_INLINE DRFLAC_GNUC_INLINE_HINT
1308 #endif
1309 #elif defined(__WATCOMC__)
1310 #define DRFLAC_INLINE __inline
1311 #else
1312 #define DRFLAC_INLINE
1313 #endif
1314 /* End Inline */
1315
1316 /*
1317 Intrinsics Support
1318
1319 There's a bug in GCC 4.2.x which results in an incorrect compilation error when using _mm_slli_epi32() where it complains with
1320
1321 "error: shift must be an immediate"
1322
1323 Unfortuantely dr_flac depends on this for a few things so we're just going to disable SSE on GCC 4.2 and below.
1324 */
1325 #if !defined(DR_FLAC_NO_SIMD)
1326 #if defined(DRFLAC_X64) || defined(DRFLAC_X86)
1327 #if defined(_MSC_VER) && !defined(__clang__)
1328 /* MSVC. */
1329 #if _MSC_VER >= 1400 && !defined(DRFLAC_NO_SSE2) /* 2005 */
1330 #define DRFLAC_SUPPORT_SSE2
1331 #endif
1332 #if _MSC_VER >= 1600 && !defined(DRFLAC_NO_SSE41) /* 2010 */
1333 #define DRFLAC_SUPPORT_SSE41
1334 #endif
1335 #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)))
1336 /* Assume GNUC-style. */
1337 #if defined(__SSE2__) && !defined(DRFLAC_NO_SSE2)
1338 #define DRFLAC_SUPPORT_SSE2
1339 #endif
1340 #if defined(__SSE4_1__) && !defined(DRFLAC_NO_SSE41)
1341 #define DRFLAC_SUPPORT_SSE41
1342 #endif
1343 #endif
1344
1345 /* If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. */
1346 #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
1347 #if !defined(DRFLAC_SUPPORT_SSE2) && !defined(DRFLAC_NO_SSE2) && __has_include(<emmintrin.h>)
1348 #define DRFLAC_SUPPORT_SSE2
1349 #endif
1350 #if !defined(DRFLAC_SUPPORT_SSE41) && !defined(DRFLAC_NO_SSE41) && __has_include(<smmintrin.h>)
1351 #define DRFLAC_SUPPORT_SSE41
1352 #endif
1353 #endif
1354
1355 #if defined(DRFLAC_SUPPORT_SSE41)
1356 #include <smmintrin.h>
1357 #elif defined(DRFLAC_SUPPORT_SSE2)
1358 #include <emmintrin.h>
1359 #endif
1360 #endif
1361
1362 #if defined(DRFLAC_ARM)
1363 #if !defined(DRFLAC_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
1364 #define DRFLAC_SUPPORT_NEON
1365 #include <arm_neon.h>
1366 #endif
1367 #endif
1368 #endif
1369
1370 /* Compile-time CPU feature support. */
1371 #if !defined(DR_FLAC_NO_SIMD) && (defined(DRFLAC_X86) || defined(DRFLAC_X64))
1372 #if defined(_MSC_VER) && !defined(__clang__)
1373 #if _MSC_VER >= 1400
1374 #include <intrin.h>
1375 static void drflac__cpuid(int info[4], int fid)
1376 {
1377 __cpuid(info, fid);
1378 }
1379 #else
1380 #define DRFLAC_NO_CPUID
1381 #endif
1382 #else
1383 #if defined(__GNUC__) || defined(__clang__)
1384 static void drflac__cpuid(int info[4], int fid)
1385 {
1386 /*
1387 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
1388 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
1389 supporting different assembly dialects.
1390
1391 What's basically happening is that we're saving and restoring the ebx register manually.
1392 */
1393 #if defined(DRFLAC_X86) && defined(__PIC__)
1394 __asm__ __volatile__ (
1395 "xchg{l} {%%}ebx, %k1;"
1396 "cpuid;"
1397 "xchg{l} {%%}ebx, %k1;"
1398 : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
1399 );
1400 #else
1401 __asm__ __volatile__ (
1402 "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
1403 );
1404 #endif
1405 }
1406 #else
1407 #define DRFLAC_NO_CPUID
1408 #endif
1409 #endif
1410 #else
1411 #define DRFLAC_NO_CPUID
1412 #endif
1413
1414 static DRFLAC_INLINE drflac_bool32 drflac_has_sse2(void)
1415 {
1416 #if defined(DRFLAC_SUPPORT_SSE2)
1417 #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE2)
1418 #if defined(DRFLAC_X64)
1419 return DRFLAC_TRUE; /* 64-bit targets always support SSE2. */
1420 #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)
1421 return DRFLAC_TRUE; /* If the compiler is allowed to freely generate SSE2 code we can assume support. */
1422 #else
1423 #if defined(DRFLAC_NO_CPUID)
1424 return DRFLAC_FALSE;
1425 #else
1426 int info[4];
1427 drflac__cpuid(info, 1);
1428 return (info[3] & (1 << 26)) != 0;
1429 #endif
1430 #endif
1431 #else
1432 return DRFLAC_FALSE; /* SSE2 is only supported on x86 and x64 architectures. */
1433 #endif
1434 #else
1435 return DRFLAC_FALSE; /* No compiler support. */
1436 #endif
1437 }
1438
1439 static DRFLAC_INLINE drflac_bool32 drflac_has_sse41(void)
1440 {
1441 #if defined(DRFLAC_SUPPORT_SSE41)
1442 #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE41)
1443 #if defined(__SSE4_1__) || defined(__AVX__)
1444 return DRFLAC_TRUE; /* If the compiler is allowed to freely generate SSE41 code we can assume support. */
1445 #else
1446 #if defined(DRFLAC_NO_CPUID)
1447 return DRFLAC_FALSE;
1448 #else
1449 int info[4];
1450 drflac__cpuid(info, 1);
1451 return (info[2] & (1 << 19)) != 0;
1452 #endif
1453 #endif
1454 #else
1455 return DRFLAC_FALSE; /* SSE41 is only supported on x86 and x64 architectures. */
1456 #endif
1457 #else
1458 return DRFLAC_FALSE; /* No compiler support. */
1459 #endif
1460 }
1461
1462
1463 #if defined(_MSC_VER) && _MSC_VER >= 1500 && (defined(DRFLAC_X86) || defined(DRFLAC_X64)) && !defined(__clang__)
1464 #define DRFLAC_HAS_LZCNT_INTRINSIC
1465 #elif (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
1466 #define DRFLAC_HAS_LZCNT_INTRINSIC
1467 #elif defined(__clang__)
1468 #if defined(__has_builtin)
1469 #if __has_builtin(__builtin_clzll) || __has_builtin(__builtin_clzl)
1470 #define DRFLAC_HAS_LZCNT_INTRINSIC
1471 #endif
1472 #endif
1473 #endif
1474
1475 #if defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(__clang__)
1476 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
1477 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
1478 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
1479 #elif defined(__clang__)
1480 #if defined(__has_builtin)
1481 #if __has_builtin(__builtin_bswap16)
1482 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
1483 #endif
1484 #if __has_builtin(__builtin_bswap32)
1485 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
1486 #endif
1487 #if __has_builtin(__builtin_bswap64)
1488 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
1489 #endif
1490 #endif
1491 #elif defined(__GNUC__)
1492 #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
1493 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
1494 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
1495 #endif
1496 #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
1497 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
1498 #endif
1499 #elif defined(__WATCOMC__) && defined(__386__)
1500 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
1501 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
1502 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
1503 extern __inline drflac_uint16 _watcom_bswap16(drflac_uint16);
1504 extern __inline drflac_uint32 _watcom_bswap32(drflac_uint32);
1505 extern __inline drflac_uint64 _watcom_bswap64(drflac_uint64);
1506 #pragma aux _watcom_bswap16 = \
1507 "xchg al, ah" \
1508 parm [ax] \
1509 value [ax] \
1510 modify nomemory;
1511 #pragma aux _watcom_bswap32 = \
1512 "bswap eax" \
1513 parm [eax] \
1514 value [eax] \
1515 modify nomemory;
1516 #pragma aux _watcom_bswap64 = \
1517 "bswap eax" \
1518 "bswap edx" \
1519 "xchg eax,edx" \
1520 parm [eax edx] \
1521 value [eax edx] \
1522 modify nomemory;
1523 #endif
1524
1525
1526 /* Standard library stuff. */
1527 #ifndef DRFLAC_ASSERT
1528 #include <assert.h>
1529 #define DRFLAC_ASSERT(expression) assert(expression)
1530 #endif
1531 #ifndef DRFLAC_MALLOC
1532 #define DRFLAC_MALLOC(sz) malloc((sz))
1533 #endif
1534 #ifndef DRFLAC_REALLOC
1535 #define DRFLAC_REALLOC(p, sz) realloc((p), (sz))
1536 #endif
1537 #ifndef DRFLAC_FREE
1538 #define DRFLAC_FREE(p) free((p))
1539 #endif
1540 #ifndef DRFLAC_COPY_MEMORY
1541 #define DRFLAC_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
1542 #endif
1543 #ifndef DRFLAC_ZERO_MEMORY
1544 #define DRFLAC_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
1545 #endif
1546 #ifndef DRFLAC_ZERO_OBJECT
1547 #define DRFLAC_ZERO_OBJECT(p) DRFLAC_ZERO_MEMORY((p), sizeof(*(p)))
1548 #endif
1549
1550 #define DRFLAC_MAX_SIMD_VECTOR_SIZE 64 /* 64 for AVX-512 in the future. */
1551
1552 /* Result Codes */
1553 typedef drflac_int32 drflac_result;
1554 #define DRFLAC_SUCCESS 0
1555 #define DRFLAC_ERROR -1 /* A generic error. */
1556 #define DRFLAC_INVALID_ARGS -2
1557 #define DRFLAC_INVALID_OPERATION -3
1558 #define DRFLAC_OUT_OF_MEMORY -4
1559 #define DRFLAC_OUT_OF_RANGE -5
1560 #define DRFLAC_ACCESS_DENIED -6
1561 #define DRFLAC_DOES_NOT_EXIST -7
1562 #define DRFLAC_ALREADY_EXISTS -8
1563 #define DRFLAC_TOO_MANY_OPEN_FILES -9
1564 #define DRFLAC_INVALID_FILE -10
1565 #define DRFLAC_TOO_BIG -11
1566 #define DRFLAC_PATH_TOO_LONG -12
1567 #define DRFLAC_NAME_TOO_LONG -13
1568 #define DRFLAC_NOT_DIRECTORY -14
1569 #define DRFLAC_IS_DIRECTORY -15
1570 #define DRFLAC_DIRECTORY_NOT_EMPTY -16
1571 #define DRFLAC_END_OF_FILE -17
1572 #define DRFLAC_NO_SPACE -18
1573 #define DRFLAC_BUSY -19
1574 #define DRFLAC_IO_ERROR -20
1575 #define DRFLAC_INTERRUPT -21
1576 #define DRFLAC_UNAVAILABLE -22
1577 #define DRFLAC_ALREADY_IN_USE -23
1578 #define DRFLAC_BAD_ADDRESS -24
1579 #define DRFLAC_BAD_SEEK -25
1580 #define DRFLAC_BAD_PIPE -26
1581 #define DRFLAC_DEADLOCK -27
1582 #define DRFLAC_TOO_MANY_LINKS -28
1583 #define DRFLAC_NOT_IMPLEMENTED -29
1584 #define DRFLAC_NO_MESSAGE -30
1585 #define DRFLAC_BAD_MESSAGE -31
1586 #define DRFLAC_NO_DATA_AVAILABLE -32
1587 #define DRFLAC_INVALID_DATA -33
1588 #define DRFLAC_TIMEOUT -34
1589 #define DRFLAC_NO_NETWORK -35
1590 #define DRFLAC_NOT_UNIQUE -36
1591 #define DRFLAC_NOT_SOCKET -37
1592 #define DRFLAC_NO_ADDRESS -38
1593 #define DRFLAC_BAD_PROTOCOL -39
1594 #define DRFLAC_PROTOCOL_UNAVAILABLE -40
1595 #define DRFLAC_PROTOCOL_NOT_SUPPORTED -41
1596 #define DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED -42
1597 #define DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED -43
1598 #define DRFLAC_SOCKET_NOT_SUPPORTED -44
1599 #define DRFLAC_CONNECTION_RESET -45
1600 #define DRFLAC_ALREADY_CONNECTED -46
1601 #define DRFLAC_NOT_CONNECTED -47
1602 #define DRFLAC_CONNECTION_REFUSED -48
1603 #define DRFLAC_NO_HOST -49
1604 #define DRFLAC_IN_PROGRESS -50
1605 #define DRFLAC_CANCELLED -51
1606 #define DRFLAC_MEMORY_ALREADY_MAPPED -52
1607 #define DRFLAC_AT_END -53
1608
1609 #define DRFLAC_CRC_MISMATCH -100
1610 /* End Result Codes */
1611
1612
1613 #define DRFLAC_SUBFRAME_CONSTANT 0
1614 #define DRFLAC_SUBFRAME_VERBATIM 1
1615 #define DRFLAC_SUBFRAME_FIXED 8
1616 #define DRFLAC_SUBFRAME_LPC 32
1617 #define DRFLAC_SUBFRAME_RESERVED 255
1618
1619 #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE 0
1620 #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 1
1621
1622 #define DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT 0
1623 #define DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE 8
1624 #define DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE 9
1625 #define DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE 10
1626
1627 #define DRFLAC_SEEKPOINT_SIZE_IN_BYTES 18
1628 #define DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES 36
1629 #define DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES 12
1630
1631 #define drflac_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
1632
1633
1634 DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision)
1635 {
1636 if (pMajor) {
1637 *pMajor = DRFLAC_VERSION_MAJOR;
1638 }
1639
1640 if (pMinor) {
1641 *pMinor = DRFLAC_VERSION_MINOR;
1642 }
1643
1644 if (pRevision) {
1645 *pRevision = DRFLAC_VERSION_REVISION;
1646 }
1647 }
1648
1649 DRFLAC_API const char* drflac_version_string(void)
1650 {
1651 return DRFLAC_VERSION_STRING;
1652 }
1653
1654
1655 /* CPU caps. */
1656 #if defined(__has_feature)
1657 #if __has_feature(thread_sanitizer)
1658 #define DRFLAC_NO_THREAD_SANITIZE __attribute__((no_sanitize("thread")))
1659 #else
1660 #define DRFLAC_NO_THREAD_SANITIZE
1661 #endif
1662 #else
1663 #define DRFLAC_NO_THREAD_SANITIZE
1664 #endif
1665
1666 #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
1667 static drflac_bool32 drflac__gIsLZCNTSupported = DRFLAC_FALSE;
1668 #endif
1669
1670 #ifndef DRFLAC_NO_CPUID
1671 static drflac_bool32 drflac__gIsSSE2Supported = DRFLAC_FALSE;
1672 static drflac_bool32 drflac__gIsSSE41Supported = DRFLAC_FALSE;
1673
1674 /*
1675 I've had a bug report that Clang's ThreadSanitizer presents a warning in this function. Having reviewed this, this does
1676 actually make sense. However, since CPU caps should never differ for a running process, I don't think the trade off of
1677 complicating internal API's by passing around CPU caps versus just disabling the warnings is worthwhile. I'm therefore
1678 just going to disable these warnings. This is disabled via the DRFLAC_NO_THREAD_SANITIZE attribute.
1679 */
1680 DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void)
1681 {
1682 static drflac_bool32 isCPUCapsInitialized = DRFLAC_FALSE;
1683
1684 if (!isCPUCapsInitialized) {
1685 /* LZCNT */
1686 #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
1687 int info[4] = {0};
1688 drflac__cpuid(info, 0x80000001);
1689 drflac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0;
1690 #endif
1691
1692 /* SSE2 */
1693 drflac__gIsSSE2Supported = drflac_has_sse2();
1694
1695 /* SSE4.1 */
1696 drflac__gIsSSE41Supported = drflac_has_sse41();
1697
1698 /* Initialized. */
1699 isCPUCapsInitialized = DRFLAC_TRUE;
1700 }
1701 }
1702 #else
1703 static drflac_bool32 drflac__gIsNEONSupported = DRFLAC_FALSE;
1704
1705 static DRFLAC_INLINE drflac_bool32 drflac__has_neon(void)
1706 {
1707 #if defined(DRFLAC_SUPPORT_NEON)
1708 #if defined(DRFLAC_ARM) && !defined(DRFLAC_NO_NEON)
1709 #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
1710 return DRFLAC_TRUE; /* If the compiler is allowed to freely generate NEON code we can assume support. */
1711 #else
1712 /* TODO: Runtime check. */
1713 return DRFLAC_FALSE;
1714 #endif
1715 #else
1716 return DRFLAC_FALSE; /* NEON is only supported on ARM architectures. */
1717 #endif
1718 #else
1719 return DRFLAC_FALSE; /* No compiler support. */
1720 #endif
1721 }
1722
1723 DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void)
1724 {
1725 drflac__gIsNEONSupported = drflac__has_neon();
1726
1727 #if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
1728 drflac__gIsLZCNTSupported = DRFLAC_TRUE;
1729 #endif
1730 }
1731 #endif
1732
1733
1734 /* Endian Management */
1735 static DRFLAC_INLINE drflac_bool32 drflac__is_little_endian(void)
1736 {
1737 #if defined(DRFLAC_X86) || defined(DRFLAC_X64)
1738 return DRFLAC_TRUE;
1739 #elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
1740 return DRFLAC_TRUE;
1741 #else
1742 int n = 1;
1743 return (*(char*)&n) == 1;
1744 #endif
1745 }
1746
1747 static DRFLAC_INLINE drflac_uint16 drflac__swap_endian_uint16(drflac_uint16 n)
1748 {
1749 #ifdef DRFLAC_HAS_BYTESWAP16_INTRINSIC
1750 #if defined(_MSC_VER) && !defined(__clang__)
1751 return _byteswap_ushort(n);
1752 #elif defined(__GNUC__) || defined(__clang__)
1753 return __builtin_bswap16(n);
1754 #elif defined(__WATCOMC__) && defined(__386__)
1755 return _watcom_bswap16(n);
1756 #else
1757 #error "This compiler does not support the byte swap intrinsic."
1758 #endif
1759 #else
1760 return ((n & 0xFF00) >> 8) |
1761 ((n & 0x00FF) << 8);
1762 #endif
1763 }
1764
1765 static DRFLAC_INLINE drflac_uint32 drflac__swap_endian_uint32(drflac_uint32 n)
1766 {
1767 #ifdef DRFLAC_HAS_BYTESWAP32_INTRINSIC
1768 #if defined(_MSC_VER) && !defined(__clang__)
1769 return _byteswap_ulong(n);
1770 #elif defined(__GNUC__) || defined(__clang__)
1771 #if defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(__ARM_ARCH_6M__) && !defined(DRFLAC_64BIT) /* <-- 64-bit inline assembly has not been tested, so disabling for now. */
1772 /* Inline assembly optimized implementation for ARM. In my testing, GCC does not generate optimized code with __builtin_bswap32(). */
1773 drflac_uint32 r;
1774 __asm__ __volatile__ (
1775 #if defined(DRFLAC_64BIT)
1776 "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! */
1777 #else
1778 "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
1779 #endif
1780 );
1781 return r;
1782 #else
1783 return __builtin_bswap32(n);
1784 #endif
1785 #elif defined(__WATCOMC__) && defined(__386__)
1786 return _watcom_bswap32(n);
1787 #else
1788 #error "This compiler does not support the byte swap intrinsic."
1789 #endif
1790 #else
1791 return ((n & 0xFF000000) >> 24) |
1792 ((n & 0x00FF0000) >> 8) |
1793 ((n & 0x0000FF00) << 8) |
1794 ((n & 0x000000FF) << 24);
1795 #endif
1796 }
1797
1798 static DRFLAC_INLINE drflac_uint64 drflac__swap_endian_uint64(drflac_uint64 n)
1799 {
1800 #ifdef DRFLAC_HAS_BYTESWAP64_INTRINSIC
1801 #if defined(_MSC_VER) && !defined(__clang__)
1802 return _byteswap_uint64(n);
1803 #elif defined(__GNUC__) || defined(__clang__)
1804 return __builtin_bswap64(n);
1805 #elif defined(__WATCOMC__) && defined(__386__)
1806 return _watcom_bswap64(n);
1807 #else
1808 #error "This compiler does not support the byte swap intrinsic."
1809 #endif
1810 #else
1811 /* Weird "<< 32" bitshift is required for C89 because it doesn't support 64-bit constants. Should be optimized out by a good compiler. */
1812 return ((n & ((drflac_uint64)0xFF000000 << 32)) >> 56) |
1813 ((n & ((drflac_uint64)0x00FF0000 << 32)) >> 40) |
1814 ((n & ((drflac_uint64)0x0000FF00 << 32)) >> 24) |
1815 ((n & ((drflac_uint64)0x000000FF << 32)) >> 8) |
1816 ((n & ((drflac_uint64)0xFF000000 )) << 8) |
1817 ((n & ((drflac_uint64)0x00FF0000 )) << 24) |
1818 ((n & ((drflac_uint64)0x0000FF00 )) << 40) |
1819 ((n & ((drflac_uint64)0x000000FF )) << 56);
1820 #endif
1821 }
1822
1823
1824 static DRFLAC_INLINE drflac_uint16 drflac__be2host_16(drflac_uint16 n)
1825 {
1826 if (drflac__is_little_endian()) {
1827 return drflac__swap_endian_uint16(n);
1828 }
1829
1830 return n;
1831 }
1832
1833 static DRFLAC_INLINE drflac_uint32 drflac__be2host_32(drflac_uint32 n)
1834 {
1835 if (drflac__is_little_endian()) {
1836 return drflac__swap_endian_uint32(n);
1837 }
1838
1839 return n;
1840 }
1841
1842 static DRFLAC_INLINE drflac_uint32 drflac__be2host_32_ptr_unaligned(const void* pData)
1843 {
1844 const drflac_uint8* pNum = (drflac_uint8*)pData;
1845 return *(pNum) << 24 | *(pNum+1) << 16 | *(pNum+2) << 8 | *(pNum+3);
1846 }
1847
1848 static DRFLAC_INLINE drflac_uint64 drflac__be2host_64(drflac_uint64 n)
1849 {
1850 if (drflac__is_little_endian()) {
1851 return drflac__swap_endian_uint64(n);
1852 }
1853
1854 return n;
1855 }
1856
1857
1858 static DRFLAC_INLINE drflac_uint32 drflac__le2host_32(drflac_uint32 n)
1859 {
1860 if (!drflac__is_little_endian()) {
1861 return drflac__swap_endian_uint32(n);
1862 }
1863
1864 return n;
1865 }
1866
1867 static DRFLAC_INLINE drflac_uint32 drflac__le2host_32_ptr_unaligned(const void* pData)
1868 {
1869 const drflac_uint8* pNum = (drflac_uint8*)pData;
1870 return *pNum | *(pNum+1) << 8 | *(pNum+2) << 16 | *(pNum+3) << 24;
1871 }
1872
1873
1874 static DRFLAC_INLINE drflac_uint32 drflac__unsynchsafe_32(drflac_uint32 n)
1875 {
1876 drflac_uint32 result = 0;
1877 result |= (n & 0x7F000000) >> 3;
1878 result |= (n & 0x007F0000) >> 2;
1879 result |= (n & 0x00007F00) >> 1;
1880 result |= (n & 0x0000007F) >> 0;
1881
1882 return result;
1883 }
1884
1885
1886
1887 /* The CRC code below is based on this document: http://zlib.net/crc_v3.txt */
1888 static drflac_uint8 drflac__crc8_table[] = {
1889 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
1890 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
1891 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
1892 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
1893 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
1894 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
1895 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
1896 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
1897 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
1898 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
1899 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
1900 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
1901 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
1902 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
1903 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
1904 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
1905 };
1906
1907 static drflac_uint16 drflac__crc16_table[] = {
1908 0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
1909 0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022,
1910 0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072,
1911 0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041,
1912 0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2,
1913 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1,
1914 0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1,
1915 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
1916 0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192,
1917 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1,
1918 0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1,
1919 0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2,
1920 0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151,
1921 0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162,
1922 0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132,
1923 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101,
1924 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312,
1925 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
1926 0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371,
1927 0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342,
1928 0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1,
1929 0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
1930 0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2,
1931 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381,
1932 0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291,
1933 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2,
1934 0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2,
1935 0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1,
1936 0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252,
1937 0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261,
1938 0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231,
1939 0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202
1940 };
1941
1942 static DRFLAC_INLINE drflac_uint8 drflac_crc8_byte(drflac_uint8 crc, drflac_uint8 data)
1943 {
1944 return drflac__crc8_table[crc ^ data];
1945 }
1946
1947 static DRFLAC_INLINE drflac_uint8 drflac_crc8(drflac_uint8 crc, drflac_uint32 data, drflac_uint32 count)
1948 {
1949 #ifdef DR_FLAC_NO_CRC
1950 (void)crc;
1951 (void)data;
1952 (void)count;
1953 return 0;
1954 #else
1955 #if 0
1956 /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc8(crc, 0, 8);") */
1957 drflac_uint8 p = 0x07;
1958 for (int i = count-1; i >= 0; --i) {
1959 drflac_uint8 bit = (data & (1 << i)) >> i;
1960 if (crc & 0x80) {
1961 crc = ((crc << 1) | bit) ^ p;
1962 } else {
1963 crc = ((crc << 1) | bit);
1964 }
1965 }
1966 return crc;
1967 #else
1968 drflac_uint32 wholeBytes;
1969 drflac_uint32 leftoverBits;
1970 drflac_uint64 leftoverDataMask;
1971
1972 static drflac_uint64 leftoverDataMaskTable[8] = {
1973 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
1974 };
1975
1976 DRFLAC_ASSERT(count <= 32);
1977
1978 wholeBytes = count >> 3;
1979 leftoverBits = count - (wholeBytes*8);
1980 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
1981
1982 switch (wholeBytes) {
1983 case 4: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
1984 case 3: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
1985 case 2: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
1986 case 1: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
1987 case 0: if (leftoverBits > 0) crc = (drflac_uint8)((crc << leftoverBits) ^ drflac__crc8_table[(crc >> (8 - leftoverBits)) ^ (data & leftoverDataMask)]);
1988 }
1989 return crc;
1990 #endif
1991 #endif
1992 }
1993
1994 static DRFLAC_INLINE drflac_uint16 drflac_crc16_byte(drflac_uint16 crc, drflac_uint8 data)
1995 {
1996 return (crc << 8) ^ drflac__crc16_table[(drflac_uint8)(crc >> 8) ^ data];
1997 }
1998
1999 static DRFLAC_INLINE drflac_uint16 drflac_crc16_cache(drflac_uint16 crc, drflac_cache_t data)
2000 {
2001 #ifdef DRFLAC_64BIT
2002 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
2003 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
2004 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
2005 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
2006 #endif
2007 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
2008 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
2009 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF));
2010 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF));
2011
2012 return crc;
2013 }
2014
2015 static DRFLAC_INLINE drflac_uint16 drflac_crc16_bytes(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 byteCount)
2016 {
2017 switch (byteCount)
2018 {
2019 #ifdef DRFLAC_64BIT
2020 case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
2021 case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
2022 case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
2023 case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
2024 #endif
2025 case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
2026 case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
2027 case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF));
2028 case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF));
2029 }
2030
2031 return crc;
2032 }
2033
2034 #if 0
2035 static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac_uint32 data, drflac_uint32 count)
2036 {
2037 #ifdef DR_FLAC_NO_CRC
2038 (void)crc;
2039 (void)data;
2040 (void)count;
2041 return 0;
2042 #else
2043 #if 0
2044 /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc16(crc, 0, 16);") */
2045 drflac_uint16 p = 0x8005;
2046 for (int i = count-1; i >= 0; --i) {
2047 drflac_uint16 bit = (data & (1ULL << i)) >> i;
2048 if (r & 0x8000) {
2049 r = ((r << 1) | bit) ^ p;
2050 } else {
2051 r = ((r << 1) | bit);
2052 }
2053 }
2054
2055 return crc;
2056 #else
2057 drflac_uint32 wholeBytes;
2058 drflac_uint32 leftoverBits;
2059 drflac_uint64 leftoverDataMask;
2060
2061 static drflac_uint64 leftoverDataMaskTable[8] = {
2062 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
2063 };
2064
2065 DRFLAC_ASSERT(count <= 64);
2066
2067 wholeBytes = count >> 3;
2068 leftoverBits = count & 7;
2069 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
2070
2071 switch (wholeBytes) {
2072 default:
2073 case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
2074 case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
2075 case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
2076 case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
2077 case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
2078 }
2079 return crc;
2080 #endif
2081 #endif
2082 }
2083
2084 static DRFLAC_INLINE drflac_uint16 drflac_crc16__64bit(drflac_uint16 crc, drflac_uint64 data, drflac_uint32 count)
2085 {
2086 #ifdef DR_FLAC_NO_CRC
2087 (void)crc;
2088 (void)data;
2089 (void)count;
2090 return 0;
2091 #else
2092 drflac_uint32 wholeBytes;
2093 drflac_uint32 leftoverBits;
2094 drflac_uint64 leftoverDataMask;
2095
2096 static drflac_uint64 leftoverDataMaskTable[8] = {
2097 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
2098 };
2099
2100 DRFLAC_ASSERT(count <= 64);
2101
2102 wholeBytes = count >> 3;
2103 leftoverBits = count & 7;
2104 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
2105
2106 switch (wholeBytes) {
2107 default:
2108 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. */
2109 case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 << 32) << leftoverBits)) >> (48 + leftoverBits)));
2110 case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 << 32) << leftoverBits)) >> (40 + leftoverBits)));
2111 case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF << 32) << leftoverBits)) >> (32 + leftoverBits)));
2112 case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 ) << leftoverBits)) >> (24 + leftoverBits)));
2113 case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 ) << leftoverBits)) >> (16 + leftoverBits)));
2114 case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 ) << leftoverBits)) >> ( 8 + leftoverBits)));
2115 case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF ) << leftoverBits)) >> ( 0 + leftoverBits)));
2116 case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
2117 }
2118 return crc;
2119 #endif
2120 }
2121
2122
2123 static DRFLAC_INLINE drflac_uint16 drflac_crc16(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 count)
2124 {
2125 #ifdef DRFLAC_64BIT
2126 return drflac_crc16__64bit(crc, data, count);
2127 #else
2128 return drflac_crc16__32bit(crc, data, count);
2129 #endif
2130 }
2131 #endif
2132
2133
2134 #ifdef DRFLAC_64BIT
2135 #define drflac__be2host__cache_line drflac__be2host_64
2136 #else
2137 #define drflac__be2host__cache_line drflac__be2host_32
2138 #endif
2139
2140 /*
2141 BIT READING ATTEMPT #2
2142
2143 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
2144 on the most significant bit. It uses the notion of an L1 and L2 cache (borrowed from CPU architecture), where the L1 cache
2145 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
2146 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
2147 from onRead() is read into.
2148 */
2149 #define DRFLAC_CACHE_L1_SIZE_BYTES(bs) (sizeof((bs)->cache))
2150 #define DRFLAC_CACHE_L1_SIZE_BITS(bs) (sizeof((bs)->cache)*8)
2151 #define DRFLAC_CACHE_L1_BITS_REMAINING(bs) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (bs)->consumedBits)
2152 #define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~((~(drflac_cache_t)0) >> (_bitCount)))
2153 #define DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount))
2154 #define DRFLAC_CACHE_L1_SELECT(bs, _bitCount) (((bs)->cache) & DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount))
2155 #define DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)))
2156 #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)))
2157 #define DRFLAC_CACHE_L2_SIZE_BYTES(bs) (sizeof((bs)->cacheL2))
2158 #define DRFLAC_CACHE_L2_LINE_COUNT(bs) (DRFLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0]))
2159 #define DRFLAC_CACHE_L2_LINES_REMAINING(bs) (DRFLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line)
2160
2161
2162 #ifndef DR_FLAC_NO_CRC
2163 static DRFLAC_INLINE void drflac__reset_crc16(drflac_bs* bs)
2164 {
2165 bs->crc16 = 0;
2166 bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
2167 }
2168
2169 static DRFLAC_INLINE void drflac__update_crc16(drflac_bs* bs)
2170 {
2171 if (bs->crc16CacheIgnoredBytes == 0) {
2172 bs->crc16 = drflac_crc16_cache(bs->crc16, bs->crc16Cache);
2173 } else {
2174 bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache, DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bs->crc16CacheIgnoredBytes);
2175 bs->crc16CacheIgnoredBytes = 0;
2176 }
2177 }
2178
2179 static DRFLAC_INLINE drflac_uint16 drflac__flush_crc16(drflac_bs* bs)
2180 {
2181 /* We should never be flushing in a situation where we are not aligned on a byte boundary. */
2182 DRFLAC_ASSERT((DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7) == 0);
2183
2184 /*
2185 The bits that were read from the L1 cache need to be accumulated. The number of bytes needing to be accumulated is determined
2186 by the number of bits that have been consumed.
2187 */
2188 if (DRFLAC_CACHE_L1_BITS_REMAINING(bs) == 0) {
2189 drflac__update_crc16(bs);
2190 } else {
2191 /* We only accumulate the consumed bits. */
2192 bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache >> DRFLAC_CACHE_L1_BITS_REMAINING(bs), (bs->consumedBits >> 3) - bs->crc16CacheIgnoredBytes);
2193
2194 /*
2195 The bits that we just accumulated should never be accumulated again. We need to keep track of how many bytes were accumulated
2196 so we can handle that later.
2197 */
2198 bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
2199 }
2200
2201 return bs->crc16;
2202 }
2203 #endif
2204
2205 static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs)
2206 {
2207 size_t bytesRead;
2208 size_t alignedL1LineCount;
2209
2210 /* Fast path. Try loading straight from L2. */
2211 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
2212 bs->cache = bs->cacheL2[bs->nextL2Line++];
2213 return DRFLAC_TRUE;
2214 }
2215
2216 /*
2217 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
2218 any left.
2219 */
2220 if (bs->unalignedByteCount > 0) {
2221 return DRFLAC_FALSE; /* If we have any unaligned bytes it means there's no more aligned bytes left in the client. */
2222 }
2223
2224 bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, DRFLAC_CACHE_L2_SIZE_BYTES(bs));
2225
2226 bs->nextL2Line = 0;
2227 if (bytesRead == DRFLAC_CACHE_L2_SIZE_BYTES(bs)) {
2228 bs->cache = bs->cacheL2[bs->nextL2Line++];
2229 return DRFLAC_TRUE;
2230 }
2231
2232
2233 /*
2234 If we get here it means we were unable to retrieve enough data to fill the entire L2 cache. It probably
2235 means we've just reached the end of the file. We need to move the valid data down to the end of the buffer
2236 and adjust the index of the next line accordingly. Also keep in mind that the L2 cache must be aligned to
2237 the size of the L1 so we'll need to seek backwards by any misaligned bytes.
2238 */
2239 alignedL1LineCount = bytesRead / DRFLAC_CACHE_L1_SIZE_BYTES(bs);
2240
2241 /* We need to keep track of any unaligned bytes for later use. */
2242 bs->unalignedByteCount = bytesRead - (alignedL1LineCount * DRFLAC_CACHE_L1_SIZE_BYTES(bs));
2243 if (bs->unalignedByteCount > 0) {
2244 bs->unalignedCache = bs->cacheL2[alignedL1LineCount];
2245 }
2246
2247 if (alignedL1LineCount > 0) {
2248 size_t offset = DRFLAC_CACHE_L2_LINE_COUNT(bs) - alignedL1LineCount;
2249 size_t i;
2250 for (i = alignedL1LineCount; i > 0; --i) {
2251 bs->cacheL2[i-1 + offset] = bs->cacheL2[i-1];
2252 }
2253
2254 bs->nextL2Line = (drflac_uint32)offset;
2255 bs->cache = bs->cacheL2[bs->nextL2Line++];
2256 return DRFLAC_TRUE;
2257 } else {
2258 /* If we get into this branch it means we weren't able to load any L1-aligned data. */
2259 bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs);
2260 return DRFLAC_FALSE;
2261 }
2262 }
2263
2264 static drflac_bool32 drflac__reload_cache(drflac_bs* bs)
2265 {
2266 size_t bytesRead;
2267
2268 #ifndef DR_FLAC_NO_CRC
2269 drflac__update_crc16(bs);
2270 #endif
2271
2272 /* Fast path. Try just moving the next value in the L2 cache to the L1 cache. */
2273 if (drflac__reload_l1_cache_from_l2(bs)) {
2274 bs->cache = drflac__be2host__cache_line(bs->cache);
2275 bs->consumedBits = 0;
2276 #ifndef DR_FLAC_NO_CRC
2277 bs->crc16Cache = bs->cache;
2278 #endif
2279 return DRFLAC_TRUE;
2280 }
2281
2282 /* Slow path. */
2283
2284 /*
2285 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
2286 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
2287 data from the unaligned cache.
2288 */
2289 bytesRead = bs->unalignedByteCount;
2290 if (bytesRead == 0) {
2291 bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); /* <-- The stream has been exhausted, so marked the bits as consumed. */
2292 return DRFLAC_FALSE;
2293 }
2294
2295 DRFLAC_ASSERT(bytesRead < DRFLAC_CACHE_L1_SIZE_BYTES(bs));
2296 bs->consumedBits = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bytesRead) * 8;
2297
2298 bs->cache = drflac__be2host__cache_line(bs->unalignedCache);
2299 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. */
2300 bs->unalignedByteCount = 0; /* <-- At this point the unaligned bytes have been moved into the cache and we thus have no more unaligned bytes. */
2301
2302 #ifndef DR_FLAC_NO_CRC
2303 bs->crc16Cache = bs->cache >> bs->consumedBits;
2304 bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
2305 #endif
2306 return DRFLAC_TRUE;
2307 }
2308
2309 static void drflac__reset_cache(drflac_bs* bs)
2310 {
2311 bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs); /* <-- This clears the L2 cache. */
2312 bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); /* <-- This clears the L1 cache. */
2313 bs->cache = 0;
2314 bs->unalignedByteCount = 0; /* <-- This clears the trailing unaligned bytes. */
2315 bs->unalignedCache = 0;
2316
2317 #ifndef DR_FLAC_NO_CRC
2318 bs->crc16Cache = 0;
2319 bs->crc16CacheIgnoredBytes = 0;
2320 #endif
2321 }
2322
2323
2324 static DRFLAC_INLINE drflac_bool32 drflac__read_uint32(drflac_bs* bs, unsigned int bitCount, drflac_uint32* pResultOut)
2325 {
2326 DRFLAC_ASSERT(bs != NULL);
2327 DRFLAC_ASSERT(pResultOut != NULL);
2328 DRFLAC_ASSERT(bitCount > 0);
2329 DRFLAC_ASSERT(bitCount <= 32);
2330
2331 if (bs->consumedBits == DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
2332 if (!drflac__reload_cache(bs)) {
2333 return DRFLAC_FALSE;
2334 }
2335 }
2336
2337 if (bitCount <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2338 /*
2339 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
2340 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
2341 more optimal solution for this.
2342 */
2343 #ifdef DRFLAC_64BIT
2344 *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
2345 bs->consumedBits += bitCount;
2346 bs->cache <<= bitCount;
2347 #else
2348 if (bitCount < DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
2349 *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
2350 bs->consumedBits += bitCount;
2351 bs->cache <<= bitCount;
2352 } else {
2353 /* Cannot shift by 32-bits, so need to do it differently. */
2354 *pResultOut = (drflac_uint32)bs->cache;
2355 bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);
2356 bs->cache = 0;
2357 }
2358 #endif
2359
2360 return DRFLAC_TRUE;
2361 } else {
2362 /* 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. */
2363 drflac_uint32 bitCountHi = DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2364 drflac_uint32 bitCountLo = bitCount - bitCountHi;
2365 drflac_uint32 resultHi;
2366
2367 DRFLAC_ASSERT(bitCountHi > 0);
2368 DRFLAC_ASSERT(bitCountHi < 32);
2369 resultHi = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountHi);
2370
2371 if (!drflac__reload_cache(bs)) {
2372 return DRFLAC_FALSE;
2373 }
2374 if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2375 /* This happens when we get to end of stream */
2376 return DRFLAC_FALSE;
2377 }
2378
2379 *pResultOut = (resultHi << bitCountLo) | (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo);
2380 bs->consumedBits += bitCountLo;
2381 bs->cache <<= bitCountLo;
2382 return DRFLAC_TRUE;
2383 }
2384 }
2385
2386 static drflac_bool32 drflac__read_int32(drflac_bs* bs, unsigned int bitCount, drflac_int32* pResult)
2387 {
2388 drflac_uint32 result;
2389
2390 DRFLAC_ASSERT(bs != NULL);
2391 DRFLAC_ASSERT(pResult != NULL);
2392 DRFLAC_ASSERT(bitCount > 0);
2393 DRFLAC_ASSERT(bitCount <= 32);
2394
2395 if (!drflac__read_uint32(bs, bitCount, &result)) {
2396 return DRFLAC_FALSE;
2397 }
2398
2399 /* Do not attempt to shift by 32 as it's undefined. */
2400 if (bitCount < 32) {
2401 drflac_uint32 signbit;
2402 signbit = ((result >> (bitCount-1)) & 0x01);
2403 result |= (~signbit + 1) << bitCount;
2404 }
2405
2406 *pResult = (drflac_int32)result;
2407 return DRFLAC_TRUE;
2408 }
2409
2410 #ifdef DRFLAC_64BIT
2411 static drflac_bool32 drflac__read_uint64(drflac_bs* bs, unsigned int bitCount, drflac_uint64* pResultOut)
2412 {
2413 drflac_uint32 resultHi;
2414 drflac_uint32 resultLo;
2415
2416 DRFLAC_ASSERT(bitCount <= 64);
2417 DRFLAC_ASSERT(bitCount > 32);
2418
2419 if (!drflac__read_uint32(bs, bitCount - 32, &resultHi)) {
2420 return DRFLAC_FALSE;
2421 }
2422
2423 if (!drflac__read_uint32(bs, 32, &resultLo)) {
2424 return DRFLAC_FALSE;
2425 }
2426
2427 *pResultOut = (((drflac_uint64)resultHi) << 32) | ((drflac_uint64)resultLo);
2428 return DRFLAC_TRUE;
2429 }
2430 #endif
2431
2432 /* Function below is unused, but leaving it here in case I need to quickly add it again. */
2433 #if 0
2434 static drflac_bool32 drflac__read_int64(drflac_bs* bs, unsigned int bitCount, drflac_int64* pResultOut)
2435 {
2436 drflac_uint64 result;
2437 drflac_uint64 signbit;
2438
2439 DRFLAC_ASSERT(bitCount <= 64);
2440
2441 if (!drflac__read_uint64(bs, bitCount, &result)) {
2442 return DRFLAC_FALSE;
2443 }
2444
2445 signbit = ((result >> (bitCount-1)) & 0x01);
2446 result |= (~signbit + 1) << bitCount;
2447
2448 *pResultOut = (drflac_int64)result;
2449 return DRFLAC_TRUE;
2450 }
2451 #endif
2452
2453 static drflac_bool32 drflac__read_uint16(drflac_bs* bs, unsigned int bitCount, drflac_uint16* pResult)
2454 {
2455 drflac_uint32 result;
2456
2457 DRFLAC_ASSERT(bs != NULL);
2458 DRFLAC_ASSERT(pResult != NULL);
2459 DRFLAC_ASSERT(bitCount > 0);
2460 DRFLAC_ASSERT(bitCount <= 16);
2461
2462 if (!drflac__read_uint32(bs, bitCount, &result)) {
2463 return DRFLAC_FALSE;
2464 }
2465
2466 *pResult = (drflac_uint16)result;
2467 return DRFLAC_TRUE;
2468 }
2469
2470 #if 0
2471 static drflac_bool32 drflac__read_int16(drflac_bs* bs, unsigned int bitCount, drflac_int16* pResult)
2472 {
2473 drflac_int32 result;
2474
2475 DRFLAC_ASSERT(bs != NULL);
2476 DRFLAC_ASSERT(pResult != NULL);
2477 DRFLAC_ASSERT(bitCount > 0);
2478 DRFLAC_ASSERT(bitCount <= 16);
2479
2480 if (!drflac__read_int32(bs, bitCount, &result)) {
2481 return DRFLAC_FALSE;
2482 }
2483
2484 *pResult = (drflac_int16)result;
2485 return DRFLAC_TRUE;
2486 }
2487 #endif
2488
2489 static drflac_bool32 drflac__read_uint8(drflac_bs* bs, unsigned int bitCount, drflac_uint8* pResult)
2490 {
2491 drflac_uint32 result;
2492
2493 DRFLAC_ASSERT(bs != NULL);
2494 DRFLAC_ASSERT(pResult != NULL);
2495 DRFLAC_ASSERT(bitCount > 0);
2496 DRFLAC_ASSERT(bitCount <= 8);
2497
2498 if (!drflac__read_uint32(bs, bitCount, &result)) {
2499 return DRFLAC_FALSE;
2500 }
2501
2502 *pResult = (drflac_uint8)result;
2503 return DRFLAC_TRUE;
2504 }
2505
2506 static drflac_bool32 drflac__read_int8(drflac_bs* bs, unsigned int bitCount, drflac_int8* pResult)
2507 {
2508 drflac_int32 result;
2509
2510 DRFLAC_ASSERT(bs != NULL);
2511 DRFLAC_ASSERT(pResult != NULL);
2512 DRFLAC_ASSERT(bitCount > 0);
2513 DRFLAC_ASSERT(bitCount <= 8);
2514
2515 if (!drflac__read_int32(bs, bitCount, &result)) {
2516 return DRFLAC_FALSE;
2517 }
2518
2519 *pResult = (drflac_int8)result;
2520 return DRFLAC_TRUE;
2521 }
2522
2523
2524 static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek)
2525 {
2526 if (bitsToSeek <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2527 bs->consumedBits += (drflac_uint32)bitsToSeek;
2528 bs->cache <<= bitsToSeek;
2529 return DRFLAC_TRUE;
2530 } else {
2531 /* It straddles the cached data. This function isn't called too frequently so I'm favouring simplicity here. */
2532 bitsToSeek -= DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2533 bs->consumedBits += DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2534 bs->cache = 0;
2535
2536 /* Simple case. Seek in groups of the same number as bits that fit within a cache line. */
2537 #ifdef DRFLAC_64BIT
2538 while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
2539 drflac_uint64 bin;
2540 if (!drflac__read_uint64(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
2541 return DRFLAC_FALSE;
2542 }
2543 bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
2544 }
2545 #else
2546 while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
2547 drflac_uint32 bin;
2548 if (!drflac__read_uint32(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
2549 return DRFLAC_FALSE;
2550 }
2551 bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
2552 }
2553 #endif
2554
2555 /* Whole leftover bytes. */
2556 while (bitsToSeek >= 8) {
2557 drflac_uint8 bin;
2558 if (!drflac__read_uint8(bs, 8, &bin)) {
2559 return DRFLAC_FALSE;
2560 }
2561 bitsToSeek -= 8;
2562 }
2563
2564 /* Leftover bits. */
2565 if (bitsToSeek > 0) {
2566 drflac_uint8 bin;
2567 if (!drflac__read_uint8(bs, (drflac_uint32)bitsToSeek, &bin)) {
2568 return DRFLAC_FALSE;
2569 }
2570 bitsToSeek = 0; /* <-- Necessary for the assert below. */
2571 }
2572
2573 DRFLAC_ASSERT(bitsToSeek == 0);
2574 return DRFLAC_TRUE;
2575 }
2576 }
2577
2578
2579 /* 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. */
2580 static drflac_bool32 drflac__find_and_seek_to_next_sync_code(drflac_bs* bs)
2581 {
2582 DRFLAC_ASSERT(bs != NULL);
2583
2584 /*
2585 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
2586 thing to do is align to the next byte.
2587 */
2588 if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
2589 return DRFLAC_FALSE;
2590 }
2591
2592 for (;;) {
2593 drflac_uint8 hi;
2594
2595 #ifndef DR_FLAC_NO_CRC
2596 drflac__reset_crc16(bs);
2597 #endif
2598
2599 if (!drflac__read_uint8(bs, 8, &hi)) {
2600 return DRFLAC_FALSE;
2601 }
2602
2603 if (hi == 0xFF) {
2604 drflac_uint8 lo;
2605 if (!drflac__read_uint8(bs, 6, &lo)) {
2606 return DRFLAC_FALSE;
2607 }
2608
2609 if (lo == 0x3E) {
2610 return DRFLAC_TRUE;
2611 } else {
2612 if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
2613 return DRFLAC_FALSE;
2614 }
2615 }
2616 }
2617 }
2618
2619 /* Should never get here. */
2620 /*return DRFLAC_FALSE;*/
2621 }
2622
2623
2624 #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
2625 #define DRFLAC_IMPLEMENT_CLZ_LZCNT
2626 #endif
2627 #if defined(_MSC_VER) && _MSC_VER >= 1400 && (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(__clang__)
2628 #define DRFLAC_IMPLEMENT_CLZ_MSVC
2629 #endif
2630 #if defined(__WATCOMC__) && defined(__386__)
2631 #define DRFLAC_IMPLEMENT_CLZ_WATCOM
2632 #endif
2633 #ifdef __MRC__
2634 #include <intrinsics.h>
2635 #define DRFLAC_IMPLEMENT_CLZ_MRC
2636 #endif
2637
2638 static DRFLAC_INLINE drflac_uint32 drflac__clz_software(drflac_cache_t x)
2639 {
2640 drflac_uint32 n;
2641 static drflac_uint32 clz_table_4[] = {
2642 0,
2643 4,
2644 3, 3,
2645 2, 2, 2, 2,
2646 1, 1, 1, 1, 1, 1, 1, 1
2647 };
2648
2649 if (x == 0) {
2650 return sizeof(x)*8;
2651 }
2652
2653 n = clz_table_4[x >> (sizeof(x)*8 - 4)];
2654 if (n == 0) {
2655 #ifdef DRFLAC_64BIT
2656 if ((x & ((drflac_uint64)0xFFFFFFFF << 32)) == 0) { n = 32; x <<= 32; }
2657 if ((x & ((drflac_uint64)0xFFFF0000 << 32)) == 0) { n += 16; x <<= 16; }
2658 if ((x & ((drflac_uint64)0xFF000000 << 32)) == 0) { n += 8; x <<= 8; }
2659 if ((x & ((drflac_uint64)0xF0000000 << 32)) == 0) { n += 4; x <<= 4; }
2660 #else
2661 if ((x & 0xFFFF0000) == 0) { n = 16; x <<= 16; }
2662 if ((x & 0xFF000000) == 0) { n += 8; x <<= 8; }
2663 if ((x & 0xF0000000) == 0) { n += 4; x <<= 4; }
2664 #endif
2665 n += clz_table_4[x >> (sizeof(x)*8 - 4)];
2666 }
2667
2668 return n - 1;
2669 }
2670
2671 #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
2672 static DRFLAC_INLINE drflac_bool32 drflac__is_lzcnt_supported(void)
2673 {
2674 /* Fast compile time check for ARM. */
2675 #if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
2676 return DRFLAC_TRUE;
2677 #elif defined(__MRC__)
2678 return DRFLAC_TRUE;
2679 #else
2680 /* If the compiler itself does not support the intrinsic then we'll need to return false. */
2681 #ifdef DRFLAC_HAS_LZCNT_INTRINSIC
2682 return drflac__gIsLZCNTSupported;
2683 #else
2684 return DRFLAC_FALSE;
2685 #endif
2686 #endif
2687 }
2688
2689 static DRFLAC_INLINE drflac_uint32 drflac__clz_lzcnt(drflac_cache_t x)
2690 {
2691 /*
2692 It's critical for competitive decoding performance that this function be highly optimal. With MSVC we can use the __lzcnt64() and __lzcnt() intrinsics
2693 to achieve good performance, however on GCC and Clang it's a little bit more annoying. The __builtin_clzl() and __builtin_clzll() intrinsics leave
2694 it undefined as to the return value when `x` is 0. We need this to be well defined as returning 32 or 64, depending on whether or not it's a 32- or
2695 64-bit build. To work around this we would need to add a conditional to check for the x = 0 case, but this creates unnecessary inefficiency. To work
2696 around this problem I have written some inline assembly to emit the LZCNT (x86) or CLZ (ARM) instruction directly which removes the need to include
2697 the conditional. This has worked well in the past, but for some reason Clang's MSVC compatible driver, clang-cl, does not seem to be handling this
2698 in the same way as the normal Clang driver. It seems that `clang-cl` is just outputting the wrong results sometimes, maybe due to some register
2699 getting clobbered?
2700
2701 I'm not sure if this is a bug with dr_flac's inlined assembly (most likely), a bug in `clang-cl` or just a misunderstanding on my part with inline
2702 assembly rules for `clang-cl`. If somebody can identify an error in dr_flac's inlined assembly I'm happy to get that fixed.
2703
2704 Fortunately there is an easy workaround for this. Clang implements MSVC-specific intrinsics for compatibility. It also defines _MSC_VER for extra
2705 compatibility. We can therefore just check for _MSC_VER and use the MSVC intrinsic which, fortunately for us, Clang supports. It would still be nice
2706 to know how to fix the inlined assembly for correctness sake, however.
2707 */
2708
2709 #if defined(_MSC_VER) /*&& !defined(__clang__)*/ /* <-- Intentionally wanting Clang to use the MSVC __lzcnt64/__lzcnt intrinsics due to above ^. */
2710 #ifdef DRFLAC_64BIT
2711 return (drflac_uint32)__lzcnt64(x);
2712 #else
2713 return (drflac_uint32)__lzcnt(x);
2714 #endif
2715 #else
2716 #if defined(__GNUC__) || defined(__clang__)
2717 #if defined(DRFLAC_X64)
2718 {
2719 /*
2720 A note on lzcnt.
2721
2722 We check for the presence of the lzcnt instruction at runtime before calling this function, but we still generate this code. I have had
2723 a report where the assembler does not recognize the lzcnt instruction. To work around this we are going to use `rep; bsr` instead which
2724 has an identical byte encoding as lzcnt, and should hopefully improve compatibility with older assemblers.
2725 */
2726 drflac_uint64 r;
2727 __asm__ __volatile__ (
2728 "rep; bsr{q %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
2729 /*"lzcnt{ %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"*/
2730 );
2731
2732 return (drflac_uint32)r;
2733 }
2734 #elif defined(DRFLAC_X86)
2735 {
2736 drflac_uint32 r;
2737 __asm__ __volatile__ (
2738 "rep; bsr{l %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
2739 /*"lzcnt{l %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"*/
2740 );
2741
2742 return r;
2743 }
2744 #elif defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) && !defined(__ARM_ARCH_6M__) && !(defined(__thumb__) && !defined(__thumb2__)) && !defined(DRFLAC_64BIT) /* <-- I haven't tested 64-bit inline assembly, so only enabling this for the 32-bit build for now. */
2745 {
2746 unsigned int r;
2747 __asm__ __volatile__ (
2748 #if defined(DRFLAC_64BIT)
2749 "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! */
2750 #else
2751 "clz %[out], %[in]" : [out]"=r"(r) : [in]"r"(x)
2752 #endif
2753 );
2754
2755 return r;
2756 }
2757 #else
2758 if (x == 0) {
2759 return sizeof(x)*8;
2760 }
2761 #ifdef DRFLAC_64BIT
2762 return (drflac_uint32)__builtin_clzll((drflac_uint64)x);
2763 #else
2764 return (drflac_uint32)__builtin_clzl((drflac_uint32)x);
2765 #endif
2766 #endif
2767 #else
2768 /* Unsupported compiler. */
2769 #error "This compiler does not support the lzcnt intrinsic."
2770 #endif
2771 #endif
2772 }
2773 #endif
2774
2775 #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
2776 #include <intrin.h> /* For BitScanReverse(). */
2777
2778 static DRFLAC_INLINE drflac_uint32 drflac__clz_msvc(drflac_cache_t x)
2779 {
2780 drflac_uint32 n;
2781
2782 if (x == 0) {
2783 return sizeof(x)*8;
2784 }
2785
2786 #ifdef DRFLAC_64BIT
2787 _BitScanReverse64((unsigned long*)&n, x);
2788 #else
2789 _BitScanReverse((unsigned long*)&n, x);
2790 #endif
2791 return sizeof(x)*8 - n - 1;
2792 }
2793 #endif
2794
2795 #ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM
2796 static __inline drflac_uint32 drflac__clz_watcom (drflac_uint32);
2797 #ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM_LZCNT
2798 /* Use the LZCNT instruction (only available on some processors since the 2010s). */
2799 #pragma aux drflac__clz_watcom_lzcnt = \
2800 "db 0F3h, 0Fh, 0BDh, 0C0h" /* lzcnt eax, eax */ \
2801 parm [eax] \
2802 value [eax] \
2803 modify nomemory;
2804 #else
2805 /* Use the 386+-compatible implementation. */
2806 #pragma aux drflac__clz_watcom = \
2807 "bsr eax, eax" \
2808 "xor eax, 31" \
2809 parm [eax] nomemory \
2810 value [eax] \
2811 modify exact [eax] nomemory;
2812 #endif
2813 #endif
2814
2815 static DRFLAC_INLINE drflac_uint32 drflac__clz(drflac_cache_t x)
2816 {
2817 #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
2818 if (drflac__is_lzcnt_supported()) {
2819 return drflac__clz_lzcnt(x);
2820 } else
2821 #endif
2822 {
2823 #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
2824 return drflac__clz_msvc(x);
2825 #elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM_LZCNT)
2826 return drflac__clz_watcom_lzcnt(x);
2827 #elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM)
2828 return (x == 0) ? sizeof(x)*8 : drflac__clz_watcom(x);
2829 #elif defined(__MRC__)
2830 return __cntlzw(x);
2831 #else
2832 return drflac__clz_software(x);
2833 #endif
2834 }
2835 }
2836
2837
2838 static DRFLAC_INLINE drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsigned int* pOffsetOut)
2839 {
2840 drflac_uint32 zeroCounter = 0;
2841 drflac_uint32 setBitOffsetPlus1;
2842
2843 while (bs->cache == 0) {
2844 zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2845 if (!drflac__reload_cache(bs)) {
2846 return DRFLAC_FALSE;
2847 }
2848 }
2849
2850 if (bs->cache == 1) {
2851 /* Not catching this would lead to undefined behaviour: a shift of a 32-bit number by 32 or more is undefined */
2852 *pOffsetOut = zeroCounter + (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs) - 1;
2853 if (!drflac__reload_cache(bs)) {
2854 return DRFLAC_FALSE;
2855 }
2856
2857 return DRFLAC_TRUE;
2858 }
2859
2860 setBitOffsetPlus1 = drflac__clz(bs->cache);
2861 setBitOffsetPlus1 += 1;
2862
2863 if (setBitOffsetPlus1 > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2864 /* This happens when we get to end of stream */
2865 return DRFLAC_FALSE;
2866 }
2867
2868 bs->consumedBits += setBitOffsetPlus1;
2869 bs->cache <<= setBitOffsetPlus1;
2870
2871 *pOffsetOut = zeroCounter + setBitOffsetPlus1 - 1;
2872 return DRFLAC_TRUE;
2873 }
2874
2875
2876
2877 static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFromStart)
2878 {
2879 DRFLAC_ASSERT(bs != NULL);
2880 DRFLAC_ASSERT(offsetFromStart > 0);
2881
2882 /*
2883 Seeking from the start is not quite as trivial as it sounds because the onSeek callback takes a signed 32-bit integer (which
2884 is intentional because it simplifies the implementation of the onSeek callbacks), however offsetFromStart is unsigned 64-bit.
2885 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.
2886 */
2887 if (offsetFromStart > 0x7FFFFFFF) {
2888 drflac_uint64 bytesRemaining = offsetFromStart;
2889 if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, DRFLAC_SEEK_SET)) {
2890 return DRFLAC_FALSE;
2891 }
2892 bytesRemaining -= 0x7FFFFFFF;
2893
2894 while (bytesRemaining > 0x7FFFFFFF) {
2895 if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, DRFLAC_SEEK_CUR)) {
2896 return DRFLAC_FALSE;
2897 }
2898 bytesRemaining -= 0x7FFFFFFF;
2899 }
2900
2901 if (bytesRemaining > 0) {
2902 if (!bs->onSeek(bs->pUserData, (int)bytesRemaining, DRFLAC_SEEK_CUR)) {
2903 return DRFLAC_FALSE;
2904 }
2905 }
2906 } else {
2907 if (!bs->onSeek(bs->pUserData, (int)offsetFromStart, DRFLAC_SEEK_SET)) {
2908 return DRFLAC_FALSE;
2909 }
2910 }
2911
2912 /* The cache should be reset to force a reload of fresh data from the client. */
2913 drflac__reset_cache(bs);
2914 return DRFLAC_TRUE;
2915 }
2916
2917
2918 static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64* pNumberOut, drflac_uint8* pCRCOut)
2919 {
2920 drflac_uint8 crc;
2921 drflac_uint64 result;
2922 drflac_uint8 utf8[7] = {0};
2923 int byteCount;
2924 int i;
2925
2926 DRFLAC_ASSERT(bs != NULL);
2927 DRFLAC_ASSERT(pNumberOut != NULL);
2928 DRFLAC_ASSERT(pCRCOut != NULL);
2929
2930 crc = *pCRCOut;
2931
2932 if (!drflac__read_uint8(bs, 8, utf8)) {
2933 *pNumberOut = 0;
2934 return DRFLAC_AT_END;
2935 }
2936 crc = drflac_crc8(crc, utf8[0], 8);
2937
2938 if ((utf8[0] & 0x80) == 0) {
2939 *pNumberOut = utf8[0];
2940 *pCRCOut = crc;
2941 return DRFLAC_SUCCESS;
2942 }
2943
2944 /*byteCount = 1;*/
2945 if ((utf8[0] & 0xE0) == 0xC0) {
2946 byteCount = 2;
2947 } else if ((utf8[0] & 0xF0) == 0xE0) {
2948 byteCount = 3;
2949 } else if ((utf8[0] & 0xF8) == 0xF0) {
2950 byteCount = 4;
2951 } else if ((utf8[0] & 0xFC) == 0xF8) {
2952 byteCount = 5;
2953 } else if ((utf8[0] & 0xFE) == 0xFC) {
2954 byteCount = 6;
2955 } else if ((utf8[0] & 0xFF) == 0xFE) {
2956 byteCount = 7;
2957 } else {
2958 *pNumberOut = 0;
2959 return DRFLAC_CRC_MISMATCH; /* Bad UTF-8 encoding. */
2960 }
2961
2962 /* Read extra bytes. */
2963 DRFLAC_ASSERT(byteCount > 1);
2964
2965 result = (drflac_uint64)(utf8[0] & (0xFF >> (byteCount + 1)));
2966 for (i = 1; i < byteCount; ++i) {
2967 if (!drflac__read_uint8(bs, 8, utf8 + i)) {
2968 *pNumberOut = 0;
2969 return DRFLAC_AT_END;
2970 }
2971 crc = drflac_crc8(crc, utf8[i], 8);
2972
2973 result = (result << 6) | (utf8[i] & 0x3F);
2974 }
2975
2976 *pNumberOut = result;
2977 *pCRCOut = crc;
2978 return DRFLAC_SUCCESS;
2979 }
2980
2981
2982 static DRFLAC_INLINE drflac_uint32 drflac__ilog2_u32(drflac_uint32 x)
2983 {
2984 #if 1 /* Needs optimizing. */
2985 drflac_uint32 result = 0;
2986 while (x > 0) {
2987 result += 1;
2988 x >>= 1;
2989 }
2990
2991 return result;
2992 #endif
2993 }
2994
2995 static DRFLAC_INLINE drflac_bool32 drflac__use_64_bit_prediction(drflac_uint32 bitsPerSample, drflac_uint32 order, drflac_uint32 precision)
2996 {
2997 /* https://web.archive.org/web/20220205005724/https://github.com/ietf-wg-cellar/flac-specification/blob/37a49aa48ba4ba12e8757badfc59c0df35435fec/rfc_backmatter.md */
2998 return bitsPerSample + precision + drflac__ilog2_u32(order) > 32;
2999 }
3000
3001
3002 /*
3003 The next two functions are responsible for calculating the prediction.
3004
3005 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
3006 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.
3007 */
3008 #if defined(__clang__)
3009 __attribute__((no_sanitize("signed-integer-overflow")))
3010 #endif
3011 static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_32(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
3012 {
3013 drflac_int32 prediction = 0;
3014
3015 DRFLAC_ASSERT(order <= 32);
3016
3017 /* 32-bit version. */
3018
3019 /* VC++ optimizes this to a single jmp. I've not yet verified this for other compilers. */
3020 switch (order)
3021 {
3022 case 32: prediction += coefficients[31] * pDecodedSamples[-32];
3023 case 31: prediction += coefficients[30] * pDecodedSamples[-31];
3024 case 30: prediction += coefficients[29] * pDecodedSamples[-30];
3025 case 29: prediction += coefficients[28] * pDecodedSamples[-29];
3026 case 28: prediction += coefficients[27] * pDecodedSamples[-28];
3027 case 27: prediction += coefficients[26] * pDecodedSamples[-27];
3028 case 26: prediction += coefficients[25] * pDecodedSamples[-26];
3029 case 25: prediction += coefficients[24] * pDecodedSamples[-25];
3030 case 24: prediction += coefficients[23] * pDecodedSamples[-24];
3031 case 23: prediction += coefficients[22] * pDecodedSamples[-23];
3032 case 22: prediction += coefficients[21] * pDecodedSamples[-22];
3033 case 21: prediction += coefficients[20] * pDecodedSamples[-21];
3034 case 20: prediction += coefficients[19] * pDecodedSamples[-20];
3035 case 19: prediction += coefficients[18] * pDecodedSamples[-19];
3036 case 18: prediction += coefficients[17] * pDecodedSamples[-18];
3037 case 17: prediction += coefficients[16] * pDecodedSamples[-17];
3038 case 16: prediction += coefficients[15] * pDecodedSamples[-16];
3039 case 15: prediction += coefficients[14] * pDecodedSamples[-15];
3040 case 14: prediction += coefficients[13] * pDecodedSamples[-14];
3041 case 13: prediction += coefficients[12] * pDecodedSamples[-13];
3042 case 12: prediction += coefficients[11] * pDecodedSamples[-12];
3043 case 11: prediction += coefficients[10] * pDecodedSamples[-11];
3044 case 10: prediction += coefficients[ 9] * pDecodedSamples[-10];
3045 case 9: prediction += coefficients[ 8] * pDecodedSamples[- 9];
3046 case 8: prediction += coefficients[ 7] * pDecodedSamples[- 8];
3047 case 7: prediction += coefficients[ 6] * pDecodedSamples[- 7];
3048 case 6: prediction += coefficients[ 5] * pDecodedSamples[- 6];
3049 case 5: prediction += coefficients[ 4] * pDecodedSamples[- 5];
3050 case 4: prediction += coefficients[ 3] * pDecodedSamples[- 4];
3051 case 3: prediction += coefficients[ 2] * pDecodedSamples[- 3];
3052 case 2: prediction += coefficients[ 1] * pDecodedSamples[- 2];
3053 case 1: prediction += coefficients[ 0] * pDecodedSamples[- 1];
3054 }
3055
3056 return (drflac_int32)(prediction >> shift);
3057 }
3058
3059 static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
3060 {
3061 drflac_int64 prediction;
3062
3063 DRFLAC_ASSERT(order <= 32);
3064
3065 /* 64-bit version. */
3066
3067 /* This method is faster on the 32-bit build when compiling with VC++. See note below. */
3068 #ifndef DRFLAC_64BIT
3069 if (order == 8)
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 }
3080 else if (order == 7)
3081 {
3082 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3083 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3084 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3085 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3086 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3087 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3088 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3089 }
3090 else if (order == 3)
3091 {
3092 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3093 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3094 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3095 }
3096 else if (order == 6)
3097 {
3098 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3099 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3100 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3101 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3102 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3103 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3104 }
3105 else if (order == 5)
3106 {
3107 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3108 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3109 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3110 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3111 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3112 }
3113 else if (order == 4)
3114 {
3115 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3116 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3117 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3118 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3119 }
3120 else if (order == 12)
3121 {
3122 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3123 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3124 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3125 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3126 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3127 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3128 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3129 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3130 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3131 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
3132 prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
3133 prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
3134 }
3135 else if (order == 2)
3136 {
3137 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3138 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3139 }
3140 else if (order == 1)
3141 {
3142 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3143 }
3144 else if (order == 10)
3145 {
3146 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3147 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3148 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3149 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3150 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3151 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3152 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3153 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3154 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3155 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
3156 }
3157 else if (order == 9)
3158 {
3159 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3160 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3161 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3162 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3163 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3164 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3165 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3166 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3167 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3168 }
3169 else if (order == 11)
3170 {
3171 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3172 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3173 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3174 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3175 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3176 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3177 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3178 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3179 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3180 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
3181 prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
3182 }
3183 else
3184 {
3185 int j;
3186
3187 prediction = 0;
3188 for (j = 0; j < (int)order; ++j) {
3189 prediction += coefficients[j] * (drflac_int64)pDecodedSamples[-j-1];
3190 }
3191 }
3192 #endif
3193
3194 /*
3195 VC++ optimizes this to a single jmp instruction, but only the 64-bit build. The 32-bit build generates less efficient code for some
3196 reason. The ugly version above is faster so we'll just switch between the two depending on the target platform.
3197 */
3198 #ifdef DRFLAC_64BIT
3199 prediction = 0;
3200 switch (order)
3201 {
3202 case 32: prediction += coefficients[31] * (drflac_int64)pDecodedSamples[-32];
3203 case 31: prediction += coefficients[30] * (drflac_int64)pDecodedSamples[-31];
3204 case 30: prediction += coefficients[29] * (drflac_int64)pDecodedSamples[-30];
3205 case 29: prediction += coefficients[28] * (drflac_int64)pDecodedSamples[-29];
3206 case 28: prediction += coefficients[27] * (drflac_int64)pDecodedSamples[-28];
3207 case 27: prediction += coefficients[26] * (drflac_int64)pDecodedSamples[-27];
3208 case 26: prediction += coefficients[25] * (drflac_int64)pDecodedSamples[-26];
3209 case 25: prediction += coefficients[24] * (drflac_int64)pDecodedSamples[-25];
3210 case 24: prediction += coefficients[23] * (drflac_int64)pDecodedSamples[-24];
3211 case 23: prediction += coefficients[22] * (drflac_int64)pDecodedSamples[-23];
3212 case 22: prediction += coefficients[21] * (drflac_int64)pDecodedSamples[-22];
3213 case 21: prediction += coefficients[20] * (drflac_int64)pDecodedSamples[-21];
3214 case 20: prediction += coefficients[19] * (drflac_int64)pDecodedSamples[-20];
3215 case 19: prediction += coefficients[18] * (drflac_int64)pDecodedSamples[-19];
3216 case 18: prediction += coefficients[17] * (drflac_int64)pDecodedSamples[-18];
3217 case 17: prediction += coefficients[16] * (drflac_int64)pDecodedSamples[-17];
3218 case 16: prediction += coefficients[15] * (drflac_int64)pDecodedSamples[-16];
3219 case 15: prediction += coefficients[14] * (drflac_int64)pDecodedSamples[-15];
3220 case 14: prediction += coefficients[13] * (drflac_int64)pDecodedSamples[-14];
3221 case 13: prediction += coefficients[12] * (drflac_int64)pDecodedSamples[-13];
3222 case 12: prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
3223 case 11: prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
3224 case 10: prediction += coefficients[ 9] * (drflac_int64)pDecodedSamples[-10];
3225 case 9: prediction += coefficients[ 8] * (drflac_int64)pDecodedSamples[- 9];
3226 case 8: prediction += coefficients[ 7] * (drflac_int64)pDecodedSamples[- 8];
3227 case 7: prediction += coefficients[ 6] * (drflac_int64)pDecodedSamples[- 7];
3228 case 6: prediction += coefficients[ 5] * (drflac_int64)pDecodedSamples[- 6];
3229 case 5: prediction += coefficients[ 4] * (drflac_int64)pDecodedSamples[- 5];
3230 case 4: prediction += coefficients[ 3] * (drflac_int64)pDecodedSamples[- 4];
3231 case 3: prediction += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 3];
3232 case 2: prediction += coefficients[ 1] * (drflac_int64)pDecodedSamples[- 2];
3233 case 1: prediction += coefficients[ 0] * (drflac_int64)pDecodedSamples[- 1];
3234 }
3235 #endif
3236
3237 return (drflac_int32)(prediction >> shift);
3238 }
3239
3240
3241 #if 0
3242 /*
3243 Reference implementation for reading and decoding samples with residual. This is intentionally left unoptimized for the
3244 sake of readability and should only be used as a reference.
3245 */
3246 static drflac_bool32 drflac__decode_samples_with_residual__rice__reference(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
3247 {
3248 drflac_uint32 i;
3249
3250 DRFLAC_ASSERT(bs != NULL);
3251 DRFLAC_ASSERT(pSamplesOut != NULL);
3252
3253 for (i = 0; i < count; ++i) {
3254 drflac_uint32 zeroCounter = 0;
3255 for (;;) {
3256 drflac_uint8 bit;
3257 if (!drflac__read_uint8(bs, 1, &bit)) {
3258 return DRFLAC_FALSE;
3259 }
3260
3261 if (bit == 0) {
3262 zeroCounter += 1;
3263 } else {
3264 break;
3265 }
3266 }
3267
3268 drflac_uint32 decodedRice;
3269 if (riceParam > 0) {
3270 if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
3271 return DRFLAC_FALSE;
3272 }
3273 } else {
3274 decodedRice = 0;
3275 }
3276
3277 decodedRice |= (zeroCounter << riceParam);
3278 if ((decodedRice & 0x01)) {
3279 decodedRice = ~(decodedRice >> 1);
3280 } else {
3281 decodedRice = (decodedRice >> 1);
3282 }
3283
3284
3285 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
3286 pSamplesOut[i] = decodedRice + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
3287 } else {
3288 pSamplesOut[i] = decodedRice + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
3289 }
3290 }
3291
3292 return DRFLAC_TRUE;
3293 }
3294 #endif
3295
3296 #if 0
3297 static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
3298 {
3299 drflac_uint32 zeroCounter = 0;
3300 drflac_uint32 decodedRice;
3301
3302 for (;;) {
3303 drflac_uint8 bit;
3304 if (!drflac__read_uint8(bs, 1, &bit)) {
3305 return DRFLAC_FALSE;
3306 }
3307
3308 if (bit == 0) {
3309 zeroCounter += 1;
3310 } else {
3311 break;
3312 }
3313 }
3314
3315 if (riceParam > 0) {
3316 if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
3317 return DRFLAC_FALSE;
3318 }
3319 } else {
3320 decodedRice = 0;
3321 }
3322
3323 *pZeroCounterOut = zeroCounter;
3324 *pRiceParamPartOut = decodedRice;
3325 return DRFLAC_TRUE;
3326 }
3327 #endif
3328
3329 #if 0
3330 static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
3331 {
3332 drflac_cache_t riceParamMask;
3333 drflac_uint32 zeroCounter;
3334 drflac_uint32 setBitOffsetPlus1;
3335 drflac_uint32 riceParamPart;
3336 drflac_uint32 riceLength;
3337
3338 DRFLAC_ASSERT(riceParam > 0); /* <-- riceParam should never be 0. drflac__read_rice_parts__param_equals_zero() should be used instead for this case. */
3339
3340 riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParam);
3341
3342 zeroCounter = 0;
3343 while (bs->cache == 0) {
3344 zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
3345 if (!drflac__reload_cache(bs)) {
3346 return DRFLAC_FALSE;
3347 }
3348 }
3349
3350 setBitOffsetPlus1 = drflac__clz(bs->cache);
3351 zeroCounter += setBitOffsetPlus1;
3352 setBitOffsetPlus1 += 1;
3353
3354 riceLength = setBitOffsetPlus1 + riceParam;
3355 if (riceLength < DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3356 riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength));
3357
3358 bs->consumedBits += riceLength;
3359 bs->cache <<= riceLength;
3360 } else {
3361 drflac_uint32 bitCountLo;
3362 drflac_cache_t resultHi;
3363
3364 bs->consumedBits += riceLength;
3365 bs->cache <<= setBitOffsetPlus1 & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1); /* <-- Equivalent to "if (setBitOffsetPlus1 < DRFLAC_CACHE_L1_SIZE_BITS(bs)) { bs->cache <<= setBitOffsetPlus1; }" */
3366
3367 /* 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. */
3368 bitCountLo = bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs);
3369 resultHi = DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, riceParam); /* <-- Use DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE() if ever this function allows riceParam=0. */
3370
3371 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3372 #ifndef DR_FLAC_NO_CRC
3373 drflac__update_crc16(bs);
3374 #endif
3375 bs->cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3376 bs->consumedBits = 0;
3377 #ifndef DR_FLAC_NO_CRC
3378 bs->crc16Cache = bs->cache;
3379 #endif
3380 } else {
3381 /* Slow path. We need to fetch more data from the client. */
3382 if (!drflac__reload_cache(bs)) {
3383 return DRFLAC_FALSE;
3384 }
3385 if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3386 /* This happens when we get to end of stream */
3387 return DRFLAC_FALSE;
3388 }
3389 }
3390
3391 riceParamPart = (drflac_uint32)(resultHi | DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo));
3392
3393 bs->consumedBits += bitCountLo;
3394 bs->cache <<= bitCountLo;
3395 }
3396
3397 pZeroCounterOut[0] = zeroCounter;
3398 pRiceParamPartOut[0] = riceParamPart;
3399
3400 return DRFLAC_TRUE;
3401 }
3402 #endif
3403
3404 static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts_x1(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
3405 {
3406 drflac_uint32 riceParamPlus1 = riceParam + 1;
3407 /*drflac_cache_t riceParamPlus1Mask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParamPlus1);*/
3408 drflac_uint32 riceParamPlus1Shift = DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPlus1);
3409 drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
3410
3411 /*
3412 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
3413 no idea how this will work in practice...
3414 */
3415 drflac_cache_t bs_cache = bs->cache;
3416 drflac_uint32 bs_consumedBits = bs->consumedBits;
3417
3418 /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */
3419 drflac_uint32 lzcount = drflac__clz(bs_cache);
3420 if (lzcount < sizeof(bs_cache)*8) {
3421 pZeroCounterOut[0] = lzcount;
3422
3423 /*
3424 It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting
3425 this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled
3426 outside of this function at a higher level.
3427 */
3428 extract_rice_param_part:
3429 bs_cache <<= lzcount;
3430 bs_consumedBits += lzcount;
3431
3432 if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
3433 /* Getting here means the rice parameter part is wholly contained within the current cache line. */
3434 pRiceParamPartOut[0] = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
3435 bs_cache <<= riceParamPlus1;
3436 bs_consumedBits += riceParamPlus1;
3437 } else {
3438 drflac_uint32 riceParamPartHi;
3439 drflac_uint32 riceParamPartLo;
3440 drflac_uint32 riceParamPartLoBitCount;
3441
3442 /*
3443 Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache
3444 line, reload the cache, and then combine it with the head of the next cache line.
3445 */
3446
3447 /* Grab the high part of the rice parameter part. */
3448 riceParamPartHi = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
3449
3450 /* Before reloading the cache we need to grab the size in bits of the low part. */
3451 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
3452 DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
3453
3454 /* Now reload the cache. */
3455 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3456 #ifndef DR_FLAC_NO_CRC
3457 drflac__update_crc16(bs);
3458 #endif
3459 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3460 bs_consumedBits = riceParamPartLoBitCount;
3461 #ifndef DR_FLAC_NO_CRC
3462 bs->crc16Cache = bs_cache;
3463 #endif
3464 } else {
3465 /* Slow path. We need to fetch more data from the client. */
3466 if (!drflac__reload_cache(bs)) {
3467 return DRFLAC_FALSE;
3468 }
3469 if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3470 /* This happens when we get to end of stream */
3471 return DRFLAC_FALSE;
3472 }
3473
3474 bs_cache = bs->cache;
3475 bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
3476 }
3477
3478 /* We should now have enough information to construct the rice parameter part. */
3479 riceParamPartLo = (drflac_uint32)(bs_cache >> (DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPartLoBitCount)));
3480 pRiceParamPartOut[0] = riceParamPartHi | riceParamPartLo;
3481
3482 bs_cache <<= riceParamPartLoBitCount;
3483 }
3484 } else {
3485 /*
3486 Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call
3487 to drflac__clz() and we need to reload the cache.
3488 */
3489 drflac_uint32 zeroCounter = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BITS(bs) - bs_consumedBits);
3490 for (;;) {
3491 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3492 #ifndef DR_FLAC_NO_CRC
3493 drflac__update_crc16(bs);
3494 #endif
3495 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3496 bs_consumedBits = 0;
3497 #ifndef DR_FLAC_NO_CRC
3498 bs->crc16Cache = bs_cache;
3499 #endif
3500 } else {
3501 /* Slow path. We need to fetch more data from the client. */
3502 if (!drflac__reload_cache(bs)) {
3503 return DRFLAC_FALSE;
3504 }
3505
3506 bs_cache = bs->cache;
3507 bs_consumedBits = bs->consumedBits;
3508 }
3509
3510 lzcount = drflac__clz(bs_cache);
3511 zeroCounter += lzcount;
3512
3513 if (lzcount < sizeof(bs_cache)*8) {
3514 break;
3515 }
3516 }
3517
3518 pZeroCounterOut[0] = zeroCounter;
3519 goto extract_rice_param_part;
3520 }
3521
3522 /* Make sure the cache is restored at the end of it all. */
3523 bs->cache = bs_cache;
3524 bs->consumedBits = bs_consumedBits;
3525
3526 return DRFLAC_TRUE;
3527 }
3528
3529 static DRFLAC_INLINE drflac_bool32 drflac__seek_rice_parts(drflac_bs* bs, drflac_uint8 riceParam)
3530 {
3531 drflac_uint32 riceParamPlus1 = riceParam + 1;
3532 drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
3533
3534 /*
3535 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
3536 no idea how this will work in practice...
3537 */
3538 drflac_cache_t bs_cache = bs->cache;
3539 drflac_uint32 bs_consumedBits = bs->consumedBits;
3540
3541 /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */
3542 drflac_uint32 lzcount = drflac__clz(bs_cache);
3543 if (lzcount < sizeof(bs_cache)*8) {
3544 /*
3545 It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting
3546 this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled
3547 outside of this function at a higher level.
3548 */
3549 extract_rice_param_part:
3550 bs_cache <<= lzcount;
3551 bs_consumedBits += lzcount;
3552
3553 if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
3554 /* Getting here means the rice parameter part is wholly contained within the current cache line. */
3555 bs_cache <<= riceParamPlus1;
3556 bs_consumedBits += riceParamPlus1;
3557 } else {
3558 /*
3559 Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache
3560 line, reload the cache, and then combine it with the head of the next cache line.
3561 */
3562
3563 /* Before reloading the cache we need to grab the size in bits of the low part. */
3564 drflac_uint32 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
3565 DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
3566
3567 /* Now reload the cache. */
3568 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3569 #ifndef DR_FLAC_NO_CRC
3570 drflac__update_crc16(bs);
3571 #endif
3572 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3573 bs_consumedBits = riceParamPartLoBitCount;
3574 #ifndef DR_FLAC_NO_CRC
3575 bs->crc16Cache = bs_cache;
3576 #endif
3577 } else {
3578 /* Slow path. We need to fetch more data from the client. */
3579 if (!drflac__reload_cache(bs)) {
3580 return DRFLAC_FALSE;
3581 }
3582
3583 if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3584 /* This happens when we get to end of stream */
3585 return DRFLAC_FALSE;
3586 }
3587
3588 bs_cache = bs->cache;
3589 bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
3590 }
3591
3592 bs_cache <<= riceParamPartLoBitCount;
3593 }
3594 } else {
3595 /*
3596 Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call
3597 to drflac__clz() and we need to reload the cache.
3598 */
3599 for (;;) {
3600 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3601 #ifndef DR_FLAC_NO_CRC
3602 drflac__update_crc16(bs);
3603 #endif
3604 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3605 bs_consumedBits = 0;
3606 #ifndef DR_FLAC_NO_CRC
3607 bs->crc16Cache = bs_cache;
3608 #endif
3609 } else {
3610 /* Slow path. We need to fetch more data from the client. */
3611 if (!drflac__reload_cache(bs)) {
3612 return DRFLAC_FALSE;
3613 }
3614
3615 bs_cache = bs->cache;
3616 bs_consumedBits = bs->consumedBits;
3617 }
3618
3619 lzcount = drflac__clz(bs_cache);
3620 if (lzcount < sizeof(bs_cache)*8) {
3621 break;
3622 }
3623 }
3624
3625 goto extract_rice_param_part;
3626 }
3627
3628 /* Make sure the cache is restored at the end of it all. */
3629 bs->cache = bs_cache;
3630 bs->consumedBits = bs_consumedBits;
3631
3632 return DRFLAC_TRUE;
3633 }
3634
3635
3636 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)
3637 {
3638 drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
3639 drflac_uint32 zeroCountPart0;
3640 drflac_uint32 riceParamPart0;
3641 drflac_uint32 riceParamMask;
3642 drflac_uint32 i;
3643
3644 DRFLAC_ASSERT(bs != NULL);
3645 DRFLAC_ASSERT(pSamplesOut != NULL);
3646
3647 (void)bitsPerSample;
3648 (void)order;
3649 (void)shift;
3650 (void)coefficients;
3651
3652 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
3653
3654 i = 0;
3655 while (i < count) {
3656 /* Rice extraction. */
3657 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
3658 return DRFLAC_FALSE;
3659 }
3660
3661 /* Rice reconstruction. */
3662 riceParamPart0 &= riceParamMask;
3663 riceParamPart0 |= (zeroCountPart0 << riceParam);
3664 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3665
3666 pSamplesOut[i] = riceParamPart0;
3667
3668 i += 1;
3669 }
3670
3671 return DRFLAC_TRUE;
3672 }
3673
3674 static drflac_bool32 drflac__decode_samples_with_residual__rice__scalar(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
3675 {
3676 drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
3677 drflac_uint32 zeroCountPart0 = 0;
3678 drflac_uint32 zeroCountPart1 = 0;
3679 drflac_uint32 zeroCountPart2 = 0;
3680 drflac_uint32 zeroCountPart3 = 0;
3681 drflac_uint32 riceParamPart0 = 0;
3682 drflac_uint32 riceParamPart1 = 0;
3683 drflac_uint32 riceParamPart2 = 0;
3684 drflac_uint32 riceParamPart3 = 0;
3685 drflac_uint32 riceParamMask;
3686 const drflac_int32* pSamplesOutEnd;
3687 drflac_uint32 i;
3688
3689 DRFLAC_ASSERT(bs != NULL);
3690 DRFLAC_ASSERT(pSamplesOut != NULL);
3691
3692 if (lpcOrder == 0) {
3693 return drflac__decode_samples_with_residual__rice__scalar_zeroorder(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
3694 }
3695
3696 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
3697 pSamplesOutEnd = pSamplesOut + (count & ~3);
3698
3699 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
3700 while (pSamplesOut < pSamplesOutEnd) {
3701 /*
3702 Rice extraction. It's faster to do this one at a time against local variables than it is to use the x4 version
3703 against an array. Not sure why, but perhaps it's making more efficient use of registers?
3704 */
3705 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
3706 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
3707 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
3708 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
3709 return DRFLAC_FALSE;
3710 }
3711
3712 riceParamPart0 &= riceParamMask;
3713 riceParamPart1 &= riceParamMask;
3714 riceParamPart2 &= riceParamMask;
3715 riceParamPart3 &= riceParamMask;
3716
3717 riceParamPart0 |= (zeroCountPart0 << riceParam);
3718 riceParamPart1 |= (zeroCountPart1 << riceParam);
3719 riceParamPart2 |= (zeroCountPart2 << riceParam);
3720 riceParamPart3 |= (zeroCountPart3 << riceParam);
3721
3722 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3723 riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
3724 riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
3725 riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
3726
3727 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3728 pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
3729 pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
3730 pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
3731
3732 pSamplesOut += 4;
3733 }
3734 } else {
3735 while (pSamplesOut < pSamplesOutEnd) {
3736 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
3737 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
3738 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
3739 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
3740 return DRFLAC_FALSE;
3741 }
3742
3743 riceParamPart0 &= riceParamMask;
3744 riceParamPart1 &= riceParamMask;
3745 riceParamPart2 &= riceParamMask;
3746 riceParamPart3 &= riceParamMask;
3747
3748 riceParamPart0 |= (zeroCountPart0 << riceParam);
3749 riceParamPart1 |= (zeroCountPart1 << riceParam);
3750 riceParamPart2 |= (zeroCountPart2 << riceParam);
3751 riceParamPart3 |= (zeroCountPart3 << riceParam);
3752
3753 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3754 riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
3755 riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
3756 riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
3757
3758 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3759 pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
3760 pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
3761 pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
3762
3763 pSamplesOut += 4;
3764 }
3765 }
3766
3767 i = (count & ~3);
3768 while (i < count) {
3769 /* Rice extraction. */
3770 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
3771 return DRFLAC_FALSE;
3772 }
3773
3774 /* Rice reconstruction. */
3775 riceParamPart0 &= riceParamMask;
3776 riceParamPart0 |= (zeroCountPart0 << riceParam);
3777 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3778 /*riceParamPart0 = (riceParamPart0 >> 1) ^ (~(riceParamPart0 & 0x01) + 1);*/
3779
3780 /* Sample reconstruction. */
3781 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
3782 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3783 } else {
3784 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3785 }
3786
3787 i += 1;
3788 pSamplesOut += 1;
3789 }
3790
3791 return DRFLAC_TRUE;
3792 }
3793
3794 #if defined(DRFLAC_SUPPORT_SSE2)
3795 static DRFLAC_INLINE __m128i drflac__mm_packs_interleaved_epi32(__m128i a, __m128i b)
3796 {
3797 __m128i r;
3798
3799 /* Pack. */
3800 r = _mm_packs_epi32(a, b);
3801
3802 /* a3a2 a1a0 b3b2 b1b0 -> a3a2 b3b2 a1a0 b1b0 */
3803 r = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 1, 2, 0));
3804
3805 /* a3a2 b3b2 a1a0 b1b0 -> a3b3 a2b2 a1b1 a0b0 */
3806 r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
3807 r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
3808
3809 return r;
3810 }
3811 #endif
3812
3813 #if defined(DRFLAC_SUPPORT_SSE41)
3814 static DRFLAC_INLINE __m128i drflac__mm_not_si128(__m128i a)
3815 {
3816 return _mm_xor_si128(a, _mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128()));
3817 }
3818
3819 static DRFLAC_INLINE __m128i drflac__mm_hadd_epi32(__m128i x)
3820 {
3821 __m128i x64 = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
3822 __m128i x32 = _mm_shufflelo_epi16(x64, _MM_SHUFFLE(1, 0, 3, 2));
3823 return _mm_add_epi32(x64, x32);
3824 }
3825
3826 static DRFLAC_INLINE __m128i drflac__mm_hadd_epi64(__m128i x)
3827 {
3828 return _mm_add_epi64(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
3829 }
3830
3831 static DRFLAC_INLINE __m128i drflac__mm_srai_epi64(__m128i x, int count)
3832 {
3833 /*
3834 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
3835 is shifted with zero bits, whereas the right side is shifted with sign bits.
3836 */
3837 __m128i lo = _mm_srli_epi64(x, count);
3838 __m128i hi = _mm_srai_epi32(x, count);
3839
3840 hi = _mm_and_si128(hi, _mm_set_epi32(0xFFFFFFFF, 0, 0xFFFFFFFF, 0)); /* The high part needs to have the low part cleared. */
3841
3842 return _mm_or_si128(lo, hi);
3843 }
3844
3845 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)
3846 {
3847 int i;
3848 drflac_uint32 riceParamMask;
3849 drflac_int32* pDecodedSamples = pSamplesOut;
3850 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
3851 drflac_uint32 zeroCountParts0 = 0;
3852 drflac_uint32 zeroCountParts1 = 0;
3853 drflac_uint32 zeroCountParts2 = 0;
3854 drflac_uint32 zeroCountParts3 = 0;
3855 drflac_uint32 riceParamParts0 = 0;
3856 drflac_uint32 riceParamParts1 = 0;
3857 drflac_uint32 riceParamParts2 = 0;
3858 drflac_uint32 riceParamParts3 = 0;
3859 __m128i coefficients128_0;
3860 __m128i coefficients128_4;
3861 __m128i coefficients128_8;
3862 __m128i samples128_0;
3863 __m128i samples128_4;
3864 __m128i samples128_8;
3865 __m128i riceParamMask128;
3866
3867 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
3868
3869 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
3870 riceParamMask128 = _mm_set1_epi32(riceParamMask);
3871
3872 /* Pre-load. */
3873 coefficients128_0 = _mm_setzero_si128();
3874 coefficients128_4 = _mm_setzero_si128();
3875 coefficients128_8 = _mm_setzero_si128();
3876
3877 samples128_0 = _mm_setzero_si128();
3878 samples128_4 = _mm_setzero_si128();
3879 samples128_8 = _mm_setzero_si128();
3880
3881 /*
3882 Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
3883 what's available in the input buffers. It would be convenient to use a fall-through switch to do this, but this results
3884 in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
3885 so I think there's opportunity for this to be simplified.
3886 */
3887 #if 1
3888 {
3889 int runningOrder = order;
3890
3891 /* 0 - 3. */
3892 if (runningOrder >= 4) {
3893 coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
3894 samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
3895 runningOrder -= 4;
3896 } else {
3897 switch (runningOrder) {
3898 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;
3899 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;
3900 case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
3901 }
3902 runningOrder = 0;
3903 }
3904
3905 /* 4 - 7 */
3906 if (runningOrder >= 4) {
3907 coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
3908 samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
3909 runningOrder -= 4;
3910 } else {
3911 switch (runningOrder) {
3912 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;
3913 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;
3914 case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
3915 }
3916 runningOrder = 0;
3917 }
3918
3919 /* 8 - 11 */
3920 if (runningOrder == 4) {
3921 coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
3922 samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
3923 runningOrder -= 4;
3924 } else {
3925 switch (runningOrder) {
3926 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;
3927 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;
3928 case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
3929 }
3930 runningOrder = 0;
3931 }
3932
3933 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
3934 coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
3935 coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
3936 coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
3937 }
3938 #else
3939 /* This causes strict-aliasing warnings with GCC. */
3940 switch (order)
3941 {
3942 case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
3943 case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
3944 case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
3945 case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
3946 case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
3947 case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
3948 case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
3949 case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
3950 case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
3951 case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
3952 case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
3953 case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
3954 }
3955 #endif
3956
3957 /* For this version we are doing one sample at a time. */
3958 while (pDecodedSamples < pDecodedSamplesEnd) {
3959 __m128i prediction128;
3960 __m128i zeroCountPart128;
3961 __m128i riceParamPart128;
3962
3963 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
3964 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
3965 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
3966 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
3967 return DRFLAC_FALSE;
3968 }
3969
3970 zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
3971 riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
3972
3973 riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
3974 riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
3975 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 */
3976 /*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... */
3977
3978 if (order <= 4) {
3979 for (i = 0; i < 4; i += 1) {
3980 prediction128 = _mm_mullo_epi32(coefficients128_0, samples128_0);
3981
3982 /* Horizontal add and shift. */
3983 prediction128 = drflac__mm_hadd_epi32(prediction128);
3984 prediction128 = _mm_srai_epi32(prediction128, shift);
3985 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
3986
3987 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
3988 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
3989 }
3990 } else if (order <= 8) {
3991 for (i = 0; i < 4; i += 1) {
3992 prediction128 = _mm_mullo_epi32(coefficients128_4, samples128_4);
3993 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
3994
3995 /* Horizontal add and shift. */
3996 prediction128 = drflac__mm_hadd_epi32(prediction128);
3997 prediction128 = _mm_srai_epi32(prediction128, shift);
3998 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
3999
4000 samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
4001 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
4002 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
4003 }
4004 } else {
4005 for (i = 0; i < 4; i += 1) {
4006 prediction128 = _mm_mullo_epi32(coefficients128_8, samples128_8);
4007 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_4, samples128_4));
4008 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
4009
4010 /* Horizontal add and shift. */
4011 prediction128 = drflac__mm_hadd_epi32(prediction128);
4012 prediction128 = _mm_srai_epi32(prediction128, shift);
4013 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
4014
4015 samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
4016 samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
4017 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
4018 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
4019 }
4020 }
4021
4022 /* We store samples in groups of 4. */
4023 _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
4024 pDecodedSamples += 4;
4025 }
4026
4027 /* Make sure we process the last few samples. */
4028 i = (count & ~3);
4029 while (i < (int)count) {
4030 /* Rice extraction. */
4031 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
4032 return DRFLAC_FALSE;
4033 }
4034
4035 /* Rice reconstruction. */
4036 riceParamParts0 &= riceParamMask;
4037 riceParamParts0 |= (zeroCountParts0 << riceParam);
4038 riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
4039
4040 /* Sample reconstruction. */
4041 pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
4042
4043 i += 1;
4044 pDecodedSamples += 1;
4045 }
4046
4047 return DRFLAC_TRUE;
4048 }
4049
4050 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)
4051 {
4052 int i;
4053 drflac_uint32 riceParamMask;
4054 drflac_int32* pDecodedSamples = pSamplesOut;
4055 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
4056 drflac_uint32 zeroCountParts0 = 0;
4057 drflac_uint32 zeroCountParts1 = 0;
4058 drflac_uint32 zeroCountParts2 = 0;
4059 drflac_uint32 zeroCountParts3 = 0;
4060 drflac_uint32 riceParamParts0 = 0;
4061 drflac_uint32 riceParamParts1 = 0;
4062 drflac_uint32 riceParamParts2 = 0;
4063 drflac_uint32 riceParamParts3 = 0;
4064 __m128i coefficients128_0;
4065 __m128i coefficients128_4;
4066 __m128i coefficients128_8;
4067 __m128i samples128_0;
4068 __m128i samples128_4;
4069 __m128i samples128_8;
4070 __m128i prediction128;
4071 __m128i riceParamMask128;
4072
4073 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
4074
4075 DRFLAC_ASSERT(order <= 12);
4076
4077 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
4078 riceParamMask128 = _mm_set1_epi32(riceParamMask);
4079
4080 prediction128 = _mm_setzero_si128();
4081
4082 /* Pre-load. */
4083 coefficients128_0 = _mm_setzero_si128();
4084 coefficients128_4 = _mm_setzero_si128();
4085 coefficients128_8 = _mm_setzero_si128();
4086
4087 samples128_0 = _mm_setzero_si128();
4088 samples128_4 = _mm_setzero_si128();
4089 samples128_8 = _mm_setzero_si128();
4090
4091 #if 1
4092 {
4093 int runningOrder = order;
4094
4095 /* 0 - 3. */
4096 if (runningOrder >= 4) {
4097 coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
4098 samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
4099 runningOrder -= 4;
4100 } else {
4101 switch (runningOrder) {
4102 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;
4103 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;
4104 case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
4105 }
4106 runningOrder = 0;
4107 }
4108
4109 /* 4 - 7 */
4110 if (runningOrder >= 4) {
4111 coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
4112 samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
4113 runningOrder -= 4;
4114 } else {
4115 switch (runningOrder) {
4116 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;
4117 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;
4118 case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
4119 }
4120 runningOrder = 0;
4121 }
4122
4123 /* 8 - 11 */
4124 if (runningOrder == 4) {
4125 coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
4126 samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
4127 runningOrder -= 4;
4128 } else {
4129 switch (runningOrder) {
4130 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;
4131 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;
4132 case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
4133 }
4134 runningOrder = 0;
4135 }
4136
4137 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
4138 coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
4139 coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
4140 coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
4141 }
4142 #else
4143 switch (order)
4144 {
4145 case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
4146 case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
4147 case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
4148 case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
4149 case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
4150 case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
4151 case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
4152 case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
4153 case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
4154 case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
4155 case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
4156 case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
4157 }
4158 #endif
4159
4160 /* For this version we are doing one sample at a time. */
4161 while (pDecodedSamples < pDecodedSamplesEnd) {
4162 __m128i zeroCountPart128;
4163 __m128i riceParamPart128;
4164
4165 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
4166 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
4167 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
4168 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
4169 return DRFLAC_FALSE;
4170 }
4171
4172 zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
4173 riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
4174
4175 riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
4176 riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
4177 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)));
4178
4179 for (i = 0; i < 4; i += 1) {
4180 prediction128 = _mm_xor_si128(prediction128, prediction128); /* Reset to 0. */
4181
4182 switch (order)
4183 {
4184 case 12:
4185 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))));
4186 case 10:
4187 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))));
4188 case 8:
4189 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))));
4190 case 6:
4191 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))));
4192 case 4:
4193 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))));
4194 case 2:
4195 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))));
4196 }
4197
4198 /* Horizontal add and shift. */
4199 prediction128 = drflac__mm_hadd_epi64(prediction128);
4200 prediction128 = drflac__mm_srai_epi64(prediction128, shift);
4201 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
4202
4203 /* Our value should be sitting in prediction128[0]. We need to combine this with our SSE samples. */
4204 samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
4205 samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
4206 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
4207
4208 /* Slide our rice parameter down so that the value in position 0 contains the next one to process. */
4209 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
4210 }
4211
4212 /* We store samples in groups of 4. */
4213 _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
4214 pDecodedSamples += 4;
4215 }
4216
4217 /* Make sure we process the last few samples. */
4218 i = (count & ~3);
4219 while (i < (int)count) {
4220 /* Rice extraction. */
4221 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
4222 return DRFLAC_FALSE;
4223 }
4224
4225 /* Rice reconstruction. */
4226 riceParamParts0 &= riceParamMask;
4227 riceParamParts0 |= (zeroCountParts0 << riceParam);
4228 riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
4229
4230 /* Sample reconstruction. */
4231 pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
4232
4233 i += 1;
4234 pDecodedSamples += 1;
4235 }
4236
4237 return DRFLAC_TRUE;
4238 }
4239
4240 static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
4241 {
4242 DRFLAC_ASSERT(bs != NULL);
4243 DRFLAC_ASSERT(pSamplesOut != NULL);
4244
4245 /* 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. */
4246 if (lpcOrder > 0 && lpcOrder <= 12) {
4247 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
4248 return drflac__decode_samples_with_residual__rice__sse41_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
4249 } else {
4250 return drflac__decode_samples_with_residual__rice__sse41_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
4251 }
4252 } else {
4253 return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4254 }
4255 }
4256 #endif
4257
4258 #if defined(DRFLAC_SUPPORT_NEON)
4259 static DRFLAC_INLINE void drflac__vst2q_s32(drflac_int32* p, int32x4x2_t x)
4260 {
4261 vst1q_s32(p+0, x.val[0]);
4262 vst1q_s32(p+4, x.val[1]);
4263 }
4264
4265 static DRFLAC_INLINE void drflac__vst2q_u32(drflac_uint32* p, uint32x4x2_t x)
4266 {
4267 vst1q_u32(p+0, x.val[0]);
4268 vst1q_u32(p+4, x.val[1]);
4269 }
4270
4271 static DRFLAC_INLINE void drflac__vst2q_f32(float* p, float32x4x2_t x)
4272 {
4273 vst1q_f32(p+0, x.val[0]);
4274 vst1q_f32(p+4, x.val[1]);
4275 }
4276
4277 static DRFLAC_INLINE void drflac__vst2q_s16(drflac_int16* p, int16x4x2_t x)
4278 {
4279 vst1q_s16(p, vcombine_s16(x.val[0], x.val[1]));
4280 }
4281
4282 static DRFLAC_INLINE void drflac__vst2q_u16(drflac_uint16* p, uint16x4x2_t x)
4283 {
4284 vst1q_u16(p, vcombine_u16(x.val[0], x.val[1]));
4285 }
4286
4287 static DRFLAC_INLINE int32x4_t drflac__vdupq_n_s32x4(drflac_int32 x3, drflac_int32 x2, drflac_int32 x1, drflac_int32 x0)
4288 {
4289 drflac_int32 x[4];
4290 x[3] = x3;
4291 x[2] = x2;
4292 x[1] = x1;
4293 x[0] = x0;
4294 return vld1q_s32(x);
4295 }
4296
4297 static DRFLAC_INLINE int32x4_t drflac__valignrq_s32_1(int32x4_t a, int32x4_t b)
4298 {
4299 /* Equivalent to SSE's _mm_alignr_epi8(a, b, 4) */
4300
4301 /* Reference */
4302 /*return drflac__vdupq_n_s32x4(
4303 vgetq_lane_s32(a, 0),
4304 vgetq_lane_s32(b, 3),
4305 vgetq_lane_s32(b, 2),
4306 vgetq_lane_s32(b, 1)
4307 );*/
4308
4309 return vextq_s32(b, a, 1);
4310 }
4311
4312 static DRFLAC_INLINE uint32x4_t drflac__valignrq_u32_1(uint32x4_t a, uint32x4_t b)
4313 {
4314 /* Equivalent to SSE's _mm_alignr_epi8(a, b, 4) */
4315
4316 /* Reference */
4317 /*return drflac__vdupq_n_s32x4(
4318 vgetq_lane_s32(a, 0),
4319 vgetq_lane_s32(b, 3),
4320 vgetq_lane_s32(b, 2),
4321 vgetq_lane_s32(b, 1)
4322 );*/
4323
4324 return vextq_u32(b, a, 1);
4325 }
4326
4327 static DRFLAC_INLINE int32x2_t drflac__vhaddq_s32(int32x4_t x)
4328 {
4329 /* The sum must end up in position 0. */
4330
4331 /* Reference */
4332 /*return vdupq_n_s32(
4333 vgetq_lane_s32(x, 3) +
4334 vgetq_lane_s32(x, 2) +
4335 vgetq_lane_s32(x, 1) +
4336 vgetq_lane_s32(x, 0)
4337 );*/
4338
4339 int32x2_t r = vadd_s32(vget_high_s32(x), vget_low_s32(x));
4340 return vpadd_s32(r, r);
4341 }
4342
4343 static DRFLAC_INLINE int64x1_t drflac__vhaddq_s64(int64x2_t x)
4344 {
4345 return vadd_s64(vget_high_s64(x), vget_low_s64(x));
4346 }
4347
4348 static DRFLAC_INLINE int32x4_t drflac__vrevq_s32(int32x4_t x)
4349 {
4350 /* Reference */
4351 /*return drflac__vdupq_n_s32x4(
4352 vgetq_lane_s32(x, 0),
4353 vgetq_lane_s32(x, 1),
4354 vgetq_lane_s32(x, 2),
4355 vgetq_lane_s32(x, 3)
4356 );*/
4357
4358 return vrev64q_s32(vcombine_s32(vget_high_s32(x), vget_low_s32(x)));
4359 }
4360
4361 static DRFLAC_INLINE int32x4_t drflac__vnotq_s32(int32x4_t x)
4362 {
4363 return veorq_s32(x, vdupq_n_s32(0xFFFFFFFF));
4364 }
4365
4366 static DRFLAC_INLINE uint32x4_t drflac__vnotq_u32(uint32x4_t x)
4367 {
4368 return veorq_u32(x, vdupq_n_u32(0xFFFFFFFF));
4369 }
4370
4371 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)
4372 {
4373 int i;
4374 drflac_uint32 riceParamMask;
4375 drflac_int32* pDecodedSamples = pSamplesOut;
4376 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
4377 drflac_uint32 zeroCountParts[4];
4378 drflac_uint32 riceParamParts[4];
4379 int32x4_t coefficients128_0;
4380 int32x4_t coefficients128_4;
4381 int32x4_t coefficients128_8;
4382 int32x4_t samples128_0;
4383 int32x4_t samples128_4;
4384 int32x4_t samples128_8;
4385 uint32x4_t riceParamMask128;
4386 int32x4_t riceParam128;
4387 int32x2_t shift64;
4388 uint32x4_t one128;
4389
4390 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
4391
4392 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
4393 riceParamMask128 = vdupq_n_u32(riceParamMask);
4394
4395 riceParam128 = vdupq_n_s32(riceParam);
4396 shift64 = vdup_n_s32(-shift); /* Negate the shift because we'll be doing a variable shift using vshlq_s32(). */
4397 one128 = vdupq_n_u32(1);
4398
4399 /*
4400 Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
4401 what's available in the input buffers. It would be conenient to use a fall-through switch to do this, but this results
4402 in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
4403 so I think there's opportunity for this to be simplified.
4404 */
4405 {
4406 int runningOrder = order;
4407 drflac_int32 tempC[4] = {0, 0, 0, 0};
4408 drflac_int32 tempS[4] = {0, 0, 0, 0};
4409
4410 /* 0 - 3. */
4411 if (runningOrder >= 4) {
4412 coefficients128_0 = vld1q_s32(coefficients + 0);
4413 samples128_0 = vld1q_s32(pSamplesOut - 4);
4414 runningOrder -= 4;
4415 } else {
4416 switch (runningOrder) {
4417 case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3]; /* fallthrough */
4418 case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2]; /* fallthrough */
4419 case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1]; /* fallthrough */
4420 }
4421
4422 coefficients128_0 = vld1q_s32(tempC);
4423 samples128_0 = vld1q_s32(tempS);
4424 runningOrder = 0;
4425 }
4426
4427 /* 4 - 7 */
4428 if (runningOrder >= 4) {
4429 coefficients128_4 = vld1q_s32(coefficients + 4);
4430 samples128_4 = vld1q_s32(pSamplesOut - 8);
4431 runningOrder -= 4;
4432 } else {
4433 switch (runningOrder) {
4434 case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7]; /* fallthrough */
4435 case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6]; /* fallthrough */
4436 case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5]; /* fallthrough */
4437 }
4438
4439 coefficients128_4 = vld1q_s32(tempC);
4440 samples128_4 = vld1q_s32(tempS);
4441 runningOrder = 0;
4442 }
4443
4444 /* 8 - 11 */
4445 if (runningOrder == 4) {
4446 coefficients128_8 = vld1q_s32(coefficients + 8);
4447 samples128_8 = vld1q_s32(pSamplesOut - 12);
4448 runningOrder -= 4;
4449 } else {
4450 switch (runningOrder) {
4451 case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11]; /* fallthrough */
4452 case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10]; /* fallthrough */
4453 case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9]; /* fallthrough */
4454 }
4455
4456 coefficients128_8 = vld1q_s32(tempC);
4457 samples128_8 = vld1q_s32(tempS);
4458 runningOrder = 0;
4459 }
4460
4461 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
4462 coefficients128_0 = drflac__vrevq_s32(coefficients128_0);
4463 coefficients128_4 = drflac__vrevq_s32(coefficients128_4);
4464 coefficients128_8 = drflac__vrevq_s32(coefficients128_8);
4465 }
4466
4467 /* For this version we are doing one sample at a time. */
4468 while (pDecodedSamples < pDecodedSamplesEnd) {
4469 int32x4_t prediction128;
4470 int32x2_t prediction64;
4471 uint32x4_t zeroCountPart128;
4472 uint32x4_t riceParamPart128;
4473
4474 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
4475 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
4476 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
4477 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
4478 return DRFLAC_FALSE;
4479 }
4480
4481 zeroCountPart128 = vld1q_u32(zeroCountParts);
4482 riceParamPart128 = vld1q_u32(riceParamParts);
4483
4484 riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
4485 riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
4486 riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
4487
4488 if (order <= 4) {
4489 for (i = 0; i < 4; i += 1) {
4490 prediction128 = vmulq_s32(coefficients128_0, samples128_0);
4491
4492 /* Horizontal add and shift. */
4493 prediction64 = drflac__vhaddq_s32(prediction128);
4494 prediction64 = vshl_s32(prediction64, shift64);
4495 prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
4496
4497 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
4498 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
4499 }
4500 } else if (order <= 8) {
4501 for (i = 0; i < 4; i += 1) {
4502 prediction128 = vmulq_s32(coefficients128_4, samples128_4);
4503 prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
4504
4505 /* Horizontal add and shift. */
4506 prediction64 = drflac__vhaddq_s32(prediction128);
4507 prediction64 = vshl_s32(prediction64, shift64);
4508 prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
4509
4510 samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
4511 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
4512 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
4513 }
4514 } else {
4515 for (i = 0; i < 4; i += 1) {
4516 prediction128 = vmulq_s32(coefficients128_8, samples128_8);
4517 prediction128 = vmlaq_s32(prediction128, coefficients128_4, samples128_4);
4518 prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
4519
4520 /* Horizontal add and shift. */
4521 prediction64 = drflac__vhaddq_s32(prediction128);
4522 prediction64 = vshl_s32(prediction64, shift64);
4523 prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
4524
4525 samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8);
4526 samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
4527 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
4528 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
4529 }
4530 }
4531
4532 /* We store samples in groups of 4. */
4533 vst1q_s32(pDecodedSamples, samples128_0);
4534 pDecodedSamples += 4;
4535 }
4536
4537 /* Make sure we process the last few samples. */
4538 i = (count & ~3);
4539 while (i < (int)count) {
4540 /* Rice extraction. */
4541 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
4542 return DRFLAC_FALSE;
4543 }
4544
4545 /* Rice reconstruction. */
4546 riceParamParts[0] &= riceParamMask;
4547 riceParamParts[0] |= (zeroCountParts[0] << riceParam);
4548 riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
4549
4550 /* Sample reconstruction. */
4551 pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
4552
4553 i += 1;
4554 pDecodedSamples += 1;
4555 }
4556
4557 return DRFLAC_TRUE;
4558 }
4559
4560 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)
4561 {
4562 int i;
4563 drflac_uint32 riceParamMask;
4564 drflac_int32* pDecodedSamples = pSamplesOut;
4565 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
4566 drflac_uint32 zeroCountParts[4];
4567 drflac_uint32 riceParamParts[4];
4568 int32x4_t coefficients128_0;
4569 int32x4_t coefficients128_4;
4570 int32x4_t coefficients128_8;
4571 int32x4_t samples128_0;
4572 int32x4_t samples128_4;
4573 int32x4_t samples128_8;
4574 uint32x4_t riceParamMask128;
4575 int32x4_t riceParam128;
4576 int64x1_t shift64;
4577 uint32x4_t one128;
4578 int64x2_t prediction128 = { 0 };
4579 uint32x4_t zeroCountPart128;
4580 uint32x4_t riceParamPart128;
4581
4582 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
4583
4584 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
4585 riceParamMask128 = vdupq_n_u32(riceParamMask);
4586
4587 riceParam128 = vdupq_n_s32(riceParam);
4588 shift64 = vdup_n_s64(-shift); /* Negate the shift because we'll be doing a variable shift using vshlq_s32(). */
4589 one128 = vdupq_n_u32(1);
4590
4591 /*
4592 Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
4593 what's available in the input buffers. It would be convenient to use a fall-through switch to do this, but this results
4594 in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
4595 so I think there's opportunity for this to be simplified.
4596 */
4597 {
4598 int runningOrder = order;
4599 drflac_int32 tempC[4] = {0, 0, 0, 0};
4600 drflac_int32 tempS[4] = {0, 0, 0, 0};
4601
4602 /* 0 - 3. */
4603 if (runningOrder >= 4) {
4604 coefficients128_0 = vld1q_s32(coefficients + 0);
4605 samples128_0 = vld1q_s32(pSamplesOut - 4);
4606 runningOrder -= 4;
4607 } else {
4608 switch (runningOrder) {
4609 case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3]; /* fallthrough */
4610 case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2]; /* fallthrough */
4611 case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1]; /* fallthrough */
4612 }
4613
4614 coefficients128_0 = vld1q_s32(tempC);
4615 samples128_0 = vld1q_s32(tempS);
4616 runningOrder = 0;
4617 }
4618
4619 /* 4 - 7 */
4620 if (runningOrder >= 4) {
4621 coefficients128_4 = vld1q_s32(coefficients + 4);
4622 samples128_4 = vld1q_s32(pSamplesOut - 8);
4623 runningOrder -= 4;
4624 } else {
4625 switch (runningOrder) {
4626 case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7]; /* fallthrough */
4627 case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6]; /* fallthrough */
4628 case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5]; /* fallthrough */
4629 }
4630
4631 coefficients128_4 = vld1q_s32(tempC);
4632 samples128_4 = vld1q_s32(tempS);
4633 runningOrder = 0;
4634 }
4635
4636 /* 8 - 11 */
4637 if (runningOrder == 4) {
4638 coefficients128_8 = vld1q_s32(coefficients + 8);
4639 samples128_8 = vld1q_s32(pSamplesOut - 12);
4640 runningOrder -= 4;
4641 } else {
4642 switch (runningOrder) {
4643 case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11]; /* fallthrough */
4644 case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10]; /* fallthrough */
4645 case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9]; /* fallthrough */
4646 }
4647
4648 coefficients128_8 = vld1q_s32(tempC);
4649 samples128_8 = vld1q_s32(tempS);
4650 runningOrder = 0;
4651 }
4652
4653 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
4654 coefficients128_0 = drflac__vrevq_s32(coefficients128_0);
4655 coefficients128_4 = drflac__vrevq_s32(coefficients128_4);
4656 coefficients128_8 = drflac__vrevq_s32(coefficients128_8);
4657 }
4658
4659 /* For this version we are doing one sample at a time. */
4660 while (pDecodedSamples < pDecodedSamplesEnd) {
4661 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
4662 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
4663 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
4664 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
4665 return DRFLAC_FALSE;
4666 }
4667
4668 zeroCountPart128 = vld1q_u32(zeroCountParts);
4669 riceParamPart128 = vld1q_u32(riceParamParts);
4670
4671 riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
4672 riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
4673 riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
4674
4675 for (i = 0; i < 4; i += 1) {
4676 int64x1_t prediction64;
4677
4678 prediction128 = veorq_s64(prediction128, prediction128); /* Reset to 0. */
4679 switch (order)
4680 {
4681 case 12:
4682 case 11: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_8), vget_low_s32(samples128_8)));
4683 case 10:
4684 case 9: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_8), vget_high_s32(samples128_8)));
4685 case 8:
4686 case 7: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_4), vget_low_s32(samples128_4)));
4687 case 6:
4688 case 5: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_4), vget_high_s32(samples128_4)));
4689 case 4:
4690 case 3: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_0), vget_low_s32(samples128_0)));
4691 case 2:
4692 case 1: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_0), vget_high_s32(samples128_0)));
4693 }
4694
4695 /* Horizontal add and shift. */
4696 prediction64 = drflac__vhaddq_s64(prediction128);
4697 prediction64 = vshl_s64(prediction64, shift64);
4698 prediction64 = vadd_s64(prediction64, vdup_n_s64(vgetq_lane_u32(riceParamPart128, 0)));
4699
4700 /* Our value should be sitting in prediction64[0]. We need to combine this with our SSE samples. */
4701 samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8);
4702 samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
4703 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(vreinterpret_s32_s64(prediction64), vdup_n_s32(0)), samples128_0);
4704
4705 /* Slide our rice parameter down so that the value in position 0 contains the next one to process. */
4706 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
4707 }
4708
4709 /* We store samples in groups of 4. */
4710 vst1q_s32(pDecodedSamples, samples128_0);
4711 pDecodedSamples += 4;
4712 }
4713
4714 /* Make sure we process the last few samples. */
4715 i = (count & ~3);
4716 while (i < (int)count) {
4717 /* Rice extraction. */
4718 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
4719 return DRFLAC_FALSE;
4720 }
4721
4722 /* Rice reconstruction. */
4723 riceParamParts[0] &= riceParamMask;
4724 riceParamParts[0] |= (zeroCountParts[0] << riceParam);
4725 riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
4726
4727 /* Sample reconstruction. */
4728 pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
4729
4730 i += 1;
4731 pDecodedSamples += 1;
4732 }
4733
4734 return DRFLAC_TRUE;
4735 }
4736
4737 static drflac_bool32 drflac__decode_samples_with_residual__rice__neon(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
4738 {
4739 DRFLAC_ASSERT(bs != NULL);
4740 DRFLAC_ASSERT(pSamplesOut != NULL);
4741
4742 /* 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. */
4743 if (lpcOrder > 0 && lpcOrder <= 12) {
4744 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
4745 return drflac__decode_samples_with_residual__rice__neon_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
4746 } else {
4747 return drflac__decode_samples_with_residual__rice__neon_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
4748 }
4749 } else {
4750 return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4751 }
4752 }
4753 #endif
4754
4755 static drflac_bool32 drflac__decode_samples_with_residual__rice(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
4756 {
4757 #if defined(DRFLAC_SUPPORT_SSE41)
4758 if (drflac__gIsSSE41Supported) {
4759 return drflac__decode_samples_with_residual__rice__sse41(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4760 } else
4761 #elif defined(DRFLAC_SUPPORT_NEON)
4762 if (drflac__gIsNEONSupported) {
4763 return drflac__decode_samples_with_residual__rice__neon(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4764 } else
4765 #endif
4766 {
4767 /* Scalar fallback. */
4768 #if 0
4769 return drflac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4770 #else
4771 return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4772 #endif
4773 }
4774 }
4775
4776 /* 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. */
4777 static drflac_bool32 drflac__read_and_seek_residual__rice(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam)
4778 {
4779 drflac_uint32 i;
4780
4781 DRFLAC_ASSERT(bs != NULL);
4782
4783 for (i = 0; i < count; ++i) {
4784 if (!drflac__seek_rice_parts(bs, riceParam)) {
4785 return DRFLAC_FALSE;
4786 }
4787 }
4788
4789 return DRFLAC_TRUE;
4790 }
4791
4792 #if defined(__clang__)
4793 __attribute__((no_sanitize("signed-integer-overflow")))
4794 #endif
4795 static drflac_bool32 drflac__decode_samples_with_residual__unencoded(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 unencodedBitsPerSample, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
4796 {
4797 drflac_uint32 i;
4798
4799 DRFLAC_ASSERT(bs != NULL);
4800 DRFLAC_ASSERT(unencodedBitsPerSample <= 31); /* <-- unencodedBitsPerSample is a 5 bit number, so cannot exceed 31. */
4801 DRFLAC_ASSERT(pSamplesOut != NULL);
4802
4803 for (i = 0; i < count; ++i) {
4804 if (unencodedBitsPerSample > 0) {
4805 if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i)) {
4806 return DRFLAC_FALSE;
4807 }
4808 } else {
4809 pSamplesOut[i] = 0;
4810 }
4811
4812 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
4813 pSamplesOut[i] += drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
4814 } else {
4815 pSamplesOut[i] += drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
4816 }
4817 }
4818
4819 return DRFLAC_TRUE;
4820 }
4821
4822
4823 /*
4824 Reads and decodes the residual for the sub-frame the decoder is currently sitting on. This function should be called
4825 when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be ignored. The
4826 <blockSize> and <order> parameters are used to determine how many residual values need to be decoded.
4827 */
4828 static drflac_bool32 drflac__decode_samples_with_residual(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 blockSize, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
4829 {
4830 drflac_uint8 residualMethod;
4831 drflac_uint8 partitionOrder;
4832 drflac_uint32 samplesInPartition;
4833 drflac_uint32 partitionsRemaining;
4834
4835 DRFLAC_ASSERT(bs != NULL);
4836 DRFLAC_ASSERT(blockSize != 0);
4837 DRFLAC_ASSERT(pDecodedSamples != NULL); /* <-- Should we allow NULL, in which case we just seek past the residual rather than do a full decode? */
4838
4839 if (!drflac__read_uint8(bs, 2, &residualMethod)) {
4840 return DRFLAC_FALSE;
4841 }
4842
4843 if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
4844 return DRFLAC_FALSE; /* Unknown or unsupported residual coding method. */
4845 }
4846
4847 /* Ignore the first <order> values. */
4848 pDecodedSamples += lpcOrder;
4849
4850 if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
4851 return DRFLAC_FALSE;
4852 }
4853
4854 /*
4855 From the FLAC spec:
4856 The Rice partition order in a Rice-coded residual section must be less than or equal to 8.
4857 */
4858 if (partitionOrder > 8) {
4859 return DRFLAC_FALSE;
4860 }
4861
4862 /* Validation check. */
4863 if ((blockSize / (1 << partitionOrder)) < lpcOrder) {
4864 return DRFLAC_FALSE;
4865 }
4866
4867 samplesInPartition = (blockSize / (1 << partitionOrder)) - lpcOrder;
4868 partitionsRemaining = (1 << partitionOrder);
4869 for (;;) {
4870 drflac_uint8 riceParam = 0;
4871 if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
4872 if (!drflac__read_uint8(bs, 4, &riceParam)) {
4873 return DRFLAC_FALSE;
4874 }
4875 if (riceParam == 15) {
4876 riceParam = 0xFF;
4877 }
4878 } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
4879 if (!drflac__read_uint8(bs, 5, &riceParam)) {
4880 return DRFLAC_FALSE;
4881 }
4882 if (riceParam == 31) {
4883 riceParam = 0xFF;
4884 }
4885 }
4886
4887 if (riceParam != 0xFF) {
4888 if (!drflac__decode_samples_with_residual__rice(bs, bitsPerSample, samplesInPartition, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
4889 return DRFLAC_FALSE;
4890 }
4891 } else {
4892 drflac_uint8 unencodedBitsPerSample = 0;
4893 if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
4894 return DRFLAC_FALSE;
4895 }
4896
4897 if (!drflac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
4898 return DRFLAC_FALSE;
4899 }
4900 }
4901
4902 pDecodedSamples += samplesInPartition;
4903
4904 if (partitionsRemaining == 1) {
4905 break;
4906 }
4907
4908 partitionsRemaining -= 1;
4909
4910 if (partitionOrder != 0) {
4911 samplesInPartition = blockSize / (1 << partitionOrder);
4912 }
4913 }
4914
4915 return DRFLAC_TRUE;
4916 }
4917
4918 /*
4919 Reads and seeks past the residual for the sub-frame the decoder is currently sitting on. This function should be called
4920 when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be set to 0. The
4921 <blockSize> and <order> parameters are used to determine how many residual values need to be decoded.
4922 */
4923 static drflac_bool32 drflac__read_and_seek_residual(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 order)
4924 {
4925 drflac_uint8 residualMethod;
4926 drflac_uint8 partitionOrder;
4927 drflac_uint32 samplesInPartition;
4928 drflac_uint32 partitionsRemaining;
4929
4930 DRFLAC_ASSERT(bs != NULL);
4931 DRFLAC_ASSERT(blockSize != 0);
4932
4933 if (!drflac__read_uint8(bs, 2, &residualMethod)) {
4934 return DRFLAC_FALSE;
4935 }
4936
4937 if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
4938 return DRFLAC_FALSE; /* Unknown or unsupported residual coding method. */
4939 }
4940
4941 if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
4942 return DRFLAC_FALSE;
4943 }
4944
4945 /*
4946 From the FLAC spec:
4947 The Rice partition order in a Rice-coded residual section must be less than or equal to 8.
4948 */
4949 if (partitionOrder > 8) {
4950 return DRFLAC_FALSE;
4951 }
4952
4953 /* Validation check. */
4954 if ((blockSize / (1 << partitionOrder)) <= order) {
4955 return DRFLAC_FALSE;
4956 }
4957
4958 samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
4959 partitionsRemaining = (1 << partitionOrder);
4960 for (;;)
4961 {
4962 drflac_uint8 riceParam = 0;
4963 if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
4964 if (!drflac__read_uint8(bs, 4, &riceParam)) {
4965 return DRFLAC_FALSE;
4966 }
4967 if (riceParam == 15) {
4968 riceParam = 0xFF;
4969 }
4970 } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
4971 if (!drflac__read_uint8(bs, 5, &riceParam)) {
4972 return DRFLAC_FALSE;
4973 }
4974 if (riceParam == 31) {
4975 riceParam = 0xFF;
4976 }
4977 }
4978
4979 if (riceParam != 0xFF) {
4980 if (!drflac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) {
4981 return DRFLAC_FALSE;
4982 }
4983 } else {
4984 drflac_uint8 unencodedBitsPerSample = 0;
4985 if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
4986 return DRFLAC_FALSE;
4987 }
4988
4989 if (!drflac__seek_bits(bs, unencodedBitsPerSample * samplesInPartition)) {
4990 return DRFLAC_FALSE;
4991 }
4992 }
4993
4994
4995 if (partitionsRemaining == 1) {
4996 break;
4997 }
4998
4999 partitionsRemaining -= 1;
5000 samplesInPartition = blockSize / (1 << partitionOrder);
5001 }
5002
5003 return DRFLAC_TRUE;
5004 }
5005
5006
5007 static drflac_bool32 drflac__decode_samples__constant(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
5008 {
5009 drflac_uint32 i;
5010
5011 /* Only a single sample needs to be decoded here. */
5012 drflac_int32 sample;
5013 if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
5014 return DRFLAC_FALSE;
5015 }
5016
5017 /*
5018 We don't really need to expand this, but it does simplify the process of reading samples. If this becomes a performance issue (unlikely)
5019 we'll want to look at a more efficient way.
5020 */
5021 for (i = 0; i < blockSize; ++i) {
5022 pDecodedSamples[i] = sample;
5023 }
5024
5025 return DRFLAC_TRUE;
5026 }
5027
5028 static drflac_bool32 drflac__decode_samples__verbatim(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
5029 {
5030 drflac_uint32 i;
5031
5032 for (i = 0; i < blockSize; ++i) {
5033 drflac_int32 sample;
5034 if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
5035 return DRFLAC_FALSE;
5036 }
5037
5038 pDecodedSamples[i] = sample;
5039 }
5040
5041 return DRFLAC_TRUE;
5042 }
5043
5044 static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
5045 {
5046 drflac_uint32 i;
5047
5048 static drflac_int32 lpcCoefficientsTable[5][4] = {
5049 {0, 0, 0, 0},
5050 {1, 0, 0, 0},
5051 {2, -1, 0, 0},
5052 {3, -3, 1, 0},
5053 {4, -6, 4, -1}
5054 };
5055
5056 /* Warm up samples and coefficients. */
5057 for (i = 0; i < lpcOrder; ++i) {
5058 drflac_int32 sample;
5059 if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
5060 return DRFLAC_FALSE;
5061 }
5062
5063 pDecodedSamples[i] = sample;
5064 }
5065
5066 if (!drflac__decode_samples_with_residual(bs, subframeBitsPerSample, blockSize, lpcOrder, 0, 4, lpcCoefficientsTable[lpcOrder], pDecodedSamples)) {
5067 return DRFLAC_FALSE;
5068 }
5069
5070 return DRFLAC_TRUE;
5071 }
5072
5073 static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
5074 {
5075 drflac_uint8 i;
5076 drflac_uint8 lpcPrecision;
5077 drflac_int8 lpcShift;
5078 drflac_int32 coefficients[32];
5079
5080 /* Warm up samples. */
5081 for (i = 0; i < lpcOrder; ++i) {
5082 drflac_int32 sample;
5083 if (!drflac__read_int32(bs, bitsPerSample, &sample)) {
5084 return DRFLAC_FALSE;
5085 }
5086
5087 pDecodedSamples[i] = sample;
5088 }
5089
5090 if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
5091 return DRFLAC_FALSE;
5092 }
5093 if (lpcPrecision == 15) {
5094 return DRFLAC_FALSE; /* Invalid. */
5095 }
5096 lpcPrecision += 1;
5097
5098 if (!drflac__read_int8(bs, 5, &lpcShift)) {
5099 return DRFLAC_FALSE;
5100 }
5101
5102 /*
5103 From the FLAC specification:
5104
5105 Quantized linear predictor coefficient shift needed in bits (NOTE: this number is signed two's-complement)
5106
5107 Emphasis on the "signed two's-complement". In practice there does not seem to be any encoders nor decoders supporting negative shifts. For now dr_flac is
5108 not going to support negative shifts as I don't have any reference files. However, when a reference file comes through I will consider adding support.
5109 */
5110 if (lpcShift < 0) {
5111 return DRFLAC_FALSE;
5112 }
5113
5114 DRFLAC_ZERO_MEMORY(coefficients, sizeof(coefficients));
5115 for (i = 0; i < lpcOrder; ++i) {
5116 if (!drflac__read_int32(bs, lpcPrecision, coefficients + i)) {
5117 return DRFLAC_FALSE;
5118 }
5119 }
5120
5121 if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
5122 return DRFLAC_FALSE;
5123 }
5124
5125 return DRFLAC_TRUE;
5126 }
5127
5128
5129 static drflac_bool32 drflac__read_next_flac_frame_header(drflac_bs* bs, drflac_uint8 streaminfoBitsPerSample, drflac_frame_header* header)
5130 {
5131 const drflac_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000};
5132 const drflac_uint8 bitsPerSampleTable[8] = {0, 8, 12, (drflac_uint8)-1, 16, 20, 24, (drflac_uint8)-1}; /* -1 = reserved. */
5133
5134 DRFLAC_ASSERT(bs != NULL);
5135 DRFLAC_ASSERT(header != NULL);
5136
5137 /* Keep looping until we find a valid sync code. */
5138 for (;;) {
5139 drflac_uint8 crc8 = 0xCE; /* 0xCE = drflac_crc8(0, 0x3FFE, 14); */
5140 drflac_uint8 reserved = 0;
5141 drflac_uint8 blockingStrategy = 0;
5142 drflac_uint8 blockSize = 0;
5143 drflac_uint8 sampleRate = 0;
5144 drflac_uint8 channelAssignment = 0;
5145 drflac_uint8 bitsPerSample = 0;
5146 drflac_bool32 isVariableBlockSize;
5147
5148 if (!drflac__find_and_seek_to_next_sync_code(bs)) {
5149 return DRFLAC_FALSE;
5150 }
5151
5152 if (!drflac__read_uint8(bs, 1, &reserved)) {
5153 return DRFLAC_FALSE;
5154 }
5155 if (reserved == 1) {
5156 continue;
5157 }
5158 crc8 = drflac_crc8(crc8, reserved, 1);
5159
5160 if (!drflac__read_uint8(bs, 1, &blockingStrategy)) {
5161 return DRFLAC_FALSE;
5162 }
5163 crc8 = drflac_crc8(crc8, blockingStrategy, 1);
5164
5165 if (!drflac__read_uint8(bs, 4, &blockSize)) {
5166 return DRFLAC_FALSE;
5167 }
5168 if (blockSize == 0) {
5169 continue;
5170 }
5171 crc8 = drflac_crc8(crc8, blockSize, 4);
5172
5173 if (!drflac__read_uint8(bs, 4, &sampleRate)) {
5174 return DRFLAC_FALSE;
5175 }
5176 crc8 = drflac_crc8(crc8, sampleRate, 4);
5177
5178 if (!drflac__read_uint8(bs, 4, &channelAssignment)) {
5179 return DRFLAC_FALSE;
5180 }
5181 if (channelAssignment > 10) {
5182 continue;
5183 }
5184 crc8 = drflac_crc8(crc8, channelAssignment, 4);
5185
5186 if (!drflac__read_uint8(bs, 3, &bitsPerSample)) {
5187 return DRFLAC_FALSE;
5188 }
5189 if (bitsPerSample == 3 || bitsPerSample == 7) {
5190 continue;
5191 }
5192 crc8 = drflac_crc8(crc8, bitsPerSample, 3);
5193
5194
5195 if (!drflac__read_uint8(bs, 1, &reserved)) {
5196 return DRFLAC_FALSE;
5197 }
5198 if (reserved == 1) {
5199 continue;
5200 }
5201 crc8 = drflac_crc8(crc8, reserved, 1);
5202
5203
5204 isVariableBlockSize = blockingStrategy == 1;
5205 if (isVariableBlockSize) {
5206 drflac_uint64 pcmFrameNumber;
5207 drflac_result result = drflac__read_utf8_coded_number(bs, &pcmFrameNumber, &crc8);
5208 if (result != DRFLAC_SUCCESS) {
5209 if (result == DRFLAC_AT_END) {
5210 return DRFLAC_FALSE;
5211 } else {
5212 continue;
5213 }
5214 }
5215 header->flacFrameNumber = 0;
5216 header->pcmFrameNumber = pcmFrameNumber;
5217 } else {
5218 drflac_uint64 flacFrameNumber = 0;
5219 drflac_result result = drflac__read_utf8_coded_number(bs, &flacFrameNumber, &crc8);
5220 if (result != DRFLAC_SUCCESS) {
5221 if (result == DRFLAC_AT_END) {
5222 return DRFLAC_FALSE;
5223 } else {
5224 continue;
5225 }
5226 }
5227 header->flacFrameNumber = (drflac_uint32)flacFrameNumber; /* <-- Safe cast. */
5228 header->pcmFrameNumber = 0;
5229 }
5230
5231
5232 DRFLAC_ASSERT(blockSize > 0);
5233 if (blockSize == 1) {
5234 header->blockSizeInPCMFrames = 192;
5235 } else if (blockSize <= 5) {
5236 DRFLAC_ASSERT(blockSize >= 2);
5237 header->blockSizeInPCMFrames = 576 * (1 << (blockSize - 2));
5238 } else if (blockSize == 6) {
5239 if (!drflac__read_uint16(bs, 8, &header->blockSizeInPCMFrames)) {
5240 return DRFLAC_FALSE;
5241 }
5242 crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 8);
5243 header->blockSizeInPCMFrames += 1;
5244 } else if (blockSize == 7) {
5245 if (!drflac__read_uint16(bs, 16, &header->blockSizeInPCMFrames)) {
5246 return DRFLAC_FALSE;
5247 }
5248 crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 16);
5249 if (header->blockSizeInPCMFrames == 0xFFFF) {
5250 return DRFLAC_FALSE; /* Frame is too big. This is the size of the frame minus 1. The STREAMINFO block defines the max block size which is 16-bits. Adding one will make it 17 bits and therefore too big. */
5251 }
5252 header->blockSizeInPCMFrames += 1;
5253 } else {
5254 DRFLAC_ASSERT(blockSize >= 8);
5255 header->blockSizeInPCMFrames = 256 * (1 << (blockSize - 8));
5256 }
5257
5258
5259 if (sampleRate <= 11) {
5260 header->sampleRate = sampleRateTable[sampleRate];
5261 } else if (sampleRate == 12) {
5262 if (!drflac__read_uint32(bs, 8, &header->sampleRate)) {
5263 return DRFLAC_FALSE;
5264 }
5265 crc8 = drflac_crc8(crc8, header->sampleRate, 8);
5266 header->sampleRate *= 1000;
5267 } else if (sampleRate == 13) {
5268 if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
5269 return DRFLAC_FALSE;
5270 }
5271 crc8 = drflac_crc8(crc8, header->sampleRate, 16);
5272 } else if (sampleRate == 14) {
5273 if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
5274 return DRFLAC_FALSE;
5275 }
5276 crc8 = drflac_crc8(crc8, header->sampleRate, 16);
5277 header->sampleRate *= 10;
5278 } else {
5279 continue; /* Invalid. Assume an invalid block. */
5280 }
5281
5282
5283 header->channelAssignment = channelAssignment;
5284
5285 header->bitsPerSample = bitsPerSampleTable[bitsPerSample];
5286 if (header->bitsPerSample == 0) {
5287 header->bitsPerSample = streaminfoBitsPerSample;
5288 }
5289
5290 if (header->bitsPerSample != streaminfoBitsPerSample) {
5291 /* If this subframe has a different bitsPerSample then streaminfo or the first frame, reject it */
5292 return DRFLAC_FALSE;
5293 }
5294
5295 if (!drflac__read_uint8(bs, 8, &header->crc8)) {
5296 return DRFLAC_FALSE;
5297 }
5298
5299 #ifndef DR_FLAC_NO_CRC
5300 if (header->crc8 != crc8) {
5301 continue; /* CRC mismatch. Loop back to the top and find the next sync code. */
5302 }
5303 #endif
5304 return DRFLAC_TRUE;
5305 }
5306 }
5307
5308 static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe* pSubframe)
5309 {
5310 drflac_uint8 header;
5311 int type;
5312
5313 if (!drflac__read_uint8(bs, 8, &header)) {
5314 return DRFLAC_FALSE;
5315 }
5316
5317 /* First bit should always be 0. */
5318 if ((header & 0x80) != 0) {
5319 return DRFLAC_FALSE;
5320 }
5321
5322 /*
5323 Default to 0 for the LPC order. It's important that we always set this to 0 for non LPC
5324 and FIXED subframes because we'll be using it in a generic validation check later.
5325 */
5326 pSubframe->lpcOrder = 0;
5327
5328 type = (header & 0x7E) >> 1;
5329 if (type == 0) {
5330 pSubframe->subframeType = DRFLAC_SUBFRAME_CONSTANT;
5331 } else if (type == 1) {
5332 pSubframe->subframeType = DRFLAC_SUBFRAME_VERBATIM;
5333 } else {
5334 if ((type & 0x20) != 0) {
5335 pSubframe->subframeType = DRFLAC_SUBFRAME_LPC;
5336 pSubframe->lpcOrder = (drflac_uint8)(type & 0x1F) + 1;
5337 } else if ((type & 0x08) != 0) {
5338 pSubframe->subframeType = DRFLAC_SUBFRAME_FIXED;
5339 pSubframe->lpcOrder = (drflac_uint8)(type & 0x07);
5340 if (pSubframe->lpcOrder > 4) {
5341 pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
5342 pSubframe->lpcOrder = 0;
5343 }
5344 } else {
5345 pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
5346 }
5347 }
5348
5349 if (pSubframe->subframeType == DRFLAC_SUBFRAME_RESERVED) {
5350 return DRFLAC_FALSE;
5351 }
5352
5353 /* Wasted bits per sample. */
5354 pSubframe->wastedBitsPerSample = 0;
5355 if ((header & 0x01) == 1) {
5356 unsigned int wastedBitsPerSample;
5357 if (!drflac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) {
5358 return DRFLAC_FALSE;
5359 }
5360 pSubframe->wastedBitsPerSample = (drflac_uint8)wastedBitsPerSample + 1;
5361 }
5362
5363 return DRFLAC_TRUE;
5364 }
5365
5366 static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex, drflac_int32* pDecodedSamplesOut)
5367 {
5368 drflac_subframe* pSubframe;
5369 drflac_uint32 subframeBitsPerSample;
5370
5371 DRFLAC_ASSERT(bs != NULL);
5372 DRFLAC_ASSERT(frame != NULL);
5373
5374 pSubframe = frame->subframes + subframeIndex;
5375 if (!drflac__read_subframe_header(bs, pSubframe)) {
5376 return DRFLAC_FALSE;
5377 }
5378
5379 /* Side channels require an extra bit per sample. Took a while to figure that one out... */
5380 subframeBitsPerSample = frame->header.bitsPerSample;
5381 if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
5382 subframeBitsPerSample += 1;
5383 } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
5384 subframeBitsPerSample += 1;
5385 }
5386
5387 if (subframeBitsPerSample > 32) {
5388 /* libFLAC and ffmpeg reject 33-bit subframes as well */
5389 return DRFLAC_FALSE;
5390 }
5391
5392 /* Need to handle wasted bits per sample. */
5393 if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
5394 return DRFLAC_FALSE;
5395 }
5396 subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
5397
5398 pSubframe->pSamplesS32 = pDecodedSamplesOut;
5399
5400 /*
5401 pDecodedSamplesOut will be pointing to a buffer that was allocated with enough memory to store
5402 maxBlockSizeInPCMFrames samples (as specified in the FLAC header). We need to guard against an
5403 overflow here. At a higher level we are checking maxBlockSizeInPCMFrames from the header, but
5404 here we need to do an additional check to ensure this frame's block size fully encompasses any
5405 warmup samples which is determined by the LPC order. For non LPC and FIXED subframes, the LPC
5406 order will be have been set to 0 in drflac__read_subframe_header().
5407 */
5408 if (frame->header.blockSizeInPCMFrames < pSubframe->lpcOrder) {
5409 return DRFLAC_FALSE;
5410 }
5411
5412 switch (pSubframe->subframeType)
5413 {
5414 case DRFLAC_SUBFRAME_CONSTANT:
5415 {
5416 drflac__decode_samples__constant(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
5417 } break;
5418
5419 case DRFLAC_SUBFRAME_VERBATIM:
5420 {
5421 drflac__decode_samples__verbatim(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
5422 } break;
5423
5424 case DRFLAC_SUBFRAME_FIXED:
5425 {
5426 drflac__decode_samples__fixed(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
5427 } break;
5428
5429 case DRFLAC_SUBFRAME_LPC:
5430 {
5431 drflac__decode_samples__lpc(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
5432 } break;
5433
5434 default: return DRFLAC_FALSE;
5435 }
5436
5437 return DRFLAC_TRUE;
5438 }
5439
5440 static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex)
5441 {
5442 drflac_subframe* pSubframe;
5443 drflac_uint32 subframeBitsPerSample;
5444
5445 DRFLAC_ASSERT(bs != NULL);
5446 DRFLAC_ASSERT(frame != NULL);
5447
5448 pSubframe = frame->subframes + subframeIndex;
5449 if (!drflac__read_subframe_header(bs, pSubframe)) {
5450 return DRFLAC_FALSE;
5451 }
5452
5453 /* Side channels require an extra bit per sample. Took a while to figure that one out... */
5454 subframeBitsPerSample = frame->header.bitsPerSample;
5455 if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
5456 subframeBitsPerSample += 1;
5457 } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
5458 subframeBitsPerSample += 1;
5459 }
5460
5461 /* Need to handle wasted bits per sample. */
5462 if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
5463 return DRFLAC_FALSE;
5464 }
5465 subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
5466
5467 pSubframe->pSamplesS32 = NULL;
5468
5469 switch (pSubframe->subframeType)
5470 {
5471 case DRFLAC_SUBFRAME_CONSTANT:
5472 {
5473 if (!drflac__seek_bits(bs, subframeBitsPerSample)) {
5474 return DRFLAC_FALSE;
5475 }
5476 } break;
5477
5478 case DRFLAC_SUBFRAME_VERBATIM:
5479 {
5480 unsigned int bitsToSeek = frame->header.blockSizeInPCMFrames * subframeBitsPerSample;
5481 if (!drflac__seek_bits(bs, bitsToSeek)) {
5482 return DRFLAC_FALSE;
5483 }
5484 } break;
5485
5486 case DRFLAC_SUBFRAME_FIXED:
5487 {
5488 unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
5489 if (!drflac__seek_bits(bs, bitsToSeek)) {
5490 return DRFLAC_FALSE;
5491 }
5492
5493 if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
5494 return DRFLAC_FALSE;
5495 }
5496 } break;
5497
5498 case DRFLAC_SUBFRAME_LPC:
5499 {
5500 drflac_uint8 lpcPrecision;
5501
5502 unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
5503 if (!drflac__seek_bits(bs, bitsToSeek)) {
5504 return DRFLAC_FALSE;
5505 }
5506
5507 if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
5508 return DRFLAC_FALSE;
5509 }
5510 if (lpcPrecision == 15) {
5511 return DRFLAC_FALSE; /* Invalid. */
5512 }
5513 lpcPrecision += 1;
5514
5515
5516 bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5; /* +5 for shift. */
5517 if (!drflac__seek_bits(bs, bitsToSeek)) {
5518 return DRFLAC_FALSE;
5519 }
5520
5521 if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
5522 return DRFLAC_FALSE;
5523 }
5524 } break;
5525
5526 default: return DRFLAC_FALSE;
5527 }
5528
5529 return DRFLAC_TRUE;
5530 }
5531
5532
5533 static DRFLAC_INLINE drflac_uint8 drflac__get_channel_count_from_channel_assignment(drflac_int8 channelAssignment)
5534 {
5535 drflac_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2};
5536
5537 DRFLAC_ASSERT(channelAssignment <= 10);
5538 return lookup[channelAssignment];
5539 }
5540
5541 static drflac_result drflac__decode_flac_frame(drflac* pFlac)
5542 {
5543 int channelCount;
5544 int i;
5545 drflac_uint8 paddingSizeInBits;
5546 drflac_uint16 desiredCRC16;
5547 #ifndef DR_FLAC_NO_CRC
5548 drflac_uint16 actualCRC16;
5549 #endif
5550
5551 /* This function should be called while the stream is sitting on the first byte after the frame header. */
5552 DRFLAC_ZERO_MEMORY(pFlac->currentFLACFrame.subframes, sizeof(pFlac->currentFLACFrame.subframes));
5553
5554 /* The frame block size must never be larger than the maximum block size defined by the FLAC stream. */
5555 if (pFlac->currentFLACFrame.header.blockSizeInPCMFrames > pFlac->maxBlockSizeInPCMFrames) {
5556 return DRFLAC_ERROR;
5557 }
5558
5559 /* The number of channels in the frame must match the channel count from the STREAMINFO block. */
5560 channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
5561 if (channelCount != (int)pFlac->channels) {
5562 return DRFLAC_ERROR;
5563 }
5564
5565 for (i = 0; i < channelCount; ++i) {
5566 if (!drflac__decode_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i, pFlac->pDecodedSamples + (pFlac->currentFLACFrame.header.blockSizeInPCMFrames * i))) {
5567 return DRFLAC_ERROR;
5568 }
5569 }
5570
5571 paddingSizeInBits = (drflac_uint8)(DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7);
5572 if (paddingSizeInBits > 0) {
5573 drflac_uint8 padding = 0;
5574 if (!drflac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding)) {
5575 return DRFLAC_AT_END;
5576 }
5577 }
5578
5579 #ifndef DR_FLAC_NO_CRC
5580 actualCRC16 = drflac__flush_crc16(&pFlac->bs);
5581 #endif
5582 if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
5583 return DRFLAC_AT_END;
5584 }
5585
5586 #ifndef DR_FLAC_NO_CRC
5587 if (actualCRC16 != desiredCRC16) {
5588 return DRFLAC_CRC_MISMATCH; /* CRC mismatch. */
5589 }
5590 #endif
5591
5592 pFlac->currentFLACFrame.pcmFramesRemaining = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
5593
5594 return DRFLAC_SUCCESS;
5595 }
5596
5597 static drflac_result drflac__seek_flac_frame(drflac* pFlac)
5598 {
5599 int channelCount;
5600 int i;
5601 drflac_uint16 desiredCRC16;
5602 #ifndef DR_FLAC_NO_CRC
5603 drflac_uint16 actualCRC16;
5604 #endif
5605
5606 channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
5607 for (i = 0; i < channelCount; ++i) {
5608 if (!drflac__seek_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i)) {
5609 return DRFLAC_ERROR;
5610 }
5611 }
5612
5613 /* Padding. */
5614 if (!drflac__seek_bits(&pFlac->bs, DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7)) {
5615 return DRFLAC_ERROR;
5616 }
5617
5618 /* CRC. */
5619 #ifndef DR_FLAC_NO_CRC
5620 actualCRC16 = drflac__flush_crc16(&pFlac->bs);
5621 #endif
5622 if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
5623 return DRFLAC_AT_END;
5624 }
5625
5626 #ifndef DR_FLAC_NO_CRC
5627 if (actualCRC16 != desiredCRC16) {
5628 return DRFLAC_CRC_MISMATCH; /* CRC mismatch. */
5629 }
5630 #endif
5631
5632 return DRFLAC_SUCCESS;
5633 }
5634
5635 static drflac_bool32 drflac__read_and_decode_next_flac_frame(drflac* pFlac)
5636 {
5637 DRFLAC_ASSERT(pFlac != NULL);
5638
5639 for (;;) {
5640 drflac_result result;
5641
5642 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5643 return DRFLAC_FALSE;
5644 }
5645
5646 result = drflac__decode_flac_frame(pFlac);
5647 if (result != DRFLAC_SUCCESS) {
5648 if (result == DRFLAC_CRC_MISMATCH) {
5649 continue; /* CRC mismatch. Skip to the next frame. */
5650 } else {
5651 return DRFLAC_FALSE;
5652 }
5653 }
5654
5655 return DRFLAC_TRUE;
5656 }
5657 }
5658
5659 static void drflac__get_pcm_frame_range_of_current_flac_frame(drflac* pFlac, drflac_uint64* pFirstPCMFrame, drflac_uint64* pLastPCMFrame)
5660 {
5661 drflac_uint64 firstPCMFrame;
5662 drflac_uint64 lastPCMFrame;
5663
5664 DRFLAC_ASSERT(pFlac != NULL);
5665
5666 firstPCMFrame = pFlac->currentFLACFrame.header.pcmFrameNumber;
5667 if (firstPCMFrame == 0) {
5668 firstPCMFrame = ((drflac_uint64)pFlac->currentFLACFrame.header.flacFrameNumber) * pFlac->maxBlockSizeInPCMFrames;
5669 }
5670
5671 lastPCMFrame = firstPCMFrame + pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
5672 if (lastPCMFrame > 0) {
5673 lastPCMFrame -= 1; /* Needs to be zero based. */
5674 }
5675
5676 if (pFirstPCMFrame) {
5677 *pFirstPCMFrame = firstPCMFrame;
5678 }
5679 if (pLastPCMFrame) {
5680 *pLastPCMFrame = lastPCMFrame;
5681 }
5682 }
5683
5684 static drflac_bool32 drflac__seek_to_first_frame(drflac* pFlac)
5685 {
5686 drflac_bool32 result;
5687
5688 DRFLAC_ASSERT(pFlac != NULL);
5689
5690 result = drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes);
5691
5692 DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
5693 pFlac->currentPCMFrame = 0;
5694
5695 return result;
5696 }
5697
5698 static DRFLAC_INLINE drflac_result drflac__seek_to_next_flac_frame(drflac* pFlac)
5699 {
5700 /* This function should only ever be called while the decoder is sitting on the first byte past the FRAME_HEADER section. */
5701 DRFLAC_ASSERT(pFlac != NULL);
5702 return drflac__seek_flac_frame(pFlac);
5703 }
5704
5705
5706 static drflac_uint64 drflac__seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 pcmFramesToSeek)
5707 {
5708 drflac_uint64 pcmFramesRead = 0;
5709 while (pcmFramesToSeek > 0) {
5710 if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
5711 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
5712 break; /* Couldn't read the next frame, so just break from the loop and return. */
5713 }
5714 } else {
5715 if (pFlac->currentFLACFrame.pcmFramesRemaining > pcmFramesToSeek) {
5716 pcmFramesRead += pcmFramesToSeek;
5717 pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)pcmFramesToSeek; /* <-- Safe cast. Will always be < currentFrame.pcmFramesRemaining < 65536. */
5718 pcmFramesToSeek = 0;
5719 } else {
5720 pcmFramesRead += pFlac->currentFLACFrame.pcmFramesRemaining;
5721 pcmFramesToSeek -= pFlac->currentFLACFrame.pcmFramesRemaining;
5722 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
5723 }
5724 }
5725 }
5726
5727 pFlac->currentPCMFrame += pcmFramesRead;
5728 return pcmFramesRead;
5729 }
5730
5731
5732 static drflac_bool32 drflac__seek_to_pcm_frame__brute_force(drflac* pFlac, drflac_uint64 pcmFrameIndex)
5733 {
5734 drflac_bool32 isMidFrame = DRFLAC_FALSE;
5735 drflac_uint64 runningPCMFrameCount;
5736
5737 DRFLAC_ASSERT(pFlac != NULL);
5738
5739 /* 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. */
5740 if (pcmFrameIndex >= pFlac->currentPCMFrame) {
5741 /* Seeking forward. Need to seek from the current position. */
5742 runningPCMFrameCount = pFlac->currentPCMFrame;
5743
5744 /* The frame header for the first frame may not yet have been read. We need to do that if necessary. */
5745 if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
5746 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5747 return DRFLAC_FALSE;
5748 }
5749 } else {
5750 isMidFrame = DRFLAC_TRUE;
5751 }
5752 } else {
5753 /* Seeking backwards. Need to seek from the start of the file. */
5754 runningPCMFrameCount = 0;
5755
5756 /* Move back to the start. */
5757 if (!drflac__seek_to_first_frame(pFlac)) {
5758 return DRFLAC_FALSE;
5759 }
5760
5761 /* Decode the first frame in preparation for sample-exact seeking below. */
5762 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5763 return DRFLAC_FALSE;
5764 }
5765 }
5766
5767 /*
5768 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
5769 header. If based on the header we can determine that the frame contains the sample, we do a full decode of that frame.
5770 */
5771 for (;;) {
5772 drflac_uint64 pcmFrameCountInThisFLACFrame;
5773 drflac_uint64 firstPCMFrameInFLACFrame = 0;
5774 drflac_uint64 lastPCMFrameInFLACFrame = 0;
5775
5776 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
5777
5778 pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
5779 if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
5780 /*
5781 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
5782 it never existed and keep iterating.
5783 */
5784 drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
5785
5786 if (!isMidFrame) {
5787 drflac_result result = drflac__decode_flac_frame(pFlac);
5788 if (result == DRFLAC_SUCCESS) {
5789 /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
5790 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */
5791 } else {
5792 if (result == DRFLAC_CRC_MISMATCH) {
5793 goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */
5794 } else {
5795 return DRFLAC_FALSE;
5796 }
5797 }
5798 } else {
5799 /* We started seeking mid-frame which means we need to skip the frame decoding part. */
5800 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
5801 }
5802 } else {
5803 /*
5804 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
5805 frame never existed and leave the running sample count untouched.
5806 */
5807 if (!isMidFrame) {
5808 drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
5809 if (result == DRFLAC_SUCCESS) {
5810 runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
5811 } else {
5812 if (result == DRFLAC_CRC_MISMATCH) {
5813 goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */
5814 } else {
5815 return DRFLAC_FALSE;
5816 }
5817 }
5818 } else {
5819 /*
5820 We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with
5821 drflac__seek_to_next_flac_frame() which only works if the decoder is sitting on the byte just after the frame header.
5822 */
5823 runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
5824 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
5825 isMidFrame = DRFLAC_FALSE;
5826 }
5827
5828 /* If we are seeking to the end of the file and we've just hit it, we're done. */
5829 if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
5830 return DRFLAC_TRUE;
5831 }
5832 }
5833
5834 next_iteration:
5835 /* Grab the next frame in preparation for the next iteration. */
5836 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5837 return DRFLAC_FALSE;
5838 }
5839 }
5840 }
5841
5842
5843 #if !defined(DR_FLAC_NO_CRC)
5844 /*
5845 We use an average compression ratio to determine our approximate start location. FLAC files are generally about 50%-70% the size of their
5846 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
5847 location.
5848 */
5849 #define DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO 0.6f
5850
5851 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)
5852 {
5853 DRFLAC_ASSERT(pFlac != NULL);
5854 DRFLAC_ASSERT(pLastSuccessfulSeekOffset != NULL);
5855 DRFLAC_ASSERT(targetByte >= rangeLo);
5856 DRFLAC_ASSERT(targetByte <= rangeHi);
5857
5858 *pLastSuccessfulSeekOffset = pFlac->firstFLACFramePosInBytes;
5859
5860 for (;;) {
5861 /* After rangeLo == rangeHi == targetByte fails, we need to break out. */
5862 drflac_uint64 lastTargetByte = targetByte;
5863
5864 /* 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. */
5865 if (!drflac__seek_to_byte(&pFlac->bs, targetByte)) {
5866 /* If we couldn't even seek to the first byte in the stream we have a problem. Just abandon the whole thing. */
5867 if (targetByte == 0) {
5868 drflac__seek_to_first_frame(pFlac); /* Try to recover. */
5869 return DRFLAC_FALSE;
5870 }
5871
5872 /* Halve the byte location and continue. */
5873 targetByte = rangeLo + ((rangeHi - rangeLo)/2);
5874 rangeHi = targetByte;
5875 } else {
5876 /* Getting here should mean that we have seeked to an appropriate byte. */
5877
5878 /* Clear the details of the FLAC frame so we don't misreport data. */
5879 DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
5880
5881 /*
5882 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
5883 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
5884 so it needs to stay this way for now.
5885 */
5886 #if 1
5887 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
5888 /* Halve the byte location and continue. */
5889 targetByte = rangeLo + ((rangeHi - rangeLo)/2);
5890 rangeHi = targetByte;
5891 } else {
5892 break;
5893 }
5894 #else
5895 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5896 /* Halve the byte location and continue. */
5897 targetByte = rangeLo + ((rangeHi - rangeLo)/2);
5898 rangeHi = targetByte;
5899 } else {
5900 break;
5901 }
5902 #endif
5903 }
5904
5905 /* We already tried this byte and there are no more to try, break out. */
5906 if(targetByte == lastTargetByte) {
5907 return DRFLAC_FALSE;
5908 }
5909 }
5910
5911 /* The current PCM frame needs to be updated based on the frame we just seeked to. */
5912 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
5913
5914 DRFLAC_ASSERT(targetByte <= rangeHi);
5915
5916 *pLastSuccessfulSeekOffset = targetByte;
5917 return DRFLAC_TRUE;
5918 }
5919
5920 static drflac_bool32 drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 offset)
5921 {
5922 /* 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(). */
5923 #if 0
5924 if (drflac__decode_flac_frame(pFlac) != DRFLAC_SUCCESS) {
5925 /* We failed to decode this frame which may be due to it being corrupt. We'll just use the next valid FLAC frame. */
5926 if (drflac__read_and_decode_next_flac_frame(pFlac) == DRFLAC_FALSE) {
5927 return DRFLAC_FALSE;
5928 }
5929 }
5930 #endif
5931
5932 return drflac__seek_forward_by_pcm_frames(pFlac, offset) == offset;
5933 }
5934
5935
5936 static drflac_bool32 drflac__seek_to_pcm_frame__binary_search_internal(drflac* pFlac, drflac_uint64 pcmFrameIndex, drflac_uint64 byteRangeLo, drflac_uint64 byteRangeHi)
5937 {
5938 /* This assumes pFlac->currentPCMFrame is sitting on byteRangeLo upon entry. */
5939
5940 drflac_uint64 targetByte;
5941 drflac_uint64 pcmRangeLo = pFlac->totalPCMFrameCount;
5942 drflac_uint64 pcmRangeHi = 0;
5943 drflac_uint64 lastSuccessfulSeekOffset = (drflac_uint64)-1;
5944 drflac_uint64 closestSeekOffsetBeforeTargetPCMFrame = byteRangeLo;
5945 drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
5946
5947 targetByte = byteRangeLo + (drflac_uint64)(((drflac_int64)((pcmFrameIndex - pFlac->currentPCMFrame) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO);
5948 if (targetByte > byteRangeHi) {
5949 targetByte = byteRangeHi;
5950 }
5951
5952 for (;;) {
5953 if (drflac__seek_to_approximate_flac_frame_to_byte(pFlac, targetByte, byteRangeLo, byteRangeHi, &lastSuccessfulSeekOffset)) {
5954 /* We found a FLAC frame. We need to check if it contains the sample we're looking for. */
5955 drflac_uint64 newPCMRangeLo;
5956 drflac_uint64 newPCMRangeHi;
5957 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &newPCMRangeLo, &newPCMRangeHi);
5958
5959 /* If we selected the same frame, it means we should be pretty close. Just decode the rest. */
5960 if (pcmRangeLo == newPCMRangeLo) {
5961 if (!drflac__seek_to_approximate_flac_frame_to_byte(pFlac, closestSeekOffsetBeforeTargetPCMFrame, closestSeekOffsetBeforeTargetPCMFrame, byteRangeHi, &lastSuccessfulSeekOffset)) {
5962 break; /* Failed to seek to closest frame. */
5963 }
5964
5965 if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
5966 return DRFLAC_TRUE;
5967 } else {
5968 break; /* Failed to seek forward. */
5969 }
5970 }
5971
5972 pcmRangeLo = newPCMRangeLo;
5973 pcmRangeHi = newPCMRangeHi;
5974
5975 if (pcmRangeLo <= pcmFrameIndex && pcmRangeHi >= pcmFrameIndex) {
5976 /* The target PCM frame is in this FLAC frame. */
5977 if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame) ) {
5978 return DRFLAC_TRUE;
5979 } else {
5980 break; /* Failed to seek to FLAC frame. */
5981 }
5982 } else {
5983 const float approxCompressionRatio = (drflac_int64)(lastSuccessfulSeekOffset - pFlac->firstFLACFramePosInBytes) / ((drflac_int64)(pcmRangeLo * pFlac->channels * pFlac->bitsPerSample)/8.0f);
5984
5985 if (pcmRangeLo > pcmFrameIndex) {
5986 /* We seeked too far forward. We need to move our target byte backward and try again. */
5987 byteRangeHi = lastSuccessfulSeekOffset;
5988 if (byteRangeLo > byteRangeHi) {
5989 byteRangeLo = byteRangeHi;
5990 }
5991
5992 targetByte = byteRangeLo + ((byteRangeHi - byteRangeLo) / 2);
5993 if (targetByte < byteRangeLo) {
5994 targetByte = byteRangeLo;
5995 }
5996 } else /*if (pcmRangeHi < pcmFrameIndex)*/ {
5997 /* We didn't seek far enough. We need to move our target byte forward and try again. */
5998
5999 /* If we're close enough we can just seek forward. */
6000 if ((pcmFrameIndex - pcmRangeLo) < seekForwardThreshold) {
6001 if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
6002 return DRFLAC_TRUE;
6003 } else {
6004 break; /* Failed to seek to FLAC frame. */
6005 }
6006 } else {
6007 byteRangeLo = lastSuccessfulSeekOffset;
6008 if (byteRangeHi < byteRangeLo) {
6009 byteRangeHi = byteRangeLo;
6010 }
6011
6012 targetByte = lastSuccessfulSeekOffset + (drflac_uint64)(((drflac_int64)((pcmFrameIndex-pcmRangeLo) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * approxCompressionRatio);
6013 if (targetByte > byteRangeHi) {
6014 targetByte = byteRangeHi;
6015 }
6016
6017 if (closestSeekOffsetBeforeTargetPCMFrame < lastSuccessfulSeekOffset) {
6018 closestSeekOffsetBeforeTargetPCMFrame = lastSuccessfulSeekOffset;
6019 }
6020 }
6021 }
6022 }
6023 } else {
6024 /* Getting here is really bad. We just recover as best we can, but moving to the first frame in the stream, and then abort. */
6025 break;
6026 }
6027 }
6028
6029 drflac__seek_to_first_frame(pFlac); /* <-- Try to recover. */
6030 return DRFLAC_FALSE;
6031 }
6032
6033 static drflac_bool32 drflac__seek_to_pcm_frame__binary_search(drflac* pFlac, drflac_uint64 pcmFrameIndex)
6034 {
6035 drflac_uint64 byteRangeLo;
6036 drflac_uint64 byteRangeHi;
6037 drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
6038
6039 /* Our algorithm currently assumes the FLAC stream is currently sitting at the start. */
6040 if (drflac__seek_to_first_frame(pFlac) == DRFLAC_FALSE) {
6041 return DRFLAC_FALSE;
6042 }
6043
6044 /* If we're close enough to the start, just move to the start and seek forward. */
6045 if (pcmFrameIndex < seekForwardThreshold) {
6046 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFrameIndex) == pcmFrameIndex;
6047 }
6048
6049 /*
6050 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
6051 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.
6052 */
6053 byteRangeLo = pFlac->firstFLACFramePosInBytes;
6054 byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
6055
6056 return drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi);
6057 }
6058 #endif /* !DR_FLAC_NO_CRC */
6059
6060 static drflac_bool32 drflac__seek_to_pcm_frame__seek_table(drflac* pFlac, drflac_uint64 pcmFrameIndex)
6061 {
6062 drflac_uint32 iClosestSeekpoint = 0;
6063 drflac_bool32 isMidFrame = DRFLAC_FALSE;
6064 drflac_uint64 runningPCMFrameCount;
6065 drflac_uint32 iSeekpoint;
6066
6067
6068 DRFLAC_ASSERT(pFlac != NULL);
6069
6070 if (pFlac->pSeekpoints == NULL || pFlac->seekpointCount == 0) {
6071 return DRFLAC_FALSE;
6072 }
6073
6074 /* Do not use the seektable if pcmFramIndex is not coverd by it. */
6075 if (pFlac->pSeekpoints[0].firstPCMFrame > pcmFrameIndex) {
6076 return DRFLAC_FALSE;
6077 }
6078
6079 for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
6080 if (pFlac->pSeekpoints[iSeekpoint].firstPCMFrame >= pcmFrameIndex) {
6081 break;
6082 }
6083
6084 iClosestSeekpoint = iSeekpoint;
6085 }
6086
6087 /* There's been cases where the seek table contains only zeros. We need to do some basic validation on the closest seekpoint. */
6088 if (pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount == 0 || pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount > pFlac->maxBlockSizeInPCMFrames) {
6089 return DRFLAC_FALSE;
6090 }
6091 if (pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame > pFlac->totalPCMFrameCount && pFlac->totalPCMFrameCount > 0) {
6092 return DRFLAC_FALSE;
6093 }
6094
6095 #if !defined(DR_FLAC_NO_CRC)
6096 /* 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. */
6097 if (pFlac->totalPCMFrameCount > 0) {
6098 drflac_uint64 byteRangeLo;
6099 drflac_uint64 byteRangeHi;
6100
6101 byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
6102 byteRangeLo = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset;
6103
6104 /*
6105 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
6106 value for byteRangeHi which will clamp it appropriately.
6107
6108 Note that the next seekpoint must have an offset greater than the closest seekpoint because otherwise our binary search algorithm will break down. There
6109 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.
6110 */
6111 if (iClosestSeekpoint < pFlac->seekpointCount-1) {
6112 drflac_uint32 iNextSeekpoint = iClosestSeekpoint + 1;
6113
6114 /* Basic validation on the seekpoints to ensure they're usable. */
6115 if (pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset >= pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset || pFlac->pSeekpoints[iNextSeekpoint].pcmFrameCount == 0) {
6116 return DRFLAC_FALSE; /* The next seekpoint doesn't look right. The seek table cannot be trusted from here. Abort. */
6117 }
6118
6119 if (pFlac->pSeekpoints[iNextSeekpoint].firstPCMFrame != (((drflac_uint64)0xFFFFFFFF << 32) | 0xFFFFFFFF)) { /* Make sure it's not a placeholder seekpoint. */
6120 byteRangeHi = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset - 1; /* byteRangeHi must be zero based. */
6121 }
6122 }
6123
6124 if (drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
6125 if (drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
6126 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
6127
6128 if (drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi)) {
6129 return DRFLAC_TRUE;
6130 }
6131 }
6132 }
6133 }
6134 #endif /* !DR_FLAC_NO_CRC */
6135
6136 /* Getting here means we need to use a slower algorithm because the binary search method failed or cannot be used. */
6137
6138 /*
6139 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
6140 from the seekpoint's first sample.
6141 */
6142 if (pcmFrameIndex >= pFlac->currentPCMFrame && pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame <= pFlac->currentPCMFrame) {
6143 /* Optimized case. Just seek forward from where we are. */
6144 runningPCMFrameCount = pFlac->currentPCMFrame;
6145
6146 /* The frame header for the first frame may not yet have been read. We need to do that if necessary. */
6147 if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
6148 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
6149 return DRFLAC_FALSE;
6150 }
6151 } else {
6152 isMidFrame = DRFLAC_TRUE;
6153 }
6154 } else {
6155 /* Slower case. Seek to the start of the seekpoint and then seek forward from there. */
6156 runningPCMFrameCount = pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame;
6157
6158 if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
6159 return DRFLAC_FALSE;
6160 }
6161
6162 /* Grab the frame the seekpoint is sitting on in preparation for the sample-exact seeking below. */
6163 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
6164 return DRFLAC_FALSE;
6165 }
6166 }
6167
6168 for (;;) {
6169 drflac_uint64 pcmFrameCountInThisFLACFrame;
6170 drflac_uint64 firstPCMFrameInFLACFrame = 0;
6171 drflac_uint64 lastPCMFrameInFLACFrame = 0;
6172
6173 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
6174
6175 pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
6176 if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
6177 /*
6178 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
6179 it never existed and keep iterating.
6180 */
6181 drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
6182
6183 if (!isMidFrame) {
6184 drflac_result result = drflac__decode_flac_frame(pFlac);
6185 if (result == DRFLAC_SUCCESS) {
6186 /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
6187 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */
6188 } else {
6189 if (result == DRFLAC_CRC_MISMATCH) {
6190 goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */
6191 } else {
6192 return DRFLAC_FALSE;
6193 }
6194 }
6195 } else {
6196 /* We started seeking mid-frame which means we need to skip the frame decoding part. */
6197 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
6198 }
6199 } else {
6200 /*
6201 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
6202 frame never existed and leave the running sample count untouched.
6203 */
6204 if (!isMidFrame) {
6205 drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
6206 if (result == DRFLAC_SUCCESS) {
6207 runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
6208 } else {
6209 if (result == DRFLAC_CRC_MISMATCH) {
6210 goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */
6211 } else {
6212 return DRFLAC_FALSE;
6213 }
6214 }
6215 } else {
6216 /*
6217 We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with
6218 drflac__seek_to_next_flac_frame() which only works if the decoder is sitting on the byte just after the frame header.
6219 */
6220 runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
6221 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
6222 isMidFrame = DRFLAC_FALSE;
6223 }
6224
6225 /* If we are seeking to the end of the file and we've just hit it, we're done. */
6226 if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
6227 return DRFLAC_TRUE;
6228 }
6229 }
6230
6231 next_iteration:
6232 /* Grab the next frame in preparation for the next iteration. */
6233 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
6234 return DRFLAC_FALSE;
6235 }
6236 }
6237 }
6238
6239
6240 #ifndef DR_FLAC_NO_OGG
6241 typedef struct
6242 {
6243 drflac_uint8 capturePattern[4]; /* Should be "OggS" */
6244 drflac_uint8 structureVersion; /* Always 0. */
6245 drflac_uint8 headerType;
6246 drflac_uint64 granulePosition;
6247 drflac_uint32 serialNumber;
6248 drflac_uint32 sequenceNumber;
6249 drflac_uint32 checksum;
6250 drflac_uint8 segmentCount;
6251 drflac_uint8 segmentTable[255];
6252 } drflac_ogg_page_header;
6253 #endif
6254
6255 typedef struct
6256 {
6257 drflac_read_proc onRead;
6258 drflac_seek_proc onSeek;
6259 drflac_tell_proc onTell;
6260 drflac_meta_proc onMeta;
6261 drflac_container container;
6262 void* pUserData;
6263 void* pUserDataMD;
6264 drflac_uint32 sampleRate;
6265 drflac_uint8 channels;
6266 drflac_uint8 bitsPerSample;
6267 drflac_uint64 totalPCMFrameCount;
6268 drflac_uint16 maxBlockSizeInPCMFrames;
6269 drflac_uint64 runningFilePos;
6270 drflac_bool32 hasStreamInfoBlock;
6271 drflac_bool32 hasMetadataBlocks;
6272 drflac_bs bs; /* <-- A bit streamer is required for loading data during initialization. */
6273 drflac_frame_header firstFrameHeader; /* <-- The header of the first frame that was read during relaxed initalization. Only set if there is no STREAMINFO block. */
6274
6275 #ifndef DR_FLAC_NO_OGG
6276 drflac_uint32 oggSerial;
6277 drflac_uint64 oggFirstBytePos;
6278 drflac_ogg_page_header oggBosHeader;
6279 #endif
6280 } drflac_init_info;
6281
6282 static DRFLAC_INLINE void drflac__decode_block_header(drflac_uint32 blockHeader, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
6283 {
6284 blockHeader = drflac__be2host_32(blockHeader);
6285 *isLastBlock = (drflac_uint8)((blockHeader & 0x80000000UL) >> 31);
6286 *blockType = (drflac_uint8)((blockHeader & 0x7F000000UL) >> 24);
6287 *blockSize = (blockHeader & 0x00FFFFFFUL);
6288 }
6289
6290 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)
6291 {
6292 drflac_uint32 blockHeader;
6293
6294 *blockSize = 0;
6295 if (onRead(pUserData, &blockHeader, 4) != 4) {
6296 return DRFLAC_FALSE;
6297 }
6298
6299 drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize);
6300 return DRFLAC_TRUE;
6301 }
6302
6303 static drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, drflac_streaminfo* pStreamInfo)
6304 {
6305 drflac_uint32 blockSizes;
6306 drflac_uint64 frameSizes = 0;
6307 drflac_uint64 importantProps;
6308 drflac_uint8 md5[16];
6309
6310 /* min/max block size. */
6311 if (onRead(pUserData, &blockSizes, 4) != 4) {
6312 return DRFLAC_FALSE;
6313 }
6314
6315 /* min/max frame size. */
6316 if (onRead(pUserData, &frameSizes, 6) != 6) {
6317 return DRFLAC_FALSE;
6318 }
6319
6320 /* Sample rate, channels, bits per sample and total sample count. */
6321 if (onRead(pUserData, &importantProps, 8) != 8) {
6322 return DRFLAC_FALSE;
6323 }
6324
6325 /* MD5 */
6326 if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5)) {
6327 return DRFLAC_FALSE;
6328 }
6329
6330 blockSizes = drflac__be2host_32(blockSizes);
6331 frameSizes = drflac__be2host_64(frameSizes);
6332 importantProps = drflac__be2host_64(importantProps);
6333
6334 pStreamInfo->minBlockSizeInPCMFrames = (drflac_uint16)((blockSizes & 0xFFFF0000) >> 16);
6335 pStreamInfo->maxBlockSizeInPCMFrames = (drflac_uint16) (blockSizes & 0x0000FFFF);
6336 pStreamInfo->minFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 24)) >> 40);
6337 pStreamInfo->maxFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 0)) >> 16);
6338 pStreamInfo->sampleRate = (drflac_uint32)((importantProps & (((drflac_uint64)0x000FFFFF << 16) << 28)) >> 44);
6339 pStreamInfo->channels = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000000E << 16) << 24)) >> 41) + 1;
6340 pStreamInfo->bitsPerSample = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000001F << 16) << 20)) >> 36) + 1;
6341 pStreamInfo->totalPCMFrameCount = ((importantProps & ((((drflac_uint64)0x0000000F << 16) << 16) | 0xFFFFFFFF)));
6342 DRFLAC_COPY_MEMORY(pStreamInfo->md5, md5, sizeof(md5));
6343
6344 return DRFLAC_TRUE;
6345 }
6346
6347
6348 static void* drflac__malloc_default(size_t sz, void* pUserData)
6349 {
6350 (void)pUserData;
6351 return DRFLAC_MALLOC(sz);
6352 }
6353
6354 static void* drflac__realloc_default(void* p, size_t sz, void* pUserData)
6355 {
6356 (void)pUserData;
6357 return DRFLAC_REALLOC(p, sz);
6358 }
6359
6360 static void drflac__free_default(void* p, void* pUserData)
6361 {
6362 (void)pUserData;
6363 DRFLAC_FREE(p);
6364 }
6365
6366
6367 static void* drflac__malloc_from_callbacks(size_t sz, const drflac_allocation_callbacks* pAllocationCallbacks)
6368 {
6369 if (pAllocationCallbacks == NULL) {
6370 return NULL;
6371 }
6372
6373 if (pAllocationCallbacks->onMalloc != NULL) {
6374 return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
6375 }
6376
6377 /* Try using realloc(). */
6378 if (pAllocationCallbacks->onRealloc != NULL) {
6379 return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
6380 }
6381
6382 return NULL;
6383 }
6384
6385 static void* drflac__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drflac_allocation_callbacks* pAllocationCallbacks)
6386 {
6387 if (pAllocationCallbacks == NULL) {
6388 return NULL;
6389 }
6390
6391 if (pAllocationCallbacks->onRealloc != NULL) {
6392 return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
6393 }
6394
6395 /* Try emulating realloc() in terms of malloc()/free(). */
6396 if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
6397 void* p2;
6398
6399 p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
6400 if (p2 == NULL) {
6401 return NULL;
6402 }
6403
6404 if (p != NULL) {
6405 DRFLAC_COPY_MEMORY(p2, p, szOld);
6406 pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
6407 }
6408
6409 return p2;
6410 }
6411
6412 return NULL;
6413 }
6414
6415 static void drflac__free_from_callbacks(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
6416 {
6417 if (p == NULL || pAllocationCallbacks == NULL) {
6418 return;
6419 }
6420
6421 if (pAllocationCallbacks->onFree != NULL) {
6422 pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
6423 }
6424 }
6425
6426
6427 static drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_uint64* pFirstFramePos, drflac_uint64* pSeektablePos, drflac_uint32* pSeekpointCount, drflac_allocation_callbacks* pAllocationCallbacks)
6428 {
6429 /*
6430 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
6431 we'll be sitting on byte 42.
6432 */
6433 drflac_uint64 runningFilePos = 42;
6434 drflac_uint64 seektablePos = 0;
6435 drflac_uint32 seektableSize = 0;
6436
6437 (void)onTell;
6438
6439 for (;;) {
6440 drflac_metadata metadata;
6441 drflac_uint8 isLastBlock = 0;
6442 drflac_uint8 blockType = 0;
6443 drflac_uint32 blockSize;
6444 if (drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize) == DRFLAC_FALSE) {
6445 return DRFLAC_FALSE;
6446 }
6447 runningFilePos += 4;
6448
6449 metadata.type = blockType;
6450 metadata.rawDataSize = 0;
6451 metadata.rawDataOffset = runningFilePos;
6452 metadata.pRawData = NULL;
6453
6454 switch (blockType)
6455 {
6456 case DRFLAC_METADATA_BLOCK_TYPE_APPLICATION:
6457 {
6458 if (blockSize < 4) {
6459 return DRFLAC_FALSE;
6460 }
6461
6462 if (onMeta) {
6463 void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6464 if (pRawData == NULL) {
6465 return DRFLAC_FALSE;
6466 }
6467
6468 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6469 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6470 return DRFLAC_FALSE;
6471 }
6472
6473 metadata.pRawData = pRawData;
6474 metadata.rawDataSize = blockSize;
6475 metadata.data.application.id = drflac__be2host_32(*(drflac_uint32*)pRawData);
6476 metadata.data.application.pData = (const void*)((drflac_uint8*)pRawData + sizeof(drflac_uint32));
6477 metadata.data.application.dataSize = blockSize - sizeof(drflac_uint32);
6478 onMeta(pUserDataMD, &metadata);
6479
6480 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6481 }
6482 } break;
6483
6484 case DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE:
6485 {
6486 seektablePos = runningFilePos;
6487 seektableSize = blockSize;
6488
6489 if (onMeta) {
6490 drflac_uint32 seekpointCount;
6491 drflac_uint32 iSeekpoint;
6492 void* pRawData;
6493
6494 seekpointCount = blockSize/DRFLAC_SEEKPOINT_SIZE_IN_BYTES;
6495
6496 pRawData = drflac__malloc_from_callbacks(seekpointCount * sizeof(drflac_seekpoint), pAllocationCallbacks);
6497 if (pRawData == NULL) {
6498 return DRFLAC_FALSE;
6499 }
6500
6501 /* We need to read seekpoint by seekpoint and do some processing. */
6502 for (iSeekpoint = 0; iSeekpoint < seekpointCount; ++iSeekpoint) {
6503 drflac_seekpoint* pSeekpoint = (drflac_seekpoint*)pRawData + iSeekpoint;
6504
6505 if (onRead(pUserData, pSeekpoint, DRFLAC_SEEKPOINT_SIZE_IN_BYTES) != DRFLAC_SEEKPOINT_SIZE_IN_BYTES) {
6506 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6507 return DRFLAC_FALSE;
6508 }
6509
6510 /* Endian swap. */
6511 pSeekpoint->firstPCMFrame = drflac__be2host_64(pSeekpoint->firstPCMFrame);
6512 pSeekpoint->flacFrameOffset = drflac__be2host_64(pSeekpoint->flacFrameOffset);
6513 pSeekpoint->pcmFrameCount = drflac__be2host_16(pSeekpoint->pcmFrameCount);
6514 }
6515
6516 metadata.pRawData = pRawData;
6517 metadata.rawDataSize = blockSize;
6518 metadata.data.seektable.seekpointCount = seekpointCount;
6519 metadata.data.seektable.pSeekpoints = (const drflac_seekpoint*)pRawData;
6520
6521 onMeta(pUserDataMD, &metadata);
6522
6523 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6524 }
6525 } break;
6526
6527 case DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT:
6528 {
6529 if (blockSize < 8) {
6530 return DRFLAC_FALSE;
6531 }
6532
6533 if (onMeta) {
6534 void* pRawData;
6535 const char* pRunningData;
6536 const char* pRunningDataEnd;
6537 drflac_uint32 i;
6538
6539 pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6540 if (pRawData == NULL) {
6541 return DRFLAC_FALSE;
6542 }
6543
6544 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6545 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6546 return DRFLAC_FALSE;
6547 }
6548
6549 metadata.pRawData = pRawData;
6550 metadata.rawDataSize = blockSize;
6551
6552 pRunningData = (const char*)pRawData;
6553 pRunningDataEnd = (const char*)pRawData + blockSize;
6554
6555 metadata.data.vorbis_comment.vendorLength = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6556
6557 /* Need space for the rest of the block */
6558 if ((pRunningDataEnd - pRunningData) - 4 < (drflac_int64)metadata.data.vorbis_comment.vendorLength) { /* <-- Note the order of operations to avoid overflow to a valid value */
6559 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6560 return DRFLAC_FALSE;
6561 }
6562 metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength;
6563 metadata.data.vorbis_comment.commentCount = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6564
6565 /* Need space for 'commentCount' comments after the block, which at minimum is a drflac_uint32 per comment */
6566 if ((pRunningDataEnd - pRunningData) / sizeof(drflac_uint32) < metadata.data.vorbis_comment.commentCount) { /* <-- Note the order of operations to avoid overflow to a valid value */
6567 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6568 return DRFLAC_FALSE;
6569 }
6570 metadata.data.vorbis_comment.pComments = pRunningData;
6571
6572 /* Check that the comments section is valid before passing it to the callback */
6573 for (i = 0; i < metadata.data.vorbis_comment.commentCount; ++i) {
6574 drflac_uint32 commentLength;
6575
6576 if (pRunningDataEnd - pRunningData < 4) {
6577 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6578 return DRFLAC_FALSE;
6579 }
6580
6581 commentLength = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6582 if (pRunningDataEnd - pRunningData < (drflac_int64)commentLength) { /* <-- Note the order of operations to avoid overflow to a valid value */
6583 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6584 return DRFLAC_FALSE;
6585 }
6586 pRunningData += commentLength;
6587 }
6588
6589 onMeta(pUserDataMD, &metadata);
6590
6591 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6592 }
6593 } break;
6594
6595 case DRFLAC_METADATA_BLOCK_TYPE_CUESHEET:
6596 {
6597 if (blockSize < 396) {
6598 return DRFLAC_FALSE;
6599 }
6600
6601 if (onMeta) {
6602 void* pRawData;
6603 const char* pRunningData;
6604 const char* pRunningDataEnd;
6605 size_t bufferSize;
6606 drflac_uint8 iTrack;
6607 drflac_uint8 iIndex;
6608 void* pTrackData;
6609
6610 /*
6611 This needs to be loaded in two passes. The first pass is used to calculate the size of the memory allocation
6612 we need for storing the necessary data. The second pass will fill that buffer with usable data.
6613 */
6614 pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6615 if (pRawData == NULL) {
6616 return DRFLAC_FALSE;
6617 }
6618
6619 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6620 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6621 return DRFLAC_FALSE;
6622 }
6623
6624 metadata.pRawData = pRawData;
6625 metadata.rawDataSize = blockSize;
6626
6627 pRunningData = (const char*)pRawData;
6628 pRunningDataEnd = (const char*)pRawData + blockSize;
6629
6630 DRFLAC_COPY_MEMORY(metadata.data.cuesheet.catalog, pRunningData, 128); pRunningData += 128;
6631 metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*(const drflac_uint64*)pRunningData); pRunningData += 8;
6632 metadata.data.cuesheet.isCD = (pRunningData[0] & 0x80) != 0; pRunningData += 259;
6633 metadata.data.cuesheet.trackCount = pRunningData[0]; pRunningData += 1;
6634 metadata.data.cuesheet.pTrackData = NULL; /* Will be filled later. */
6635
6636 /* Pass 1: Calculate the size of the buffer for the track data. */
6637 {
6638 const char* pRunningDataSaved = pRunningData; /* Will be restored at the end in preparation for the second pass. */
6639
6640 bufferSize = metadata.data.cuesheet.trackCount * DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES;
6641
6642 for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) {
6643 drflac_uint8 indexCount;
6644 drflac_uint32 indexPointSize;
6645
6646 if (pRunningDataEnd - pRunningData < DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES) {
6647 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6648 return DRFLAC_FALSE;
6649 }
6650
6651 /* Skip to the index point count */
6652 pRunningData += 35;
6653
6654 indexCount = pRunningData[0];
6655 pRunningData += 1;
6656
6657 bufferSize += indexCount * sizeof(drflac_cuesheet_track_index);
6658
6659 /* Quick validation check. */
6660 indexPointSize = indexCount * DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES;
6661 if (pRunningDataEnd - pRunningData < (drflac_int64)indexPointSize) {
6662 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6663 return DRFLAC_FALSE;
6664 }
6665
6666 pRunningData += indexPointSize;
6667 }
6668
6669 pRunningData = pRunningDataSaved;
6670 }
6671
6672 /* Pass 2: Allocate a buffer and fill the data. Validation was done in the step above so can be skipped. */
6673 {
6674 char* pRunningTrackData;
6675
6676 pTrackData = drflac__malloc_from_callbacks(bufferSize, pAllocationCallbacks);
6677 if (pTrackData == NULL) {
6678 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6679 return DRFLAC_FALSE;
6680 }
6681
6682 pRunningTrackData = (char*)pTrackData;
6683
6684 for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) {
6685 drflac_uint8 indexCount;
6686
6687 DRFLAC_COPY_MEMORY(pRunningTrackData, pRunningData, DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES);
6688 pRunningData += DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1; /* Skip forward, but not beyond the last byte in the CUESHEET_TRACK block which is the index count. */
6689 pRunningTrackData += DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1;
6690
6691 /* Grab the index count for the next part. */
6692 indexCount = pRunningData[0];
6693 pRunningData += 1;
6694 pRunningTrackData += 1;
6695
6696 /* Extract each track index. */
6697 for (iIndex = 0; iIndex < indexCount; ++iIndex) {
6698 drflac_cuesheet_track_index* pTrackIndex = (drflac_cuesheet_track_index*)pRunningTrackData;
6699
6700 DRFLAC_COPY_MEMORY(pRunningTrackData, pRunningData, DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES);
6701 pRunningData += DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES;
6702 pRunningTrackData += sizeof(drflac_cuesheet_track_index);
6703
6704 pTrackIndex->offset = drflac__be2host_64(pTrackIndex->offset);
6705 }
6706 }
6707
6708 metadata.data.cuesheet.pTrackData = pTrackData;
6709 }
6710
6711 /* The original data is no longer needed. */
6712 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6713 pRawData = NULL;
6714
6715 onMeta(pUserDataMD, &metadata);
6716
6717 drflac__free_from_callbacks(pTrackData, pAllocationCallbacks);
6718 pTrackData = NULL;
6719 }
6720 } break;
6721
6722 case DRFLAC_METADATA_BLOCK_TYPE_PICTURE:
6723 {
6724 if (blockSize < 32) {
6725 return DRFLAC_FALSE;
6726 }
6727
6728 if (onMeta) {
6729 drflac_bool32 result = DRFLAC_TRUE;
6730 drflac_uint32 blockSizeRemaining = blockSize;
6731 char* pMime = NULL;
6732 char* pDescription = NULL;
6733 void* pPictureData = NULL;
6734
6735 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.type, 4) != 4) {
6736 result = DRFLAC_FALSE;
6737 goto done_flac;
6738 }
6739 blockSizeRemaining -= 4;
6740 metadata.data.picture.type = drflac__be2host_32(metadata.data.picture.type);
6741
6742
6743 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.mimeLength, 4) != 4) {
6744 result = DRFLAC_FALSE;
6745 goto done_flac;
6746 }
6747 blockSizeRemaining -= 4;
6748 metadata.data.picture.mimeLength = drflac__be2host_32(metadata.data.picture.mimeLength);
6749
6750 pMime = (char*)drflac__malloc_from_callbacks(metadata.data.picture.mimeLength + 1, pAllocationCallbacks); /* +1 for null terminator. */
6751 if (pMime == NULL) {
6752 result = DRFLAC_FALSE;
6753 goto done_flac;
6754 }
6755
6756 if (blockSizeRemaining < metadata.data.picture.mimeLength || onRead(pUserData, pMime, metadata.data.picture.mimeLength) != metadata.data.picture.mimeLength) {
6757 result = DRFLAC_FALSE;
6758 goto done_flac;
6759 }
6760 blockSizeRemaining -= metadata.data.picture.mimeLength;
6761 pMime[metadata.data.picture.mimeLength] = '\0'; /* Null terminate for safety. */
6762 metadata.data.picture.mime = (const char*)pMime;
6763
6764
6765 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.descriptionLength, 4) != 4) {
6766 result = DRFLAC_FALSE;
6767 goto done_flac;
6768 }
6769 blockSizeRemaining -= 4;
6770 metadata.data.picture.descriptionLength = drflac__be2host_32(metadata.data.picture.descriptionLength);
6771
6772 pDescription = (char*)drflac__malloc_from_callbacks(metadata.data.picture.descriptionLength + 1, pAllocationCallbacks); /* +1 for null terminator. */
6773 if (pDescription == NULL) {
6774 result = DRFLAC_FALSE;
6775 goto done_flac;
6776 }
6777
6778 if (blockSizeRemaining < metadata.data.picture.descriptionLength || onRead(pUserData, pDescription, metadata.data.picture.descriptionLength) != metadata.data.picture.descriptionLength) {
6779 result = DRFLAC_FALSE;
6780 goto done_flac;
6781 }
6782 blockSizeRemaining -= metadata.data.picture.descriptionLength;
6783 pDescription[metadata.data.picture.descriptionLength] = '\0'; /* Null terminate for safety. */
6784 metadata.data.picture.description = (const char*)pDescription;
6785
6786
6787 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.width, 4) != 4) {
6788 result = DRFLAC_FALSE;
6789 goto done_flac;
6790 }
6791 blockSizeRemaining -= 4;
6792 metadata.data.picture.width = drflac__be2host_32(metadata.data.picture.width);
6793
6794 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.height, 4) != 4) {
6795 result = DRFLAC_FALSE;
6796 goto done_flac;
6797 }
6798 blockSizeRemaining -= 4;
6799 metadata.data.picture.height = drflac__be2host_32(metadata.data.picture.height);
6800
6801 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.colorDepth, 4) != 4) {
6802 result = DRFLAC_FALSE;
6803 goto done_flac;
6804 }
6805 blockSizeRemaining -= 4;
6806 metadata.data.picture.colorDepth = drflac__be2host_32(metadata.data.picture.colorDepth);
6807
6808 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.indexColorCount, 4) != 4) {
6809 result = DRFLAC_FALSE;
6810 goto done_flac;
6811 }
6812 blockSizeRemaining -= 4;
6813 metadata.data.picture.indexColorCount = drflac__be2host_32(metadata.data.picture.indexColorCount);
6814
6815
6816 /* Picture data. */
6817 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.pictureDataSize, 4) != 4) {
6818 result = DRFLAC_FALSE;
6819 goto done_flac;
6820 }
6821 blockSizeRemaining -= 4;
6822 metadata.data.picture.pictureDataSize = drflac__be2host_32(metadata.data.picture.pictureDataSize);
6823
6824 if (blockSizeRemaining < metadata.data.picture.pictureDataSize) {
6825 result = DRFLAC_FALSE;
6826 goto done_flac;
6827 }
6828
6829 /* For the actual image data we want to store the offset to the start of the stream. */
6830 metadata.data.picture.pictureDataOffset = runningFilePos + (blockSize - blockSizeRemaining);
6831
6832 /*
6833 For the allocation of image data, we can allow memory allocation to fail, in which case we just leave
6834 the pointer as null. If it fails, we need to fall back to seeking past the image data.
6835 */
6836 #ifndef DR_FLAC_NO_PICTURE_METADATA_MALLOC
6837 pPictureData = drflac__malloc_from_callbacks(metadata.data.picture.pictureDataSize, pAllocationCallbacks);
6838 if (pPictureData != NULL) {
6839 if (onRead(pUserData, pPictureData, metadata.data.picture.pictureDataSize) != metadata.data.picture.pictureDataSize) {
6840 result = DRFLAC_FALSE;
6841 goto done_flac;
6842 }
6843 } else
6844 #endif
6845 {
6846 /* Allocation failed. We need to seek past the picture data. */
6847 if (!onSeek(pUserData, metadata.data.picture.pictureDataSize, DRFLAC_SEEK_CUR)) {
6848 result = DRFLAC_FALSE;
6849 goto done_flac;
6850 }
6851 }
6852
6853 blockSizeRemaining -= metadata.data.picture.pictureDataSize;
6854 (void)blockSizeRemaining;
6855
6856 metadata.data.picture.pPictureData = (const drflac_uint8*)pPictureData;
6857
6858
6859 /* Only fire the callback if we actually have a way to read the image data. We must have either a valid offset, or a valid data pointer. */
6860 if (metadata.data.picture.pictureDataOffset != 0 || metadata.data.picture.pPictureData != NULL) {
6861 onMeta(pUserDataMD, &metadata);
6862 } else {
6863 /* Don't have a valid offset or data pointer, so just pretend we don't have a picture metadata. */
6864 }
6865
6866 done_flac:
6867 drflac__free_from_callbacks(pMime, pAllocationCallbacks);
6868 drflac__free_from_callbacks(pDescription, pAllocationCallbacks);
6869 drflac__free_from_callbacks(pPictureData, pAllocationCallbacks);
6870
6871 if (result != DRFLAC_TRUE) {
6872 return DRFLAC_FALSE;
6873 }
6874 }
6875 } break;
6876
6877 case DRFLAC_METADATA_BLOCK_TYPE_PADDING:
6878 {
6879 if (onMeta) {
6880 metadata.data.padding.unused = 0;
6881
6882 /* 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. */
6883 if (!onSeek(pUserData, blockSize, DRFLAC_SEEK_CUR)) {
6884 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. */
6885 } else {
6886 onMeta(pUserDataMD, &metadata);
6887 }
6888 }
6889 } break;
6890
6891 case DRFLAC_METADATA_BLOCK_TYPE_INVALID:
6892 {
6893 /* Invalid chunk. Just skip over this one. */
6894 if (onMeta) {
6895 if (!onSeek(pUserData, blockSize, DRFLAC_SEEK_CUR)) {
6896 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. */
6897 }
6898 }
6899 } break;
6900
6901 default:
6902 {
6903 /*
6904 It's an unknown chunk, but not necessarily invalid. There's a chance more metadata blocks might be defined later on, so we
6905 can at the very least report the chunk to the application and let it look at the raw data.
6906 */
6907 if (onMeta) {
6908 void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6909 if (pRawData != NULL) {
6910 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6911 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6912 return DRFLAC_FALSE;
6913 }
6914 } else {
6915 /* Allocation failed. We need to seek past the block. */
6916 if (!onSeek(pUserData, blockSize, DRFLAC_SEEK_CUR)) {
6917 return DRFLAC_FALSE;
6918 }
6919 }
6920
6921 metadata.pRawData = pRawData;
6922 metadata.rawDataSize = blockSize;
6923 onMeta(pUserDataMD, &metadata);
6924
6925 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6926 }
6927 } break;
6928 }
6929
6930 /* 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. */
6931 if (onMeta == NULL && blockSize > 0) {
6932 if (!onSeek(pUserData, blockSize, DRFLAC_SEEK_CUR)) {
6933 isLastBlock = DRFLAC_TRUE;
6934 }
6935 }
6936
6937 runningFilePos += blockSize;
6938 if (isLastBlock) {
6939 break;
6940 }
6941 }
6942
6943 *pSeektablePos = seektablePos;
6944 *pSeekpointCount = seektableSize / DRFLAC_SEEKPOINT_SIZE_IN_BYTES;
6945 *pFirstFramePos = runningFilePos;
6946
6947 return DRFLAC_TRUE;
6948 }
6949
6950 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)
6951 {
6952 /* Pre Condition: The bit stream should be sitting just past the 4-byte id header. */
6953
6954 drflac_uint8 isLastBlock;
6955 drflac_uint8 blockType;
6956 drflac_uint32 blockSize;
6957
6958 (void)onSeek;
6959
6960 pInit->container = drflac_container_native;
6961
6962 /* The first metadata block should be the STREAMINFO block. */
6963 if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
6964 return DRFLAC_FALSE;
6965 }
6966
6967 if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
6968 if (!relaxed) {
6969 /* We're opening in strict mode and the first block is not the STREAMINFO block. Error. */
6970 return DRFLAC_FALSE;
6971 } else {
6972 /*
6973 Relaxed mode. To open from here we need to just find the first frame and set the sample rate, etc. to whatever is defined
6974 for that frame.
6975 */
6976 pInit->hasStreamInfoBlock = DRFLAC_FALSE;
6977 pInit->hasMetadataBlocks = DRFLAC_FALSE;
6978
6979 if (!drflac__read_next_flac_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) {
6980 return DRFLAC_FALSE; /* Couldn't find a frame. */
6981 }
6982
6983 if (pInit->firstFrameHeader.bitsPerSample == 0) {
6984 return DRFLAC_FALSE; /* Failed to initialize because the first frame depends on the STREAMINFO block, which does not exist. */
6985 }
6986
6987 pInit->sampleRate = pInit->firstFrameHeader.sampleRate;
6988 pInit->channels = drflac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment);
6989 pInit->bitsPerSample = pInit->firstFrameHeader.bitsPerSample;
6990 pInit->maxBlockSizeInPCMFrames = 65535; /* <-- See notes here: https://xiph.org/flac/format.html#metadata_block_streaminfo */
6991 return DRFLAC_TRUE;
6992 }
6993 } else {
6994 drflac_streaminfo streaminfo;
6995 if (!drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
6996 return DRFLAC_FALSE;
6997 }
6998
6999 pInit->hasStreamInfoBlock = DRFLAC_TRUE;
7000 pInit->sampleRate = streaminfo.sampleRate;
7001 pInit->channels = streaminfo.channels;
7002 pInit->bitsPerSample = streaminfo.bitsPerSample;
7003 pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
7004 pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames; /* Don't care about the min block size - only the max (used for determining the size of the memory allocation). */
7005 pInit->hasMetadataBlocks = !isLastBlock;
7006
7007 if (onMeta) {
7008 drflac_metadata metadata;
7009 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
7010 metadata.pRawData = NULL;
7011 metadata.rawDataSize = 0;
7012 metadata.data.streaminfo = streaminfo;
7013 onMeta(pUserDataMD, &metadata);
7014 }
7015
7016 return DRFLAC_TRUE;
7017 }
7018 }
7019
7020 #ifndef DR_FLAC_NO_OGG
7021 #define DRFLAC_OGG_MAX_PAGE_SIZE 65307
7022 #define DRFLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199 /* CRC-32 of "OggS". */
7023
7024 typedef enum
7025 {
7026 drflac_ogg_recover_on_crc_mismatch,
7027 drflac_ogg_fail_on_crc_mismatch
7028 } drflac_ogg_crc_mismatch_recovery;
7029
7030 #ifndef DR_FLAC_NO_CRC
7031 static drflac_uint32 drflac__crc32_table[] = {
7032 0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L,
7033 0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L,
7034 0x2608EDB8L, 0x22C9F00FL, 0x2F8AD6D6L, 0x2B4BCB61L,
7035 0x350C9B64L, 0x31CD86D3L, 0x3C8EA00AL, 0x384FBDBDL,
7036 0x4C11DB70L, 0x48D0C6C7L, 0x4593E01EL, 0x4152FDA9L,
7037 0x5F15ADACL, 0x5BD4B01BL, 0x569796C2L, 0x52568B75L,
7038 0x6A1936C8L, 0x6ED82B7FL, 0x639B0DA6L, 0x675A1011L,
7039 0x791D4014L, 0x7DDC5DA3L, 0x709F7B7AL, 0x745E66CDL,
7040 0x9823B6E0L, 0x9CE2AB57L, 0x91A18D8EL, 0x95609039L,
7041 0x8B27C03CL, 0x8FE6DD8BL, 0x82A5FB52L, 0x8664E6E5L,
7042 0xBE2B5B58L, 0xBAEA46EFL, 0xB7A96036L, 0xB3687D81L,
7043 0xAD2F2D84L, 0xA9EE3033L, 0xA4AD16EAL, 0xA06C0B5DL,
7044 0xD4326D90L, 0xD0F37027L, 0xDDB056FEL, 0xD9714B49L,
7045 0xC7361B4CL, 0xC3F706FBL, 0xCEB42022L, 0xCA753D95L,
7046 0xF23A8028L, 0xF6FB9D9FL, 0xFBB8BB46L, 0xFF79A6F1L,
7047 0xE13EF6F4L, 0xE5FFEB43L, 0xE8BCCD9AL, 0xEC7DD02DL,
7048 0x34867077L, 0x30476DC0L, 0x3D044B19L, 0x39C556AEL,
7049 0x278206ABL, 0x23431B1CL, 0x2E003DC5L, 0x2AC12072L,
7050 0x128E9DCFL, 0x164F8078L, 0x1B0CA6A1L, 0x1FCDBB16L,
7051 0x018AEB13L, 0x054BF6A4L, 0x0808D07DL, 0x0CC9CDCAL,
7052 0x7897AB07L, 0x7C56B6B0L, 0x71159069L, 0x75D48DDEL,
7053 0x6B93DDDBL, 0x6F52C06CL, 0x6211E6B5L, 0x66D0FB02L,
7054 0x5E9F46BFL, 0x5A5E5B08L, 0x571D7DD1L, 0x53DC6066L,
7055 0x4D9B3063L, 0x495A2DD4L, 0x44190B0DL, 0x40D816BAL,
7056 0xACA5C697L, 0xA864DB20L, 0xA527FDF9L, 0xA1E6E04EL,
7057 0xBFA1B04BL, 0xBB60ADFCL, 0xB6238B25L, 0xB2E29692L,
7058 0x8AAD2B2FL, 0x8E6C3698L, 0x832F1041L, 0x87EE0DF6L,
7059 0x99A95DF3L, 0x9D684044L, 0x902B669DL, 0x94EA7B2AL,
7060 0xE0B41DE7L, 0xE4750050L, 0xE9362689L, 0xEDF73B3EL,
7061 0xF3B06B3BL, 0xF771768CL, 0xFA325055L, 0xFEF34DE2L,
7062 0xC6BCF05FL, 0xC27DEDE8L, 0xCF3ECB31L, 0xCBFFD686L,
7063 0xD5B88683L, 0xD1799B34L, 0xDC3ABDEDL, 0xD8FBA05AL,
7064 0x690CE0EEL, 0x6DCDFD59L, 0x608EDB80L, 0x644FC637L,
7065 0x7A089632L, 0x7EC98B85L, 0x738AAD5CL, 0x774BB0EBL,
7066 0x4F040D56L, 0x4BC510E1L, 0x46863638L, 0x42472B8FL,
7067 0x5C007B8AL, 0x58C1663DL, 0x558240E4L, 0x51435D53L,
7068 0x251D3B9EL, 0x21DC2629L, 0x2C9F00F0L, 0x285E1D47L,
7069 0x36194D42L, 0x32D850F5L, 0x3F9B762CL, 0x3B5A6B9BL,
7070 0x0315D626L, 0x07D4CB91L, 0x0A97ED48L, 0x0E56F0FFL,
7071 0x1011A0FAL, 0x14D0BD4DL, 0x19939B94L, 0x1D528623L,
7072 0xF12F560EL, 0xF5EE4BB9L, 0xF8AD6D60L, 0xFC6C70D7L,
7073 0xE22B20D2L, 0xE6EA3D65L, 0xEBA91BBCL, 0xEF68060BL,
7074 0xD727BBB6L, 0xD3E6A601L, 0xDEA580D8L, 0xDA649D6FL,
7075 0xC423CD6AL, 0xC0E2D0DDL, 0xCDA1F604L, 0xC960EBB3L,
7076 0xBD3E8D7EL, 0xB9FF90C9L, 0xB4BCB610L, 0xB07DABA7L,
7077 0xAE3AFBA2L, 0xAAFBE615L, 0xA7B8C0CCL, 0xA379DD7BL,
7078 0x9B3660C6L, 0x9FF77D71L, 0x92B45BA8L, 0x9675461FL,
7079 0x8832161AL, 0x8CF30BADL, 0x81B02D74L, 0x857130C3L,
7080 0x5D8A9099L, 0x594B8D2EL, 0x5408ABF7L, 0x50C9B640L,
7081 0x4E8EE645L, 0x4A4FFBF2L, 0x470CDD2BL, 0x43CDC09CL,
7082 0x7B827D21L, 0x7F436096L, 0x7200464FL, 0x76C15BF8L,
7083 0x68860BFDL, 0x6C47164AL, 0x61043093L, 0x65C52D24L,
7084 0x119B4BE9L, 0x155A565EL, 0x18197087L, 0x1CD86D30L,
7085 0x029F3D35L, 0x065E2082L, 0x0B1D065BL, 0x0FDC1BECL,
7086 0x3793A651L, 0x3352BBE6L, 0x3E119D3FL, 0x3AD08088L,
7087 0x2497D08DL, 0x2056CD3AL, 0x2D15EBE3L, 0x29D4F654L,
7088 0xC5A92679L, 0xC1683BCEL, 0xCC2B1D17L, 0xC8EA00A0L,
7089 0xD6AD50A5L, 0xD26C4D12L, 0xDF2F6BCBL, 0xDBEE767CL,
7090 0xE3A1CBC1L, 0xE760D676L, 0xEA23F0AFL, 0xEEE2ED18L,
7091 0xF0A5BD1DL, 0xF464A0AAL, 0xF9278673L, 0xFDE69BC4L,
7092 0x89B8FD09L, 0x8D79E0BEL, 0x803AC667L, 0x84FBDBD0L,
7093 0x9ABC8BD5L, 0x9E7D9662L, 0x933EB0BBL, 0x97FFAD0CL,
7094 0xAFB010B1L, 0xAB710D06L, 0xA6322BDFL, 0xA2F33668L,
7095 0xBCB4666DL, 0xB8757BDAL, 0xB5365D03L, 0xB1F740B4L
7096 };
7097 #endif
7098
7099 static DRFLAC_INLINE drflac_uint32 drflac_crc32_byte(drflac_uint32 crc32, drflac_uint8 data)
7100 {
7101 #ifndef DR_FLAC_NO_CRC
7102 return (crc32 << 8) ^ drflac__crc32_table[(drflac_uint8)((crc32 >> 24) & 0xFF) ^ data];
7103 #else
7104 (void)data;
7105 return crc32;
7106 #endif
7107 }
7108
7109 #if 0
7110 static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint32(drflac_uint32 crc32, drflac_uint32 data)
7111 {
7112 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 24) & 0xFF));
7113 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 16) & 0xFF));
7114 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 8) & 0xFF));
7115 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 0) & 0xFF));
7116 return crc32;
7117 }
7118
7119 static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint64(drflac_uint32 crc32, drflac_uint64 data)
7120 {
7121 crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 32) & 0xFFFFFFFF));
7122 crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 0) & 0xFFFFFFFF));
7123 return crc32;
7124 }
7125 #endif
7126
7127 static DRFLAC_INLINE drflac_uint32 drflac_crc32_buffer(drflac_uint32 crc32, drflac_uint8* pData, drflac_uint32 dataSize)
7128 {
7129 /* This can be optimized. */
7130 drflac_uint32 i;
7131 for (i = 0; i < dataSize; ++i) {
7132 crc32 = drflac_crc32_byte(crc32, pData[i]);
7133 }
7134 return crc32;
7135 }
7136
7137
7138 static DRFLAC_INLINE drflac_bool32 drflac_ogg__is_capture_pattern(drflac_uint8 pattern[4])
7139 {
7140 return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S';
7141 }
7142
7143 static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_header_size(drflac_ogg_page_header* pHeader)
7144 {
7145 return 27 + pHeader->segmentCount;
7146 }
7147
7148 static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_body_size(drflac_ogg_page_header* pHeader)
7149 {
7150 drflac_uint32 pageBodySize = 0;
7151 int i;
7152
7153 for (i = 0; i < pHeader->segmentCount; ++i) {
7154 pageBodySize += pHeader->segmentTable[i];
7155 }
7156
7157 return pageBodySize;
7158 }
7159
7160 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)
7161 {
7162 drflac_uint8 data[23];
7163 drflac_uint32 i;
7164
7165 DRFLAC_ASSERT(*pCRC32 == DRFLAC_OGG_CAPTURE_PATTERN_CRC32);
7166
7167 if (onRead(pUserData, data, 23) != 23) {
7168 return DRFLAC_AT_END;
7169 }
7170 *pBytesRead += 23;
7171
7172 /*
7173 It's not actually used, but set the capture pattern to 'OggS' for completeness. Not doing this will cause static analysers to complain about
7174 us trying to access uninitialized data. We could alternatively just comment out this member of the drflac_ogg_page_header structure, but I
7175 like to have it map to the structure of the underlying data.
7176 */
7177 pHeader->capturePattern[0] = 'O';
7178 pHeader->capturePattern[1] = 'g';
7179 pHeader->capturePattern[2] = 'g';
7180 pHeader->capturePattern[3] = 'S';
7181
7182 pHeader->structureVersion = data[0];
7183 pHeader->headerType = data[1];
7184 DRFLAC_COPY_MEMORY(&pHeader->granulePosition, &data[ 2], 8);
7185 DRFLAC_COPY_MEMORY(&pHeader->serialNumber, &data[10], 4);
7186 DRFLAC_COPY_MEMORY(&pHeader->sequenceNumber, &data[14], 4);
7187 DRFLAC_COPY_MEMORY(&pHeader->checksum, &data[18], 4);
7188 pHeader->segmentCount = data[22];
7189
7190 /* Calculate the CRC. Note that for the calculation the checksum part of the page needs to be set to 0. */
7191 data[18] = 0;
7192 data[19] = 0;
7193 data[20] = 0;
7194 data[21] = 0;
7195
7196 for (i = 0; i < 23; ++i) {
7197 *pCRC32 = drflac_crc32_byte(*pCRC32, data[i]);
7198 }
7199
7200
7201 if (onRead(pUserData, pHeader->segmentTable, pHeader->segmentCount) != pHeader->segmentCount) {
7202 return DRFLAC_AT_END;
7203 }
7204 *pBytesRead += pHeader->segmentCount;
7205
7206 for (i = 0; i < pHeader->segmentCount; ++i) {
7207 *pCRC32 = drflac_crc32_byte(*pCRC32, pHeader->segmentTable[i]);
7208 }
7209
7210 return DRFLAC_SUCCESS;
7211 }
7212
7213 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)
7214 {
7215 drflac_uint8 id[4];
7216
7217 *pBytesRead = 0;
7218
7219 if (onRead(pUserData, id, 4) != 4) {
7220 return DRFLAC_AT_END;
7221 }
7222 *pBytesRead += 4;
7223
7224 /* We need to read byte-by-byte until we find the OggS capture pattern. */
7225 for (;;) {
7226 if (drflac_ogg__is_capture_pattern(id)) {
7227 drflac_result result;
7228
7229 *pCRC32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
7230
7231 result = drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32);
7232 if (result == DRFLAC_SUCCESS) {
7233 return DRFLAC_SUCCESS;
7234 } else {
7235 if (result == DRFLAC_CRC_MISMATCH) {
7236 continue;
7237 } else {
7238 return result;
7239 }
7240 }
7241 } else {
7242 /* The first 4 bytes did not equal the capture pattern. Read the next byte and try again. */
7243 id[0] = id[1];
7244 id[1] = id[2];
7245 id[2] = id[3];
7246 if (onRead(pUserData, &id[3], 1) != 1) {
7247 return DRFLAC_AT_END;
7248 }
7249 *pBytesRead += 1;
7250 }
7251 }
7252 }
7253
7254
7255 /*
7256 The main part of the Ogg encapsulation is the conversion from the physical Ogg bitstream to the native FLAC bitstream. It works
7257 in three general stages: Ogg Physical Bitstream -> Ogg/FLAC Logical Bitstream -> FLAC Native Bitstream. dr_flac is designed
7258 in such a way that the core sections assume everything is delivered in native format. Therefore, for each encapsulation type
7259 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
7260 the physical Ogg bitstream are converted and delivered in native FLAC format.
7261 */
7262 typedef struct
7263 {
7264 drflac_read_proc onRead; /* The original onRead callback from drflac_open() and family. */
7265 drflac_seek_proc onSeek; /* The original onSeek callback from drflac_open() and family. */
7266 drflac_tell_proc onTell; /* The original onTell callback from drflac_open() and family. */
7267 void* pUserData; /* The user data passed on onRead and onSeek. This is the user data that was passed on drflac_open() and family. */
7268 drflac_uint64 currentBytePos; /* The position of the byte we are sitting on in the physical byte stream. Used for efficient seeking. */
7269 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. */
7270 drflac_uint32 serialNumber; /* The serial number of the FLAC audio pages. This is determined by the initial header page that was read during initialization. */
7271 drflac_ogg_page_header bosPageHeader; /* Used for seeking. */
7272 drflac_ogg_page_header currentPageHeader;
7273 drflac_uint32 bytesRemainingInPage;
7274 drflac_uint32 pageDataSize;
7275 drflac_uint8 pageData[DRFLAC_OGG_MAX_PAGE_SIZE];
7276 } drflac_oggbs; /* oggbs = Ogg Bitstream */
7277
7278 static size_t drflac_oggbs__read_physical(drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead)
7279 {
7280 size_t bytesActuallyRead = oggbs->onRead(oggbs->pUserData, bufferOut, bytesToRead);
7281 oggbs->currentBytePos += bytesActuallyRead;
7282
7283 return bytesActuallyRead;
7284 }
7285
7286 static drflac_bool32 drflac_oggbs__seek_physical(drflac_oggbs* oggbs, drflac_uint64 offset, drflac_seek_origin origin)
7287 {
7288 if (origin == DRFLAC_SEEK_SET) {
7289 if (offset <= 0x7FFFFFFF) {
7290 if (!oggbs->onSeek(oggbs->pUserData, (int)offset, DRFLAC_SEEK_SET)) {
7291 return DRFLAC_FALSE;
7292 }
7293 oggbs->currentBytePos = offset;
7294
7295 return DRFLAC_TRUE;
7296 } else {
7297 if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, DRFLAC_SEEK_SET)) {
7298 return DRFLAC_FALSE;
7299 }
7300 oggbs->currentBytePos = offset;
7301
7302 return drflac_oggbs__seek_physical(oggbs, offset - 0x7FFFFFFF, DRFLAC_SEEK_CUR);
7303 }
7304 } else {
7305 while (offset > 0x7FFFFFFF) {
7306 if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, DRFLAC_SEEK_CUR)) {
7307 return DRFLAC_FALSE;
7308 }
7309 oggbs->currentBytePos += 0x7FFFFFFF;
7310 offset -= 0x7FFFFFFF;
7311 }
7312
7313 if (!oggbs->onSeek(oggbs->pUserData, (int)offset, DRFLAC_SEEK_CUR)) { /* <-- Safe cast thanks to the loop above. */
7314 return DRFLAC_FALSE;
7315 }
7316 oggbs->currentBytePos += offset;
7317
7318 return DRFLAC_TRUE;
7319 }
7320 }
7321
7322 static drflac_bool32 drflac_oggbs__goto_next_page(drflac_oggbs* oggbs, drflac_ogg_crc_mismatch_recovery recoveryMethod)
7323 {
7324 drflac_ogg_page_header header;
7325 for (;;) {
7326 drflac_uint32 crc32 = 0;
7327 drflac_uint32 bytesRead;
7328 drflac_uint32 pageBodySize;
7329 #ifndef DR_FLAC_NO_CRC
7330 drflac_uint32 actualCRC32;
7331 #endif
7332
7333 if (drflac_ogg__read_page_header(oggbs->onRead, oggbs->pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
7334 return DRFLAC_FALSE;
7335 }
7336 oggbs->currentBytePos += bytesRead;
7337
7338 pageBodySize = drflac_ogg__get_page_body_size(&header);
7339 if (pageBodySize > DRFLAC_OGG_MAX_PAGE_SIZE) {
7340 continue; /* Invalid page size. Assume it's corrupted and just move to the next page. */
7341 }
7342
7343 if (header.serialNumber != oggbs->serialNumber) {
7344 /* It's not a FLAC page. Skip it. */
7345 if (pageBodySize > 0 && !drflac_oggbs__seek_physical(oggbs, pageBodySize, DRFLAC_SEEK_CUR)) {
7346 return DRFLAC_FALSE;
7347 }
7348 continue;
7349 }
7350
7351
7352 /* 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. */
7353 if (drflac_oggbs__read_physical(oggbs, oggbs->pageData, pageBodySize) != pageBodySize) {
7354 return DRFLAC_FALSE;
7355 }
7356 oggbs->pageDataSize = pageBodySize;
7357
7358 #ifndef DR_FLAC_NO_CRC
7359 actualCRC32 = drflac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize);
7360 if (actualCRC32 != header.checksum) {
7361 if (recoveryMethod == drflac_ogg_recover_on_crc_mismatch) {
7362 continue; /* CRC mismatch. Skip this page. */
7363 } else {
7364 /*
7365 Even though we are failing on a CRC mismatch, we still want our stream to be in a good state. Therefore we
7366 go to the next valid page to ensure we're in a good state, but return false to let the caller know that the
7367 seek did not fully complete.
7368 */
7369 drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch);
7370 return DRFLAC_FALSE;
7371 }
7372 }
7373 #else
7374 (void)recoveryMethod; /* <-- Silence a warning. */
7375 #endif
7376
7377 oggbs->currentPageHeader = header;
7378 oggbs->bytesRemainingInPage = pageBodySize;
7379 return DRFLAC_TRUE;
7380 }
7381 }
7382
7383 /* Function below is unused at the moment, but I might be re-adding it later. */
7384 #if 0
7385 static drflac_uint8 drflac_oggbs__get_current_segment_index(drflac_oggbs* oggbs, drflac_uint8* pBytesRemainingInSeg)
7386 {
7387 drflac_uint32 bytesConsumedInPage = drflac_ogg__get_page_body_size(&oggbs->currentPageHeader) - oggbs->bytesRemainingInPage;
7388 drflac_uint8 iSeg = 0;
7389 drflac_uint32 iByte = 0;
7390 while (iByte < bytesConsumedInPage) {
7391 drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
7392 if (iByte + segmentSize > bytesConsumedInPage) {
7393 break;
7394 } else {
7395 iSeg += 1;
7396 iByte += segmentSize;
7397 }
7398 }
7399
7400 *pBytesRemainingInSeg = oggbs->currentPageHeader.segmentTable[iSeg] - (drflac_uint8)(bytesConsumedInPage - iByte);
7401 return iSeg;
7402 }
7403
7404 static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs)
7405 {
7406 /* 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. */
7407 for (;;) {
7408 drflac_bool32 atEndOfPage = DRFLAC_FALSE;
7409
7410 drflac_uint8 bytesRemainingInSeg;
7411 drflac_uint8 iFirstSeg = drflac_oggbs__get_current_segment_index(oggbs, &bytesRemainingInSeg);
7412
7413 drflac_uint32 bytesToEndOfPacketOrPage = bytesRemainingInSeg;
7414 for (drflac_uint8 iSeg = iFirstSeg; iSeg < oggbs->currentPageHeader.segmentCount; ++iSeg) {
7415 drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
7416 if (segmentSize < 255) {
7417 if (iSeg == oggbs->currentPageHeader.segmentCount-1) {
7418 atEndOfPage = DRFLAC_TRUE;
7419 }
7420
7421 break;
7422 }
7423
7424 bytesToEndOfPacketOrPage += segmentSize;
7425 }
7426
7427 /*
7428 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
7429 want to load the next page and keep searching for the end of the packet.
7430 */
7431 drflac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, DRFLAC_SEEK_CUR);
7432 oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage;
7433
7434 if (atEndOfPage) {
7435 /*
7436 We're potentially at the next packet, but we need to check the next page first to be sure because the packet may
7437 straddle pages.
7438 */
7439 if (!drflac_oggbs__goto_next_page(oggbs)) {
7440 return DRFLAC_FALSE;
7441 }
7442
7443 /* If it's a fresh packet it most likely means we're at the next packet. */
7444 if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
7445 return DRFLAC_TRUE;
7446 }
7447 } else {
7448 /* We're at the next packet. */
7449 return DRFLAC_TRUE;
7450 }
7451 }
7452 }
7453
7454 static drflac_bool32 drflac_oggbs__seek_to_next_frame(drflac_oggbs* oggbs)
7455 {
7456 /* The bitstream should be sitting on the first byte just after the header of the frame. */
7457
7458 /* What we're actually doing here is seeking to the start of the next packet. */
7459 return drflac_oggbs__seek_to_next_packet(oggbs);
7460 }
7461 #endif
7462
7463 static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead)
7464 {
7465 drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
7466 drflac_uint8* pRunningBufferOut = (drflac_uint8*)bufferOut;
7467 size_t bytesRead = 0;
7468
7469 DRFLAC_ASSERT(oggbs != NULL);
7470 DRFLAC_ASSERT(pRunningBufferOut != NULL);
7471
7472 /* Reading is done page-by-page. If we've run out of bytes in the page we need to move to the next one. */
7473 while (bytesRead < bytesToRead) {
7474 size_t bytesRemainingToRead = bytesToRead - bytesRead;
7475
7476 if (oggbs->bytesRemainingInPage >= bytesRemainingToRead) {
7477 DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), bytesRemainingToRead);
7478 bytesRead += bytesRemainingToRead;
7479 oggbs->bytesRemainingInPage -= (drflac_uint32)bytesRemainingToRead;
7480 break;
7481 }
7482
7483 /* If we get here it means some of the requested data is contained in the next pages. */
7484 if (oggbs->bytesRemainingInPage > 0) {
7485 DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage);
7486 bytesRead += oggbs->bytesRemainingInPage;
7487 pRunningBufferOut += oggbs->bytesRemainingInPage;
7488 oggbs->bytesRemainingInPage = 0;
7489 }
7490
7491 DRFLAC_ASSERT(bytesRemainingToRead > 0);
7492 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
7493 break; /* Failed to go to the next page. Might have simply hit the end of the stream. */
7494 }
7495 }
7496
7497 return bytesRead;
7498 }
7499
7500 static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_seek_origin origin)
7501 {
7502 drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
7503 int bytesSeeked = 0;
7504
7505 DRFLAC_ASSERT(oggbs != NULL);
7506 DRFLAC_ASSERT(offset >= 0); /* <-- Never seek backwards. */
7507
7508 /* Seeking is always forward which makes things a lot simpler. */
7509 if (origin == DRFLAC_SEEK_SET) {
7510 if (!drflac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, DRFLAC_SEEK_SET)) {
7511 return DRFLAC_FALSE;
7512 }
7513
7514 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
7515 return DRFLAC_FALSE;
7516 }
7517
7518 return drflac__on_seek_ogg(pUserData, offset, DRFLAC_SEEK_CUR);
7519 } else if (origin == DRFLAC_SEEK_CUR) {
7520 while (bytesSeeked < offset) {
7521 int bytesRemainingToSeek = offset - bytesSeeked;
7522 DRFLAC_ASSERT(bytesRemainingToSeek >= 0);
7523
7524 if (oggbs->bytesRemainingInPage >= (size_t)bytesRemainingToSeek) {
7525 bytesSeeked += bytesRemainingToSeek;
7526 (void)bytesSeeked; /* <-- Silence a dead store warning emitted by Clang Static Analyzer. */
7527 oggbs->bytesRemainingInPage -= bytesRemainingToSeek;
7528 break;
7529 }
7530
7531 /* If we get here it means some of the requested data is contained in the next pages. */
7532 if (oggbs->bytesRemainingInPage > 0) {
7533 bytesSeeked += (int)oggbs->bytesRemainingInPage;
7534 oggbs->bytesRemainingInPage = 0;
7535 }
7536
7537 DRFLAC_ASSERT(bytesRemainingToSeek > 0);
7538 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
7539 /* Failed to go to the next page. We either hit the end of the stream or had a CRC mismatch. */
7540 return DRFLAC_FALSE;
7541 }
7542 }
7543 } else if (origin == DRFLAC_SEEK_END) {
7544 /* Seeking to the end is not supported. */
7545 return DRFLAC_FALSE;
7546 }
7547
7548 return DRFLAC_TRUE;
7549 }
7550
7551 static drflac_bool32 drflac__on_tell_ogg(void* pUserData, drflac_int64* pCursor)
7552 {
7553 /*
7554 Not implemented for Ogg containers because we don't currently track the byte position of the logical bitstream. To support this, we'll need
7555 to track the position in drflac__on_read_ogg and drflac__on_seek_ogg.
7556 */
7557 (void)pUserData;
7558 (void)pCursor;
7559 return DRFLAC_FALSE;
7560 }
7561
7562
7563 static drflac_bool32 drflac_ogg__seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
7564 {
7565 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
7566 drflac_uint64 originalBytePos;
7567 drflac_uint64 runningGranulePosition;
7568 drflac_uint64 runningFrameBytePos;
7569 drflac_uint64 runningPCMFrameCount;
7570
7571 DRFLAC_ASSERT(oggbs != NULL);
7572
7573 originalBytePos = oggbs->currentBytePos; /* For recovery. Points to the OggS identifier. */
7574
7575 /* First seek to the first frame. */
7576 if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes)) {
7577 return DRFLAC_FALSE;
7578 }
7579 oggbs->bytesRemainingInPage = 0;
7580
7581 runningGranulePosition = 0;
7582 for (;;) {
7583 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
7584 drflac_oggbs__seek_physical(oggbs, originalBytePos, DRFLAC_SEEK_SET);
7585 return DRFLAC_FALSE; /* Never did find that sample... */
7586 }
7587
7588 runningFrameBytePos = oggbs->currentBytePos - drflac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize;
7589 if (oggbs->currentPageHeader.granulePosition >= pcmFrameIndex) {
7590 break; /* The sample is somewhere in the previous page. */
7591 }
7592
7593 /*
7594 At this point we know the sample is not in the previous page. It could possibly be in this page. For simplicity we
7595 disregard any pages that do not begin a fresh packet.
7596 */
7597 if ((oggbs->currentPageHeader.headerType & 0x01) == 0) { /* <-- Is it a fresh page? */
7598 if (oggbs->currentPageHeader.segmentTable[0] >= 2) {
7599 drflac_uint8 firstBytesInPage[2];
7600 firstBytesInPage[0] = oggbs->pageData[0];
7601 firstBytesInPage[1] = oggbs->pageData[1];
7602
7603 if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) { /* <-- Does the page begin with a frame's sync code? */
7604 runningGranulePosition = oggbs->currentPageHeader.granulePosition;
7605 }
7606
7607 continue;
7608 }
7609 }
7610 }
7611
7612 /*
7613 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
7614 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
7615 a new frame. This property means that after we've seeked to the page we can immediately start looping over frames until
7616 we find the one containing the target sample.
7617 */
7618 if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, DRFLAC_SEEK_SET)) {
7619 return DRFLAC_FALSE;
7620 }
7621 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
7622 return DRFLAC_FALSE;
7623 }
7624
7625 /*
7626 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
7627 looping over these frames until we find the one containing the sample we're after.
7628 */
7629 runningPCMFrameCount = runningGranulePosition;
7630 for (;;) {
7631 /*
7632 There are two ways to find the sample and seek past irrelevant frames:
7633 1) Use the native FLAC decoder.
7634 2) Use Ogg's framing system.
7635
7636 Both of these options have their own pros and cons. Using the native FLAC decoder is slower because it needs to
7637 do a full decode of the frame. Using Ogg's framing system is faster, but more complicated and involves some code
7638 duplication for the decoding of frame headers.
7639
7640 Another thing to consider is that using the Ogg framing system will perform direct seeking of the physical Ogg
7641 bitstream. This is important to consider because it means we cannot read data from the drflac_bs object using the
7642 standard drflac__*() APIs because that will read in extra data for its own internal caching which in turn breaks
7643 the positioning of the read pointer of the physical Ogg bitstream. Therefore, anything that would normally be read
7644 using the native FLAC decoding APIs, such as drflac__read_next_flac_frame_header(), need to be re-implemented so as to
7645 avoid the use of the drflac_bs object.
7646
7647 Considering these issues, I have decided to use the slower native FLAC decoding method for the following reasons:
7648 1) Seeking is already partially accelerated using Ogg's paging system in the code block above.
7649 2) Seeking in an Ogg encapsulated FLAC stream is probably quite uncommon.
7650 3) Simplicity.
7651 */
7652 drflac_uint64 firstPCMFrameInFLACFrame = 0;
7653 drflac_uint64 lastPCMFrameInFLACFrame = 0;
7654 drflac_uint64 pcmFrameCountInThisFrame;
7655
7656 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
7657 return DRFLAC_FALSE;
7658 }
7659
7660 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
7661
7662 pcmFrameCountInThisFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
7663
7664 /* If we are seeking to the end of the file and we've just hit it, we're done. */
7665 if (pcmFrameIndex == pFlac->totalPCMFrameCount && (runningPCMFrameCount + pcmFrameCountInThisFrame) == pFlac->totalPCMFrameCount) {
7666 drflac_result result = drflac__decode_flac_frame(pFlac);
7667 if (result == DRFLAC_SUCCESS) {
7668 pFlac->currentPCMFrame = pcmFrameIndex;
7669 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
7670 return DRFLAC_TRUE;
7671 } else {
7672 return DRFLAC_FALSE;
7673 }
7674 }
7675
7676 if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFrame)) {
7677 /*
7678 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
7679 it never existed and keep iterating.
7680 */
7681 drflac_result result = drflac__decode_flac_frame(pFlac);
7682 if (result == DRFLAC_SUCCESS) {
7683 /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
7684 drflac_uint64 pcmFramesToDecode = (size_t)(pcmFrameIndex - runningPCMFrameCount); /* <-- Safe cast because the maximum number of samples in a frame is 65535. */
7685 if (pcmFramesToDecode == 0) {
7686 return DRFLAC_TRUE;
7687 }
7688
7689 pFlac->currentPCMFrame = runningPCMFrameCount;
7690
7691 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */
7692 } else {
7693 if (result == DRFLAC_CRC_MISMATCH) {
7694 continue; /* CRC mismatch. Pretend this frame never existed. */
7695 } else {
7696 return DRFLAC_FALSE;
7697 }
7698 }
7699 } else {
7700 /*
7701 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
7702 frame never existed and leave the running sample count untouched.
7703 */
7704 drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
7705 if (result == DRFLAC_SUCCESS) {
7706 runningPCMFrameCount += pcmFrameCountInThisFrame;
7707 } else {
7708 if (result == DRFLAC_CRC_MISMATCH) {
7709 continue; /* CRC mismatch. Pretend this frame never existed. */
7710 } else {
7711 return DRFLAC_FALSE;
7712 }
7713 }
7714 }
7715 }
7716 }
7717
7718
7719
7720 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)
7721 {
7722 drflac_ogg_page_header header;
7723 drflac_uint32 crc32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
7724 drflac_uint32 bytesRead = 0;
7725
7726 /* Pre Condition: The bit stream should be sitting just past the 4-byte OggS capture pattern. */
7727 (void)relaxed;
7728
7729 pInit->container = drflac_container_ogg;
7730 pInit->oggFirstBytePos = 0;
7731
7732 /*
7733 We'll get here if the first 4 bytes of the stream were the OggS capture pattern, however it doesn't necessarily mean the
7734 stream includes FLAC encoded audio. To check for this we need to scan the beginning-of-stream page markers and check if
7735 any match the FLAC specification. Important to keep in mind that the stream may be multiplexed.
7736 */
7737 if (drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
7738 return DRFLAC_FALSE;
7739 }
7740 pInit->runningFilePos += bytesRead;
7741
7742 for (;;) {
7743 int pageBodySize;
7744
7745 /* Break if we're past the beginning of stream page. */
7746 if ((header.headerType & 0x02) == 0) {
7747 return DRFLAC_FALSE;
7748 }
7749
7750 /* Check if it's a FLAC header. */
7751 pageBodySize = drflac_ogg__get_page_body_size(&header);
7752 if (pageBodySize == 51) { /* 51 = the lacing value of the FLAC header packet. */
7753 /* It could be a FLAC page... */
7754 drflac_uint32 bytesRemainingInPage = pageBodySize;
7755 drflac_uint8 packetType;
7756
7757 if (onRead(pUserData, &packetType, 1) != 1) {
7758 return DRFLAC_FALSE;
7759 }
7760
7761 bytesRemainingInPage -= 1;
7762 if (packetType == 0x7F) {
7763 /* Increasingly more likely to be a FLAC page... */
7764 drflac_uint8 sig[4];
7765 if (onRead(pUserData, sig, 4) != 4) {
7766 return DRFLAC_FALSE;
7767 }
7768
7769 bytesRemainingInPage -= 4;
7770 if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') {
7771 /* Almost certainly a FLAC page... */
7772 drflac_uint8 mappingVersion[2];
7773 if (onRead(pUserData, mappingVersion, 2) != 2) {
7774 return DRFLAC_FALSE;
7775 }
7776
7777 if (mappingVersion[0] != 1) {
7778 return DRFLAC_FALSE; /* Only supporting version 1.x of the Ogg mapping. */
7779 }
7780
7781 /*
7782 The next 2 bytes are the non-audio packets, not including this one. We don't care about this because we're going to
7783 be handling it in a generic way based on the serial number and packet types.
7784 */
7785 if (!onSeek(pUserData, 2, DRFLAC_SEEK_CUR)) {
7786 return DRFLAC_FALSE;
7787 }
7788
7789 /* Expecting the native FLAC signature "fLaC". */
7790 if (onRead(pUserData, sig, 4) != 4) {
7791 return DRFLAC_FALSE;
7792 }
7793
7794 if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C') {
7795 /* The remaining data in the page should be the STREAMINFO block. */
7796 drflac_streaminfo streaminfo;
7797 drflac_uint8 isLastBlock;
7798 drflac_uint8 blockType;
7799 drflac_uint32 blockSize;
7800 if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
7801 return DRFLAC_FALSE;
7802 }
7803
7804 if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
7805 return DRFLAC_FALSE; /* Invalid block type. First block must be the STREAMINFO block. */
7806 }
7807
7808 if (drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
7809 /* Success! */
7810 pInit->hasStreamInfoBlock = DRFLAC_TRUE;
7811 pInit->sampleRate = streaminfo.sampleRate;
7812 pInit->channels = streaminfo.channels;
7813 pInit->bitsPerSample = streaminfo.bitsPerSample;
7814 pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
7815 pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames;
7816 pInit->hasMetadataBlocks = !isLastBlock;
7817
7818 if (onMeta) {
7819 drflac_metadata metadata;
7820 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
7821 metadata.pRawData = NULL;
7822 metadata.rawDataSize = 0;
7823 metadata.data.streaminfo = streaminfo;
7824 onMeta(pUserDataMD, &metadata);
7825 }
7826
7827 pInit->runningFilePos += pageBodySize;
7828 pInit->oggFirstBytePos = pInit->runningFilePos - 79; /* Subtracting 79 will place us right on top of the "OggS" identifier of the FLAC bos page. */
7829 pInit->oggSerial = header.serialNumber;
7830 pInit->oggBosHeader = header;
7831 break;
7832 } else {
7833 /* Failed to read STREAMINFO block. Aww, so close... */
7834 return DRFLAC_FALSE;
7835 }
7836 } else {
7837 /* Invalid file. */
7838 return DRFLAC_FALSE;
7839 }
7840 } else {
7841 /* Not a FLAC header. Skip it. */
7842 if (!onSeek(pUserData, bytesRemainingInPage, DRFLAC_SEEK_CUR)) {
7843 return DRFLAC_FALSE;
7844 }
7845 }
7846 } else {
7847 /* Not a FLAC header. Seek past the entire page and move on to the next. */
7848 if (!onSeek(pUserData, bytesRemainingInPage, DRFLAC_SEEK_CUR)) {
7849 return DRFLAC_FALSE;
7850 }
7851 }
7852 } else {
7853 if (!onSeek(pUserData, pageBodySize, DRFLAC_SEEK_CUR)) {
7854 return DRFLAC_FALSE;
7855 }
7856 }
7857
7858 pInit->runningFilePos += pageBodySize;
7859
7860
7861 /* Read the header of the next page. */
7862 if (drflac_ogg__read_page_header(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
7863 return DRFLAC_FALSE;
7864 }
7865 pInit->runningFilePos += bytesRead;
7866 }
7867
7868 /*
7869 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
7870 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
7871 Ogg bistream object.
7872 */
7873 pInit->hasMetadataBlocks = DRFLAC_TRUE; /* <-- Always have at least VORBIS_COMMENT metadata block. */
7874 return DRFLAC_TRUE;
7875 }
7876 #endif
7877
7878 static drflac_bool32 drflac__init_private(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD)
7879 {
7880 drflac_bool32 relaxed;
7881 drflac_uint8 id[4];
7882
7883 if (pInit == NULL || onRead == NULL || onSeek == NULL) { /* <-- onTell is optional. */
7884 return DRFLAC_FALSE;
7885 }
7886
7887 DRFLAC_ZERO_MEMORY(pInit, sizeof(*pInit));
7888 pInit->onRead = onRead;
7889 pInit->onSeek = onSeek;
7890 pInit->onTell = onTell;
7891 pInit->onMeta = onMeta;
7892 pInit->container = container;
7893 pInit->pUserData = pUserData;
7894 pInit->pUserDataMD = pUserDataMD;
7895
7896 pInit->bs.onRead = onRead;
7897 pInit->bs.onSeek = onSeek;
7898 pInit->bs.onTell = onTell;
7899 pInit->bs.pUserData = pUserData;
7900 drflac__reset_cache(&pInit->bs);
7901
7902
7903 /* If the container is explicitly defined then we can try opening in relaxed mode. */
7904 relaxed = container != drflac_container_unknown;
7905
7906 /* Skip over any ID3 tags. */
7907 for (;;) {
7908 if (onRead(pUserData, id, 4) != 4) {
7909 return DRFLAC_FALSE; /* Ran out of data. */
7910 }
7911 pInit->runningFilePos += 4;
7912
7913 if (id[0] == 'I' && id[1] == 'D' && id[2] == '3') {
7914 drflac_uint8 header[6];
7915 drflac_uint8 flags;
7916 drflac_uint32 headerSize;
7917
7918 if (onRead(pUserData, header, 6) != 6) {
7919 return DRFLAC_FALSE; /* Ran out of data. */
7920 }
7921 pInit->runningFilePos += 6;
7922
7923 flags = header[1];
7924
7925 DRFLAC_COPY_MEMORY(&headerSize, header+2, 4);
7926 headerSize = drflac__unsynchsafe_32(drflac__be2host_32(headerSize));
7927 if (flags & 0x10) {
7928 headerSize += 10;
7929 }
7930
7931 if (!onSeek(pUserData, headerSize, DRFLAC_SEEK_CUR)) {
7932 return DRFLAC_FALSE; /* Failed to seek past the tag. */
7933 }
7934 pInit->runningFilePos += headerSize;
7935 } else {
7936 break;
7937 }
7938 }
7939
7940 if (id[0] == 'f' && id[1] == 'L' && id[2] == 'a' && id[3] == 'C') {
7941 return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
7942 }
7943 #ifndef DR_FLAC_NO_OGG
7944 if (id[0] == 'O' && id[1] == 'g' && id[2] == 'g' && id[3] == 'S') {
7945 return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
7946 }
7947 #endif
7948
7949 /* If we get here it means we likely don't have a header. Try opening in relaxed mode, if applicable. */
7950 if (relaxed) {
7951 if (container == drflac_container_native) {
7952 return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
7953 }
7954 #ifndef DR_FLAC_NO_OGG
7955 if (container == drflac_container_ogg) {
7956 return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
7957 }
7958 #endif
7959 }
7960
7961 /* Unsupported container. */
7962 return DRFLAC_FALSE;
7963 }
7964
7965 static void drflac__init_from_info(drflac* pFlac, const drflac_init_info* pInit)
7966 {
7967 DRFLAC_ASSERT(pFlac != NULL);
7968 DRFLAC_ASSERT(pInit != NULL);
7969
7970 DRFLAC_ZERO_MEMORY(pFlac, sizeof(*pFlac));
7971 pFlac->bs = pInit->bs;
7972 pFlac->onMeta = pInit->onMeta;
7973 pFlac->pUserDataMD = pInit->pUserDataMD;
7974 pFlac->maxBlockSizeInPCMFrames = pInit->maxBlockSizeInPCMFrames;
7975 pFlac->sampleRate = pInit->sampleRate;
7976 pFlac->channels = (drflac_uint8)pInit->channels;
7977 pFlac->bitsPerSample = (drflac_uint8)pInit->bitsPerSample;
7978 pFlac->totalPCMFrameCount = pInit->totalPCMFrameCount;
7979 pFlac->container = pInit->container;
7980 }
7981
7982
7983 static drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD, const drflac_allocation_callbacks* pAllocationCallbacks)
7984 {
7985 drflac_init_info init;
7986 drflac_uint32 allocationSize;
7987 drflac_uint32 wholeSIMDVectorCountPerChannel;
7988 drflac_uint32 decodedSamplesAllocationSize;
7989 #ifndef DR_FLAC_NO_OGG
7990 drflac_oggbs* pOggbs = NULL;
7991 #endif
7992 drflac_uint64 firstFramePos;
7993 drflac_uint64 seektablePos;
7994 drflac_uint32 seekpointCount;
7995 drflac_allocation_callbacks allocationCallbacks;
7996 drflac* pFlac;
7997
7998 /* CPU support first. */
7999 drflac__init_cpu_caps();
8000
8001 if (!drflac__init_private(&init, onRead, onSeek, onTell, onMeta, container, pUserData, pUserDataMD)) {
8002 return NULL;
8003 }
8004
8005 if (pAllocationCallbacks != NULL) {
8006 allocationCallbacks = *pAllocationCallbacks;
8007 if (allocationCallbacks.onFree == NULL || (allocationCallbacks.onMalloc == NULL && allocationCallbacks.onRealloc == NULL)) {
8008 return NULL; /* Invalid allocation callbacks. */
8009 }
8010 } else {
8011 allocationCallbacks.pUserData = NULL;
8012 allocationCallbacks.onMalloc = drflac__malloc_default;
8013 allocationCallbacks.onRealloc = drflac__realloc_default;
8014 allocationCallbacks.onFree = drflac__free_default;
8015 }
8016
8017
8018 /*
8019 The size of the allocation for the drflac object needs to be large enough to fit the following:
8020 1) The main members of the drflac structure
8021 2) A block of memory large enough to store the decoded samples of the largest frame in the stream
8022 3) If the container is Ogg, a drflac_oggbs object
8023
8024 The complicated part of the allocation is making sure there's enough room the decoded samples, taking into consideration
8025 the different SIMD instruction sets.
8026 */
8027 allocationSize = sizeof(drflac);
8028
8029 /*
8030 The allocation size for decoded frames depends on the number of 32-bit integers that fit inside the largest SIMD vector
8031 we are supporting.
8032 */
8033 if ((init.maxBlockSizeInPCMFrames % (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) == 0) {
8034 wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32)));
8035 } else {
8036 wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) + 1;
8037 }
8038
8039 decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * DRFLAC_MAX_SIMD_VECTOR_SIZE * init.channels;
8040
8041 allocationSize += decodedSamplesAllocationSize;
8042 allocationSize += DRFLAC_MAX_SIMD_VECTOR_SIZE; /* Allocate extra bytes to ensure we have enough for alignment. */
8043
8044 #ifndef DR_FLAC_NO_OGG
8045 /* There's additional data required for Ogg streams. */
8046 if (init.container == drflac_container_ogg) {
8047 allocationSize += sizeof(drflac_oggbs);
8048
8049 pOggbs = (drflac_oggbs*)drflac__malloc_from_callbacks(sizeof(*pOggbs), &allocationCallbacks);
8050 if (pOggbs == NULL) {
8051 return NULL; /*DRFLAC_OUT_OF_MEMORY;*/
8052 }
8053
8054 DRFLAC_ZERO_MEMORY(pOggbs, sizeof(*pOggbs));
8055 pOggbs->onRead = onRead;
8056 pOggbs->onSeek = onSeek;
8057 pOggbs->onTell = onTell;
8058 pOggbs->pUserData = pUserData;
8059 pOggbs->currentBytePos = init.oggFirstBytePos;
8060 pOggbs->firstBytePos = init.oggFirstBytePos;
8061 pOggbs->serialNumber = init.oggSerial;
8062 pOggbs->bosPageHeader = init.oggBosHeader;
8063 pOggbs->bytesRemainingInPage = 0;
8064 }
8065 #endif
8066
8067 /*
8068 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
8069 consist of only a single heap allocation. To this, the size of the seek table needs to be known, which we determine when reading
8070 and decoding the metadata.
8071 */
8072 firstFramePos = 42; /* <-- We know we are at byte 42 at this point. */
8073 seektablePos = 0;
8074 seekpointCount = 0;
8075 if (init.hasMetadataBlocks) {
8076 drflac_read_proc onReadOverride = onRead;
8077 drflac_seek_proc onSeekOverride = onSeek;
8078 drflac_tell_proc onTellOverride = onTell;
8079 void* pUserDataOverride = pUserData;
8080
8081 #ifndef DR_FLAC_NO_OGG
8082 if (init.container == drflac_container_ogg) {
8083 onReadOverride = drflac__on_read_ogg;
8084 onSeekOverride = drflac__on_seek_ogg;
8085 onTellOverride = drflac__on_tell_ogg;
8086 pUserDataOverride = (void*)pOggbs;
8087 }
8088 #endif
8089
8090 if (!drflac__read_and_decode_metadata(onReadOverride, onSeekOverride, onTellOverride, onMeta, pUserDataOverride, pUserDataMD, &firstFramePos, &seektablePos, &seekpointCount, &allocationCallbacks)) {
8091 #ifndef DR_FLAC_NO_OGG
8092 drflac__free_from_callbacks(pOggbs, &allocationCallbacks);
8093 #endif
8094 return NULL;
8095 }
8096
8097 allocationSize += seekpointCount * sizeof(drflac_seekpoint);
8098 }
8099
8100
8101 pFlac = (drflac*)drflac__malloc_from_callbacks(allocationSize, &allocationCallbacks);
8102 if (pFlac == NULL) {
8103 #ifndef DR_FLAC_NO_OGG
8104 drflac__free_from_callbacks(pOggbs, &allocationCallbacks);
8105 #endif
8106 return NULL;
8107 }
8108
8109 drflac__init_from_info(pFlac, &init);
8110 pFlac->allocationCallbacks = allocationCallbacks;
8111 pFlac->pDecodedSamples = (drflac_int32*)drflac_align((size_t)pFlac->pExtraData, DRFLAC_MAX_SIMD_VECTOR_SIZE);
8112
8113 #ifndef DR_FLAC_NO_OGG
8114 if (init.container == drflac_container_ogg) {
8115 drflac_oggbs* pInternalOggbs = (drflac_oggbs*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize + (seekpointCount * sizeof(drflac_seekpoint)));
8116 DRFLAC_COPY_MEMORY(pInternalOggbs, pOggbs, sizeof(*pOggbs));
8117
8118 /* At this point the pOggbs object has been handed over to pInternalOggbs and can be freed. */
8119 drflac__free_from_callbacks(pOggbs, &allocationCallbacks);
8120 pOggbs = NULL;
8121
8122 /* The Ogg bistream needs to be layered on top of the original bitstream. */
8123 pFlac->bs.onRead = drflac__on_read_ogg;
8124 pFlac->bs.onSeek = drflac__on_seek_ogg;
8125 pFlac->bs.onTell = drflac__on_tell_ogg;
8126 pFlac->bs.pUserData = (void*)pInternalOggbs;
8127 pFlac->_oggbs = (void*)pInternalOggbs;
8128 }
8129 #endif
8130
8131 pFlac->firstFLACFramePosInBytes = firstFramePos;
8132
8133 /* 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. */
8134 #ifndef DR_FLAC_NO_OGG
8135 if (init.container == drflac_container_ogg)
8136 {
8137 pFlac->pSeekpoints = NULL;
8138 pFlac->seekpointCount = 0;
8139 }
8140 else
8141 #endif
8142 {
8143 /* If we have a seektable we need to load it now, making sure we move back to where we were previously. */
8144 if (seektablePos != 0) {
8145 pFlac->seekpointCount = seekpointCount;
8146 pFlac->pSeekpoints = (drflac_seekpoint*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize);
8147
8148 DRFLAC_ASSERT(pFlac->bs.onSeek != NULL);
8149 DRFLAC_ASSERT(pFlac->bs.onRead != NULL);
8150
8151 /* Seek to the seektable, then just read directly into our seektable buffer. */
8152 if (pFlac->bs.onSeek(pFlac->bs.pUserData, (int)seektablePos, DRFLAC_SEEK_SET)) {
8153 drflac_uint32 iSeekpoint;
8154
8155 for (iSeekpoint = 0; iSeekpoint < seekpointCount; iSeekpoint += 1) {
8156 if (pFlac->bs.onRead(pFlac->bs.pUserData, pFlac->pSeekpoints + iSeekpoint, DRFLAC_SEEKPOINT_SIZE_IN_BYTES) == DRFLAC_SEEKPOINT_SIZE_IN_BYTES) {
8157 /* Endian swap. */
8158 pFlac->pSeekpoints[iSeekpoint].firstPCMFrame = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].firstPCMFrame);
8159 pFlac->pSeekpoints[iSeekpoint].flacFrameOffset = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].flacFrameOffset);
8160 pFlac->pSeekpoints[iSeekpoint].pcmFrameCount = drflac__be2host_16(pFlac->pSeekpoints[iSeekpoint].pcmFrameCount);
8161 } else {
8162 /* Failed to read the seektable. Pretend we don't have one. */
8163 pFlac->pSeekpoints = NULL;
8164 pFlac->seekpointCount = 0;
8165 break;
8166 }
8167 }
8168
8169 /* We need to seek back to where we were. If this fails it's a critical error. */
8170 if (!pFlac->bs.onSeek(pFlac->bs.pUserData, (int)pFlac->firstFLACFramePosInBytes, DRFLAC_SEEK_SET)) {
8171 drflac__free_from_callbacks(pFlac, &allocationCallbacks);
8172 return NULL;
8173 }
8174 } else {
8175 /* Failed to seek to the seektable. Ominous sign, but for now we can just pretend we don't have one. */
8176 pFlac->pSeekpoints = NULL;
8177 pFlac->seekpointCount = 0;
8178 }
8179 }
8180 }
8181
8182
8183 /*
8184 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
8185 the first frame.
8186 */
8187 if (!init.hasStreamInfoBlock) {
8188 pFlac->currentFLACFrame.header = init.firstFrameHeader;
8189 for (;;) {
8190 drflac_result result = drflac__decode_flac_frame(pFlac);
8191 if (result == DRFLAC_SUCCESS) {
8192 break;
8193 } else {
8194 if (result == DRFLAC_CRC_MISMATCH) {
8195 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
8196 drflac__free_from_callbacks(pFlac, &allocationCallbacks);
8197 return NULL;
8198 }
8199 continue;
8200 } else {
8201 drflac__free_from_callbacks(pFlac, &allocationCallbacks);
8202 return NULL;
8203 }
8204 }
8205 }
8206 }
8207
8208 return pFlac;
8209 }
8210
8211
8212
8213 #ifndef DR_FLAC_NO_STDIO
8214 #include <stdio.h>
8215 #ifndef DR_FLAC_NO_WCHAR
8216 #include <wchar.h> /* For wcslen(), wcsrtombs() */
8217 #endif
8218
8219 /* Errno */
8220 /* 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. */
8221 #include <errno.h>
8222 static drflac_result drflac_result_from_errno(int e)
8223 {
8224 switch (e)
8225 {
8226 case 0: return DRFLAC_SUCCESS;
8227 #ifdef EPERM
8228 case EPERM: return DRFLAC_INVALID_OPERATION;
8229 #endif
8230 #ifdef ENOENT
8231 case ENOENT: return DRFLAC_DOES_NOT_EXIST;
8232 #endif
8233 #ifdef ESRCH
8234 case ESRCH: return DRFLAC_DOES_NOT_EXIST;
8235 #endif
8236 #ifdef EINTR
8237 case EINTR: return DRFLAC_INTERRUPT;
8238 #endif
8239 #ifdef EIO
8240 case EIO: return DRFLAC_IO_ERROR;
8241 #endif
8242 #ifdef ENXIO
8243 case ENXIO: return DRFLAC_DOES_NOT_EXIST;
8244 #endif
8245 #ifdef E2BIG
8246 case E2BIG: return DRFLAC_INVALID_ARGS;
8247 #endif
8248 #ifdef ENOEXEC
8249 case ENOEXEC: return DRFLAC_INVALID_FILE;
8250 #endif
8251 #ifdef EBADF
8252 case EBADF: return DRFLAC_INVALID_FILE;
8253 #endif
8254 #ifdef ECHILD
8255 case ECHILD: return DRFLAC_ERROR;
8256 #endif
8257 #ifdef EAGAIN
8258 case EAGAIN: return DRFLAC_UNAVAILABLE;
8259 #endif
8260 #ifdef ENOMEM
8261 case ENOMEM: return DRFLAC_OUT_OF_MEMORY;
8262 #endif
8263 #ifdef EACCES
8264 case EACCES: return DRFLAC_ACCESS_DENIED;
8265 #endif
8266 #ifdef EFAULT
8267 case EFAULT: return DRFLAC_BAD_ADDRESS;
8268 #endif
8269 #ifdef ENOTBLK
8270 case ENOTBLK: return DRFLAC_ERROR;
8271 #endif
8272 #ifdef EBUSY
8273 case EBUSY: return DRFLAC_BUSY;
8274 #endif
8275 #ifdef EEXIST
8276 case EEXIST: return DRFLAC_ALREADY_EXISTS;
8277 #endif
8278 #ifdef EXDEV
8279 case EXDEV: return DRFLAC_ERROR;
8280 #endif
8281 #ifdef ENODEV
8282 case ENODEV: return DRFLAC_DOES_NOT_EXIST;
8283 #endif
8284 #ifdef ENOTDIR
8285 case ENOTDIR: return DRFLAC_NOT_DIRECTORY;
8286 #endif
8287 #ifdef EISDIR
8288 case EISDIR: return DRFLAC_IS_DIRECTORY;
8289 #endif
8290 #ifdef EINVAL
8291 case EINVAL: return DRFLAC_INVALID_ARGS;
8292 #endif
8293 #ifdef ENFILE
8294 case ENFILE: return DRFLAC_TOO_MANY_OPEN_FILES;
8295 #endif
8296 #ifdef EMFILE
8297 case EMFILE: return DRFLAC_TOO_MANY_OPEN_FILES;
8298 #endif
8299 #ifdef ENOTTY
8300 case ENOTTY: return DRFLAC_INVALID_OPERATION;
8301 #endif
8302 #ifdef ETXTBSY
8303 case ETXTBSY: return DRFLAC_BUSY;
8304 #endif
8305 #ifdef EFBIG
8306 case EFBIG: return DRFLAC_TOO_BIG;
8307 #endif
8308 #ifdef ENOSPC
8309 case ENOSPC: return DRFLAC_NO_SPACE;
8310 #endif
8311 #ifdef ESPIPE
8312 case ESPIPE: return DRFLAC_BAD_SEEK;
8313 #endif
8314 #ifdef EROFS
8315 case EROFS: return DRFLAC_ACCESS_DENIED;
8316 #endif
8317 #ifdef EMLINK
8318 case EMLINK: return DRFLAC_TOO_MANY_LINKS;
8319 #endif
8320 #ifdef EPIPE
8321 case EPIPE: return DRFLAC_BAD_PIPE;
8322 #endif
8323 #ifdef EDOM
8324 case EDOM: return DRFLAC_OUT_OF_RANGE;
8325 #endif
8326 #ifdef ERANGE
8327 case ERANGE: return DRFLAC_OUT_OF_RANGE;
8328 #endif
8329 #ifdef EDEADLK
8330 case EDEADLK: return DRFLAC_DEADLOCK;
8331 #endif
8332 #ifdef ENAMETOOLONG
8333 case ENAMETOOLONG: return DRFLAC_PATH_TOO_LONG;
8334 #endif
8335 #ifdef ENOLCK
8336 case ENOLCK: return DRFLAC_ERROR;
8337 #endif
8338 #ifdef ENOSYS
8339 case ENOSYS: return DRFLAC_NOT_IMPLEMENTED;
8340 #endif
8341 #if defined(ENOTEMPTY) && ENOTEMPTY != EEXIST /* In AIX, ENOTEMPTY and EEXIST use the same value. */
8342 case ENOTEMPTY: return DRFLAC_DIRECTORY_NOT_EMPTY;
8343 #endif
8344 #ifdef ELOOP
8345 case ELOOP: return DRFLAC_TOO_MANY_LINKS;
8346 #endif
8347 #ifdef ENOMSG
8348 case ENOMSG: return DRFLAC_NO_MESSAGE;
8349 #endif
8350 #ifdef EIDRM
8351 case EIDRM: return DRFLAC_ERROR;
8352 #endif
8353 #ifdef ECHRNG
8354 case ECHRNG: return DRFLAC_ERROR;
8355 #endif
8356 #ifdef EL2NSYNC
8357 case EL2NSYNC: return DRFLAC_ERROR;
8358 #endif
8359 #ifdef EL3HLT
8360 case EL3HLT: return DRFLAC_ERROR;
8361 #endif
8362 #ifdef EL3RST
8363 case EL3RST: return DRFLAC_ERROR;
8364 #endif
8365 #ifdef ELNRNG
8366 case ELNRNG: return DRFLAC_OUT_OF_RANGE;
8367 #endif
8368 #ifdef EUNATCH
8369 case EUNATCH: return DRFLAC_ERROR;
8370 #endif
8371 #ifdef ENOCSI
8372 case ENOCSI: return DRFLAC_ERROR;
8373 #endif
8374 #ifdef EL2HLT
8375 case EL2HLT: return DRFLAC_ERROR;
8376 #endif
8377 #ifdef EBADE
8378 case EBADE: return DRFLAC_ERROR;
8379 #endif
8380 #ifdef EBADR
8381 case EBADR: return DRFLAC_ERROR;
8382 #endif
8383 #ifdef EXFULL
8384 case EXFULL: return DRFLAC_ERROR;
8385 #endif
8386 #ifdef ENOANO
8387 case ENOANO: return DRFLAC_ERROR;
8388 #endif
8389 #ifdef EBADRQC
8390 case EBADRQC: return DRFLAC_ERROR;
8391 #endif
8392 #ifdef EBADSLT
8393 case EBADSLT: return DRFLAC_ERROR;
8394 #endif
8395 #ifdef EBFONT
8396 case EBFONT: return DRFLAC_INVALID_FILE;
8397 #endif
8398 #ifdef ENOSTR
8399 case ENOSTR: return DRFLAC_ERROR;
8400 #endif
8401 #ifdef ENODATA
8402 case ENODATA: return DRFLAC_NO_DATA_AVAILABLE;
8403 #endif
8404 #ifdef ETIME
8405 case ETIME: return DRFLAC_TIMEOUT;
8406 #endif
8407 #ifdef ENOSR
8408 case ENOSR: return DRFLAC_NO_DATA_AVAILABLE;
8409 #endif
8410 #ifdef ENONET
8411 case ENONET: return DRFLAC_NO_NETWORK;
8412 #endif
8413 #ifdef ENOPKG
8414 case ENOPKG: return DRFLAC_ERROR;
8415 #endif
8416 #ifdef EREMOTE
8417 case EREMOTE: return DRFLAC_ERROR;
8418 #endif
8419 #ifdef ENOLINK
8420 case ENOLINK: return DRFLAC_ERROR;
8421 #endif
8422 #ifdef EADV
8423 case EADV: return DRFLAC_ERROR;
8424 #endif
8425 #ifdef ESRMNT
8426 case ESRMNT: return DRFLAC_ERROR;
8427 #endif
8428 #ifdef ECOMM
8429 case ECOMM: return DRFLAC_ERROR;
8430 #endif
8431 #ifdef EPROTO
8432 case EPROTO: return DRFLAC_ERROR;
8433 #endif
8434 #ifdef EMULTIHOP
8435 case EMULTIHOP: return DRFLAC_ERROR;
8436 #endif
8437 #ifdef EDOTDOT
8438 case EDOTDOT: return DRFLAC_ERROR;
8439 #endif
8440 #ifdef EBADMSG
8441 case EBADMSG: return DRFLAC_BAD_MESSAGE;
8442 #endif
8443 #ifdef EOVERFLOW
8444 case EOVERFLOW: return DRFLAC_TOO_BIG;
8445 #endif
8446 #ifdef ENOTUNIQ
8447 case ENOTUNIQ: return DRFLAC_NOT_UNIQUE;
8448 #endif
8449 #ifdef EBADFD
8450 case EBADFD: return DRFLAC_ERROR;
8451 #endif
8452 #ifdef EREMCHG
8453 case EREMCHG: return DRFLAC_ERROR;
8454 #endif
8455 #ifdef ELIBACC
8456 case ELIBACC: return DRFLAC_ACCESS_DENIED;
8457 #endif
8458 #ifdef ELIBBAD
8459 case ELIBBAD: return DRFLAC_INVALID_FILE;
8460 #endif
8461 #ifdef ELIBSCN
8462 case ELIBSCN: return DRFLAC_INVALID_FILE;
8463 #endif
8464 #ifdef ELIBMAX
8465 case ELIBMAX: return DRFLAC_ERROR;
8466 #endif
8467 #ifdef ELIBEXEC
8468 case ELIBEXEC: return DRFLAC_ERROR;
8469 #endif
8470 #ifdef EILSEQ
8471 case EILSEQ: return DRFLAC_INVALID_DATA;
8472 #endif
8473 #ifdef ERESTART
8474 case ERESTART: return DRFLAC_ERROR;
8475 #endif
8476 #ifdef ESTRPIPE
8477 case ESTRPIPE: return DRFLAC_ERROR;
8478 #endif
8479 #ifdef EUSERS
8480 case EUSERS: return DRFLAC_ERROR;
8481 #endif
8482 #ifdef ENOTSOCK
8483 case ENOTSOCK: return DRFLAC_NOT_SOCKET;
8484 #endif
8485 #ifdef EDESTADDRREQ
8486 case EDESTADDRREQ: return DRFLAC_NO_ADDRESS;
8487 #endif
8488 #ifdef EMSGSIZE
8489 case EMSGSIZE: return DRFLAC_TOO_BIG;
8490 #endif
8491 #ifdef EPROTOTYPE
8492 case EPROTOTYPE: return DRFLAC_BAD_PROTOCOL;
8493 #endif
8494 #ifdef ENOPROTOOPT
8495 case ENOPROTOOPT: return DRFLAC_PROTOCOL_UNAVAILABLE;
8496 #endif
8497 #ifdef EPROTONOSUPPORT
8498 case EPROTONOSUPPORT: return DRFLAC_PROTOCOL_NOT_SUPPORTED;
8499 #endif
8500 #ifdef ESOCKTNOSUPPORT
8501 case ESOCKTNOSUPPORT: return DRFLAC_SOCKET_NOT_SUPPORTED;
8502 #endif
8503 #ifdef EOPNOTSUPP
8504 case EOPNOTSUPP: return DRFLAC_INVALID_OPERATION;
8505 #endif
8506 #ifdef EPFNOSUPPORT
8507 case EPFNOSUPPORT: return DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED;
8508 #endif
8509 #ifdef EAFNOSUPPORT
8510 case EAFNOSUPPORT: return DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED;
8511 #endif
8512 #ifdef EADDRINUSE
8513 case EADDRINUSE: return DRFLAC_ALREADY_IN_USE;
8514 #endif
8515 #ifdef EADDRNOTAVAIL
8516 case EADDRNOTAVAIL: return DRFLAC_ERROR;
8517 #endif
8518 #ifdef ENETDOWN
8519 case ENETDOWN: return DRFLAC_NO_NETWORK;
8520 #endif
8521 #ifdef ENETUNREACH
8522 case ENETUNREACH: return DRFLAC_NO_NETWORK;
8523 #endif
8524 #ifdef ENETRESET
8525 case ENETRESET: return DRFLAC_NO_NETWORK;
8526 #endif
8527 #ifdef ECONNABORTED
8528 case ECONNABORTED: return DRFLAC_NO_NETWORK;
8529 #endif
8530 #ifdef ECONNRESET
8531 case ECONNRESET: return DRFLAC_CONNECTION_RESET;
8532 #endif
8533 #ifdef ENOBUFS
8534 case ENOBUFS: return DRFLAC_NO_SPACE;
8535 #endif
8536 #ifdef EISCONN
8537 case EISCONN: return DRFLAC_ALREADY_CONNECTED;
8538 #endif
8539 #ifdef ENOTCONN
8540 case ENOTCONN: return DRFLAC_NOT_CONNECTED;
8541 #endif
8542 #ifdef ESHUTDOWN
8543 case ESHUTDOWN: return DRFLAC_ERROR;
8544 #endif
8545 #ifdef ETOOMANYREFS
8546 case ETOOMANYREFS: return DRFLAC_ERROR;
8547 #endif
8548 #ifdef ETIMEDOUT
8549 case ETIMEDOUT: return DRFLAC_TIMEOUT;
8550 #endif
8551 #ifdef ECONNREFUSED
8552 case ECONNREFUSED: return DRFLAC_CONNECTION_REFUSED;
8553 #endif
8554 #ifdef EHOSTDOWN
8555 case EHOSTDOWN: return DRFLAC_NO_HOST;
8556 #endif
8557 #ifdef EHOSTUNREACH
8558 case EHOSTUNREACH: return DRFLAC_NO_HOST;
8559 #endif
8560 #ifdef EALREADY
8561 case EALREADY: return DRFLAC_IN_PROGRESS;
8562 #endif
8563 #ifdef EINPROGRESS
8564 case EINPROGRESS: return DRFLAC_IN_PROGRESS;
8565 #endif
8566 #ifdef ESTALE
8567 case ESTALE: return DRFLAC_INVALID_FILE;
8568 #endif
8569 #ifdef EUCLEAN
8570 case EUCLEAN: return DRFLAC_ERROR;
8571 #endif
8572 #ifdef ENOTNAM
8573 case ENOTNAM: return DRFLAC_ERROR;
8574 #endif
8575 #ifdef ENAVAIL
8576 case ENAVAIL: return DRFLAC_ERROR;
8577 #endif
8578 #ifdef EISNAM
8579 case EISNAM: return DRFLAC_ERROR;
8580 #endif
8581 #ifdef EREMOTEIO
8582 case EREMOTEIO: return DRFLAC_IO_ERROR;
8583 #endif
8584 #ifdef EDQUOT
8585 case EDQUOT: return DRFLAC_NO_SPACE;
8586 #endif
8587 #ifdef ENOMEDIUM
8588 case ENOMEDIUM: return DRFLAC_DOES_NOT_EXIST;
8589 #endif
8590 #ifdef EMEDIUMTYPE
8591 case EMEDIUMTYPE: return DRFLAC_ERROR;
8592 #endif
8593 #ifdef ECANCELED
8594 case ECANCELED: return DRFLAC_CANCELLED;
8595 #endif
8596 #ifdef ENOKEY
8597 case ENOKEY: return DRFLAC_ERROR;
8598 #endif
8599 #ifdef EKEYEXPIRED
8600 case EKEYEXPIRED: return DRFLAC_ERROR;
8601 #endif
8602 #ifdef EKEYREVOKED
8603 case EKEYREVOKED: return DRFLAC_ERROR;
8604 #endif
8605 #ifdef EKEYREJECTED
8606 case EKEYREJECTED: return DRFLAC_ERROR;
8607 #endif
8608 #ifdef EOWNERDEAD
8609 case EOWNERDEAD: return DRFLAC_ERROR;
8610 #endif
8611 #ifdef ENOTRECOVERABLE
8612 case ENOTRECOVERABLE: return DRFLAC_ERROR;
8613 #endif
8614 #ifdef ERFKILL
8615 case ERFKILL: return DRFLAC_ERROR;
8616 #endif
8617 #ifdef EHWPOISON
8618 case EHWPOISON: return DRFLAC_ERROR;
8619 #endif
8620 default: return DRFLAC_ERROR;
8621 }
8622 }
8623 /* End Errno */
8624
8625 /* fopen */
8626 static drflac_result drflac_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
8627 {
8628 #if defined(_MSC_VER) && _MSC_VER >= 1400
8629 errno_t err;
8630 #endif
8631
8632 if (ppFile != NULL) {
8633 *ppFile = NULL; /* Safety. */
8634 }
8635
8636 if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
8637 return DRFLAC_INVALID_ARGS;
8638 }
8639
8640 #if defined(_MSC_VER) && _MSC_VER >= 1400
8641 err = fopen_s(ppFile, pFilePath, pOpenMode);
8642 if (err != 0) {
8643 return drflac_result_from_errno(err);
8644 }
8645 #else
8646 #if defined(_WIN32) || defined(__APPLE__)
8647 *ppFile = fopen(pFilePath, pOpenMode);
8648 #else
8649 #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
8650 *ppFile = fopen64(pFilePath, pOpenMode);
8651 #else
8652 *ppFile = fopen(pFilePath, pOpenMode);
8653 #endif
8654 #endif
8655 if (*ppFile == NULL) {
8656 drflac_result result = drflac_result_from_errno(errno);
8657 if (result == DRFLAC_SUCCESS) {
8658 result = DRFLAC_ERROR; /* Just a safety check to make sure we never ever return success when pFile == NULL. */
8659 }
8660
8661 return result;
8662 }
8663 #endif
8664
8665 return DRFLAC_SUCCESS;
8666 }
8667
8668 /*
8669 _wfopen() isn't always available in all compilation environments.
8670
8671 * Windows only.
8672 * MSVC seems to support it universally as far back as VC6 from what I can tell (haven't checked further back).
8673 * MinGW-64 (both 32- and 64-bit) seems to support it.
8674 * MinGW wraps it in !defined(__STRICT_ANSI__).
8675 * OpenWatcom wraps it in !defined(_NO_EXT_KEYS).
8676
8677 This can be reviewed as compatibility issues arise. The preference is to use _wfopen_s() and _wfopen() as opposed to the wcsrtombs()
8678 fallback, so if you notice your compiler not detecting this properly I'm happy to look at adding support.
8679 */
8680 #if defined(_WIN32)
8681 #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
8682 #define DRFLAC_HAS_WFOPEN
8683 #endif
8684 #endif
8685
8686 #ifndef DR_FLAC_NO_WCHAR
8687 static drflac_result drflac_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const drflac_allocation_callbacks* pAllocationCallbacks)
8688 {
8689 if (ppFile != NULL) {
8690 *ppFile = NULL; /* Safety. */
8691 }
8692
8693 if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
8694 return DRFLAC_INVALID_ARGS;
8695 }
8696
8697 #if defined(DRFLAC_HAS_WFOPEN)
8698 {
8699 /* Use _wfopen() on Windows. */
8700 #if defined(_MSC_VER) && _MSC_VER >= 1400
8701 errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
8702 if (err != 0) {
8703 return drflac_result_from_errno(err);
8704 }
8705 #else
8706 *ppFile = _wfopen(pFilePath, pOpenMode);
8707 if (*ppFile == NULL) {
8708 return drflac_result_from_errno(errno);
8709 }
8710 #endif
8711 (void)pAllocationCallbacks;
8712 }
8713 #else
8714 /*
8715 Use fopen() on anything other than Windows. Requires a conversion. This is annoying because
8716 fopen() is locale specific. The only real way I can think of to do this is with wcsrtombs(). Note
8717 that wcstombs() is apparently not thread-safe because it uses a static global mbstate_t object for
8718 maintaining state. I've checked this with -std=c89 and it works, but if somebody get's a compiler
8719 error I'll look into improving compatibility.
8720 */
8721
8722 /*
8723 Some compilers don't support wchar_t or wcsrtombs() which we're using below. In this case we just
8724 need to abort with an error. If you encounter a compiler lacking such support, add it to this list
8725 and submit a bug report and it'll be added to the library upstream.
8726 */
8727 #if defined(__DJGPP__)
8728 {
8729 /* Nothing to do here. This will fall through to the error check below. */
8730 }
8731 #else
8732 {
8733 mbstate_t mbs;
8734 size_t lenMB;
8735 const wchar_t* pFilePathTemp = pFilePath;
8736 char* pFilePathMB = NULL;
8737 char pOpenModeMB[32] = {0};
8738
8739 /* Get the length first. */
8740 DRFLAC_ZERO_OBJECT(&mbs);
8741 lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
8742 if (lenMB == (size_t)-1) {
8743 return drflac_result_from_errno(errno);
8744 }
8745
8746 pFilePathMB = (char*)drflac__malloc_from_callbacks(lenMB + 1, pAllocationCallbacks);
8747 if (pFilePathMB == NULL) {
8748 return DRFLAC_OUT_OF_MEMORY;
8749 }
8750
8751 pFilePathTemp = pFilePath;
8752 DRFLAC_ZERO_OBJECT(&mbs);
8753 wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
8754
8755 /* The open mode should always consist of ASCII characters so we should be able to do a trivial conversion. */
8756 {
8757 size_t i = 0;
8758 for (;;) {
8759 if (pOpenMode[i] == 0) {
8760 pOpenModeMB[i] = '\0';
8761 break;
8762 }
8763
8764 pOpenModeMB[i] = (char)pOpenMode[i];
8765 i += 1;
8766 }
8767 }
8768
8769 *ppFile = fopen(pFilePathMB, pOpenModeMB);
8770
8771 drflac__free_from_callbacks(pFilePathMB, pAllocationCallbacks);
8772 }
8773 #endif
8774
8775 if (*ppFile == NULL) {
8776 return DRFLAC_ERROR;
8777 }
8778 #endif
8779
8780 return DRFLAC_SUCCESS;
8781 }
8782 #endif
8783 /* End fopen */
8784
8785 static size_t drflac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead)
8786 {
8787 return fread(bufferOut, 1, bytesToRead, (FILE*)pUserData);
8788 }
8789
8790 static drflac_bool32 drflac__on_seek_stdio(void* pUserData, int offset, drflac_seek_origin origin)
8791 {
8792 int whence = SEEK_SET;
8793 if (origin == DRFLAC_SEEK_CUR) {
8794 whence = SEEK_CUR;
8795 } else if (origin == DRFLAC_SEEK_END) {
8796 whence = SEEK_END;
8797 }
8798
8799 return fseek((FILE*)pUserData, offset, whence) == 0;
8800 }
8801
8802 static drflac_bool32 drflac__on_tell_stdio(void* pUserData, drflac_int64* pCursor)
8803 {
8804 FILE* pFileStdio = (FILE*)pUserData;
8805 drflac_int64 result;
8806
8807 /* These were all validated at a higher level. */
8808 DRFLAC_ASSERT(pFileStdio != NULL);
8809 DRFLAC_ASSERT(pCursor != NULL);
8810
8811 #if defined(_WIN32) && !defined(NXDK)
8812 #if defined(_MSC_VER) && _MSC_VER > 1200
8813 result = _ftelli64(pFileStdio);
8814 #else
8815 result = ftell(pFileStdio);
8816 #endif
8817 #else
8818 result = ftell(pFileStdio);
8819 #endif
8820
8821 *pCursor = result;
8822
8823 return DRFLAC_TRUE;
8824 }
8825
8826
8827
8828 DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks)
8829 {
8830 drflac* pFlac;
8831 FILE* pFile;
8832
8833 if (drflac_fopen(&pFile, pFileName, "rb") != DRFLAC_SUCCESS) {
8834 return NULL;
8835 }
8836
8837 pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, drflac__on_tell_stdio, (void*)pFile, pAllocationCallbacks);
8838 if (pFlac == NULL) {
8839 fclose(pFile);
8840 return NULL;
8841 }
8842
8843 return pFlac;
8844 }
8845
8846 #ifndef DR_FLAC_NO_WCHAR
8847 DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks)
8848 {
8849 drflac* pFlac;
8850 FILE* pFile;
8851
8852 if (drflac_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != DRFLAC_SUCCESS) {
8853 return NULL;
8854 }
8855
8856 pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, drflac__on_tell_stdio, (void*)pFile, pAllocationCallbacks);
8857 if (pFlac == NULL) {
8858 fclose(pFile);
8859 return NULL;
8860 }
8861
8862 return pFlac;
8863 }
8864 #endif
8865
8866 DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
8867 {
8868 drflac* pFlac;
8869 FILE* pFile;
8870
8871 if (drflac_fopen(&pFile, pFileName, "rb") != DRFLAC_SUCCESS) {
8872 return NULL;
8873 }
8874
8875 pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, drflac__on_tell_stdio, onMeta, drflac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks);
8876 if (pFlac == NULL) {
8877 fclose(pFile);
8878 return pFlac;
8879 }
8880
8881 return pFlac;
8882 }
8883
8884 #ifndef DR_FLAC_NO_WCHAR
8885 DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
8886 {
8887 drflac* pFlac;
8888 FILE* pFile;
8889
8890 if (drflac_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != DRFLAC_SUCCESS) {
8891 return NULL;
8892 }
8893
8894 pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, drflac__on_tell_stdio, onMeta, drflac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks);
8895 if (pFlac == NULL) {
8896 fclose(pFile);
8897 return pFlac;
8898 }
8899
8900 return pFlac;
8901 }
8902 #endif
8903 #endif /* DR_FLAC_NO_STDIO */
8904
8905 static size_t drflac__on_read_memory(void* pUserData, void* bufferOut, size_t bytesToRead)
8906 {
8907 drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
8908 size_t bytesRemaining;
8909
8910 DRFLAC_ASSERT(memoryStream != NULL);
8911 DRFLAC_ASSERT(memoryStream->dataSize >= memoryStream->currentReadPos);
8912
8913 bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos;
8914 if (bytesToRead > bytesRemaining) {
8915 bytesToRead = bytesRemaining;
8916 }
8917
8918 if (bytesToRead > 0) {
8919 DRFLAC_COPY_MEMORY(bufferOut, memoryStream->data + memoryStream->currentReadPos, bytesToRead);
8920 memoryStream->currentReadPos += bytesToRead;
8921 }
8922
8923 return bytesToRead;
8924 }
8925
8926 static drflac_bool32 drflac__on_seek_memory(void* pUserData, int offset, drflac_seek_origin origin)
8927 {
8928 drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
8929 drflac_int64 newCursor;
8930
8931 DRFLAC_ASSERT(memoryStream != NULL);
8932
8933 if (origin == DRFLAC_SEEK_SET) {
8934 newCursor = 0;
8935 } else if (origin == DRFLAC_SEEK_CUR) {
8936 newCursor = (drflac_int64)memoryStream->currentReadPos;
8937 } else if (origin == DRFLAC_SEEK_END) {
8938 newCursor = (drflac_int64)memoryStream->dataSize;
8939 } else {
8940 DRFLAC_ASSERT(!"Invalid seek origin");
8941 return DRFLAC_FALSE;
8942 }
8943
8944 newCursor += offset;
8945
8946 if (newCursor < 0) {
8947 return DRFLAC_FALSE; /* Trying to seek prior to the start of the buffer. */
8948 }
8949 if ((size_t)newCursor > memoryStream->dataSize) {
8950 return DRFLAC_FALSE; /* Trying to seek beyond the end of the buffer. */
8951 }
8952
8953 memoryStream->currentReadPos = (size_t)newCursor;
8954
8955 return DRFLAC_TRUE;
8956 }
8957
8958 static drflac_bool32 drflac__on_tell_memory(void* pUserData, drflac_int64* pCursor)
8959 {
8960 drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
8961
8962 DRFLAC_ASSERT(memoryStream != NULL);
8963 DRFLAC_ASSERT(pCursor != NULL);
8964
8965 *pCursor = (drflac_int64)memoryStream->currentReadPos;
8966 return DRFLAC_TRUE;
8967 }
8968
8969 DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks)
8970 {
8971 drflac__memory_stream memoryStream;
8972 drflac* pFlac;
8973
8974 memoryStream.data = (const drflac_uint8*)pData;
8975 memoryStream.dataSize = dataSize;
8976 memoryStream.currentReadPos = 0;
8977 pFlac = drflac_open(drflac__on_read_memory, drflac__on_seek_memory, drflac__on_tell_memory, &memoryStream, pAllocationCallbacks);
8978 if (pFlac == NULL) {
8979 return NULL;
8980 }
8981
8982 pFlac->memoryStream = memoryStream;
8983
8984 /* This is an awful hack... */
8985 #ifndef DR_FLAC_NO_OGG
8986 if (pFlac->container == drflac_container_ogg)
8987 {
8988 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
8989 oggbs->pUserData = &pFlac->memoryStream;
8990 }
8991 else
8992 #endif
8993 {
8994 pFlac->bs.pUserData = &pFlac->memoryStream;
8995 }
8996
8997 return pFlac;
8998 }
8999
9000 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)
9001 {
9002 drflac__memory_stream memoryStream;
9003 drflac* pFlac;
9004
9005 memoryStream.data = (const drflac_uint8*)pData;
9006 memoryStream.dataSize = dataSize;
9007 memoryStream.currentReadPos = 0;
9008 pFlac = drflac_open_with_metadata_private(drflac__on_read_memory, drflac__on_seek_memory, drflac__on_tell_memory, onMeta, drflac_container_unknown, &memoryStream, pUserData, pAllocationCallbacks);
9009 if (pFlac == NULL) {
9010 return NULL;
9011 }
9012
9013 pFlac->memoryStream = memoryStream;
9014
9015 /* This is an awful hack... */
9016 #ifndef DR_FLAC_NO_OGG
9017 if (pFlac->container == drflac_container_ogg)
9018 {
9019 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
9020 oggbs->pUserData = &pFlac->memoryStream;
9021 }
9022 else
9023 #endif
9024 {
9025 pFlac->bs.pUserData = &pFlac->memoryStream;
9026 }
9027
9028 return pFlac;
9029 }
9030
9031
9032
9033 DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
9034 {
9035 return drflac_open_with_metadata_private(onRead, onSeek, onTell, NULL, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
9036 }
9037 DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
9038 {
9039 return drflac_open_with_metadata_private(onRead, onSeek, onTell, NULL, container, pUserData, pUserData, pAllocationCallbacks);
9040 }
9041
9042 DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
9043 {
9044 return drflac_open_with_metadata_private(onRead, onSeek, onTell, onMeta, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
9045 }
9046 DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
9047 {
9048 return drflac_open_with_metadata_private(onRead, onSeek, onTell, onMeta, container, pUserData, pUserData, pAllocationCallbacks);
9049 }
9050
9051 DRFLAC_API void drflac_close(drflac* pFlac)
9052 {
9053 if (pFlac == NULL) {
9054 return;
9055 }
9056
9057 #ifndef DR_FLAC_NO_STDIO
9058 /*
9059 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()
9060 was used by looking at the callbacks.
9061 */
9062 if (pFlac->bs.onRead == drflac__on_read_stdio) {
9063 fclose((FILE*)pFlac->bs.pUserData);
9064 }
9065
9066 #ifndef DR_FLAC_NO_OGG
9067 /* Need to clean up Ogg streams a bit differently due to the way the bit streaming is chained. */
9068 if (pFlac->container == drflac_container_ogg) {
9069 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
9070 DRFLAC_ASSERT(pFlac->bs.onRead == drflac__on_read_ogg);
9071
9072 if (oggbs->onRead == drflac__on_read_stdio) {
9073 fclose((FILE*)oggbs->pUserData);
9074 }
9075 }
9076 #endif
9077 #endif
9078
9079 drflac__free_from_callbacks(pFlac, &pFlac->allocationCallbacks);
9080 }
9081
9082
9083 #if 0
9084 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)
9085 {
9086 drflac_uint64 i;
9087 for (i = 0; i < frameCount; ++i) {
9088 drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9089 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9090 drflac_uint32 right = left - side;
9091
9092 pOutputSamples[i*2+0] = (drflac_int32)left;
9093 pOutputSamples[i*2+1] = (drflac_int32)right;
9094 }
9095 }
9096 #endif
9097
9098 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)
9099 {
9100 drflac_uint64 i;
9101 drflac_uint64 frameCount4 = frameCount >> 2;
9102 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9103 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9104 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9105 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9106
9107 for (i = 0; i < frameCount4; ++i) {
9108 drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
9109 drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
9110 drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
9111 drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
9112
9113 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
9114 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
9115 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
9116 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
9117
9118 drflac_uint32 right0 = left0 - side0;
9119 drflac_uint32 right1 = left1 - side1;
9120 drflac_uint32 right2 = left2 - side2;
9121 drflac_uint32 right3 = left3 - side3;
9122
9123 pOutputSamples[i*8+0] = (drflac_int32)left0;
9124 pOutputSamples[i*8+1] = (drflac_int32)right0;
9125 pOutputSamples[i*8+2] = (drflac_int32)left1;
9126 pOutputSamples[i*8+3] = (drflac_int32)right1;
9127 pOutputSamples[i*8+4] = (drflac_int32)left2;
9128 pOutputSamples[i*8+5] = (drflac_int32)right2;
9129 pOutputSamples[i*8+6] = (drflac_int32)left3;
9130 pOutputSamples[i*8+7] = (drflac_int32)right3;
9131 }
9132
9133 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9134 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9135 drflac_uint32 side = pInputSamples1U32[i] << shift1;
9136 drflac_uint32 right = left - side;
9137
9138 pOutputSamples[i*2+0] = (drflac_int32)left;
9139 pOutputSamples[i*2+1] = (drflac_int32)right;
9140 }
9141 }
9142
9143 #if defined(DRFLAC_SUPPORT_SSE2)
9144 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)
9145 {
9146 drflac_uint64 i;
9147 drflac_uint64 frameCount4 = frameCount >> 2;
9148 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9149 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9150 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9151 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9152
9153 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9154
9155 for (i = 0; i < frameCount4; ++i) {
9156 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
9157 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
9158 __m128i right = _mm_sub_epi32(left, side);
9159
9160 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9161 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9162 }
9163
9164 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9165 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9166 drflac_uint32 side = pInputSamples1U32[i] << shift1;
9167 drflac_uint32 right = left - side;
9168
9169 pOutputSamples[i*2+0] = (drflac_int32)left;
9170 pOutputSamples[i*2+1] = (drflac_int32)right;
9171 }
9172 }
9173 #endif
9174
9175 #if defined(DRFLAC_SUPPORT_NEON)
9176 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)
9177 {
9178 drflac_uint64 i;
9179 drflac_uint64 frameCount4 = frameCount >> 2;
9180 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9181 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9182 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9183 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9184 int32x4_t shift0_4;
9185 int32x4_t shift1_4;
9186
9187 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9188
9189 shift0_4 = vdupq_n_s32(shift0);
9190 shift1_4 = vdupq_n_s32(shift1);
9191
9192 for (i = 0; i < frameCount4; ++i) {
9193 uint32x4_t left;
9194 uint32x4_t side;
9195 uint32x4_t right;
9196
9197 left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
9198 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
9199 right = vsubq_u32(left, side);
9200
9201 drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
9202 }
9203
9204 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9205 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9206 drflac_uint32 side = pInputSamples1U32[i] << shift1;
9207 drflac_uint32 right = left - side;
9208
9209 pOutputSamples[i*2+0] = (drflac_int32)left;
9210 pOutputSamples[i*2+1] = (drflac_int32)right;
9211 }
9212 }
9213 #endif
9214
9215 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)
9216 {
9217 #if defined(DRFLAC_SUPPORT_SSE2)
9218 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9219 drflac_read_pcm_frames_s32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9220 } else
9221 #elif defined(DRFLAC_SUPPORT_NEON)
9222 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9223 drflac_read_pcm_frames_s32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9224 } else
9225 #endif
9226 {
9227 /* Scalar fallback. */
9228 #if 0
9229 drflac_read_pcm_frames_s32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9230 #else
9231 drflac_read_pcm_frames_s32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9232 #endif
9233 }
9234 }
9235
9236
9237 #if 0
9238 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)
9239 {
9240 drflac_uint64 i;
9241 for (i = 0; i < frameCount; ++i) {
9242 drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9243 drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9244 drflac_uint32 left = right + side;
9245
9246 pOutputSamples[i*2+0] = (drflac_int32)left;
9247 pOutputSamples[i*2+1] = (drflac_int32)right;
9248 }
9249 }
9250 #endif
9251
9252 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)
9253 {
9254 drflac_uint64 i;
9255 drflac_uint64 frameCount4 = frameCount >> 2;
9256 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9257 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9258 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9259 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9260
9261 for (i = 0; i < frameCount4; ++i) {
9262 drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
9263 drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
9264 drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
9265 drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
9266
9267 drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
9268 drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
9269 drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
9270 drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
9271
9272 drflac_uint32 left0 = right0 + side0;
9273 drflac_uint32 left1 = right1 + side1;
9274 drflac_uint32 left2 = right2 + side2;
9275 drflac_uint32 left3 = right3 + side3;
9276
9277 pOutputSamples[i*8+0] = (drflac_int32)left0;
9278 pOutputSamples[i*8+1] = (drflac_int32)right0;
9279 pOutputSamples[i*8+2] = (drflac_int32)left1;
9280 pOutputSamples[i*8+3] = (drflac_int32)right1;
9281 pOutputSamples[i*8+4] = (drflac_int32)left2;
9282 pOutputSamples[i*8+5] = (drflac_int32)right2;
9283 pOutputSamples[i*8+6] = (drflac_int32)left3;
9284 pOutputSamples[i*8+7] = (drflac_int32)right3;
9285 }
9286
9287 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9288 drflac_uint32 side = pInputSamples0U32[i] << shift0;
9289 drflac_uint32 right = pInputSamples1U32[i] << shift1;
9290 drflac_uint32 left = right + side;
9291
9292 pOutputSamples[i*2+0] = (drflac_int32)left;
9293 pOutputSamples[i*2+1] = (drflac_int32)right;
9294 }
9295 }
9296
9297 #if defined(DRFLAC_SUPPORT_SSE2)
9298 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)
9299 {
9300 drflac_uint64 i;
9301 drflac_uint64 frameCount4 = frameCount >> 2;
9302 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9303 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9304 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9305 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9306
9307 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9308
9309 for (i = 0; i < frameCount4; ++i) {
9310 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
9311 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
9312 __m128i left = _mm_add_epi32(right, side);
9313
9314 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9315 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9316 }
9317
9318 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9319 drflac_uint32 side = pInputSamples0U32[i] << shift0;
9320 drflac_uint32 right = pInputSamples1U32[i] << shift1;
9321 drflac_uint32 left = right + side;
9322
9323 pOutputSamples[i*2+0] = (drflac_int32)left;
9324 pOutputSamples[i*2+1] = (drflac_int32)right;
9325 }
9326 }
9327 #endif
9328
9329 #if defined(DRFLAC_SUPPORT_NEON)
9330 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)
9331 {
9332 drflac_uint64 i;
9333 drflac_uint64 frameCount4 = frameCount >> 2;
9334 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9335 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9336 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9337 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9338 int32x4_t shift0_4;
9339 int32x4_t shift1_4;
9340
9341 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9342
9343 shift0_4 = vdupq_n_s32(shift0);
9344 shift1_4 = vdupq_n_s32(shift1);
9345
9346 for (i = 0; i < frameCount4; ++i) {
9347 uint32x4_t side;
9348 uint32x4_t right;
9349 uint32x4_t left;
9350
9351 side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
9352 right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
9353 left = vaddq_u32(right, side);
9354
9355 drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
9356 }
9357
9358 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9359 drflac_uint32 side = pInputSamples0U32[i] << shift0;
9360 drflac_uint32 right = pInputSamples1U32[i] << shift1;
9361 drflac_uint32 left = right + side;
9362
9363 pOutputSamples[i*2+0] = (drflac_int32)left;
9364 pOutputSamples[i*2+1] = (drflac_int32)right;
9365 }
9366 }
9367 #endif
9368
9369 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)
9370 {
9371 #if defined(DRFLAC_SUPPORT_SSE2)
9372 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9373 drflac_read_pcm_frames_s32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9374 } else
9375 #elif defined(DRFLAC_SUPPORT_NEON)
9376 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9377 drflac_read_pcm_frames_s32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9378 } else
9379 #endif
9380 {
9381 /* Scalar fallback. */
9382 #if 0
9383 drflac_read_pcm_frames_s32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9384 #else
9385 drflac_read_pcm_frames_s32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9386 #endif
9387 }
9388 }
9389
9390
9391 #if 0
9392 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)
9393 {
9394 for (drflac_uint64 i = 0; i < frameCount; ++i) {
9395 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9396 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9397
9398 mid = (mid << 1) | (side & 0x01);
9399
9400 pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
9401 pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
9402 }
9403 }
9404 #endif
9405
9406 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)
9407 {
9408 drflac_uint64 i;
9409 drflac_uint64 frameCount4 = frameCount >> 2;
9410 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9411 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9412 drflac_int32 shift = unusedBitsPerSample;
9413
9414 if (shift > 0) {
9415 shift -= 1;
9416 for (i = 0; i < frameCount4; ++i) {
9417 drflac_uint32 temp0L;
9418 drflac_uint32 temp1L;
9419 drflac_uint32 temp2L;
9420 drflac_uint32 temp3L;
9421 drflac_uint32 temp0R;
9422 drflac_uint32 temp1R;
9423 drflac_uint32 temp2R;
9424 drflac_uint32 temp3R;
9425
9426 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9427 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9428 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9429 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9430
9431 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9432 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9433 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9434 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9435
9436 mid0 = (mid0 << 1) | (side0 & 0x01);
9437 mid1 = (mid1 << 1) | (side1 & 0x01);
9438 mid2 = (mid2 << 1) | (side2 & 0x01);
9439 mid3 = (mid3 << 1) | (side3 & 0x01);
9440
9441 temp0L = (mid0 + side0) << shift;
9442 temp1L = (mid1 + side1) << shift;
9443 temp2L = (mid2 + side2) << shift;
9444 temp3L = (mid3 + side3) << shift;
9445
9446 temp0R = (mid0 - side0) << shift;
9447 temp1R = (mid1 - side1) << shift;
9448 temp2R = (mid2 - side2) << shift;
9449 temp3R = (mid3 - side3) << shift;
9450
9451 pOutputSamples[i*8+0] = (drflac_int32)temp0L;
9452 pOutputSamples[i*8+1] = (drflac_int32)temp0R;
9453 pOutputSamples[i*8+2] = (drflac_int32)temp1L;
9454 pOutputSamples[i*8+3] = (drflac_int32)temp1R;
9455 pOutputSamples[i*8+4] = (drflac_int32)temp2L;
9456 pOutputSamples[i*8+5] = (drflac_int32)temp2R;
9457 pOutputSamples[i*8+6] = (drflac_int32)temp3L;
9458 pOutputSamples[i*8+7] = (drflac_int32)temp3R;
9459 }
9460 } else {
9461 for (i = 0; i < frameCount4; ++i) {
9462 drflac_uint32 temp0L;
9463 drflac_uint32 temp1L;
9464 drflac_uint32 temp2L;
9465 drflac_uint32 temp3L;
9466 drflac_uint32 temp0R;
9467 drflac_uint32 temp1R;
9468 drflac_uint32 temp2R;
9469 drflac_uint32 temp3R;
9470
9471 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9472 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9473 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9474 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9475
9476 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9477 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9478 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9479 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9480
9481 mid0 = (mid0 << 1) | (side0 & 0x01);
9482 mid1 = (mid1 << 1) | (side1 & 0x01);
9483 mid2 = (mid2 << 1) | (side2 & 0x01);
9484 mid3 = (mid3 << 1) | (side3 & 0x01);
9485
9486 temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
9487 temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
9488 temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
9489 temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
9490
9491 temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
9492 temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
9493 temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
9494 temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
9495
9496 pOutputSamples[i*8+0] = (drflac_int32)temp0L;
9497 pOutputSamples[i*8+1] = (drflac_int32)temp0R;
9498 pOutputSamples[i*8+2] = (drflac_int32)temp1L;
9499 pOutputSamples[i*8+3] = (drflac_int32)temp1R;
9500 pOutputSamples[i*8+4] = (drflac_int32)temp2L;
9501 pOutputSamples[i*8+5] = (drflac_int32)temp2R;
9502 pOutputSamples[i*8+6] = (drflac_int32)temp3L;
9503 pOutputSamples[i*8+7] = (drflac_int32)temp3R;
9504 }
9505 }
9506
9507 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9508 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9509 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9510
9511 mid = (mid << 1) | (side & 0x01);
9512
9513 pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
9514 pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
9515 }
9516 }
9517
9518 #if defined(DRFLAC_SUPPORT_SSE2)
9519 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)
9520 {
9521 drflac_uint64 i;
9522 drflac_uint64 frameCount4 = frameCount >> 2;
9523 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9524 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9525 drflac_int32 shift = unusedBitsPerSample;
9526
9527 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9528
9529 if (shift == 0) {
9530 for (i = 0; i < frameCount4; ++i) {
9531 __m128i mid;
9532 __m128i side;
9533 __m128i left;
9534 __m128i right;
9535
9536 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9537 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9538
9539 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
9540
9541 left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
9542 right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
9543
9544 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9545 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9546 }
9547
9548 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9549 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9550 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9551
9552 mid = (mid << 1) | (side & 0x01);
9553
9554 pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
9555 pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
9556 }
9557 } else {
9558 shift -= 1;
9559 for (i = 0; i < frameCount4; ++i) {
9560 __m128i mid;
9561 __m128i side;
9562 __m128i left;
9563 __m128i right;
9564
9565 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9566 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9567
9568 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
9569
9570 left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
9571 right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
9572
9573 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9574 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9575 }
9576
9577 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9578 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9579 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9580
9581 mid = (mid << 1) | (side & 0x01);
9582
9583 pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
9584 pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
9585 }
9586 }
9587 }
9588 #endif
9589
9590 #if defined(DRFLAC_SUPPORT_NEON)
9591 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)
9592 {
9593 drflac_uint64 i;
9594 drflac_uint64 frameCount4 = frameCount >> 2;
9595 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9596 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9597 drflac_int32 shift = unusedBitsPerSample;
9598 int32x4_t wbpsShift0_4; /* wbps = Wasted Bits Per Sample */
9599 int32x4_t wbpsShift1_4; /* wbps = Wasted Bits Per Sample */
9600 uint32x4_t one4;
9601
9602 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9603
9604 wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9605 wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9606 one4 = vdupq_n_u32(1);
9607
9608 if (shift == 0) {
9609 for (i = 0; i < frameCount4; ++i) {
9610 uint32x4_t mid;
9611 uint32x4_t side;
9612 int32x4_t left;
9613 int32x4_t right;
9614
9615 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
9616 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
9617
9618 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
9619
9620 left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
9621 right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
9622
9623 drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
9624 }
9625
9626 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9627 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9628 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9629
9630 mid = (mid << 1) | (side & 0x01);
9631
9632 pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
9633 pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
9634 }
9635 } else {
9636 int32x4_t shift4;
9637
9638 shift -= 1;
9639 shift4 = vdupq_n_s32(shift);
9640
9641 for (i = 0; i < frameCount4; ++i) {
9642 uint32x4_t mid;
9643 uint32x4_t side;
9644 int32x4_t left;
9645 int32x4_t right;
9646
9647 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
9648 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
9649
9650 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
9651
9652 left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
9653 right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
9654
9655 drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
9656 }
9657
9658 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9659 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9660 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9661
9662 mid = (mid << 1) | (side & 0x01);
9663
9664 pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
9665 pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
9666 }
9667 }
9668 }
9669 #endif
9670
9671 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)
9672 {
9673 #if defined(DRFLAC_SUPPORT_SSE2)
9674 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9675 drflac_read_pcm_frames_s32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9676 } else
9677 #elif defined(DRFLAC_SUPPORT_NEON)
9678 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9679 drflac_read_pcm_frames_s32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9680 } else
9681 #endif
9682 {
9683 /* Scalar fallback. */
9684 #if 0
9685 drflac_read_pcm_frames_s32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9686 #else
9687 drflac_read_pcm_frames_s32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9688 #endif
9689 }
9690 }
9691
9692
9693 #if 0
9694 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)
9695 {
9696 for (drflac_uint64 i = 0; i < frameCount; ++i) {
9697 pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample));
9698 pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample));
9699 }
9700 }
9701 #endif
9702
9703 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)
9704 {
9705 drflac_uint64 i;
9706 drflac_uint64 frameCount4 = frameCount >> 2;
9707 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9708 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9709 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9710 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9711
9712 for (i = 0; i < frameCount4; ++i) {
9713 drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
9714 drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
9715 drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
9716 drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
9717
9718 drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
9719 drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
9720 drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
9721 drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
9722
9723 pOutputSamples[i*8+0] = (drflac_int32)tempL0;
9724 pOutputSamples[i*8+1] = (drflac_int32)tempR0;
9725 pOutputSamples[i*8+2] = (drflac_int32)tempL1;
9726 pOutputSamples[i*8+3] = (drflac_int32)tempR1;
9727 pOutputSamples[i*8+4] = (drflac_int32)tempL2;
9728 pOutputSamples[i*8+5] = (drflac_int32)tempR2;
9729 pOutputSamples[i*8+6] = (drflac_int32)tempL3;
9730 pOutputSamples[i*8+7] = (drflac_int32)tempR3;
9731 }
9732
9733 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9734 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
9735 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
9736 }
9737 }
9738
9739 #if defined(DRFLAC_SUPPORT_SSE2)
9740 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)
9741 {
9742 drflac_uint64 i;
9743 drflac_uint64 frameCount4 = frameCount >> 2;
9744 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9745 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9746 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9747 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9748
9749 for (i = 0; i < frameCount4; ++i) {
9750 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
9751 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
9752
9753 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9754 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9755 }
9756
9757 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9758 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
9759 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
9760 }
9761 }
9762 #endif
9763
9764 #if defined(DRFLAC_SUPPORT_NEON)
9765 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)
9766 {
9767 drflac_uint64 i;
9768 drflac_uint64 frameCount4 = frameCount >> 2;
9769 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9770 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9771 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9772 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9773
9774 int32x4_t shift4_0 = vdupq_n_s32(shift0);
9775 int32x4_t shift4_1 = vdupq_n_s32(shift1);
9776
9777 for (i = 0; i < frameCount4; ++i) {
9778 int32x4_t left;
9779 int32x4_t right;
9780
9781 left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift4_0));
9782 right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift4_1));
9783
9784 drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
9785 }
9786
9787 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9788 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
9789 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
9790 }
9791 }
9792 #endif
9793
9794 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)
9795 {
9796 #if defined(DRFLAC_SUPPORT_SSE2)
9797 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9798 drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9799 } else
9800 #elif defined(DRFLAC_SUPPORT_NEON)
9801 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9802 drflac_read_pcm_frames_s32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9803 } else
9804 #endif
9805 {
9806 /* Scalar fallback. */
9807 #if 0
9808 drflac_read_pcm_frames_s32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9809 #else
9810 drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9811 #endif
9812 }
9813 }
9814
9815
9816 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut)
9817 {
9818 drflac_uint64 framesRead;
9819 drflac_uint32 unusedBitsPerSample;
9820
9821 if (pFlac == NULL || framesToRead == 0) {
9822 return 0;
9823 }
9824
9825 if (pBufferOut == NULL) {
9826 return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
9827 }
9828
9829 DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
9830 unusedBitsPerSample = 32 - pFlac->bitsPerSample;
9831
9832 framesRead = 0;
9833 while (framesToRead > 0) {
9834 /* If we've run out of samples in this frame, go to the next. */
9835 if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
9836 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
9837 break; /* Couldn't read the next frame, so just break from the loop and return. */
9838 }
9839 } else {
9840 unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
9841 drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
9842 drflac_uint64 frameCountThisIteration = framesToRead;
9843
9844 if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
9845 frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
9846 }
9847
9848 if (channelCount == 2) {
9849 const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
9850 const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
9851
9852 switch (pFlac->currentFLACFrame.header.channelAssignment)
9853 {
9854 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
9855 {
9856 drflac_read_pcm_frames_s32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
9857 } break;
9858
9859 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
9860 {
9861 drflac_read_pcm_frames_s32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
9862 } break;
9863
9864 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
9865 {
9866 drflac_read_pcm_frames_s32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
9867 } break;
9868
9869 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
9870 default:
9871 {
9872 drflac_read_pcm_frames_s32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
9873 } break;
9874 }
9875 } else {
9876 /* Generic interleaving. */
9877 drflac_uint64 i;
9878 for (i = 0; i < frameCountThisIteration; ++i) {
9879 unsigned int j;
9880 for (j = 0; j < channelCount; ++j) {
9881 pBufferOut[(i*channelCount)+j] = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
9882 }
9883 }
9884 }
9885
9886 framesRead += frameCountThisIteration;
9887 pBufferOut += frameCountThisIteration * channelCount;
9888 framesToRead -= frameCountThisIteration;
9889 pFlac->currentPCMFrame += frameCountThisIteration;
9890 pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
9891 }
9892 }
9893
9894 return framesRead;
9895 }
9896
9897
9898 #if 0
9899 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)
9900 {
9901 drflac_uint64 i;
9902 for (i = 0; i < frameCount; ++i) {
9903 drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9904 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9905 drflac_uint32 right = left - side;
9906
9907 left >>= 16;
9908 right >>= 16;
9909
9910 pOutputSamples[i*2+0] = (drflac_int16)left;
9911 pOutputSamples[i*2+1] = (drflac_int16)right;
9912 }
9913 }
9914 #endif
9915
9916 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)
9917 {
9918 drflac_uint64 i;
9919 drflac_uint64 frameCount4 = frameCount >> 2;
9920 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9921 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9922 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9923 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9924
9925 for (i = 0; i < frameCount4; ++i) {
9926 drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
9927 drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
9928 drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
9929 drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
9930
9931 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
9932 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
9933 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
9934 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
9935
9936 drflac_uint32 right0 = left0 - side0;
9937 drflac_uint32 right1 = left1 - side1;
9938 drflac_uint32 right2 = left2 - side2;
9939 drflac_uint32 right3 = left3 - side3;
9940
9941 left0 >>= 16;
9942 left1 >>= 16;
9943 left2 >>= 16;
9944 left3 >>= 16;
9945
9946 right0 >>= 16;
9947 right1 >>= 16;
9948 right2 >>= 16;
9949 right3 >>= 16;
9950
9951 pOutputSamples[i*8+0] = (drflac_int16)left0;
9952 pOutputSamples[i*8+1] = (drflac_int16)right0;
9953 pOutputSamples[i*8+2] = (drflac_int16)left1;
9954 pOutputSamples[i*8+3] = (drflac_int16)right1;
9955 pOutputSamples[i*8+4] = (drflac_int16)left2;
9956 pOutputSamples[i*8+5] = (drflac_int16)right2;
9957 pOutputSamples[i*8+6] = (drflac_int16)left3;
9958 pOutputSamples[i*8+7] = (drflac_int16)right3;
9959 }
9960
9961 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9962 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9963 drflac_uint32 side = pInputSamples1U32[i] << shift1;
9964 drflac_uint32 right = left - side;
9965
9966 left >>= 16;
9967 right >>= 16;
9968
9969 pOutputSamples[i*2+0] = (drflac_int16)left;
9970 pOutputSamples[i*2+1] = (drflac_int16)right;
9971 }
9972 }
9973
9974 #if defined(DRFLAC_SUPPORT_SSE2)
9975 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)
9976 {
9977 drflac_uint64 i;
9978 drflac_uint64 frameCount4 = frameCount >> 2;
9979 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9980 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9981 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9982 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9983
9984 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9985
9986 for (i = 0; i < frameCount4; ++i) {
9987 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
9988 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
9989 __m128i right = _mm_sub_epi32(left, side);
9990
9991 left = _mm_srai_epi32(left, 16);
9992 right = _mm_srai_epi32(right, 16);
9993
9994 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
9995 }
9996
9997 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9998 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9999 drflac_uint32 side = pInputSamples1U32[i] << shift1;
10000 drflac_uint32 right = left - side;
10001
10002 left >>= 16;
10003 right >>= 16;
10004
10005 pOutputSamples[i*2+0] = (drflac_int16)left;
10006 pOutputSamples[i*2+1] = (drflac_int16)right;
10007 }
10008 }
10009 #endif
10010
10011 #if defined(DRFLAC_SUPPORT_NEON)
10012 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)
10013 {
10014 drflac_uint64 i;
10015 drflac_uint64 frameCount4 = frameCount >> 2;
10016 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10017 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10018 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10019 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10020 int32x4_t shift0_4;
10021 int32x4_t shift1_4;
10022
10023 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10024
10025 shift0_4 = vdupq_n_s32(shift0);
10026 shift1_4 = vdupq_n_s32(shift1);
10027
10028 for (i = 0; i < frameCount4; ++i) {
10029 uint32x4_t left;
10030 uint32x4_t side;
10031 uint32x4_t right;
10032
10033 left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
10034 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
10035 right = vsubq_u32(left, side);
10036
10037 left = vshrq_n_u32(left, 16);
10038 right = vshrq_n_u32(right, 16);
10039
10040 drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
10041 }
10042
10043 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10044 drflac_uint32 left = pInputSamples0U32[i] << shift0;
10045 drflac_uint32 side = pInputSamples1U32[i] << shift1;
10046 drflac_uint32 right = left - side;
10047
10048 left >>= 16;
10049 right >>= 16;
10050
10051 pOutputSamples[i*2+0] = (drflac_int16)left;
10052 pOutputSamples[i*2+1] = (drflac_int16)right;
10053 }
10054 }
10055 #endif
10056
10057 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)
10058 {
10059 #if defined(DRFLAC_SUPPORT_SSE2)
10060 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10061 drflac_read_pcm_frames_s16__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10062 } else
10063 #elif defined(DRFLAC_SUPPORT_NEON)
10064 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10065 drflac_read_pcm_frames_s16__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10066 } else
10067 #endif
10068 {
10069 /* Scalar fallback. */
10070 #if 0
10071 drflac_read_pcm_frames_s16__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10072 #else
10073 drflac_read_pcm_frames_s16__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10074 #endif
10075 }
10076 }
10077
10078
10079 #if 0
10080 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)
10081 {
10082 drflac_uint64 i;
10083 for (i = 0; i < frameCount; ++i) {
10084 drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10085 drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10086 drflac_uint32 left = right + side;
10087
10088 left >>= 16;
10089 right >>= 16;
10090
10091 pOutputSamples[i*2+0] = (drflac_int16)left;
10092 pOutputSamples[i*2+1] = (drflac_int16)right;
10093 }
10094 }
10095 #endif
10096
10097 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)
10098 {
10099 drflac_uint64 i;
10100 drflac_uint64 frameCount4 = frameCount >> 2;
10101 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10102 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10103 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10104 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10105
10106 for (i = 0; i < frameCount4; ++i) {
10107 drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
10108 drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
10109 drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
10110 drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
10111
10112 drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
10113 drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
10114 drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
10115 drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
10116
10117 drflac_uint32 left0 = right0 + side0;
10118 drflac_uint32 left1 = right1 + side1;
10119 drflac_uint32 left2 = right2 + side2;
10120 drflac_uint32 left3 = right3 + side3;
10121
10122 left0 >>= 16;
10123 left1 >>= 16;
10124 left2 >>= 16;
10125 left3 >>= 16;
10126
10127 right0 >>= 16;
10128 right1 >>= 16;
10129 right2 >>= 16;
10130 right3 >>= 16;
10131
10132 pOutputSamples[i*8+0] = (drflac_int16)left0;
10133 pOutputSamples[i*8+1] = (drflac_int16)right0;
10134 pOutputSamples[i*8+2] = (drflac_int16)left1;
10135 pOutputSamples[i*8+3] = (drflac_int16)right1;
10136 pOutputSamples[i*8+4] = (drflac_int16)left2;
10137 pOutputSamples[i*8+5] = (drflac_int16)right2;
10138 pOutputSamples[i*8+6] = (drflac_int16)left3;
10139 pOutputSamples[i*8+7] = (drflac_int16)right3;
10140 }
10141
10142 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10143 drflac_uint32 side = pInputSamples0U32[i] << shift0;
10144 drflac_uint32 right = pInputSamples1U32[i] << shift1;
10145 drflac_uint32 left = right + side;
10146
10147 left >>= 16;
10148 right >>= 16;
10149
10150 pOutputSamples[i*2+0] = (drflac_int16)left;
10151 pOutputSamples[i*2+1] = (drflac_int16)right;
10152 }
10153 }
10154
10155 #if defined(DRFLAC_SUPPORT_SSE2)
10156 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)
10157 {
10158 drflac_uint64 i;
10159 drflac_uint64 frameCount4 = frameCount >> 2;
10160 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10161 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10162 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10163 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10164
10165 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10166
10167 for (i = 0; i < frameCount4; ++i) {
10168 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
10169 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
10170 __m128i left = _mm_add_epi32(right, side);
10171
10172 left = _mm_srai_epi32(left, 16);
10173 right = _mm_srai_epi32(right, 16);
10174
10175 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
10176 }
10177
10178 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10179 drflac_uint32 side = pInputSamples0U32[i] << shift0;
10180 drflac_uint32 right = pInputSamples1U32[i] << shift1;
10181 drflac_uint32 left = right + side;
10182
10183 left >>= 16;
10184 right >>= 16;
10185
10186 pOutputSamples[i*2+0] = (drflac_int16)left;
10187 pOutputSamples[i*2+1] = (drflac_int16)right;
10188 }
10189 }
10190 #endif
10191
10192 #if defined(DRFLAC_SUPPORT_NEON)
10193 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)
10194 {
10195 drflac_uint64 i;
10196 drflac_uint64 frameCount4 = frameCount >> 2;
10197 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10198 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10199 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10200 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10201 int32x4_t shift0_4;
10202 int32x4_t shift1_4;
10203
10204 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10205
10206 shift0_4 = vdupq_n_s32(shift0);
10207 shift1_4 = vdupq_n_s32(shift1);
10208
10209 for (i = 0; i < frameCount4; ++i) {
10210 uint32x4_t side;
10211 uint32x4_t right;
10212 uint32x4_t left;
10213
10214 side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
10215 right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
10216 left = vaddq_u32(right, side);
10217
10218 left = vshrq_n_u32(left, 16);
10219 right = vshrq_n_u32(right, 16);
10220
10221 drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
10222 }
10223
10224 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10225 drflac_uint32 side = pInputSamples0U32[i] << shift0;
10226 drflac_uint32 right = pInputSamples1U32[i] << shift1;
10227 drflac_uint32 left = right + side;
10228
10229 left >>= 16;
10230 right >>= 16;
10231
10232 pOutputSamples[i*2+0] = (drflac_int16)left;
10233 pOutputSamples[i*2+1] = (drflac_int16)right;
10234 }
10235 }
10236 #endif
10237
10238 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)
10239 {
10240 #if defined(DRFLAC_SUPPORT_SSE2)
10241 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10242 drflac_read_pcm_frames_s16__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10243 } else
10244 #elif defined(DRFLAC_SUPPORT_NEON)
10245 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10246 drflac_read_pcm_frames_s16__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10247 } else
10248 #endif
10249 {
10250 /* Scalar fallback. */
10251 #if 0
10252 drflac_read_pcm_frames_s16__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10253 #else
10254 drflac_read_pcm_frames_s16__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10255 #endif
10256 }
10257 }
10258
10259
10260 #if 0
10261 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)
10262 {
10263 for (drflac_uint64 i = 0; i < frameCount; ++i) {
10264 drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10265 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10266
10267 mid = (mid << 1) | (side & 0x01);
10268
10269 pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
10270 pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
10271 }
10272 }
10273 #endif
10274
10275 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)
10276 {
10277 drflac_uint64 i;
10278 drflac_uint64 frameCount4 = frameCount >> 2;
10279 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10280 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10281 drflac_uint32 shift = unusedBitsPerSample;
10282
10283 if (shift > 0) {
10284 shift -= 1;
10285 for (i = 0; i < frameCount4; ++i) {
10286 drflac_uint32 temp0L;
10287 drflac_uint32 temp1L;
10288 drflac_uint32 temp2L;
10289 drflac_uint32 temp3L;
10290 drflac_uint32 temp0R;
10291 drflac_uint32 temp1R;
10292 drflac_uint32 temp2R;
10293 drflac_uint32 temp3R;
10294
10295 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10296 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10297 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10298 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10299
10300 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10301 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10302 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10303 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10304
10305 mid0 = (mid0 << 1) | (side0 & 0x01);
10306 mid1 = (mid1 << 1) | (side1 & 0x01);
10307 mid2 = (mid2 << 1) | (side2 & 0x01);
10308 mid3 = (mid3 << 1) | (side3 & 0x01);
10309
10310 temp0L = (mid0 + side0) << shift;
10311 temp1L = (mid1 + side1) << shift;
10312 temp2L = (mid2 + side2) << shift;
10313 temp3L = (mid3 + side3) << shift;
10314
10315 temp0R = (mid0 - side0) << shift;
10316 temp1R = (mid1 - side1) << shift;
10317 temp2R = (mid2 - side2) << shift;
10318 temp3R = (mid3 - side3) << shift;
10319
10320 temp0L >>= 16;
10321 temp1L >>= 16;
10322 temp2L >>= 16;
10323 temp3L >>= 16;
10324
10325 temp0R >>= 16;
10326 temp1R >>= 16;
10327 temp2R >>= 16;
10328 temp3R >>= 16;
10329
10330 pOutputSamples[i*8+0] = (drflac_int16)temp0L;
10331 pOutputSamples[i*8+1] = (drflac_int16)temp0R;
10332 pOutputSamples[i*8+2] = (drflac_int16)temp1L;
10333 pOutputSamples[i*8+3] = (drflac_int16)temp1R;
10334 pOutputSamples[i*8+4] = (drflac_int16)temp2L;
10335 pOutputSamples[i*8+5] = (drflac_int16)temp2R;
10336 pOutputSamples[i*8+6] = (drflac_int16)temp3L;
10337 pOutputSamples[i*8+7] = (drflac_int16)temp3R;
10338 }
10339 } else {
10340 for (i = 0; i < frameCount4; ++i) {
10341 drflac_uint32 temp0L;
10342 drflac_uint32 temp1L;
10343 drflac_uint32 temp2L;
10344 drflac_uint32 temp3L;
10345 drflac_uint32 temp0R;
10346 drflac_uint32 temp1R;
10347 drflac_uint32 temp2R;
10348 drflac_uint32 temp3R;
10349
10350 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10351 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10352 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10353 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10354
10355 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10356 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10357 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10358 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10359
10360 mid0 = (mid0 << 1) | (side0 & 0x01);
10361 mid1 = (mid1 << 1) | (side1 & 0x01);
10362 mid2 = (mid2 << 1) | (side2 & 0x01);
10363 mid3 = (mid3 << 1) | (side3 & 0x01);
10364
10365 temp0L = ((drflac_int32)(mid0 + side0) >> 1);
10366 temp1L = ((drflac_int32)(mid1 + side1) >> 1);
10367 temp2L = ((drflac_int32)(mid2 + side2) >> 1);
10368 temp3L = ((drflac_int32)(mid3 + side3) >> 1);
10369
10370 temp0R = ((drflac_int32)(mid0 - side0) >> 1);
10371 temp1R = ((drflac_int32)(mid1 - side1) >> 1);
10372 temp2R = ((drflac_int32)(mid2 - side2) >> 1);
10373 temp3R = ((drflac_int32)(mid3 - side3) >> 1);
10374
10375 temp0L >>= 16;
10376 temp1L >>= 16;
10377 temp2L >>= 16;
10378 temp3L >>= 16;
10379
10380 temp0R >>= 16;
10381 temp1R >>= 16;
10382 temp2R >>= 16;
10383 temp3R >>= 16;
10384
10385 pOutputSamples[i*8+0] = (drflac_int16)temp0L;
10386 pOutputSamples[i*8+1] = (drflac_int16)temp0R;
10387 pOutputSamples[i*8+2] = (drflac_int16)temp1L;
10388 pOutputSamples[i*8+3] = (drflac_int16)temp1R;
10389 pOutputSamples[i*8+4] = (drflac_int16)temp2L;
10390 pOutputSamples[i*8+5] = (drflac_int16)temp2R;
10391 pOutputSamples[i*8+6] = (drflac_int16)temp3L;
10392 pOutputSamples[i*8+7] = (drflac_int16)temp3R;
10393 }
10394 }
10395
10396 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10397 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10398 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10399
10400 mid = (mid << 1) | (side & 0x01);
10401
10402 pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
10403 pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
10404 }
10405 }
10406
10407 #if defined(DRFLAC_SUPPORT_SSE2)
10408 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)
10409 {
10410 drflac_uint64 i;
10411 drflac_uint64 frameCount4 = frameCount >> 2;
10412 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10413 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10414 drflac_uint32 shift = unusedBitsPerSample;
10415
10416 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10417
10418 if (shift == 0) {
10419 for (i = 0; i < frameCount4; ++i) {
10420 __m128i mid;
10421 __m128i side;
10422 __m128i left;
10423 __m128i right;
10424
10425 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10426 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10427
10428 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
10429
10430 left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
10431 right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
10432
10433 left = _mm_srai_epi32(left, 16);
10434 right = _mm_srai_epi32(right, 16);
10435
10436 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
10437 }
10438
10439 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10440 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10441 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10442
10443 mid = (mid << 1) | (side & 0x01);
10444
10445 pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
10446 pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
10447 }
10448 } else {
10449 shift -= 1;
10450 for (i = 0; i < frameCount4; ++i) {
10451 __m128i mid;
10452 __m128i side;
10453 __m128i left;
10454 __m128i right;
10455
10456 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10457 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10458
10459 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
10460
10461 left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
10462 right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
10463
10464 left = _mm_srai_epi32(left, 16);
10465 right = _mm_srai_epi32(right, 16);
10466
10467 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
10468 }
10469
10470 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10471 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10472 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10473
10474 mid = (mid << 1) | (side & 0x01);
10475
10476 pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
10477 pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
10478 }
10479 }
10480 }
10481 #endif
10482
10483 #if defined(DRFLAC_SUPPORT_NEON)
10484 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)
10485 {
10486 drflac_uint64 i;
10487 drflac_uint64 frameCount4 = frameCount >> 2;
10488 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10489 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10490 drflac_uint32 shift = unusedBitsPerSample;
10491 int32x4_t wbpsShift0_4; /* wbps = Wasted Bits Per Sample */
10492 int32x4_t wbpsShift1_4; /* wbps = Wasted Bits Per Sample */
10493
10494 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10495
10496 wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10497 wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10498
10499 if (shift == 0) {
10500 for (i = 0; i < frameCount4; ++i) {
10501 uint32x4_t mid;
10502 uint32x4_t side;
10503 int32x4_t left;
10504 int32x4_t right;
10505
10506 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
10507 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
10508
10509 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
10510
10511 left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
10512 right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
10513
10514 left = vshrq_n_s32(left, 16);
10515 right = vshrq_n_s32(right, 16);
10516
10517 drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
10518 }
10519
10520 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10521 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10522 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10523
10524 mid = (mid << 1) | (side & 0x01);
10525
10526 pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
10527 pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
10528 }
10529 } else {
10530 int32x4_t shift4;
10531
10532 shift -= 1;
10533 shift4 = vdupq_n_s32(shift);
10534
10535 for (i = 0; i < frameCount4; ++i) {
10536 uint32x4_t mid;
10537 uint32x4_t side;
10538 int32x4_t left;
10539 int32x4_t right;
10540
10541 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
10542 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
10543
10544 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
10545
10546 left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
10547 right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
10548
10549 left = vshrq_n_s32(left, 16);
10550 right = vshrq_n_s32(right, 16);
10551
10552 drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
10553 }
10554
10555 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10556 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10557 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10558
10559 mid = (mid << 1) | (side & 0x01);
10560
10561 pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
10562 pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
10563 }
10564 }
10565 }
10566 #endif
10567
10568 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)
10569 {
10570 #if defined(DRFLAC_SUPPORT_SSE2)
10571 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10572 drflac_read_pcm_frames_s16__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10573 } else
10574 #elif defined(DRFLAC_SUPPORT_NEON)
10575 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10576 drflac_read_pcm_frames_s16__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10577 } else
10578 #endif
10579 {
10580 /* Scalar fallback. */
10581 #if 0
10582 drflac_read_pcm_frames_s16__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10583 #else
10584 drflac_read_pcm_frames_s16__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10585 #endif
10586 }
10587 }
10588
10589
10590 #if 0
10591 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)
10592 {
10593 for (drflac_uint64 i = 0; i < frameCount; ++i) {
10594 pOutputSamples[i*2+0] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) >> 16);
10595 pOutputSamples[i*2+1] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) >> 16);
10596 }
10597 }
10598 #endif
10599
10600 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)
10601 {
10602 drflac_uint64 i;
10603 drflac_uint64 frameCount4 = frameCount >> 2;
10604 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10605 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10606 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10607 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10608
10609 for (i = 0; i < frameCount4; ++i) {
10610 drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
10611 drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
10612 drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
10613 drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
10614
10615 drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
10616 drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
10617 drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
10618 drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
10619
10620 tempL0 >>= 16;
10621 tempL1 >>= 16;
10622 tempL2 >>= 16;
10623 tempL3 >>= 16;
10624
10625 tempR0 >>= 16;
10626 tempR1 >>= 16;
10627 tempR2 >>= 16;
10628 tempR3 >>= 16;
10629
10630 pOutputSamples[i*8+0] = (drflac_int16)tempL0;
10631 pOutputSamples[i*8+1] = (drflac_int16)tempR0;
10632 pOutputSamples[i*8+2] = (drflac_int16)tempL1;
10633 pOutputSamples[i*8+3] = (drflac_int16)tempR1;
10634 pOutputSamples[i*8+4] = (drflac_int16)tempL2;
10635 pOutputSamples[i*8+5] = (drflac_int16)tempR2;
10636 pOutputSamples[i*8+6] = (drflac_int16)tempL3;
10637 pOutputSamples[i*8+7] = (drflac_int16)tempR3;
10638 }
10639
10640 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10641 pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
10642 pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
10643 }
10644 }
10645
10646 #if defined(DRFLAC_SUPPORT_SSE2)
10647 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)
10648 {
10649 drflac_uint64 i;
10650 drflac_uint64 frameCount4 = frameCount >> 2;
10651 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10652 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10653 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10654 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10655
10656 for (i = 0; i < frameCount4; ++i) {
10657 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
10658 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
10659
10660 left = _mm_srai_epi32(left, 16);
10661 right = _mm_srai_epi32(right, 16);
10662
10663 /* 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. */
10664 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
10665 }
10666
10667 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10668 pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
10669 pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
10670 }
10671 }
10672 #endif
10673
10674 #if defined(DRFLAC_SUPPORT_NEON)
10675 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)
10676 {
10677 drflac_uint64 i;
10678 drflac_uint64 frameCount4 = frameCount >> 2;
10679 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10680 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10681 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10682 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10683
10684 int32x4_t shift0_4 = vdupq_n_s32(shift0);
10685 int32x4_t shift1_4 = vdupq_n_s32(shift1);
10686
10687 for (i = 0; i < frameCount4; ++i) {
10688 int32x4_t left;
10689 int32x4_t right;
10690
10691 left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
10692 right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
10693
10694 left = vshrq_n_s32(left, 16);
10695 right = vshrq_n_s32(right, 16);
10696
10697 drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
10698 }
10699
10700 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10701 pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
10702 pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
10703 }
10704 }
10705 #endif
10706
10707 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)
10708 {
10709 #if defined(DRFLAC_SUPPORT_SSE2)
10710 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10711 drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10712 } else
10713 #elif defined(DRFLAC_SUPPORT_NEON)
10714 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10715 drflac_read_pcm_frames_s16__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10716 } else
10717 #endif
10718 {
10719 /* Scalar fallback. */
10720 #if 0
10721 drflac_read_pcm_frames_s16__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10722 #else
10723 drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10724 #endif
10725 }
10726 }
10727
10728 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut)
10729 {
10730 drflac_uint64 framesRead;
10731 drflac_uint32 unusedBitsPerSample;
10732
10733 if (pFlac == NULL || framesToRead == 0) {
10734 return 0;
10735 }
10736
10737 if (pBufferOut == NULL) {
10738 return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
10739 }
10740
10741 DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
10742 unusedBitsPerSample = 32 - pFlac->bitsPerSample;
10743
10744 framesRead = 0;
10745 while (framesToRead > 0) {
10746 /* If we've run out of samples in this frame, go to the next. */
10747 if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
10748 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
10749 break; /* Couldn't read the next frame, so just break from the loop and return. */
10750 }
10751 } else {
10752 unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
10753 drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
10754 drflac_uint64 frameCountThisIteration = framesToRead;
10755
10756 if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
10757 frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
10758 }
10759
10760 if (channelCount == 2) {
10761 const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
10762 const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
10763
10764 switch (pFlac->currentFLACFrame.header.channelAssignment)
10765 {
10766 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
10767 {
10768 drflac_read_pcm_frames_s16__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
10769 } break;
10770
10771 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
10772 {
10773 drflac_read_pcm_frames_s16__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
10774 } break;
10775
10776 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
10777 {
10778 drflac_read_pcm_frames_s16__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
10779 } break;
10780
10781 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
10782 default:
10783 {
10784 drflac_read_pcm_frames_s16__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
10785 } break;
10786 }
10787 } else {
10788 /* Generic interleaving. */
10789 drflac_uint64 i;
10790 for (i = 0; i < frameCountThisIteration; ++i) {
10791 unsigned int j;
10792 for (j = 0; j < channelCount; ++j) {
10793 drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
10794 pBufferOut[(i*channelCount)+j] = (drflac_int16)(sampleS32 >> 16);
10795 }
10796 }
10797 }
10798
10799 framesRead += frameCountThisIteration;
10800 pBufferOut += frameCountThisIteration * channelCount;
10801 framesToRead -= frameCountThisIteration;
10802 pFlac->currentPCMFrame += frameCountThisIteration;
10803 pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
10804 }
10805 }
10806
10807 return framesRead;
10808 }
10809
10810
10811 #if 0
10812 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)
10813 {
10814 drflac_uint64 i;
10815 for (i = 0; i < frameCount; ++i) {
10816 drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10817 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10818 drflac_uint32 right = left - side;
10819
10820 pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0);
10821 pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
10822 }
10823 }
10824 #endif
10825
10826 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)
10827 {
10828 drflac_uint64 i;
10829 drflac_uint64 frameCount4 = frameCount >> 2;
10830 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10831 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10832 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10833 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10834
10835 float factor = 1 / 2147483648.0;
10836
10837 for (i = 0; i < frameCount4; ++i) {
10838 drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
10839 drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
10840 drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
10841 drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
10842
10843 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
10844 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
10845 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
10846 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
10847
10848 drflac_uint32 right0 = left0 - side0;
10849 drflac_uint32 right1 = left1 - side1;
10850 drflac_uint32 right2 = left2 - side2;
10851 drflac_uint32 right3 = left3 - side3;
10852
10853 pOutputSamples[i*8+0] = (drflac_int32)left0 * factor;
10854 pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
10855 pOutputSamples[i*8+2] = (drflac_int32)left1 * factor;
10856 pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
10857 pOutputSamples[i*8+4] = (drflac_int32)left2 * factor;
10858 pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
10859 pOutputSamples[i*8+6] = (drflac_int32)left3 * factor;
10860 pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
10861 }
10862
10863 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10864 drflac_uint32 left = pInputSamples0U32[i] << shift0;
10865 drflac_uint32 side = pInputSamples1U32[i] << shift1;
10866 drflac_uint32 right = left - side;
10867
10868 pOutputSamples[i*2+0] = (drflac_int32)left * factor;
10869 pOutputSamples[i*2+1] = (drflac_int32)right * factor;
10870 }
10871 }
10872
10873 #if defined(DRFLAC_SUPPORT_SSE2)
10874 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)
10875 {
10876 drflac_uint64 i;
10877 drflac_uint64 frameCount4 = frameCount >> 2;
10878 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10879 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10880 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
10881 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
10882 __m128 factor;
10883
10884 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10885
10886 factor = _mm_set1_ps(1.0f / 8388608.0f);
10887
10888 for (i = 0; i < frameCount4; ++i) {
10889 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
10890 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
10891 __m128i right = _mm_sub_epi32(left, side);
10892 __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
10893 __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
10894
10895 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
10896 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
10897 }
10898
10899 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10900 drflac_uint32 left = pInputSamples0U32[i] << shift0;
10901 drflac_uint32 side = pInputSamples1U32[i] << shift1;
10902 drflac_uint32 right = left - side;
10903
10904 pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
10905 pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
10906 }
10907 }
10908 #endif
10909
10910 #if defined(DRFLAC_SUPPORT_NEON)
10911 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)
10912 {
10913 drflac_uint64 i;
10914 drflac_uint64 frameCount4 = frameCount >> 2;
10915 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10916 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10917 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
10918 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
10919 float32x4_t factor4;
10920 int32x4_t shift0_4;
10921 int32x4_t shift1_4;
10922
10923 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10924
10925 factor4 = vdupq_n_f32(1.0f / 8388608.0f);
10926 shift0_4 = vdupq_n_s32(shift0);
10927 shift1_4 = vdupq_n_s32(shift1);
10928
10929 for (i = 0; i < frameCount4; ++i) {
10930 uint32x4_t left;
10931 uint32x4_t side;
10932 uint32x4_t right;
10933 float32x4_t leftf;
10934 float32x4_t rightf;
10935
10936 left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
10937 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
10938 right = vsubq_u32(left, side);
10939 leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
10940 rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
10941
10942 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
10943 }
10944
10945 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10946 drflac_uint32 left = pInputSamples0U32[i] << shift0;
10947 drflac_uint32 side = pInputSamples1U32[i] << shift1;
10948 drflac_uint32 right = left - side;
10949
10950 pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
10951 pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
10952 }
10953 }
10954 #endif
10955
10956 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)
10957 {
10958 #if defined(DRFLAC_SUPPORT_SSE2)
10959 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10960 drflac_read_pcm_frames_f32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10961 } else
10962 #elif defined(DRFLAC_SUPPORT_NEON)
10963 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10964 drflac_read_pcm_frames_f32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10965 } else
10966 #endif
10967 {
10968 /* Scalar fallback. */
10969 #if 0
10970 drflac_read_pcm_frames_f32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10971 #else
10972 drflac_read_pcm_frames_f32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10973 #endif
10974 }
10975 }
10976
10977
10978 #if 0
10979 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)
10980 {
10981 drflac_uint64 i;
10982 for (i = 0; i < frameCount; ++i) {
10983 drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10984 drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10985 drflac_uint32 left = right + side;
10986
10987 pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0);
10988 pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
10989 }
10990 }
10991 #endif
10992
10993 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)
10994 {
10995 drflac_uint64 i;
10996 drflac_uint64 frameCount4 = frameCount >> 2;
10997 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10998 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10999 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11000 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11001 float factor = 1 / 2147483648.0;
11002
11003 for (i = 0; i < frameCount4; ++i) {
11004 drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
11005 drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
11006 drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
11007 drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
11008
11009 drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
11010 drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
11011 drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
11012 drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
11013
11014 drflac_uint32 left0 = right0 + side0;
11015 drflac_uint32 left1 = right1 + side1;
11016 drflac_uint32 left2 = right2 + side2;
11017 drflac_uint32 left3 = right3 + side3;
11018
11019 pOutputSamples[i*8+0] = (drflac_int32)left0 * factor;
11020 pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
11021 pOutputSamples[i*8+2] = (drflac_int32)left1 * factor;
11022 pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
11023 pOutputSamples[i*8+4] = (drflac_int32)left2 * factor;
11024 pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
11025 pOutputSamples[i*8+6] = (drflac_int32)left3 * factor;
11026 pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
11027 }
11028
11029 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11030 drflac_uint32 side = pInputSamples0U32[i] << shift0;
11031 drflac_uint32 right = pInputSamples1U32[i] << shift1;
11032 drflac_uint32 left = right + side;
11033
11034 pOutputSamples[i*2+0] = (drflac_int32)left * factor;
11035 pOutputSamples[i*2+1] = (drflac_int32)right * factor;
11036 }
11037 }
11038
11039 #if defined(DRFLAC_SUPPORT_SSE2)
11040 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)
11041 {
11042 drflac_uint64 i;
11043 drflac_uint64 frameCount4 = frameCount >> 2;
11044 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11045 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11046 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
11047 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
11048 __m128 factor;
11049
11050 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
11051
11052 factor = _mm_set1_ps(1.0f / 8388608.0f);
11053
11054 for (i = 0; i < frameCount4; ++i) {
11055 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
11056 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
11057 __m128i left = _mm_add_epi32(right, side);
11058 __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
11059 __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
11060
11061 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
11062 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
11063 }
11064
11065 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11066 drflac_uint32 side = pInputSamples0U32[i] << shift0;
11067 drflac_uint32 right = pInputSamples1U32[i] << shift1;
11068 drflac_uint32 left = right + side;
11069
11070 pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
11071 pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
11072 }
11073 }
11074 #endif
11075
11076 #if defined(DRFLAC_SUPPORT_NEON)
11077 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)
11078 {
11079 drflac_uint64 i;
11080 drflac_uint64 frameCount4 = frameCount >> 2;
11081 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11082 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11083 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
11084 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
11085 float32x4_t factor4;
11086 int32x4_t shift0_4;
11087 int32x4_t shift1_4;
11088
11089 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
11090
11091 factor4 = vdupq_n_f32(1.0f / 8388608.0f);
11092 shift0_4 = vdupq_n_s32(shift0);
11093 shift1_4 = vdupq_n_s32(shift1);
11094
11095 for (i = 0; i < frameCount4; ++i) {
11096 uint32x4_t side;
11097 uint32x4_t right;
11098 uint32x4_t left;
11099 float32x4_t leftf;
11100 float32x4_t rightf;
11101
11102 side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
11103 right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
11104 left = vaddq_u32(right, side);
11105 leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
11106 rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
11107
11108 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
11109 }
11110
11111 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11112 drflac_uint32 side = pInputSamples0U32[i] << shift0;
11113 drflac_uint32 right = pInputSamples1U32[i] << shift1;
11114 drflac_uint32 left = right + side;
11115
11116 pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
11117 pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
11118 }
11119 }
11120 #endif
11121
11122 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)
11123 {
11124 #if defined(DRFLAC_SUPPORT_SSE2)
11125 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
11126 drflac_read_pcm_frames_f32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11127 } else
11128 #elif defined(DRFLAC_SUPPORT_NEON)
11129 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
11130 drflac_read_pcm_frames_f32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11131 } else
11132 #endif
11133 {
11134 /* Scalar fallback. */
11135 #if 0
11136 drflac_read_pcm_frames_f32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11137 #else
11138 drflac_read_pcm_frames_f32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11139 #endif
11140 }
11141 }
11142
11143
11144 #if 0
11145 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)
11146 {
11147 for (drflac_uint64 i = 0; i < frameCount; ++i) {
11148 drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11149 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11150
11151 mid = (mid << 1) | (side & 0x01);
11152
11153 pOutputSamples[i*2+0] = (float)((((drflac_int32)(mid + side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
11154 pOutputSamples[i*2+1] = (float)((((drflac_int32)(mid - side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
11155 }
11156 }
11157 #endif
11158
11159 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)
11160 {
11161 drflac_uint64 i;
11162 drflac_uint64 frameCount4 = frameCount >> 2;
11163 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11164 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11165 drflac_uint32 shift = unusedBitsPerSample;
11166 float factor = 1 / 2147483648.0;
11167
11168 if (shift > 0) {
11169 shift -= 1;
11170 for (i = 0; i < frameCount4; ++i) {
11171 drflac_uint32 temp0L;
11172 drflac_uint32 temp1L;
11173 drflac_uint32 temp2L;
11174 drflac_uint32 temp3L;
11175 drflac_uint32 temp0R;
11176 drflac_uint32 temp1R;
11177 drflac_uint32 temp2R;
11178 drflac_uint32 temp3R;
11179
11180 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11181 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11182 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11183 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11184
11185 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11186 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11187 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11188 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11189
11190 mid0 = (mid0 << 1) | (side0 & 0x01);
11191 mid1 = (mid1 << 1) | (side1 & 0x01);
11192 mid2 = (mid2 << 1) | (side2 & 0x01);
11193 mid3 = (mid3 << 1) | (side3 & 0x01);
11194
11195 temp0L = (mid0 + side0) << shift;
11196 temp1L = (mid1 + side1) << shift;
11197 temp2L = (mid2 + side2) << shift;
11198 temp3L = (mid3 + side3) << shift;
11199
11200 temp0R = (mid0 - side0) << shift;
11201 temp1R = (mid1 - side1) << shift;
11202 temp2R = (mid2 - side2) << shift;
11203 temp3R = (mid3 - side3) << shift;
11204
11205 pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
11206 pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
11207 pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
11208 pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
11209 pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
11210 pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
11211 pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
11212 pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
11213 }
11214 } else {
11215 for (i = 0; i < frameCount4; ++i) {
11216 drflac_uint32 temp0L;
11217 drflac_uint32 temp1L;
11218 drflac_uint32 temp2L;
11219 drflac_uint32 temp3L;
11220 drflac_uint32 temp0R;
11221 drflac_uint32 temp1R;
11222 drflac_uint32 temp2R;
11223 drflac_uint32 temp3R;
11224
11225 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11226 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11227 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11228 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11229
11230 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11231 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11232 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11233 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11234
11235 mid0 = (mid0 << 1) | (side0 & 0x01);
11236 mid1 = (mid1 << 1) | (side1 & 0x01);
11237 mid2 = (mid2 << 1) | (side2 & 0x01);
11238 mid3 = (mid3 << 1) | (side3 & 0x01);
11239
11240 temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
11241 temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
11242 temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
11243 temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
11244
11245 temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
11246 temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
11247 temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
11248 temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
11249
11250 pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
11251 pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
11252 pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
11253 pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
11254 pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
11255 pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
11256 pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
11257 pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
11258 }
11259 }
11260
11261 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11262 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11263 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11264
11265 mid = (mid << 1) | (side & 0x01);
11266
11267 pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) * factor;
11268 pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) * factor;
11269 }
11270 }
11271
11272 #if defined(DRFLAC_SUPPORT_SSE2)
11273 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)
11274 {
11275 drflac_uint64 i;
11276 drflac_uint64 frameCount4 = frameCount >> 2;
11277 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11278 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11279 drflac_uint32 shift = unusedBitsPerSample - 8;
11280 float factor;
11281 __m128 factor128;
11282
11283 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
11284
11285 factor = 1.0f / 8388608.0f;
11286 factor128 = _mm_set1_ps(factor);
11287
11288 if (shift == 0) {
11289 for (i = 0; i < frameCount4; ++i) {
11290 __m128i mid;
11291 __m128i side;
11292 __m128i tempL;
11293 __m128i tempR;
11294 __m128 leftf;
11295 __m128 rightf;
11296
11297 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
11298 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
11299
11300 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
11301
11302 tempL = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
11303 tempR = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
11304
11305 leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
11306 rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
11307
11308 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
11309 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
11310 }
11311
11312 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11313 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11314 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11315
11316 mid = (mid << 1) | (side & 0x01);
11317
11318 pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
11319 pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
11320 }
11321 } else {
11322 shift -= 1;
11323 for (i = 0; i < frameCount4; ++i) {
11324 __m128i mid;
11325 __m128i side;
11326 __m128i tempL;
11327 __m128i tempR;
11328 __m128 leftf;
11329 __m128 rightf;
11330
11331 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
11332 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
11333
11334 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
11335
11336 tempL = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
11337 tempR = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
11338
11339 leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
11340 rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
11341
11342 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
11343 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
11344 }
11345
11346 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11347 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11348 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11349
11350 mid = (mid << 1) | (side & 0x01);
11351
11352 pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
11353 pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
11354 }
11355 }
11356 }
11357 #endif
11358
11359 #if defined(DRFLAC_SUPPORT_NEON)
11360 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)
11361 {
11362 drflac_uint64 i;
11363 drflac_uint64 frameCount4 = frameCount >> 2;
11364 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11365 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11366 drflac_uint32 shift = unusedBitsPerSample - 8;
11367 float factor;
11368 float32x4_t factor4;
11369 int32x4_t shift4;
11370 int32x4_t wbps0_4; /* Wasted Bits Per Sample */
11371 int32x4_t wbps1_4; /* Wasted Bits Per Sample */
11372
11373 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
11374
11375 factor = 1.0f / 8388608.0f;
11376 factor4 = vdupq_n_f32(factor);
11377 wbps0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
11378 wbps1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
11379
11380 if (shift == 0) {
11381 for (i = 0; i < frameCount4; ++i) {
11382 int32x4_t lefti;
11383 int32x4_t righti;
11384 float32x4_t leftf;
11385 float32x4_t rightf;
11386
11387 uint32x4_t mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
11388 uint32x4_t side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
11389
11390 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
11391
11392 lefti = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
11393 righti = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
11394
11395 leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
11396 rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
11397
11398 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
11399 }
11400
11401 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11402 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11403 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11404
11405 mid = (mid << 1) | (side & 0x01);
11406
11407 pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
11408 pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
11409 }
11410 } else {
11411 shift -= 1;
11412 shift4 = vdupq_n_s32(shift);
11413 for (i = 0; i < frameCount4; ++i) {
11414 uint32x4_t mid;
11415 uint32x4_t side;
11416 int32x4_t lefti;
11417 int32x4_t righti;
11418 float32x4_t leftf;
11419 float32x4_t rightf;
11420
11421 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
11422 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
11423
11424 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
11425
11426 lefti = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
11427 righti = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
11428
11429 leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
11430 rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
11431
11432 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
11433 }
11434
11435 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11436 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11437 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11438
11439 mid = (mid << 1) | (side & 0x01);
11440
11441 pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
11442 pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
11443 }
11444 }
11445 }
11446 #endif
11447
11448 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)
11449 {
11450 #if defined(DRFLAC_SUPPORT_SSE2)
11451 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
11452 drflac_read_pcm_frames_f32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11453 } else
11454 #elif defined(DRFLAC_SUPPORT_NEON)
11455 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
11456 drflac_read_pcm_frames_f32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11457 } else
11458 #endif
11459 {
11460 /* Scalar fallback. */
11461 #if 0
11462 drflac_read_pcm_frames_f32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11463 #else
11464 drflac_read_pcm_frames_f32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11465 #endif
11466 }
11467 }
11468
11469 #if 0
11470 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)
11471 {
11472 for (drflac_uint64 i = 0; i < frameCount; ++i) {
11473 pOutputSamples[i*2+0] = (float)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) / 2147483648.0);
11474 pOutputSamples[i*2+1] = (float)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) / 2147483648.0);
11475 }
11476 }
11477 #endif
11478
11479 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)
11480 {
11481 drflac_uint64 i;
11482 drflac_uint64 frameCount4 = frameCount >> 2;
11483 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11484 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11485 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11486 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11487 float factor = 1 / 2147483648.0;
11488
11489 for (i = 0; i < frameCount4; ++i) {
11490 drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
11491 drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
11492 drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
11493 drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
11494
11495 drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
11496 drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
11497 drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
11498 drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
11499
11500 pOutputSamples[i*8+0] = (drflac_int32)tempL0 * factor;
11501 pOutputSamples[i*8+1] = (drflac_int32)tempR0 * factor;
11502 pOutputSamples[i*8+2] = (drflac_int32)tempL1 * factor;
11503 pOutputSamples[i*8+3] = (drflac_int32)tempR1 * factor;
11504 pOutputSamples[i*8+4] = (drflac_int32)tempL2 * factor;
11505 pOutputSamples[i*8+5] = (drflac_int32)tempR2 * factor;
11506 pOutputSamples[i*8+6] = (drflac_int32)tempL3 * factor;
11507 pOutputSamples[i*8+7] = (drflac_int32)tempR3 * factor;
11508 }
11509
11510 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11511 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
11512 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
11513 }
11514 }
11515
11516 #if defined(DRFLAC_SUPPORT_SSE2)
11517 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)
11518 {
11519 drflac_uint64 i;
11520 drflac_uint64 frameCount4 = frameCount >> 2;
11521 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11522 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11523 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
11524 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
11525
11526 float factor = 1.0f / 8388608.0f;
11527 __m128 factor128 = _mm_set1_ps(factor);
11528
11529 for (i = 0; i < frameCount4; ++i) {
11530 __m128i lefti;
11531 __m128i righti;
11532 __m128 leftf;
11533 __m128 rightf;
11534
11535 lefti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
11536 righti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
11537
11538 leftf = _mm_mul_ps(_mm_cvtepi32_ps(lefti), factor128);
11539 rightf = _mm_mul_ps(_mm_cvtepi32_ps(righti), factor128);
11540
11541 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
11542 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
11543 }
11544
11545 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11546 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
11547 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
11548 }
11549 }
11550 #endif
11551
11552 #if defined(DRFLAC_SUPPORT_NEON)
11553 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)
11554 {
11555 drflac_uint64 i;
11556 drflac_uint64 frameCount4 = frameCount >> 2;
11557 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11558 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11559 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
11560 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
11561
11562 float factor = 1.0f / 8388608.0f;
11563 float32x4_t factor4 = vdupq_n_f32(factor);
11564 int32x4_t shift0_4 = vdupq_n_s32(shift0);
11565 int32x4_t shift1_4 = vdupq_n_s32(shift1);
11566
11567 for (i = 0; i < frameCount4; ++i) {
11568 int32x4_t lefti;
11569 int32x4_t righti;
11570 float32x4_t leftf;
11571 float32x4_t rightf;
11572
11573 lefti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
11574 righti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
11575
11576 leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
11577 rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
11578
11579 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
11580 }
11581
11582 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11583 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
11584 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
11585 }
11586 }
11587 #endif
11588
11589 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)
11590 {
11591 #if defined(DRFLAC_SUPPORT_SSE2)
11592 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
11593 drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11594 } else
11595 #elif defined(DRFLAC_SUPPORT_NEON)
11596 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
11597 drflac_read_pcm_frames_f32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11598 } else
11599 #endif
11600 {
11601 /* Scalar fallback. */
11602 #if 0
11603 drflac_read_pcm_frames_f32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11604 #else
11605 drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11606 #endif
11607 }
11608 }
11609
11610 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut)
11611 {
11612 drflac_uint64 framesRead;
11613 drflac_uint32 unusedBitsPerSample;
11614
11615 if (pFlac == NULL || framesToRead == 0) {
11616 return 0;
11617 }
11618
11619 if (pBufferOut == NULL) {
11620 return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
11621 }
11622
11623 DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
11624 unusedBitsPerSample = 32 - pFlac->bitsPerSample;
11625
11626 framesRead = 0;
11627 while (framesToRead > 0) {
11628 /* If we've run out of samples in this frame, go to the next. */
11629 if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
11630 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
11631 break; /* Couldn't read the next frame, so just break from the loop and return. */
11632 }
11633 } else {
11634 unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
11635 drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
11636 drflac_uint64 frameCountThisIteration = framesToRead;
11637
11638 if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
11639 frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
11640 }
11641
11642 if (channelCount == 2) {
11643 const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
11644 const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
11645
11646 switch (pFlac->currentFLACFrame.header.channelAssignment)
11647 {
11648 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
11649 {
11650 drflac_read_pcm_frames_f32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
11651 } break;
11652
11653 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
11654 {
11655 drflac_read_pcm_frames_f32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
11656 } break;
11657
11658 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
11659 {
11660 drflac_read_pcm_frames_f32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
11661 } break;
11662
11663 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
11664 default:
11665 {
11666 drflac_read_pcm_frames_f32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
11667 } break;
11668 }
11669 } else {
11670 /* Generic interleaving. */
11671 drflac_uint64 i;
11672 for (i = 0; i < frameCountThisIteration; ++i) {
11673 unsigned int j;
11674 for (j = 0; j < channelCount; ++j) {
11675 drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
11676 pBufferOut[(i*channelCount)+j] = (float)(sampleS32 / 2147483648.0);
11677 }
11678 }
11679 }
11680
11681 framesRead += frameCountThisIteration;
11682 pBufferOut += frameCountThisIteration * channelCount;
11683 framesToRead -= frameCountThisIteration;
11684 pFlac->currentPCMFrame += frameCountThisIteration;
11685 pFlac->currentFLACFrame.pcmFramesRemaining -= (unsigned int)frameCountThisIteration;
11686 }
11687 }
11688
11689 return framesRead;
11690 }
11691
11692
11693 DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
11694 {
11695 if (pFlac == NULL) {
11696 return DRFLAC_FALSE;
11697 }
11698
11699 /* Don't do anything if we're already on the seek point. */
11700 if (pFlac->currentPCMFrame == pcmFrameIndex) {
11701 return DRFLAC_TRUE;
11702 }
11703
11704 /*
11705 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
11706 when the decoder was opened.
11707 */
11708 if (pFlac->firstFLACFramePosInBytes == 0) {
11709 return DRFLAC_FALSE;
11710 }
11711
11712 if (pcmFrameIndex == 0) {
11713 pFlac->currentPCMFrame = 0;
11714 return drflac__seek_to_first_frame(pFlac);
11715 } else {
11716 drflac_bool32 wasSuccessful = DRFLAC_FALSE;
11717 drflac_uint64 originalPCMFrame = pFlac->currentPCMFrame;
11718
11719 /* Clamp the sample to the end. */
11720 if (pcmFrameIndex > pFlac->totalPCMFrameCount) {
11721 pcmFrameIndex = pFlac->totalPCMFrameCount;
11722 }
11723
11724 /* If the target sample and the current sample are in the same frame we just move the position forward. */
11725 if (pcmFrameIndex > pFlac->currentPCMFrame) {
11726 /* Forward. */
11727 drflac_uint32 offset = (drflac_uint32)(pcmFrameIndex - pFlac->currentPCMFrame);
11728 if (pFlac->currentFLACFrame.pcmFramesRemaining > offset) {
11729 pFlac->currentFLACFrame.pcmFramesRemaining -= offset;
11730 pFlac->currentPCMFrame = pcmFrameIndex;
11731 return DRFLAC_TRUE;
11732 }
11733 } else {
11734 /* Backward. */
11735 drflac_uint32 offsetAbs = (drflac_uint32)(pFlac->currentPCMFrame - pcmFrameIndex);
11736 drflac_uint32 currentFLACFramePCMFrameCount = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
11737 drflac_uint32 currentFLACFramePCMFramesConsumed = currentFLACFramePCMFrameCount - pFlac->currentFLACFrame.pcmFramesRemaining;
11738 if (currentFLACFramePCMFramesConsumed > offsetAbs) {
11739 pFlac->currentFLACFrame.pcmFramesRemaining += offsetAbs;
11740 pFlac->currentPCMFrame = pcmFrameIndex;
11741 return DRFLAC_TRUE;
11742 }
11743 }
11744
11745 /*
11746 Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so
11747 we'll instead use Ogg's natural seeking facility.
11748 */
11749 #ifndef DR_FLAC_NO_OGG
11750 if (pFlac->container == drflac_container_ogg)
11751 {
11752 wasSuccessful = drflac_ogg__seek_to_pcm_frame(pFlac, pcmFrameIndex);
11753 }
11754 else
11755 #endif
11756 {
11757 /* First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower. */
11758 if (/*!wasSuccessful && */!pFlac->_noSeekTableSeek) {
11759 wasSuccessful = drflac__seek_to_pcm_frame__seek_table(pFlac, pcmFrameIndex);
11760 }
11761
11762 #if !defined(DR_FLAC_NO_CRC)
11763 /* Fall back to binary search if seek table seeking fails. This requires the length of the stream to be known. */
11764 if (!wasSuccessful && !pFlac->_noBinarySearchSeek && pFlac->totalPCMFrameCount > 0) {
11765 wasSuccessful = drflac__seek_to_pcm_frame__binary_search(pFlac, pcmFrameIndex);
11766 }
11767 #endif
11768
11769 /* Fall back to brute force if all else fails. */
11770 if (!wasSuccessful && !pFlac->_noBruteForceSeek) {
11771 wasSuccessful = drflac__seek_to_pcm_frame__brute_force(pFlac, pcmFrameIndex);
11772 }
11773 }
11774
11775 if (wasSuccessful) {
11776 pFlac->currentPCMFrame = pcmFrameIndex;
11777 } else {
11778 /* Seek failed. Try putting the decoder back to it's original state. */
11779 if (drflac_seek_to_pcm_frame(pFlac, originalPCMFrame) == DRFLAC_FALSE) {
11780 /* Failed to seek back to the original PCM frame. Fall back to 0. */
11781 drflac_seek_to_pcm_frame(pFlac, 0);
11782 }
11783 }
11784
11785 return wasSuccessful;
11786 }
11787 }
11788
11789
11790
11791 /* High Level APIs */
11792
11793 /* SIZE_MAX */
11794 #if defined(SIZE_MAX)
11795 #define DRFLAC_SIZE_MAX SIZE_MAX
11796 #else
11797 #if defined(DRFLAC_64BIT)
11798 #define DRFLAC_SIZE_MAX ((drflac_uint64)0xFFFFFFFFFFFFFFFF)
11799 #else
11800 #define DRFLAC_SIZE_MAX 0xFFFFFFFF
11801 #endif
11802 #endif
11803 /* End SIZE_MAX */
11804
11805
11806 /* Using a macro as the definition of the drflac__full_decode_and_close_*() API family. Sue me. */
11807 #define DRFLAC_DEFINE_FULL_READ_AND_CLOSE(extension, type) \
11808 static type* drflac__full_read_and_close_ ## extension (drflac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut)\
11809 { \
11810 type* pSampleData = NULL; \
11811 drflac_uint64 totalPCMFrameCount; \
11812 type buffer[4096]; \
11813 drflac_uint64 pcmFramesRead; \
11814 size_t sampleDataBufferSize = sizeof(buffer); \
11815 \
11816 DRFLAC_ASSERT(pFlac != NULL); \
11817 \
11818 totalPCMFrameCount = 0; \
11819 \
11820 pSampleData = (type*)drflac__malloc_from_callbacks(sampleDataBufferSize, &pFlac->allocationCallbacks); \
11821 if (pSampleData == NULL) { \
11822 goto on_error; \
11823 } \
11824 \
11825 while ((pcmFramesRead = (drflac_uint64)drflac_read_pcm_frames_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0])/pFlac->channels, buffer)) > 0) { \
11826 if (((totalPCMFrameCount + pcmFramesRead) * pFlac->channels * sizeof(type)) > sampleDataBufferSize) { \
11827 type* pNewSampleData; \
11828 size_t newSampleDataBufferSize; \
11829 \
11830 newSampleDataBufferSize = sampleDataBufferSize * 2; \
11831 pNewSampleData = (type*)drflac__realloc_from_callbacks(pSampleData, newSampleDataBufferSize, sampleDataBufferSize, &pFlac->allocationCallbacks); \
11832 if (pNewSampleData == NULL) { \
11833 drflac__free_from_callbacks(pSampleData, &pFlac->allocationCallbacks); \
11834 goto on_error; \
11835 } \
11836 \
11837 sampleDataBufferSize = newSampleDataBufferSize; \
11838 pSampleData = pNewSampleData; \
11839 } \
11840 \
11841 DRFLAC_COPY_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), buffer, (size_t)(pcmFramesRead*pFlac->channels*sizeof(type))); \
11842 totalPCMFrameCount += pcmFramesRead; \
11843 } \
11844 \
11845 /* At this point everything should be decoded, but we just want to fill the unused part buffer with silence - need to \
11846 protect those ears from random noise! */ \
11847 DRFLAC_ZERO_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), (size_t)(sampleDataBufferSize - totalPCMFrameCount*pFlac->channels*sizeof(type))); \
11848 \
11849 if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \
11850 if (channelsOut) *channelsOut = pFlac->channels; \
11851 if (totalPCMFrameCountOut) *totalPCMFrameCountOut = totalPCMFrameCount; \
11852 \
11853 drflac_close(pFlac); \
11854 return pSampleData; \
11855 \
11856 on_error: \
11857 drflac_close(pFlac); \
11858 return NULL; \
11859 }
11860
11861 DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s32, drflac_int32)
11862 DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s16, drflac_int16)
11863 DRFLAC_DEFINE_FULL_READ_AND_CLOSE(f32, float)
11864
11865 DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
11866 {
11867 drflac* pFlac;
11868
11869 if (channelsOut) {
11870 *channelsOut = 0;
11871 }
11872 if (sampleRateOut) {
11873 *sampleRateOut = 0;
11874 }
11875 if (totalPCMFrameCountOut) {
11876 *totalPCMFrameCountOut = 0;
11877 }
11878
11879 pFlac = drflac_open(onRead, onSeek, onTell, pUserData, pAllocationCallbacks);
11880 if (pFlac == NULL) {
11881 return NULL;
11882 }
11883
11884 return drflac__full_read_and_close_s32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
11885 }
11886
11887 DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
11888 {
11889 drflac* pFlac;
11890
11891 if (channelsOut) {
11892 *channelsOut = 0;
11893 }
11894 if (sampleRateOut) {
11895 *sampleRateOut = 0;
11896 }
11897 if (totalPCMFrameCountOut) {
11898 *totalPCMFrameCountOut = 0;
11899 }
11900
11901 pFlac = drflac_open(onRead, onSeek, onTell, pUserData, pAllocationCallbacks);
11902 if (pFlac == NULL) {
11903 return NULL;
11904 }
11905
11906 return drflac__full_read_and_close_s16(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
11907 }
11908
11909 DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
11910 {
11911 drflac* pFlac;
11912
11913 if (channelsOut) {
11914 *channelsOut = 0;
11915 }
11916 if (sampleRateOut) {
11917 *sampleRateOut = 0;
11918 }
11919 if (totalPCMFrameCountOut) {
11920 *totalPCMFrameCountOut = 0;
11921 }
11922
11923 pFlac = drflac_open(onRead, onSeek, onTell, pUserData, pAllocationCallbacks);
11924 if (pFlac == NULL) {
11925 return NULL;
11926 }
11927
11928 return drflac__full_read_and_close_f32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
11929 }
11930
11931 #ifndef DR_FLAC_NO_STDIO
11932 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)
11933 {
11934 drflac* pFlac;
11935
11936 if (sampleRate) {
11937 *sampleRate = 0;
11938 }
11939 if (channels) {
11940 *channels = 0;
11941 }
11942 if (totalPCMFrameCount) {
11943 *totalPCMFrameCount = 0;
11944 }
11945
11946 pFlac = drflac_open_file(filename, pAllocationCallbacks);
11947 if (pFlac == NULL) {
11948 return NULL;
11949 }
11950
11951 return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
11952 }
11953
11954 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)
11955 {
11956 drflac* pFlac;
11957
11958 if (sampleRate) {
11959 *sampleRate = 0;
11960 }
11961 if (channels) {
11962 *channels = 0;
11963 }
11964 if (totalPCMFrameCount) {
11965 *totalPCMFrameCount = 0;
11966 }
11967
11968 pFlac = drflac_open_file(filename, pAllocationCallbacks);
11969 if (pFlac == NULL) {
11970 return NULL;
11971 }
11972
11973 return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
11974 }
11975
11976 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)
11977 {
11978 drflac* pFlac;
11979
11980 if (sampleRate) {
11981 *sampleRate = 0;
11982 }
11983 if (channels) {
11984 *channels = 0;
11985 }
11986 if (totalPCMFrameCount) {
11987 *totalPCMFrameCount = 0;
11988 }
11989
11990 pFlac = drflac_open_file(filename, pAllocationCallbacks);
11991 if (pFlac == NULL) {
11992 return NULL;
11993 }
11994
11995 return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
11996 }
11997 #endif
11998
11999 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)
12000 {
12001 drflac* pFlac;
12002
12003 if (sampleRate) {
12004 *sampleRate = 0;
12005 }
12006 if (channels) {
12007 *channels = 0;
12008 }
12009 if (totalPCMFrameCount) {
12010 *totalPCMFrameCount = 0;
12011 }
12012
12013 pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
12014 if (pFlac == NULL) {
12015 return NULL;
12016 }
12017
12018 return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
12019 }
12020
12021 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)
12022 {
12023 drflac* pFlac;
12024
12025 if (sampleRate) {
12026 *sampleRate = 0;
12027 }
12028 if (channels) {
12029 *channels = 0;
12030 }
12031 if (totalPCMFrameCount) {
12032 *totalPCMFrameCount = 0;
12033 }
12034
12035 pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
12036 if (pFlac == NULL) {
12037 return NULL;
12038 }
12039
12040 return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
12041 }
12042
12043 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)
12044 {
12045 drflac* pFlac;
12046
12047 if (sampleRate) {
12048 *sampleRate = 0;
12049 }
12050 if (channels) {
12051 *channels = 0;
12052 }
12053 if (totalPCMFrameCount) {
12054 *totalPCMFrameCount = 0;
12055 }
12056
12057 pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
12058 if (pFlac == NULL) {
12059 return NULL;
12060 }
12061
12062 return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
12063 }
12064
12065
12066 DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
12067 {
12068 if (pAllocationCallbacks != NULL) {
12069 drflac__free_from_callbacks(p, pAllocationCallbacks);
12070 } else {
12071 drflac__free_default(p, NULL);
12072 }
12073 }
12074
12075
12076
12077
12078 DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments)
12079 {
12080 if (pIter == NULL) {
12081 return;
12082 }
12083
12084 pIter->countRemaining = commentCount;
12085 pIter->pRunningData = (const char*)pComments;
12086 }
12087
12088 DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut)
12089 {
12090 drflac_int32 length;
12091 const char* pComment;
12092
12093 /* Safety. */
12094 if (pCommentLengthOut) {
12095 *pCommentLengthOut = 0;
12096 }
12097
12098 if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
12099 return NULL;
12100 }
12101
12102 length = drflac__le2host_32_ptr_unaligned(pIter->pRunningData);
12103 pIter->pRunningData += 4;
12104
12105 pComment = pIter->pRunningData;
12106 pIter->pRunningData += length;
12107 pIter->countRemaining -= 1;
12108
12109 if (pCommentLengthOut) {
12110 *pCommentLengthOut = length;
12111 }
12112
12113 return pComment;
12114 }
12115
12116
12117
12118
12119 DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData)
12120 {
12121 if (pIter == NULL) {
12122 return;
12123 }
12124
12125 pIter->countRemaining = trackCount;
12126 pIter->pRunningData = (const char*)pTrackData;
12127 }
12128
12129 DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack)
12130 {
12131 drflac_cuesheet_track cuesheetTrack;
12132 const char* pRunningData;
12133 drflac_uint64 offsetHi;
12134 drflac_uint64 offsetLo;
12135
12136 if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
12137 return DRFLAC_FALSE;
12138 }
12139
12140 pRunningData = pIter->pRunningData;
12141
12142 offsetHi = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
12143 offsetLo = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
12144 cuesheetTrack.offset = offsetLo | (offsetHi << 32);
12145 cuesheetTrack.trackNumber = pRunningData[0]; pRunningData += 1;
12146 DRFLAC_COPY_MEMORY(cuesheetTrack.ISRC, pRunningData, sizeof(cuesheetTrack.ISRC)); pRunningData += 12;
12147 cuesheetTrack.isAudio = (pRunningData[0] & 0x80) != 0;
12148 cuesheetTrack.preEmphasis = (pRunningData[0] & 0x40) != 0; pRunningData += 14;
12149 cuesheetTrack.indexCount = pRunningData[0]; pRunningData += 1;
12150 cuesheetTrack.pIndexPoints = (const drflac_cuesheet_track_index*)pRunningData; pRunningData += cuesheetTrack.indexCount * sizeof(drflac_cuesheet_track_index);
12151
12152 pIter->pRunningData = pRunningData;
12153 pIter->countRemaining -= 1;
12154
12155 if (pCuesheetTrack) {
12156 *pCuesheetTrack = cuesheetTrack;
12157 }
12158
12159 return DRFLAC_TRUE;
12160 }
12161
12162 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
12163 #pragma GCC diagnostic pop
12164 #endif
12165 #endif /* dr_flac_c */
12166 #endif /* DR_FLAC_IMPLEMENTATION */
12167
12168
12169 /*
12170 REVISION HISTORY
12171 ================
12172 v0.13.3 - 2026-01-17
12173 - Fix a compiler compatibility issue with some inlined assembly.
12174 - Fix a compilation warning.
12175
12176 v0.13.2 - 2025-12-02
12177 - Improve robustness of the parsing of picture metadata to improve support for memory constrained embedded devices.
12178 - Fix a warning about an assigned by unused variable.
12179 - Improvements to drflac_open_and_read_pcm_frames_*() and family to avoid excessively large memory allocations from malformed files.
12180
12181 v0.13.1 - 2025-09-10
12182 - Fix an error with the NXDK build.
12183
12184 v0.13.0 - 2025-07-23
12185 - API CHANGE: Seek origin enums have been renamed to match the naming convention used by other dr_libs libraries:
12186 - drflac_seek_origin_start -> DRFLAC_SEEK_SET
12187 - drflac_seek_origin_current -> DRFLAC_SEEK_CUR
12188 - DRFLAC_SEEK_END (new)
12189 - API CHANGE: A new seek origin has been added to allow seeking from the end of the file. If you implement your own `onSeek` callback, you should now detect and handle `DRFLAC_SEEK_END`. If seeking to the end is not supported, return `DRFLAC_FALSE`. If you only use `*_open_file()` or `*_open_memory()`, you need not change anything.
12190 - API CHANGE: An `onTell` callback has been added to the following functions:
12191 - drflac_open()
12192 - drflac_open_relaxed()
12193 - drflac_open_with_metadata()
12194 - drflac_open_with_metadata_relaxed()
12195 - drflac_open_and_read_pcm_frames_s32()
12196 - drflac_open_and_read_pcm_frames_s16()
12197 - drflac_open_and_read_pcm_frames_f32()
12198 - Fix compilation for AIX OS.
12199
12200 v0.12.43 - 2024-12-17
12201 - Fix a possible buffer overflow during decoding.
12202 - Improve detection of ARM64EC
12203
12204 v0.12.42 - 2023-11-02
12205 - Fix build for ARMv6-M.
12206 - Fix a compilation warning with GCC.
12207
12208 v0.12.41 - 2023-06-17
12209 - Fix an incorrect date in revision history. No functional change.
12210
12211 v0.12.40 - 2023-05-22
12212 - Minor code restructure. No functional change.
12213
12214 v0.12.39 - 2022-09-17
12215 - Fix compilation with DJGPP.
12216 - Fix compilation error with Visual Studio 2019 and the ARM build.
12217 - Fix an error with SSE 4.1 detection.
12218 - Add support for disabling wchar_t with DR_WAV_NO_WCHAR.
12219 - Improve compatibility with compilers which lack support for explicit struct packing.
12220 - Improve compatibility with low-end and embedded hardware by reducing the amount of stack
12221 allocation when loading an Ogg encapsulated file.
12222
12223 v0.12.38 - 2022-04-10
12224 - Fix compilation error on older versions of GCC.
12225
12226 v0.12.37 - 2022-02-12
12227 - Improve ARM detection.
12228
12229 v0.12.36 - 2022-02-07
12230 - Fix a compilation error with the ARM build.
12231
12232 v0.12.35 - 2022-02-06
12233 - Fix a bug due to underestimating the amount of precision required for the prediction stage.
12234 - Fix some bugs found from fuzz testing.
12235
12236 v0.12.34 - 2022-01-07
12237 - Fix some misalignment bugs when reading metadata.
12238
12239 v0.12.33 - 2021-12-22
12240 - Fix a bug with seeking when the seek table does not start at PCM frame 0.
12241
12242 v0.12.32 - 2021-12-11
12243 - Fix a warning with Clang.
12244
12245 v0.12.31 - 2021-08-16
12246 - Silence some warnings.
12247
12248 v0.12.30 - 2021-07-31
12249 - Fix platform detection for ARM64.
12250
12251 v0.12.29 - 2021-04-02
12252 - Fix a bug where the running PCM frame index is set to an invalid value when over-seeking.
12253 - Fix a decoding error due to an incorrect validation check.
12254
12255 v0.12.28 - 2021-02-21
12256 - Fix a warning due to referencing _MSC_VER when it is undefined.
12257
12258 v0.12.27 - 2021-01-31
12259 - Fix a static analysis warning.
12260
12261 v0.12.26 - 2021-01-17
12262 - Fix a compilation warning due to _BSD_SOURCE being deprecated.
12263
12264 v0.12.25 - 2020-12-26
12265 - Update documentation.
12266
12267 v0.12.24 - 2020-11-29
12268 - Fix ARM64/NEON detection when compiling with MSVC.
12269
12270 v0.12.23 - 2020-11-21
12271 - Fix compilation with OpenWatcom.
12272
12273 v0.12.22 - 2020-11-01
12274 - Fix an error with the previous release.
12275
12276 v0.12.21 - 2020-11-01
12277 - Fix a possible deadlock when seeking.
12278 - Improve compiler support for older versions of GCC.
12279
12280 v0.12.20 - 2020-09-08
12281 - Fix a compilation error on older compilers.
12282
12283 v0.12.19 - 2020-08-30
12284 - Fix a bug due to an undefined 32-bit shift.
12285
12286 v0.12.18 - 2020-08-14
12287 - Fix a crash when compiling with clang-cl.
12288
12289 v0.12.17 - 2020-08-02
12290 - Simplify sized types.
12291
12292 v0.12.16 - 2020-07-25
12293 - Fix a compilation warning.
12294
12295 v0.12.15 - 2020-07-06
12296 - Check for negative LPC shifts and return an error.
12297
12298 v0.12.14 - 2020-06-23
12299 - Add include guard for the implementation section.
12300
12301 v0.12.13 - 2020-05-16
12302 - Add compile-time and run-time version querying.
12303 - DRFLAC_VERSION_MINOR
12304 - DRFLAC_VERSION_MAJOR
12305 - DRFLAC_VERSION_REVISION
12306 - DRFLAC_VERSION_STRING
12307 - drflac_version()
12308 - drflac_version_string()
12309
12310 v0.12.12 - 2020-04-30
12311 - Fix compilation errors with VC6.
12312
12313 v0.12.11 - 2020-04-19
12314 - Fix some pedantic warnings.
12315 - Fix some undefined behaviour warnings.
12316
12317 v0.12.10 - 2020-04-10
12318 - Fix some bugs when trying to seek with an invalid seek table.
12319
12320 v0.12.9 - 2020-04-05
12321 - Fix warnings.
12322
12323 v0.12.8 - 2020-04-04
12324 - Add drflac_open_file_w() and drflac_open_file_with_metadata_w().
12325 - Fix some static analysis warnings.
12326 - Minor documentation updates.
12327
12328 v0.12.7 - 2020-03-14
12329 - Fix compilation errors with VC6.
12330
12331 v0.12.6 - 2020-03-07
12332 - Fix compilation error with Visual Studio .NET 2003.
12333
12334 v0.12.5 - 2020-01-30
12335 - Silence some static analysis warnings.
12336
12337 v0.12.4 - 2020-01-29
12338 - Silence some static analysis warnings.
12339
12340 v0.12.3 - 2019-12-02
12341 - Fix some warnings when compiling with GCC and the -Og flag.
12342 - Fix a crash in out-of-memory situations.
12343 - Fix potential integer overflow bug.
12344 - Fix some static analysis warnings.
12345 - Fix a possible crash when using custom memory allocators without a custom realloc() implementation.
12346 - Fix a bug with binary search seeking where the bits per sample is not a multiple of 8.
12347
12348 v0.12.2 - 2019-10-07
12349 - Internal code clean up.
12350
12351 v0.12.1 - 2019-09-29
12352 - Fix some Clang Static Analyzer warnings.
12353 - Fix an unused variable warning.
12354
12355 v0.12.0 - 2019-09-23
12356 - API CHANGE: Add support for user defined memory allocation routines. This system allows the program to specify their own memory allocation
12357 routines with a user data pointer for client-specific contextual data. This adds an extra parameter to the end of the following APIs:
12358 - drflac_open()
12359 - drflac_open_relaxed()
12360 - drflac_open_with_metadata()
12361 - drflac_open_with_metadata_relaxed()
12362 - drflac_open_file()
12363 - drflac_open_file_with_metadata()
12364 - drflac_open_memory()
12365 - drflac_open_memory_with_metadata()
12366 - drflac_open_and_read_pcm_frames_s32()
12367 - drflac_open_and_read_pcm_frames_s16()
12368 - drflac_open_and_read_pcm_frames_f32()
12369 - drflac_open_file_and_read_pcm_frames_s32()
12370 - drflac_open_file_and_read_pcm_frames_s16()
12371 - drflac_open_file_and_read_pcm_frames_f32()
12372 - drflac_open_memory_and_read_pcm_frames_s32()
12373 - drflac_open_memory_and_read_pcm_frames_s16()
12374 - drflac_open_memory_and_read_pcm_frames_f32()
12375 Set this extra parameter to NULL to use defaults which is the same as the previous behaviour. Setting this NULL will use
12376 DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE.
12377 - Remove deprecated APIs:
12378 - drflac_read_s32()
12379 - drflac_read_s16()
12380 - drflac_read_f32()
12381 - drflac_seek_to_sample()
12382 - drflac_open_and_decode_s32()
12383 - drflac_open_and_decode_s16()
12384 - drflac_open_and_decode_f32()
12385 - drflac_open_and_decode_file_s32()
12386 - drflac_open_and_decode_file_s16()
12387 - drflac_open_and_decode_file_f32()
12388 - drflac_open_and_decode_memory_s32()
12389 - drflac_open_and_decode_memory_s16()
12390 - drflac_open_and_decode_memory_f32()
12391 - Remove drflac.totalSampleCount which is now replaced with drflac.totalPCMFrameCount. You can emulate drflac.totalSampleCount
12392 by doing pFlac->totalPCMFrameCount*pFlac->channels.
12393 - Rename drflac.currentFrame to drflac.currentFLACFrame to remove ambiguity with PCM frames.
12394 - Fix errors when seeking to the end of a stream.
12395 - Optimizations to seeking.
12396 - SSE improvements and optimizations.
12397 - ARM NEON optimizations.
12398 - Optimizations to drflac_read_pcm_frames_s16().
12399 - Optimizations to drflac_read_pcm_frames_s32().
12400
12401 v0.11.10 - 2019-06-26
12402 - Fix a compiler error.
12403
12404 v0.11.9 - 2019-06-16
12405 - Silence some ThreadSanitizer warnings.
12406
12407 v0.11.8 - 2019-05-21
12408 - Fix warnings.
12409
12410 v0.11.7 - 2019-05-06
12411 - C89 fixes.
12412
12413 v0.11.6 - 2019-05-05
12414 - Add support for C89.
12415 - Fix a compiler warning when CRC is disabled.
12416 - Change license to choice of public domain or MIT-0.
12417
12418 v0.11.5 - 2019-04-19
12419 - Fix a compiler error with GCC.
12420
12421 v0.11.4 - 2019-04-17
12422 - Fix some warnings with GCC when compiling with -std=c99.
12423
12424 v0.11.3 - 2019-04-07
12425 - Silence warnings with GCC.
12426
12427 v0.11.2 - 2019-03-10
12428 - Fix a warning.
12429
12430 v0.11.1 - 2019-02-17
12431 - Fix a potential bug with seeking.
12432
12433 v0.11.0 - 2018-12-16
12434 - API CHANGE: Deprecated drflac_read_s32(), drflac_read_s16() and drflac_read_f32() and replaced them with
12435 drflac_read_pcm_frames_s32(), drflac_read_pcm_frames_s16() and drflac_read_pcm_frames_f32(). The new APIs take
12436 and return PCM frame counts instead of sample counts. To upgrade you will need to change the input count by
12437 dividing it by the channel count, and then do the same with the return value.
12438 - API_CHANGE: Deprecated drflac_seek_to_sample() and replaced with drflac_seek_to_pcm_frame(). Same rules as
12439 the changes to drflac_read_*() apply.
12440 - API CHANGE: Deprecated drflac_open_and_decode_*() and replaced with drflac_open_*_and_read_*(). Same rules as
12441 the changes to drflac_read_*() apply.
12442 - Optimizations.
12443
12444 v0.10.0 - 2018-09-11
12445 - Remove the DR_FLAC_NO_WIN32_IO option and the Win32 file IO functionality. If you need to use Win32 file IO you
12446 need to do it yourself via the callback API.
12447 - Fix the clang build.
12448 - Fix undefined behavior.
12449 - Fix errors with CUESHEET metdata blocks.
12450 - Add an API for iterating over each cuesheet track in the CUESHEET metadata block. This works the same way as the
12451 Vorbis comment API.
12452 - Other miscellaneous bug fixes, mostly relating to invalid FLAC streams.
12453 - Minor optimizations.
12454
12455 v0.9.11 - 2018-08-29
12456 - Fix a bug with sample reconstruction.
12457
12458 v0.9.10 - 2018-08-07
12459 - Improve 64-bit detection.
12460
12461 v0.9.9 - 2018-08-05
12462 - Fix C++ build on older versions of GCC.
12463
12464 v0.9.8 - 2018-07-24
12465 - Fix compilation errors.
12466
12467 v0.9.7 - 2018-07-05
12468 - Fix a warning.
12469
12470 v0.9.6 - 2018-06-29
12471 - Fix some typos.
12472
12473 v0.9.5 - 2018-06-23
12474 - Fix some warnings.
12475
12476 v0.9.4 - 2018-06-14
12477 - Optimizations to seeking.
12478 - Clean up.
12479
12480 v0.9.3 - 2018-05-22
12481 - Bug fix.
12482
12483 v0.9.2 - 2018-05-12
12484 - Fix a compilation error due to a missing break statement.
12485
12486 v0.9.1 - 2018-04-29
12487 - Fix compilation error with Clang.
12488
12489 v0.9 - 2018-04-24
12490 - Fix Clang build.
12491 - Start using major.minor.revision versioning.
12492
12493 v0.8g - 2018-04-19
12494 - Fix build on non-x86/x64 architectures.
12495
12496 v0.8f - 2018-02-02
12497 - Stop pretending to support changing rate/channels mid stream.
12498
12499 v0.8e - 2018-02-01
12500 - Fix a crash when the block size of a frame is larger than the maximum block size defined by the FLAC stream.
12501 - Fix a crash the the Rice partition order is invalid.
12502
12503 v0.8d - 2017-09-22
12504 - Add support for decoding streams with ID3 tags. ID3 tags are just skipped.
12505
12506 v0.8c - 2017-09-07
12507 - Fix warning on non-x86/x64 architectures.
12508
12509 v0.8b - 2017-08-19
12510 - Fix build on non-x86/x64 architectures.
12511
12512 v0.8a - 2017-08-13
12513 - A small optimization for the Clang build.
12514
12515 v0.8 - 2017-08-12
12516 - API CHANGE: Rename dr_* types to drflac_*.
12517 - Optimizations. This brings dr_flac back to about the same class of efficiency as the reference implementation.
12518 - Add support for custom implementations of malloc(), realloc(), etc.
12519 - Add CRC checking to Ogg encapsulated streams.
12520 - Fix VC++ 6 build. This is only for the C++ compiler. The C compiler is not currently supported.
12521 - Bug fixes.
12522
12523 v0.7 - 2017-07-23
12524 - Add support for opening a stream without a header block. To do this, use drflac_open_relaxed() / drflac_open_with_metadata_relaxed().
12525
12526 v0.6 - 2017-07-22
12527 - Add support for recovering from invalid frames. With this change, dr_flac will simply skip over invalid frames as if they
12528 never existed. Frames are checked against their sync code, the CRC-8 of the frame header and the CRC-16 of the whole frame.
12529
12530 v0.5 - 2017-07-16
12531 - Fix typos.
12532 - Change drflac_bool* types to unsigned.
12533 - Add CRC checking. This makes dr_flac slower, but can be disabled with #define DR_FLAC_NO_CRC.
12534
12535 v0.4f - 2017-03-10
12536 - Fix a couple of bugs with the bitstreaming code.
12537
12538 v0.4e - 2017-02-17
12539 - Fix some warnings.
12540
12541 v0.4d - 2016-12-26
12542 - Add support for 32-bit floating-point PCM decoding.
12543 - Use drflac_int* and drflac_uint* sized types to improve compiler support.
12544 - Minor improvements to documentation.
12545
12546 v0.4c - 2016-12-26
12547 - Add support for signed 16-bit integer PCM decoding.
12548
12549 v0.4b - 2016-10-23
12550 - A minor change to drflac_bool8 and drflac_bool32 types.
12551
12552 v0.4a - 2016-10-11
12553 - Rename drBool32 to drflac_bool32 for styling consistency.
12554
12555 v0.4 - 2016-09-29
12556 - API/ABI CHANGE: Use fixed size 32-bit booleans instead of the built-in bool type.
12557 - API CHANGE: Rename drflac_open_and_decode*() to drflac_open_and_decode*_s32().
12558 - API CHANGE: Swap the order of "channels" and "sampleRate" parameters in drflac_open_and_decode*(). Rationale for this is to
12559 keep it consistent with drflac_audio.
12560
12561 v0.3f - 2016-09-21
12562 - Fix a warning with GCC.
12563
12564 v0.3e - 2016-09-18
12565 - Fixed a bug where GCC 4.3+ was not getting properly identified.
12566 - Fixed a few typos.
12567 - Changed date formats to ISO 8601 (YYYY-MM-DD).
12568
12569 v0.3d - 2016-06-11
12570 - Minor clean up.
12571
12572 v0.3c - 2016-05-28
12573 - Fixed compilation error.
12574
12575 v0.3b - 2016-05-16
12576 - Fixed Linux/GCC build.
12577 - Updated documentation.
12578
12579 v0.3a - 2016-05-15
12580 - Minor fixes to documentation.
12581
12582 v0.3 - 2016-05-11
12583 - Optimizations. Now at about parity with the reference implementation on 32-bit builds.
12584 - Lots of clean up.
12585
12586 v0.2b - 2016-05-10
12587 - Bug fixes.
12588
12589 v0.2a - 2016-05-10
12590 - Made drflac_open_and_decode() more robust.
12591 - Removed an unused debugging variable
12592
12593 v0.2 - 2016-05-09
12594 - Added support for Ogg encapsulation.
12595 - API CHANGE. Have the onSeek callback take a third argument which specifies whether or not the seek
12596 should be relative to the start or the current position. Also changes the seeking rules such that
12597 seeking offsets will never be negative.
12598 - Have drflac_open_and_decode() fail gracefully if the stream has an unknown total sample count.
12599
12600 v0.1b - 2016-05-07
12601 - Properly close the file handle in drflac_open_file() and family when the decoder fails to initialize.
12602 - Removed a stale comment.
12603
12604 v0.1a - 2016-05-05
12605 - Minor formatting changes.
12606 - Fixed a warning on the GCC build.
12607
12608 v0.1 - 2016-05-03
12609 - Initial versioned release.
12610 */
12611
12612 /*
12613 This software is available as a choice of the following licenses. Choose
12614 whichever you prefer.
12615
12616 ===============================================================================
12617 ALTERNATIVE 1 - Public Domain (www.unlicense.org)
12618 ===============================================================================
12619 This is free and unencumbered software released into the public domain.
12620
12621 Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
12622 software, either in source code form or as a compiled binary, for any purpose,
12623 commercial or non-commercial, and by any means.
12624
12625 In jurisdictions that recognize copyright laws, the author or authors of this
12626 software dedicate any and all copyright interest in the software to the public
12627 domain. We make this dedication for the benefit of the public at large and to
12628 the detriment of our heirs and successors. We intend this dedication to be an
12629 overt act of relinquishment in perpetuity of all present and future rights to
12630 this software under copyright law.
12631
12632 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12633 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12634 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12635 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
12636 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
12637 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12638
12639 For more information, please refer to <http://unlicense.org/>
12640
12641 ===============================================================================
12642 ALTERNATIVE 2 - MIT No Attribution
12643 ===============================================================================
12644 Copyright 2023 David Reid
12645
12646 Permission is hereby granted, free of charge, to any person obtaining a copy of
12647 this software and associated documentation files (the "Software"), to deal in
12648 the Software without restriction, including without limitation the rights to
12649 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
12650 of the Software, and to permit persons to whom the Software is furnished to do
12651 so.
12652
12653 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12654 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12655 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12656 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12657 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12658 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
12659 SOFTWARE.
12660 */