Debian Codegraph @

include/dr_libs/dr_flac.h

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
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 drflac_cache_t r;
2720 __asm__ __volatile__ (
•2721 "lzcnt{ %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
2722 );
2723
2724 return (drflac_uint32)r;
2725 }
2726 #elif defined(DRFLAC_X86)
2727 {
2728 drflac_uint32 r;
2729 __asm__ __volatile__ (
•2730 "lzcnt{l %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
2731 );
2732
2733 return r;
2734 }
2735 #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. */
2736 {
2737 unsigned int r;
2738 __asm__ __volatile__ (
2739 #if defined(DRFLAC_64BIT)
2740 "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! */
2741 #else
2742 "clz %[out], %[in]" : [out]"=r"(r) : [in]"r"(x)
2743 #endif
2744 );
2745
2746 return r;
2747 }
2748 #else
2749 if (x == 0) {
2750 return sizeof(x)*8;
2751 }
2752 #ifdef DRFLAC_64BIT
2753 return (drflac_uint32)__builtin_clzll((drflac_uint64)x);
2754 #else
2755 return (drflac_uint32)__builtin_clzl((drflac_uint32)x);
2756 #endif
2757 #endif
2758 #else
2759 /* Unsupported compiler. */
2760 #error "This compiler does not support the lzcnt intrinsic."
2761 #endif
2762 #endif
2763 }
2764 #endif
2765
2766 #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
2767 #include <intrin.h> /* For BitScanReverse(). */
2768
2769 static DRFLAC_INLINE drflac_uint32 drflac__clz_msvc(drflac_cache_t x)
2770 {
2771 drflac_uint32 n;
2772
2773 if (x == 0) {
2774 return sizeof(x)*8;
2775 }
2776
2777 #ifdef DRFLAC_64BIT
2778 _BitScanReverse64((unsigned long*)&n, x);
2779 #else
2780 _BitScanReverse((unsigned long*)&n, x);
2781 #endif
2782 return sizeof(x)*8 - n - 1;
2783 }
2784 #endif
2785
2786 #ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM
2787 static __inline drflac_uint32 drflac__clz_watcom (drflac_uint32);
2788 #ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM_LZCNT
2789 /* Use the LZCNT instruction (only available on some processors since the 2010s). */
2790 #pragma aux drflac__clz_watcom_lzcnt = \
2791 "db 0F3h, 0Fh, 0BDh, 0C0h" /* lzcnt eax, eax */ \
2792 parm [eax] \
2793 value [eax] \
2794 modify nomemory;
2795 #else
2796 /* Use the 386+-compatible implementation. */
2797 #pragma aux drflac__clz_watcom = \
2798 "bsr eax, eax" \
2799 "xor eax, 31" \
2800 parm [eax] nomemory \
2801 value [eax] \
2802 modify exact [eax] nomemory;
2803 #endif
2804 #endif
2805
2806 static DRFLAC_INLINE drflac_uint32 drflac__clz(drflac_cache_t x)
2807 {
2808 #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
2809 if (drflac__is_lzcnt_supported()) {
2810 return drflac__clz_lzcnt(x);
2811 } else
2812 #endif
2813 {
2814 #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
2815 return drflac__clz_msvc(x);
2816 #elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM_LZCNT)
2817 return drflac__clz_watcom_lzcnt(x);
2818 #elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM)
2819 return (x == 0) ? sizeof(x)*8 : drflac__clz_watcom(x);
2820 #elif defined(__MRC__)
2821 return __cntlzw(x);
2822 #else
2823 return drflac__clz_software(x);
2824 #endif
2825 }
2826 }
2827
2828
2829 static DRFLAC_INLINE drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsigned int* pOffsetOut)
2830 {
2831 drflac_uint32 zeroCounter = 0;
2832 drflac_uint32 setBitOffsetPlus1;
2833
2834 while (bs->cache == 0) {
2835 zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2836 if (!drflac__reload_cache(bs)) {
2837 return DRFLAC_FALSE;
2838 }
2839 }
2840
2841 if (bs->cache == 1) {
2842 /* Not catching this would lead to undefined behaviour: a shift of a 32-bit number by 32 or more is undefined */
2843 *pOffsetOut = zeroCounter + (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs) - 1;
2844 if (!drflac__reload_cache(bs)) {
2845 return DRFLAC_FALSE;
2846 }
2847
2848 return DRFLAC_TRUE;
2849 }
2850
2851 setBitOffsetPlus1 = drflac__clz(bs->cache);
2852 setBitOffsetPlus1 += 1;
2853
2854 if (setBitOffsetPlus1 > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2855 /* This happens when we get to end of stream */
2856 return DRFLAC_FALSE;
2857 }
2858
2859 bs->consumedBits += setBitOffsetPlus1;
2860 bs->cache <<= setBitOffsetPlus1;
2861
2862 *pOffsetOut = zeroCounter + setBitOffsetPlus1 - 1;
2863 return DRFLAC_TRUE;
2864 }
2865
2866
2867
2868 static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFromStart)
2869 {
2870 DRFLAC_ASSERT(bs != NULL);
2871 DRFLAC_ASSERT(offsetFromStart > 0);
2872
2873 /*
2874 Seeking from the start is not quite as trivial as it sounds because the onSeek callback takes a signed 32-bit integer (which
2875 is intentional because it simplifies the implementation of the onSeek callbacks), however offsetFromStart is unsigned 64-bit.
2876 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.
2877 */
2878 if (offsetFromStart > 0x7FFFFFFF) {
2879 drflac_uint64 bytesRemaining = offsetFromStart;
2880 if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, DRFLAC_SEEK_SET)) {
2881 return DRFLAC_FALSE;
2882 }
2883 bytesRemaining -= 0x7FFFFFFF;
2884
2885 while (bytesRemaining > 0x7FFFFFFF) {
2886 if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, DRFLAC_SEEK_CUR)) {
2887 return DRFLAC_FALSE;
2888 }
2889 bytesRemaining -= 0x7FFFFFFF;
2890 }
2891
2892 if (bytesRemaining > 0) {
2893 if (!bs->onSeek(bs->pUserData, (int)bytesRemaining, DRFLAC_SEEK_CUR)) {
2894 return DRFLAC_FALSE;
2895 }
2896 }
2897 } else {
2898 if (!bs->onSeek(bs->pUserData, (int)offsetFromStart, DRFLAC_SEEK_SET)) {
2899 return DRFLAC_FALSE;
2900 }
2901 }
2902
2903 /* The cache should be reset to force a reload of fresh data from the client. */
2904 drflac__reset_cache(bs);
2905 return DRFLAC_TRUE;
2906 }
2907
2908
2909 static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64* pNumberOut, drflac_uint8* pCRCOut)
2910 {
2911 drflac_uint8 crc;
2912 drflac_uint64 result;
2913 drflac_uint8 utf8[7] = {0};
2914 int byteCount;
2915 int i;
2916
2917 DRFLAC_ASSERT(bs != NULL);
2918 DRFLAC_ASSERT(pNumberOut != NULL);
2919 DRFLAC_ASSERT(pCRCOut != NULL);
2920
2921 crc = *pCRCOut;
2922
2923 if (!drflac__read_uint8(bs, 8, utf8)) {
2924 *pNumberOut = 0;
2925 return DRFLAC_AT_END;
2926 }
2927 crc = drflac_crc8(crc, utf8[0], 8);
2928
2929 if ((utf8[0] & 0x80) == 0) {
2930 *pNumberOut = utf8[0];
2931 *pCRCOut = crc;
2932 return DRFLAC_SUCCESS;
2933 }
2934
2935 /*byteCount = 1;*/
2936 if ((utf8[0] & 0xE0) == 0xC0) {
2937 byteCount = 2;
2938 } else if ((utf8[0] & 0xF0) == 0xE0) {
2939 byteCount = 3;
2940 } else if ((utf8[0] & 0xF8) == 0xF0) {
2941 byteCount = 4;
2942 } else if ((utf8[0] & 0xFC) == 0xF8) {
2943 byteCount = 5;
2944 } else if ((utf8[0] & 0xFE) == 0xFC) {
2945 byteCount = 6;
2946 } else if ((utf8[0] & 0xFF) == 0xFE) {
2947 byteCount = 7;
2948 } else {
2949 *pNumberOut = 0;
2950 return DRFLAC_CRC_MISMATCH; /* Bad UTF-8 encoding. */
2951 }
2952
2953 /* Read extra bytes. */
2954 DRFLAC_ASSERT(byteCount > 1);
2955
2956 result = (drflac_uint64)(utf8[0] & (0xFF >> (byteCount + 1)));
2957 for (i = 1; i < byteCount; ++i) {
2958 if (!drflac__read_uint8(bs, 8, utf8 + i)) {
2959 *pNumberOut = 0;
2960 return DRFLAC_AT_END;
2961 }
2962 crc = drflac_crc8(crc, utf8[i], 8);
2963
2964 result = (result << 6) | (utf8[i] & 0x3F);
2965 }
2966
2967 *pNumberOut = result;
2968 *pCRCOut = crc;
2969 return DRFLAC_SUCCESS;
2970 }
2971
2972
2973 static DRFLAC_INLINE drflac_uint32 drflac__ilog2_u32(drflac_uint32 x)
2974 {
2975 #if 1 /* Needs optimizing. */
2976 drflac_uint32 result = 0;
2977 while (x > 0) {
2978 result += 1;
2979 x >>= 1;
2980 }
2981
2982 return result;
2983 #endif
2984 }
2985
2986 static DRFLAC_INLINE drflac_bool32 drflac__use_64_bit_prediction(drflac_uint32 bitsPerSample, drflac_uint32 order, drflac_uint32 precision)
2987 {
2988 /* https://web.archive.org/web/20220205005724/https://github.com/ietf-wg-cellar/flac-specification/blob/37a49aa48ba4ba12e8757badfc59c0df35435fec/rfc_backmatter.md */
2989 return bitsPerSample + precision + drflac__ilog2_u32(order) > 32;
2990 }
2991
2992
2993 /*
2994 The next two functions are responsible for calculating the prediction.
2995
2996 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
2997 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.
2998 */
2999 #if defined(__clang__)
3000 __attribute__((no_sanitize("signed-integer-overflow")))
3001 #endif
3002 static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_32(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
3003 {
3004 drflac_int32 prediction = 0;
3005
3006 DRFLAC_ASSERT(order <= 32);
3007
3008 /* 32-bit version. */
3009
3010 /* VC++ optimizes this to a single jmp. I've not yet verified this for other compilers. */
3011 switch (order)
3012 {
3013 case 32: prediction += coefficients[31] * pDecodedSamples[-32];
3014 case 31: prediction += coefficients[30] * pDecodedSamples[-31];
3015 case 30: prediction += coefficients[29] * pDecodedSamples[-30];
3016 case 29: prediction += coefficients[28] * pDecodedSamples[-29];
3017 case 28: prediction += coefficients[27] * pDecodedSamples[-28];
3018 case 27: prediction += coefficients[26] * pDecodedSamples[-27];
3019 case 26: prediction += coefficients[25] * pDecodedSamples[-26];
3020 case 25: prediction += coefficients[24] * pDecodedSamples[-25];
3021 case 24: prediction += coefficients[23] * pDecodedSamples[-24];
3022 case 23: prediction += coefficients[22] * pDecodedSamples[-23];
3023 case 22: prediction += coefficients[21] * pDecodedSamples[-22];
3024 case 21: prediction += coefficients[20] * pDecodedSamples[-21];
3025 case 20: prediction += coefficients[19] * pDecodedSamples[-20];
3026 case 19: prediction += coefficients[18] * pDecodedSamples[-19];
3027 case 18: prediction += coefficients[17] * pDecodedSamples[-18];
3028 case 17: prediction += coefficients[16] * pDecodedSamples[-17];
3029 case 16: prediction += coefficients[15] * pDecodedSamples[-16];
3030 case 15: prediction += coefficients[14] * pDecodedSamples[-15];
3031 case 14: prediction += coefficients[13] * pDecodedSamples[-14];
3032 case 13: prediction += coefficients[12] * pDecodedSamples[-13];
3033 case 12: prediction += coefficients[11] * pDecodedSamples[-12];
3034 case 11: prediction += coefficients[10] * pDecodedSamples[-11];
3035 case 10: prediction += coefficients[ 9] * pDecodedSamples[-10];
3036 case 9: prediction += coefficients[ 8] * pDecodedSamples[- 9];
3037 case 8: prediction += coefficients[ 7] * pDecodedSamples[- 8];
3038 case 7: prediction += coefficients[ 6] * pDecodedSamples[- 7];
3039 case 6: prediction += coefficients[ 5] * pDecodedSamples[- 6];
3040 case 5: prediction += coefficients[ 4] * pDecodedSamples[- 5];
3041 case 4: prediction += coefficients[ 3] * pDecodedSamples[- 4];
3042 case 3: prediction += coefficients[ 2] * pDecodedSamples[- 3];
3043 case 2: prediction += coefficients[ 1] * pDecodedSamples[- 2];
3044 case 1: prediction += coefficients[ 0] * pDecodedSamples[- 1];
3045 }
3046
3047 return (drflac_int32)(prediction >> shift);
3048 }
3049
3050 static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
3051 {
3052 drflac_int64 prediction;
3053
3054 DRFLAC_ASSERT(order <= 32);
3055
3056 /* 64-bit version. */
3057
3058 /* This method is faster on the 32-bit build when compiling with VC++. See note below. */
3059 #ifndef DRFLAC_64BIT
3060 if (order == 8)
3061 {
3062 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3063 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3064 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3065 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3066 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3067 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3068 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3069 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3070 }
3071 else if (order == 7)
3072 {
3073 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3074 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3075 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3076 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3077 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3078 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3079 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3080 }
3081 else if (order == 3)
3082 {
3083 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3084 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3085 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3086 }
3087 else if (order == 6)
3088 {
3089 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3090 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3091 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3092 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3093 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3094 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3095 }
3096 else if (order == 5)
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 }
3104 else if (order == 4)
3105 {
3106 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3107 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3108 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3109 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3110 }
3111 else if (order == 12)
3112 {
3113 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3114 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3115 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3116 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3117 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3118 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3119 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3120 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3121 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3122 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
3123 prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
3124 prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
3125 }
3126 else if (order == 2)
3127 {
3128 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3129 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3130 }
3131 else if (order == 1)
3132 {
3133 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3134 }
3135 else if (order == 10)
3136 {
3137 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3138 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3139 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3140 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3141 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3142 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3143 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3144 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3145 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3146 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
3147 }
3148 else if (order == 9)
3149 {
3150 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3151 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3152 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3153 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3154 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3155 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3156 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3157 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3158 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3159 }
3160 else if (order == 11)
3161 {
3162 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3163 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3164 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3165 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3166 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3167 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3168 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3169 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3170 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3171 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
3172 prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
3173 }
3174 else
3175 {
3176 int j;
3177
3178 prediction = 0;
3179 for (j = 0; j < (int)order; ++j) {
3180 prediction += coefficients[j] * (drflac_int64)pDecodedSamples[-j-1];
3181 }
3182 }
3183 #endif
3184
3185 /*
3186 VC++ optimizes this to a single jmp instruction, but only the 64-bit build. The 32-bit build generates less efficient code for some
3187 reason. The ugly version above is faster so we'll just switch between the two depending on the target platform.
3188 */
3189 #ifdef DRFLAC_64BIT
3190 prediction = 0;
3191 switch (order)
3192 {
3193 case 32: prediction += coefficients[31] * (drflac_int64)pDecodedSamples[-32];
3194 case 31: prediction += coefficients[30] * (drflac_int64)pDecodedSamples[-31];
3195 case 30: prediction += coefficients[29] * (drflac_int64)pDecodedSamples[-30];
3196 case 29: prediction += coefficients[28] * (drflac_int64)pDecodedSamples[-29];
3197 case 28: prediction += coefficients[27] * (drflac_int64)pDecodedSamples[-28];
3198 case 27: prediction += coefficients[26] * (drflac_int64)pDecodedSamples[-27];
3199 case 26: prediction += coefficients[25] * (drflac_int64)pDecodedSamples[-26];
3200 case 25: prediction += coefficients[24] * (drflac_int64)pDecodedSamples[-25];
3201 case 24: prediction += coefficients[23] * (drflac_int64)pDecodedSamples[-24];
3202 case 23: prediction += coefficients[22] * (drflac_int64)pDecodedSamples[-23];
3203 case 22: prediction += coefficients[21] * (drflac_int64)pDecodedSamples[-22];
3204 case 21: prediction += coefficients[20] * (drflac_int64)pDecodedSamples[-21];
3205 case 20: prediction += coefficients[19] * (drflac_int64)pDecodedSamples[-20];
3206 case 19: prediction += coefficients[18] * (drflac_int64)pDecodedSamples[-19];
3207 case 18: prediction += coefficients[17] * (drflac_int64)pDecodedSamples[-18];
3208 case 17: prediction += coefficients[16] * (drflac_int64)pDecodedSamples[-17];
3209 case 16: prediction += coefficients[15] * (drflac_int64)pDecodedSamples[-16];
3210 case 15: prediction += coefficients[14] * (drflac_int64)pDecodedSamples[-15];
3211 case 14: prediction += coefficients[13] * (drflac_int64)pDecodedSamples[-14];
3212 case 13: prediction += coefficients[12] * (drflac_int64)pDecodedSamples[-13];
3213 case 12: prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
3214 case 11: prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
3215 case 10: prediction += coefficients[ 9] * (drflac_int64)pDecodedSamples[-10];
3216 case 9: prediction += coefficients[ 8] * (drflac_int64)pDecodedSamples[- 9];
3217 case 8: prediction += coefficients[ 7] * (drflac_int64)pDecodedSamples[- 8];
3218 case 7: prediction += coefficients[ 6] * (drflac_int64)pDecodedSamples[- 7];
3219 case 6: prediction += coefficients[ 5] * (drflac_int64)pDecodedSamples[- 6];
3220 case 5: prediction += coefficients[ 4] * (drflac_int64)pDecodedSamples[- 5];
3221 case 4: prediction += coefficients[ 3] * (drflac_int64)pDecodedSamples[- 4];
3222 case 3: prediction += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 3];
3223 case 2: prediction += coefficients[ 1] * (drflac_int64)pDecodedSamples[- 2];
3224 case 1: prediction += coefficients[ 0] * (drflac_int64)pDecodedSamples[- 1];
3225 }
3226 #endif
3227
3228 return (drflac_int32)(prediction >> shift);
3229 }
3230
3231
3232 #if 0
3233 /*
3234 Reference implementation for reading and decoding samples with residual. This is intentionally left unoptimized for the
3235 sake of readability and should only be used as a reference.
3236 */
3237 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)
3238 {
3239 drflac_uint32 i;
3240
3241 DRFLAC_ASSERT(bs != NULL);
3242 DRFLAC_ASSERT(pSamplesOut != NULL);
3243
3244 for (i = 0; i < count; ++i) {
3245 drflac_uint32 zeroCounter = 0;
3246 for (;;) {
3247 drflac_uint8 bit;
3248 if (!drflac__read_uint8(bs, 1, &bit)) {
3249 return DRFLAC_FALSE;
3250 }
3251
3252 if (bit == 0) {
3253 zeroCounter += 1;
3254 } else {
3255 break;
3256 }
3257 }
3258
3259 drflac_uint32 decodedRice;
3260 if (riceParam > 0) {
3261 if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
3262 return DRFLAC_FALSE;
3263 }
3264 } else {
3265 decodedRice = 0;
3266 }
3267
3268 decodedRice |= (zeroCounter << riceParam);
3269 if ((decodedRice & 0x01)) {
3270 decodedRice = ~(decodedRice >> 1);
3271 } else {
3272 decodedRice = (decodedRice >> 1);
3273 }
3274
3275
3276 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
3277 pSamplesOut[i] = decodedRice + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
3278 } else {
3279 pSamplesOut[i] = decodedRice + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
3280 }
3281 }
3282
3283 return DRFLAC_TRUE;
3284 }
3285 #endif
3286
3287 #if 0
3288 static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
3289 {
3290 drflac_uint32 zeroCounter = 0;
3291 drflac_uint32 decodedRice;
3292
3293 for (;;) {
3294 drflac_uint8 bit;
3295 if (!drflac__read_uint8(bs, 1, &bit)) {
3296 return DRFLAC_FALSE;
3297 }
3298
3299 if (bit == 0) {
3300 zeroCounter += 1;
3301 } else {
3302 break;
3303 }
3304 }
3305
3306 if (riceParam > 0) {
3307 if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
3308 return DRFLAC_FALSE;
3309 }
3310 } else {
3311 decodedRice = 0;
3312 }
3313
3314 *pZeroCounterOut = zeroCounter;
3315 *pRiceParamPartOut = decodedRice;
3316 return DRFLAC_TRUE;
3317 }
3318 #endif
3319
3320 #if 0
3321 static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
3322 {
3323 drflac_cache_t riceParamMask;
3324 drflac_uint32 zeroCounter;
3325 drflac_uint32 setBitOffsetPlus1;
3326 drflac_uint32 riceParamPart;
3327 drflac_uint32 riceLength;
3328
3329 DRFLAC_ASSERT(riceParam > 0); /* <-- riceParam should never be 0. drflac__read_rice_parts__param_equals_zero() should be used instead for this case. */
3330
3331 riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParam);
3332
3333 zeroCounter = 0;
3334 while (bs->cache == 0) {
3335 zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
3336 if (!drflac__reload_cache(bs)) {
3337 return DRFLAC_FALSE;
3338 }
3339 }
3340
3341 setBitOffsetPlus1 = drflac__clz(bs->cache);
3342 zeroCounter += setBitOffsetPlus1;
3343 setBitOffsetPlus1 += 1;
3344
3345 riceLength = setBitOffsetPlus1 + riceParam;
3346 if (riceLength < DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3347 riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength));
3348
3349 bs->consumedBits += riceLength;
3350 bs->cache <<= riceLength;
3351 } else {
3352 drflac_uint32 bitCountLo;
3353 drflac_cache_t resultHi;
3354
3355 bs->consumedBits += riceLength;
3356 bs->cache <<= setBitOffsetPlus1 & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1); /* <-- Equivalent to "if (setBitOffsetPlus1 < DRFLAC_CACHE_L1_SIZE_BITS(bs)) { bs->cache <<= setBitOffsetPlus1; }" */
3357
3358 /* 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. */
3359 bitCountLo = bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs);
3360 resultHi = DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, riceParam); /* <-- Use DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE() if ever this function allows riceParam=0. */
3361
3362 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3363 #ifndef DR_FLAC_NO_CRC
3364 drflac__update_crc16(bs);
3365 #endif
3366 bs->cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3367 bs->consumedBits = 0;
3368 #ifndef DR_FLAC_NO_CRC
3369 bs->crc16Cache = bs->cache;
3370 #endif
3371 } else {
3372 /* Slow path. We need to fetch more data from the client. */
3373 if (!drflac__reload_cache(bs)) {
3374 return DRFLAC_FALSE;
3375 }
3376 if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3377 /* This happens when we get to end of stream */
3378 return DRFLAC_FALSE;
3379 }
3380 }
3381
3382 riceParamPart = (drflac_uint32)(resultHi | DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo));
3383
3384 bs->consumedBits += bitCountLo;
3385 bs->cache <<= bitCountLo;
3386 }
3387
3388 pZeroCounterOut[0] = zeroCounter;
3389 pRiceParamPartOut[0] = riceParamPart;
3390
3391 return DRFLAC_TRUE;
3392 }
3393 #endif
3394
3395 static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts_x1(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
3396 {
3397 drflac_uint32 riceParamPlus1 = riceParam + 1;
3398 /*drflac_cache_t riceParamPlus1Mask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParamPlus1);*/
3399 drflac_uint32 riceParamPlus1Shift = DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPlus1);
3400 drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
3401
3402 /*
3403 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
3404 no idea how this will work in practice...
3405 */
3406 drflac_cache_t bs_cache = bs->cache;
3407 drflac_uint32 bs_consumedBits = bs->consumedBits;
3408
3409 /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */
3410 drflac_uint32 lzcount = drflac__clz(bs_cache);
3411 if (lzcount < sizeof(bs_cache)*8) {
3412 pZeroCounterOut[0] = lzcount;
3413
3414 /*
3415 It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting
3416 this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled
3417 outside of this function at a higher level.
3418 */
3419 extract_rice_param_part:
3420 bs_cache <<= lzcount;
3421 bs_consumedBits += lzcount;
3422
3423 if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
3424 /* Getting here means the rice parameter part is wholly contained within the current cache line. */
3425 pRiceParamPartOut[0] = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
3426 bs_cache <<= riceParamPlus1;
3427 bs_consumedBits += riceParamPlus1;
3428 } else {
3429 drflac_uint32 riceParamPartHi;
3430 drflac_uint32 riceParamPartLo;
3431 drflac_uint32 riceParamPartLoBitCount;
3432
3433 /*
3434 Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache
3435 line, reload the cache, and then combine it with the head of the next cache line.
3436 */
3437
3438 /* Grab the high part of the rice parameter part. */
3439 riceParamPartHi = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
3440
3441 /* Before reloading the cache we need to grab the size in bits of the low part. */
3442 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
3443 DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
3444
3445 /* Now reload the cache. */
3446 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3447 #ifndef DR_FLAC_NO_CRC
3448 drflac__update_crc16(bs);
3449 #endif
3450 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3451 bs_consumedBits = riceParamPartLoBitCount;
3452 #ifndef DR_FLAC_NO_CRC
3453 bs->crc16Cache = bs_cache;
3454 #endif
3455 } else {
3456 /* Slow path. We need to fetch more data from the client. */
3457 if (!drflac__reload_cache(bs)) {
3458 return DRFLAC_FALSE;
3459 }
3460 if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3461 /* This happens when we get to end of stream */
3462 return DRFLAC_FALSE;
3463 }
3464
3465 bs_cache = bs->cache;
3466 bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
3467 }
3468
3469 /* We should now have enough information to construct the rice parameter part. */
3470 riceParamPartLo = (drflac_uint32)(bs_cache >> (DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPartLoBitCount)));
3471 pRiceParamPartOut[0] = riceParamPartHi | riceParamPartLo;
3472
3473 bs_cache <<= riceParamPartLoBitCount;
3474 }
3475 } else {
3476 /*
3477 Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call
3478 to drflac__clz() and we need to reload the cache.
3479 */
3480 drflac_uint32 zeroCounter = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BITS(bs) - bs_consumedBits);
3481 for (;;) {
3482 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3483 #ifndef DR_FLAC_NO_CRC
3484 drflac__update_crc16(bs);
3485 #endif
3486 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3487 bs_consumedBits = 0;
3488 #ifndef DR_FLAC_NO_CRC
3489 bs->crc16Cache = bs_cache;
3490 #endif
3491 } else {
3492 /* Slow path. We need to fetch more data from the client. */
3493 if (!drflac__reload_cache(bs)) {
3494 return DRFLAC_FALSE;
3495 }
3496
3497 bs_cache = bs->cache;
3498 bs_consumedBits = bs->consumedBits;
3499 }
3500
3501 lzcount = drflac__clz(bs_cache);
3502 zeroCounter += lzcount;
3503
3504 if (lzcount < sizeof(bs_cache)*8) {
3505 break;
3506 }
3507 }
3508
3509 pZeroCounterOut[0] = zeroCounter;
3510 goto extract_rice_param_part;
3511 }
3512
3513 /* Make sure the cache is restored at the end of it all. */
3514 bs->cache = bs_cache;
3515 bs->consumedBits = bs_consumedBits;
3516
3517 return DRFLAC_TRUE;
3518 }
3519
3520 static DRFLAC_INLINE drflac_bool32 drflac__seek_rice_parts(drflac_bs* bs, drflac_uint8 riceParam)
3521 {
3522 drflac_uint32 riceParamPlus1 = riceParam + 1;
3523 drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
3524
3525 /*
3526 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
3527 no idea how this will work in practice...
3528 */
3529 drflac_cache_t bs_cache = bs->cache;
3530 drflac_uint32 bs_consumedBits = bs->consumedBits;
3531
3532 /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */
3533 drflac_uint32 lzcount = drflac__clz(bs_cache);
3534 if (lzcount < sizeof(bs_cache)*8) {
3535 /*
3536 It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting
3537 this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled
3538 outside of this function at a higher level.
3539 */
3540 extract_rice_param_part:
3541 bs_cache <<= lzcount;
3542 bs_consumedBits += lzcount;
3543
3544 if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
3545 /* Getting here means the rice parameter part is wholly contained within the current cache line. */
3546 bs_cache <<= riceParamPlus1;
3547 bs_consumedBits += riceParamPlus1;
3548 } else {
3549 /*
3550 Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache
3551 line, reload the cache, and then combine it with the head of the next cache line.
3552 */
3553
3554 /* Before reloading the cache we need to grab the size in bits of the low part. */
3555 drflac_uint32 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
3556 DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
3557
3558 /* Now reload the cache. */
3559 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3560 #ifndef DR_FLAC_NO_CRC
3561 drflac__update_crc16(bs);
3562 #endif
3563 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3564 bs_consumedBits = riceParamPartLoBitCount;
3565 #ifndef DR_FLAC_NO_CRC
3566 bs->crc16Cache = bs_cache;
3567 #endif
3568 } else {
3569 /* Slow path. We need to fetch more data from the client. */
3570 if (!drflac__reload_cache(bs)) {
3571 return DRFLAC_FALSE;
3572 }
3573
3574 if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3575 /* This happens when we get to end of stream */
3576 return DRFLAC_FALSE;
3577 }
3578
3579 bs_cache = bs->cache;
3580 bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
3581 }
3582
3583 bs_cache <<= riceParamPartLoBitCount;
3584 }
3585 } else {
3586 /*
3587 Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call
3588 to drflac__clz() and we need to reload the cache.
3589 */
3590 for (;;) {
3591 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3592 #ifndef DR_FLAC_NO_CRC
3593 drflac__update_crc16(bs);
3594 #endif
3595 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3596 bs_consumedBits = 0;
3597 #ifndef DR_FLAC_NO_CRC
3598 bs->crc16Cache = bs_cache;
3599 #endif
3600 } else {
3601 /* Slow path. We need to fetch more data from the client. */
3602 if (!drflac__reload_cache(bs)) {
3603 return DRFLAC_FALSE;
3604 }
3605
3606 bs_cache = bs->cache;
3607 bs_consumedBits = bs->consumedBits;
3608 }
3609
3610 lzcount = drflac__clz(bs_cache);
3611 if (lzcount < sizeof(bs_cache)*8) {
3612 break;
3613 }
3614 }
3615
3616 goto extract_rice_param_part;
3617 }
3618
3619 /* Make sure the cache is restored at the end of it all. */
3620 bs->cache = bs_cache;
3621 bs->consumedBits = bs_consumedBits;
3622
3623 return DRFLAC_TRUE;
3624 }
3625
3626
3627 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)
3628 {
3629 drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
3630 drflac_uint32 zeroCountPart0;
3631 drflac_uint32 riceParamPart0;
3632 drflac_uint32 riceParamMask;
3633 drflac_uint32 i;
3634
3635 DRFLAC_ASSERT(bs != NULL);
3636 DRFLAC_ASSERT(pSamplesOut != NULL);
3637
3638 (void)bitsPerSample;
3639 (void)order;
3640 (void)shift;
3641 (void)coefficients;
3642
3643 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
3644
3645 i = 0;
3646 while (i < count) {
3647 /* Rice extraction. */
3648 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
3649 return DRFLAC_FALSE;
3650 }
3651
3652 /* Rice reconstruction. */
3653 riceParamPart0 &= riceParamMask;
3654 riceParamPart0 |= (zeroCountPart0 << riceParam);
3655 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3656
3657 pSamplesOut[i] = riceParamPart0;
3658
3659 i += 1;
3660 }
3661
3662 return DRFLAC_TRUE;
3663 }
3664
3665 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)
3666 {
3667 drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
3668 drflac_uint32 zeroCountPart0 = 0;
3669 drflac_uint32 zeroCountPart1 = 0;
3670 drflac_uint32 zeroCountPart2 = 0;
3671 drflac_uint32 zeroCountPart3 = 0;
3672 drflac_uint32 riceParamPart0 = 0;
3673 drflac_uint32 riceParamPart1 = 0;
3674 drflac_uint32 riceParamPart2 = 0;
3675 drflac_uint32 riceParamPart3 = 0;
3676 drflac_uint32 riceParamMask;
3677 const drflac_int32* pSamplesOutEnd;
3678 drflac_uint32 i;
3679
3680 DRFLAC_ASSERT(bs != NULL);
3681 DRFLAC_ASSERT(pSamplesOut != NULL);
3682
3683 if (lpcOrder == 0) {
3684 return drflac__decode_samples_with_residual__rice__scalar_zeroorder(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
3685 }
3686
3687 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
3688 pSamplesOutEnd = pSamplesOut + (count & ~3);
3689
3690 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
3691 while (pSamplesOut < pSamplesOutEnd) {
3692 /*
3693 Rice extraction. It's faster to do this one at a time against local variables than it is to use the x4 version
3694 against an array. Not sure why, but perhaps it's making more efficient use of registers?
3695 */
3696 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
3697 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
3698 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
3699 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
3700 return DRFLAC_FALSE;
3701 }
3702
3703 riceParamPart0 &= riceParamMask;
3704 riceParamPart1 &= riceParamMask;
3705 riceParamPart2 &= riceParamMask;
3706 riceParamPart3 &= riceParamMask;
3707
3708 riceParamPart0 |= (zeroCountPart0 << riceParam);
3709 riceParamPart1 |= (zeroCountPart1 << riceParam);
3710 riceParamPart2 |= (zeroCountPart2 << riceParam);
3711 riceParamPart3 |= (zeroCountPart3 << riceParam);
3712
3713 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3714 riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
3715 riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
3716 riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
3717
3718 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3719 pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
3720 pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
3721 pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
3722
3723 pSamplesOut += 4;
3724 }
3725 } else {
3726 while (pSamplesOut < pSamplesOutEnd) {
3727 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
3728 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
3729 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
3730 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
3731 return DRFLAC_FALSE;
3732 }
3733
3734 riceParamPart0 &= riceParamMask;
3735 riceParamPart1 &= riceParamMask;
3736 riceParamPart2 &= riceParamMask;
3737 riceParamPart3 &= riceParamMask;
3738
3739 riceParamPart0 |= (zeroCountPart0 << riceParam);
3740 riceParamPart1 |= (zeroCountPart1 << riceParam);
3741 riceParamPart2 |= (zeroCountPart2 << riceParam);
3742 riceParamPart3 |= (zeroCountPart3 << riceParam);
3743
3744 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3745 riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
3746 riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
3747 riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
3748
3749 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3750 pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
3751 pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
3752 pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
3753
3754 pSamplesOut += 4;
3755 }
3756 }
3757
3758 i = (count & ~3);
3759 while (i < count) {
3760 /* Rice extraction. */
3761 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
3762 return DRFLAC_FALSE;
3763 }
3764
3765 /* Rice reconstruction. */
3766 riceParamPart0 &= riceParamMask;
3767 riceParamPart0 |= (zeroCountPart0 << riceParam);
3768 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3769 /*riceParamPart0 = (riceParamPart0 >> 1) ^ (~(riceParamPart0 & 0x01) + 1);*/
3770
3771 /* Sample reconstruction. */
3772 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
3773 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3774 } else {
3775 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3776 }
3777
3778 i += 1;
3779 pSamplesOut += 1;
3780 }
3781
3782 return DRFLAC_TRUE;
3783 }
3784
3785 #if defined(DRFLAC_SUPPORT_SSE2)
3786 static DRFLAC_INLINE __m128i drflac__mm_packs_interleaved_epi32(__m128i a, __m128i b)
3787 {
3788 __m128i r;
3789
3790 /* Pack. */
3791 r = _mm_packs_epi32(a, b);
3792
3793 /* a3a2 a1a0 b3b2 b1b0 -> a3a2 b3b2 a1a0 b1b0 */
3794 r = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 1, 2, 0));
3795
3796 /* a3a2 b3b2 a1a0 b1b0 -> a3b3 a2b2 a1b1 a0b0 */
3797 r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
3798 r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
3799
3800 return r;
3801 }
3802 #endif
3803
3804 #if defined(DRFLAC_SUPPORT_SSE41)
3805 static DRFLAC_INLINE __m128i drflac__mm_not_si128(__m128i a)
3806 {
3807 return _mm_xor_si128(a, _mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128()));
3808 }
3809
3810 static DRFLAC_INLINE __m128i drflac__mm_hadd_epi32(__m128i x)
3811 {
3812 __m128i x64 = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
3813 __m128i x32 = _mm_shufflelo_epi16(x64, _MM_SHUFFLE(1, 0, 3, 2));
3814 return _mm_add_epi32(x64, x32);
3815 }
3816
3817 static DRFLAC_INLINE __m128i drflac__mm_hadd_epi64(__m128i x)
3818 {
3819 return _mm_add_epi64(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
3820 }
3821
3822 static DRFLAC_INLINE __m128i drflac__mm_srai_epi64(__m128i x, int count)
3823 {
3824 /*
3825 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
3826 is shifted with zero bits, whereas the right side is shifted with sign bits.
3827 */
3828 __m128i lo = _mm_srli_epi64(x, count);
3829 __m128i hi = _mm_srai_epi32(x, count);
3830
3831 hi = _mm_and_si128(hi, _mm_set_epi32(0xFFFFFFFF, 0, 0xFFFFFFFF, 0)); /* The high part needs to have the low part cleared. */
3832
3833 return _mm_or_si128(lo, hi);
3834 }
3835
3836 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)
3837 {
3838 int i;
3839 drflac_uint32 riceParamMask;
3840 drflac_int32* pDecodedSamples = pSamplesOut;
3841 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
3842 drflac_uint32 zeroCountParts0 = 0;
3843 drflac_uint32 zeroCountParts1 = 0;
3844 drflac_uint32 zeroCountParts2 = 0;
3845 drflac_uint32 zeroCountParts3 = 0;
3846 drflac_uint32 riceParamParts0 = 0;
3847 drflac_uint32 riceParamParts1 = 0;
3848 drflac_uint32 riceParamParts2 = 0;
3849 drflac_uint32 riceParamParts3 = 0;
3850 __m128i coefficients128_0;
3851 __m128i coefficients128_4;
3852 __m128i coefficients128_8;
3853 __m128i samples128_0;
3854 __m128i samples128_4;
3855 __m128i samples128_8;
3856 __m128i riceParamMask128;
3857
3858 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
3859
3860 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
3861 riceParamMask128 = _mm_set1_epi32(riceParamMask);
3862
3863 /* Pre-load. */
3864 coefficients128_0 = _mm_setzero_si128();
3865 coefficients128_4 = _mm_setzero_si128();
3866 coefficients128_8 = _mm_setzero_si128();
3867
3868 samples128_0 = _mm_setzero_si128();
3869 samples128_4 = _mm_setzero_si128();
3870 samples128_8 = _mm_setzero_si128();
3871
3872 /*
3873 Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
3874 what's available in the input buffers. It would be convenient to use a fall-through switch to do this, but this results
3875 in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
3876 so I think there's opportunity for this to be simplified.
3877 */
3878 #if 1
3879 {
3880 int runningOrder = order;
3881
3882 /* 0 - 3. */
3883 if (runningOrder >= 4) {
3884 coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
3885 samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
3886 runningOrder -= 4;
3887 } else {
3888 switch (runningOrder) {
3889 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;
3890 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;
3891 case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
3892 }
3893 runningOrder = 0;
3894 }
3895
3896 /* 4 - 7 */
3897 if (runningOrder >= 4) {
3898 coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
3899 samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
3900 runningOrder -= 4;
3901 } else {
3902 switch (runningOrder) {
3903 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;
3904 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;
3905 case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
3906 }
3907 runningOrder = 0;
3908 }
3909
3910 /* 8 - 11 */
3911 if (runningOrder == 4) {
3912 coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
3913 samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
3914 runningOrder -= 4;
3915 } else {
3916 switch (runningOrder) {
3917 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;
3918 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;
3919 case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
3920 }
3921 runningOrder = 0;
3922 }
3923
3924 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
3925 coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
3926 coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
3927 coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
3928 }
3929 #else
3930 /* This causes strict-aliasing warnings with GCC. */
3931 switch (order)
3932 {
3933 case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
3934 case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
3935 case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
3936 case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
3937 case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
3938 case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
3939 case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
3940 case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
3941 case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
3942 case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
3943 case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
3944 case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
3945 }
3946 #endif
3947
3948 /* For this version we are doing one sample at a time. */
3949 while (pDecodedSamples < pDecodedSamplesEnd) {
3950 __m128i prediction128;
3951 __m128i zeroCountPart128;
3952 __m128i riceParamPart128;
3953
3954 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
3955 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
3956 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
3957 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
3958 return DRFLAC_FALSE;
3959 }
3960
3961 zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
3962 riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
3963
3964 riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
3965 riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
3966 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 */
3967 /*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... */
3968
3969 if (order <= 4) {
3970 for (i = 0; i < 4; i += 1) {
3971 prediction128 = _mm_mullo_epi32(coefficients128_0, samples128_0);
3972
3973 /* Horizontal add and shift. */
3974 prediction128 = drflac__mm_hadd_epi32(prediction128);
3975 prediction128 = _mm_srai_epi32(prediction128, shift);
3976 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
3977
3978 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
3979 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
3980 }
3981 } else if (order <= 8) {
3982 for (i = 0; i < 4; i += 1) {
3983 prediction128 = _mm_mullo_epi32(coefficients128_4, samples128_4);
3984 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
3985
3986 /* Horizontal add and shift. */
3987 prediction128 = drflac__mm_hadd_epi32(prediction128);
3988 prediction128 = _mm_srai_epi32(prediction128, shift);
3989 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
3990
3991 samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
3992 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
3993 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
3994 }
3995 } else {
3996 for (i = 0; i < 4; i += 1) {
3997 prediction128 = _mm_mullo_epi32(coefficients128_8, samples128_8);
3998 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_4, samples128_4));
3999 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
4000
4001 /* Horizontal add and shift. */
4002 prediction128 = drflac__mm_hadd_epi32(prediction128);
4003 prediction128 = _mm_srai_epi32(prediction128, shift);
4004 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
4005
4006 samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
4007 samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
4008 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
4009 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
4010 }
4011 }
4012
4013 /* We store samples in groups of 4. */
4014 _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
4015 pDecodedSamples += 4;
4016 }
4017
4018 /* Make sure we process the last few samples. */
4019 i = (count & ~3);
4020 while (i < (int)count) {
4021 /* Rice extraction. */
4022 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
4023 return DRFLAC_FALSE;
4024 }
4025
4026 /* Rice reconstruction. */
4027 riceParamParts0 &= riceParamMask;
4028 riceParamParts0 |= (zeroCountParts0 << riceParam);
4029 riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
4030
4031 /* Sample reconstruction. */
4032 pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
4033
4034 i += 1;
4035 pDecodedSamples += 1;
4036 }
4037
4038 return DRFLAC_TRUE;
4039 }
4040
4041 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)
4042 {
4043 int i;
4044 drflac_uint32 riceParamMask;
4045 drflac_int32* pDecodedSamples = pSamplesOut;
4046 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
4047 drflac_uint32 zeroCountParts0 = 0;
4048 drflac_uint32 zeroCountParts1 = 0;
4049 drflac_uint32 zeroCountParts2 = 0;
4050 drflac_uint32 zeroCountParts3 = 0;
4051 drflac_uint32 riceParamParts0 = 0;
4052 drflac_uint32 riceParamParts1 = 0;
4053 drflac_uint32 riceParamParts2 = 0;
4054 drflac_uint32 riceParamParts3 = 0;
4055 __m128i coefficients128_0;
4056 __m128i coefficients128_4;
4057 __m128i coefficients128_8;
4058 __m128i samples128_0;
4059 __m128i samples128_4;
4060 __m128i samples128_8;
4061 __m128i prediction128;
4062 __m128i riceParamMask128;
4063
4064 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
4065
4066 DRFLAC_ASSERT(order <= 12);
4067
4068 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
4069 riceParamMask128 = _mm_set1_epi32(riceParamMask);
4070
4071 prediction128 = _mm_setzero_si128();
4072
4073 /* Pre-load. */
4074 coefficients128_0 = _mm_setzero_si128();
4075 coefficients128_4 = _mm_setzero_si128();
4076 coefficients128_8 = _mm_setzero_si128();
4077
4078 samples128_0 = _mm_setzero_si128();
4079 samples128_4 = _mm_setzero_si128();
4080 samples128_8 = _mm_setzero_si128();
4081
4082 #if 1
4083 {
4084 int runningOrder = order;
4085
4086 /* 0 - 3. */
4087 if (runningOrder >= 4) {
4088 coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
4089 samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
4090 runningOrder -= 4;
4091 } else {
4092 switch (runningOrder) {
4093 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;
4094 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;
4095 case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
4096 }
4097 runningOrder = 0;
4098 }
4099
4100 /* 4 - 7 */
4101 if (runningOrder >= 4) {
4102 coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
4103 samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
4104 runningOrder -= 4;
4105 } else {
4106 switch (runningOrder) {
4107 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;
4108 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;
4109 case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
4110 }
4111 runningOrder = 0;
4112 }
4113
4114 /* 8 - 11 */
4115 if (runningOrder == 4) {
4116 coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
4117 samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
4118 runningOrder -= 4;
4119 } else {
4120 switch (runningOrder) {
4121 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;
4122 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;
4123 case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
4124 }
4125 runningOrder = 0;
4126 }
4127
4128 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
4129 coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
4130 coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
4131 coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
4132 }
4133 #else
4134 switch (order)
4135 {
4136 case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
4137 case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
4138 case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
4139 case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
4140 case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
4141 case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
4142 case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
4143 case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
4144 case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
4145 case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
4146 case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
4147 case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
4148 }
4149 #endif
4150
4151 /* For this version we are doing one sample at a time. */
4152 while (pDecodedSamples < pDecodedSamplesEnd) {
4153 __m128i zeroCountPart128;
4154 __m128i riceParamPart128;
4155
4156 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
4157 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
4158 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
4159 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
4160 return DRFLAC_FALSE;
4161 }
4162
4163 zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
4164 riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
4165
4166 riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
4167 riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
4168 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)));
4169
4170 for (i = 0; i < 4; i += 1) {
4171 prediction128 = _mm_xor_si128(prediction128, prediction128); /* Reset to 0. */
4172
4173 switch (order)
4174 {
4175 case 12:
4176 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))));
4177 case 10:
4178 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))));
4179 case 8:
4180 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))));
4181 case 6:
4182 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))));
4183 case 4:
4184 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))));
4185 case 2:
4186 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))));
4187 }
4188
4189 /* Horizontal add and shift. */
4190 prediction128 = drflac__mm_hadd_epi64(prediction128);
4191 prediction128 = drflac__mm_srai_epi64(prediction128, shift);
4192 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
4193
4194 /* Our value should be sitting in prediction128[0]. We need to combine this with our SSE samples. */
4195 samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
4196 samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
4197 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
4198
4199 /* Slide our rice parameter down so that the value in position 0 contains the next one to process. */
4200 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
4201 }
4202
4203 /* We store samples in groups of 4. */
4204 _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
4205 pDecodedSamples += 4;
4206 }
4207
4208 /* Make sure we process the last few samples. */
4209 i = (count & ~3);
4210 while (i < (int)count) {
4211 /* Rice extraction. */
4212 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
4213 return DRFLAC_FALSE;
4214 }
4215
4216 /* Rice reconstruction. */
4217 riceParamParts0 &= riceParamMask;
4218 riceParamParts0 |= (zeroCountParts0 << riceParam);
4219 riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
4220
4221 /* Sample reconstruction. */
4222 pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
4223
4224 i += 1;
4225 pDecodedSamples += 1;
4226 }
4227
4228 return DRFLAC_TRUE;
4229 }
4230
4231 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)
4232 {
4233 DRFLAC_ASSERT(bs != NULL);
4234 DRFLAC_ASSERT(pSamplesOut != NULL);
4235
4236 /* 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. */
4237 if (lpcOrder > 0 && lpcOrder <= 12) {
4238 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
4239 return drflac__decode_samples_with_residual__rice__sse41_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
4240 } else {
4241 return drflac__decode_samples_with_residual__rice__sse41_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
4242 }
4243 } else {
4244 return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4245 }
4246 }
4247 #endif
4248
4249 #if defined(DRFLAC_SUPPORT_NEON)
4250 static DRFLAC_INLINE void drflac__vst2q_s32(drflac_int32* p, int32x4x2_t x)
4251 {
4252 vst1q_s32(p+0, x.val[0]);
4253 vst1q_s32(p+4, x.val[1]);
4254 }
4255
4256 static DRFLAC_INLINE void drflac__vst2q_u32(drflac_uint32* p, uint32x4x2_t x)
4257 {
4258 vst1q_u32(p+0, x.val[0]);
4259 vst1q_u32(p+4, x.val[1]);
4260 }
4261
4262 static DRFLAC_INLINE void drflac__vst2q_f32(float* p, float32x4x2_t x)
4263 {
4264 vst1q_f32(p+0, x.val[0]);
4265 vst1q_f32(p+4, x.val[1]);
4266 }
4267
4268 static DRFLAC_INLINE void drflac__vst2q_s16(drflac_int16* p, int16x4x2_t x)
4269 {
4270 vst1q_s16(p, vcombine_s16(x.val[0], x.val[1]));
4271 }
4272
4273 static DRFLAC_INLINE void drflac__vst2q_u16(drflac_uint16* p, uint16x4x2_t x)
4274 {
4275 vst1q_u16(p, vcombine_u16(x.val[0], x.val[1]));
4276 }
4277
4278 static DRFLAC_INLINE int32x4_t drflac__vdupq_n_s32x4(drflac_int32 x3, drflac_int32 x2, drflac_int32 x1, drflac_int32 x0)
4279 {
4280 drflac_int32 x[4];
4281 x[3] = x3;
4282 x[2] = x2;
4283 x[1] = x1;
4284 x[0] = x0;
4285 return vld1q_s32(x);
4286 }
4287
4288 static DRFLAC_INLINE int32x4_t drflac__valignrq_s32_1(int32x4_t a, int32x4_t b)
4289 {
4290 /* Equivalent to SSE's _mm_alignr_epi8(a, b, 4) */
4291
4292 /* Reference */
4293 /*return drflac__vdupq_n_s32x4(
4294 vgetq_lane_s32(a, 0),
4295 vgetq_lane_s32(b, 3),
4296 vgetq_lane_s32(b, 2),
4297 vgetq_lane_s32(b, 1)
4298 );*/
4299
4300 return vextq_s32(b, a, 1);
4301 }
4302
4303 static DRFLAC_INLINE uint32x4_t drflac__valignrq_u32_1(uint32x4_t a, uint32x4_t b)
4304 {
4305 /* Equivalent to SSE's _mm_alignr_epi8(a, b, 4) */
4306
4307 /* Reference */
4308 /*return drflac__vdupq_n_s32x4(
4309 vgetq_lane_s32(a, 0),
4310 vgetq_lane_s32(b, 3),
4311 vgetq_lane_s32(b, 2),
4312 vgetq_lane_s32(b, 1)
4313 );*/
4314
4315 return vextq_u32(b, a, 1);
4316 }
4317
4318 static DRFLAC_INLINE int32x2_t drflac__vhaddq_s32(int32x4_t x)
4319 {
4320 /* The sum must end up in position 0. */
4321
4322 /* Reference */
4323 /*return vdupq_n_s32(
4324 vgetq_lane_s32(x, 3) +
4325 vgetq_lane_s32(x, 2) +
4326 vgetq_lane_s32(x, 1) +
4327 vgetq_lane_s32(x, 0)
4328 );*/
4329
4330 int32x2_t r = vadd_s32(vget_high_s32(x), vget_low_s32(x));
4331 return vpadd_s32(r, r);
4332 }
4333
4334 static DRFLAC_INLINE int64x1_t drflac__vhaddq_s64(int64x2_t x)
4335 {
4336 return vadd_s64(vget_high_s64(x), vget_low_s64(x));
4337 }
4338
4339 static DRFLAC_INLINE int32x4_t drflac__vrevq_s32(int32x4_t x)
4340 {
4341 /* Reference */
4342 /*return drflac__vdupq_n_s32x4(
4343 vgetq_lane_s32(x, 0),
4344 vgetq_lane_s32(x, 1),
4345 vgetq_lane_s32(x, 2),
4346 vgetq_lane_s32(x, 3)
4347 );*/
4348
4349 return vrev64q_s32(vcombine_s32(vget_high_s32(x), vget_low_s32(x)));
4350 }
4351
4352 static DRFLAC_INLINE int32x4_t drflac__vnotq_s32(int32x4_t x)
4353 {
4354 return veorq_s32(x, vdupq_n_s32(0xFFFFFFFF));
4355 }
4356
4357 static DRFLAC_INLINE uint32x4_t drflac__vnotq_u32(uint32x4_t x)
4358 {
4359 return veorq_u32(x, vdupq_n_u32(0xFFFFFFFF));
4360 }
4361
4362 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)
4363 {
4364 int i;
4365 drflac_uint32 riceParamMask;
4366 drflac_int32* pDecodedSamples = pSamplesOut;
4367 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
4368 drflac_uint32 zeroCountParts[4];
4369 drflac_uint32 riceParamParts[4];
4370 int32x4_t coefficients128_0;
4371 int32x4_t coefficients128_4;
4372 int32x4_t coefficients128_8;
4373 int32x4_t samples128_0;
4374 int32x4_t samples128_4;
4375 int32x4_t samples128_8;
4376 uint32x4_t riceParamMask128;
4377 int32x4_t riceParam128;
4378 int32x2_t shift64;
4379 uint32x4_t one128;
4380
4381 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
4382
4383 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
4384 riceParamMask128 = vdupq_n_u32(riceParamMask);
4385
4386 riceParam128 = vdupq_n_s32(riceParam);
4387 shift64 = vdup_n_s32(-shift); /* Negate the shift because we'll be doing a variable shift using vshlq_s32(). */
4388 one128 = vdupq_n_u32(1);
4389
4390 /*
4391 Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
4392 what's available in the input buffers. It would be conenient to use a fall-through switch to do this, but this results
4393 in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
4394 so I think there's opportunity for this to be simplified.
4395 */
4396 {
4397 int runningOrder = order;
4398 drflac_int32 tempC[4] = {0, 0, 0, 0};
4399 drflac_int32 tempS[4] = {0, 0, 0, 0};
4400
4401 /* 0 - 3. */
4402 if (runningOrder >= 4) {
4403 coefficients128_0 = vld1q_s32(coefficients + 0);
4404 samples128_0 = vld1q_s32(pSamplesOut - 4);
4405 runningOrder -= 4;
4406 } else {
4407 switch (runningOrder) {
4408 case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3]; /* fallthrough */
4409 case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2]; /* fallthrough */
4410 case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1]; /* fallthrough */
4411 }
4412
4413 coefficients128_0 = vld1q_s32(tempC);
4414 samples128_0 = vld1q_s32(tempS);
4415 runningOrder = 0;
4416 }
4417
4418 /* 4 - 7 */
4419 if (runningOrder >= 4) {
4420 coefficients128_4 = vld1q_s32(coefficients + 4);
4421 samples128_4 = vld1q_s32(pSamplesOut - 8);
4422 runningOrder -= 4;
4423 } else {
4424 switch (runningOrder) {
4425 case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7]; /* fallthrough */
4426 case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6]; /* fallthrough */
4427 case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5]; /* fallthrough */
4428 }
4429
4430 coefficients128_4 = vld1q_s32(tempC);
4431 samples128_4 = vld1q_s32(tempS);
4432 runningOrder = 0;
4433 }
4434
4435 /* 8 - 11 */
4436 if (runningOrder == 4) {
4437 coefficients128_8 = vld1q_s32(coefficients + 8);
4438 samples128_8 = vld1q_s32(pSamplesOut - 12);
4439 runningOrder -= 4;
4440 } else {
4441 switch (runningOrder) {
4442 case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11]; /* fallthrough */
4443 case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10]; /* fallthrough */
4444 case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9]; /* fallthrough */
4445 }
4446
4447 coefficients128_8 = vld1q_s32(tempC);
4448 samples128_8 = vld1q_s32(tempS);
4449 runningOrder = 0;
4450 }
4451
4452 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
4453 coefficients128_0 = drflac__vrevq_s32(coefficients128_0);
4454 coefficients128_4 = drflac__vrevq_s32(coefficients128_4);
4455 coefficients128_8 = drflac__vrevq_s32(coefficients128_8);
4456 }
4457
4458 /* For this version we are doing one sample at a time. */
4459 while (pDecodedSamples < pDecodedSamplesEnd) {
4460 int32x4_t prediction128;
4461 int32x2_t prediction64;
4462 uint32x4_t zeroCountPart128;
4463 uint32x4_t riceParamPart128;
4464
4465 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
4466 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
4467 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
4468 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
4469 return DRFLAC_FALSE;
4470 }
4471
4472 zeroCountPart128 = vld1q_u32(zeroCountParts);
4473 riceParamPart128 = vld1q_u32(riceParamParts);
4474
4475 riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
4476 riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
4477 riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
4478
4479 if (order <= 4) {
4480 for (i = 0; i < 4; i += 1) {
4481 prediction128 = vmulq_s32(coefficients128_0, samples128_0);
4482
4483 /* Horizontal add and shift. */
4484 prediction64 = drflac__vhaddq_s32(prediction128);
4485 prediction64 = vshl_s32(prediction64, shift64);
4486 prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
4487
4488 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
4489 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
4490 }
4491 } else if (order <= 8) {
4492 for (i = 0; i < 4; i += 1) {
4493 prediction128 = vmulq_s32(coefficients128_4, samples128_4);
4494 prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
4495
4496 /* Horizontal add and shift. */
4497 prediction64 = drflac__vhaddq_s32(prediction128);
4498 prediction64 = vshl_s32(prediction64, shift64);
4499 prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
4500
4501 samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
4502 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
4503 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
4504 }
4505 } else {
4506 for (i = 0; i < 4; i += 1) {
4507 prediction128 = vmulq_s32(coefficients128_8, samples128_8);
4508 prediction128 = vmlaq_s32(prediction128, coefficients128_4, samples128_4);
4509 prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
4510
4511 /* Horizontal add and shift. */
4512 prediction64 = drflac__vhaddq_s32(prediction128);
4513 prediction64 = vshl_s32(prediction64, shift64);
4514 prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
4515
4516 samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8);
4517 samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
4518 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
4519 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
4520 }
4521 }
4522
4523 /* We store samples in groups of 4. */
4524 vst1q_s32(pDecodedSamples, samples128_0);
4525 pDecodedSamples += 4;
4526 }
4527
4528 /* Make sure we process the last few samples. */
4529 i = (count & ~3);
4530 while (i < (int)count) {
4531 /* Rice extraction. */
4532 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
4533 return DRFLAC_FALSE;
4534 }
4535
4536 /* Rice reconstruction. */
4537 riceParamParts[0] &= riceParamMask;
4538 riceParamParts[0] |= (zeroCountParts[0] << riceParam);
4539 riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
4540
4541 /* Sample reconstruction. */
4542 pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
4543
4544 i += 1;
4545 pDecodedSamples += 1;
4546 }
4547
4548 return DRFLAC_TRUE;
4549 }
4550
4551 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)
4552 {
4553 int i;
4554 drflac_uint32 riceParamMask;
4555 drflac_int32* pDecodedSamples = pSamplesOut;
4556 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
4557 drflac_uint32 zeroCountParts[4];
4558 drflac_uint32 riceParamParts[4];
4559 int32x4_t coefficients128_0;
4560 int32x4_t coefficients128_4;
4561 int32x4_t coefficients128_8;
4562 int32x4_t samples128_0;
4563 int32x4_t samples128_4;
4564 int32x4_t samples128_8;
4565 uint32x4_t riceParamMask128;
4566 int32x4_t riceParam128;
4567 int64x1_t shift64;
4568 uint32x4_t one128;
4569 int64x2_t prediction128 = { 0 };
4570 uint32x4_t zeroCountPart128;
4571 uint32x4_t riceParamPart128;
4572
4573 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
4574
4575 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
4576 riceParamMask128 = vdupq_n_u32(riceParamMask);
4577
4578 riceParam128 = vdupq_n_s32(riceParam);
4579 shift64 = vdup_n_s64(-shift); /* Negate the shift because we'll be doing a variable shift using vshlq_s32(). */
4580 one128 = vdupq_n_u32(1);
4581
4582 /*
4583 Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
4584 what's available in the input buffers. It would be convenient to use a fall-through switch to do this, but this results
4585 in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
4586 so I think there's opportunity for this to be simplified.
4587 */
4588 {
4589 int runningOrder = order;
4590 drflac_int32 tempC[4] = {0, 0, 0, 0};
4591 drflac_int32 tempS[4] = {0, 0, 0, 0};
4592
4593 /* 0 - 3. */
4594 if (runningOrder >= 4) {
4595 coefficients128_0 = vld1q_s32(coefficients + 0);
4596 samples128_0 = vld1q_s32(pSamplesOut - 4);
4597 runningOrder -= 4;
4598 } else {
4599 switch (runningOrder) {
4600 case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3]; /* fallthrough */
4601 case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2]; /* fallthrough */
4602 case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1]; /* fallthrough */
4603 }
4604
4605 coefficients128_0 = vld1q_s32(tempC);
4606 samples128_0 = vld1q_s32(tempS);
4607 runningOrder = 0;
4608 }
4609
4610 /* 4 - 7 */
4611 if (runningOrder >= 4) {
4612 coefficients128_4 = vld1q_s32(coefficients + 4);
4613 samples128_4 = vld1q_s32(pSamplesOut - 8);
4614 runningOrder -= 4;
4615 } else {
4616 switch (runningOrder) {
4617 case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7]; /* fallthrough */
4618 case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6]; /* fallthrough */
4619 case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5]; /* fallthrough */
4620 }
4621
4622 coefficients128_4 = vld1q_s32(tempC);
4623 samples128_4 = vld1q_s32(tempS);
4624 runningOrder = 0;
4625 }
4626
4627 /* 8 - 11 */
4628 if (runningOrder == 4) {
4629 coefficients128_8 = vld1q_s32(coefficients + 8);
4630 samples128_8 = vld1q_s32(pSamplesOut - 12);
4631 runningOrder -= 4;
4632 } else {
4633 switch (runningOrder) {
4634 case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11]; /* fallthrough */
4635 case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10]; /* fallthrough */
4636 case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9]; /* fallthrough */
4637 }
4638
4639 coefficients128_8 = vld1q_s32(tempC);
4640 samples128_8 = vld1q_s32(tempS);
4641 runningOrder = 0;
4642 }
4643
4644 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
4645 coefficients128_0 = drflac__vrevq_s32(coefficients128_0);
4646 coefficients128_4 = drflac__vrevq_s32(coefficients128_4);
4647 coefficients128_8 = drflac__vrevq_s32(coefficients128_8);
4648 }
4649
4650 /* For this version we are doing one sample at a time. */
4651 while (pDecodedSamples < pDecodedSamplesEnd) {
4652 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
4653 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
4654 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
4655 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
4656 return DRFLAC_FALSE;
4657 }
4658
4659 zeroCountPart128 = vld1q_u32(zeroCountParts);
4660 riceParamPart128 = vld1q_u32(riceParamParts);
4661
4662 riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
4663 riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
4664 riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
4665
4666 for (i = 0; i < 4; i += 1) {
4667 int64x1_t prediction64;
4668
4669 prediction128 = veorq_s64(prediction128, prediction128); /* Reset to 0. */
4670 switch (order)
4671 {
4672 case 12:
4673 case 11: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_8), vget_low_s32(samples128_8)));
4674 case 10:
4675 case 9: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_8), vget_high_s32(samples128_8)));
4676 case 8:
4677 case 7: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_4), vget_low_s32(samples128_4)));
4678 case 6:
4679 case 5: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_4), vget_high_s32(samples128_4)));
4680 case 4:
4681 case 3: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_0), vget_low_s32(samples128_0)));
4682 case 2:
4683 case 1: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_0), vget_high_s32(samples128_0)));
4684 }
4685
4686 /* Horizontal add and shift. */
4687 prediction64 = drflac__vhaddq_s64(prediction128);
4688 prediction64 = vshl_s64(prediction64, shift64);
4689 prediction64 = vadd_s64(prediction64, vdup_n_s64(vgetq_lane_u32(riceParamPart128, 0)));
4690
4691 /* Our value should be sitting in prediction64[0]. We need to combine this with our SSE samples. */
4692 samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8);
4693 samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
4694 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(vreinterpret_s32_s64(prediction64), vdup_n_s32(0)), samples128_0);
4695
4696 /* Slide our rice parameter down so that the value in position 0 contains the next one to process. */
4697 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
4698 }
4699
4700 /* We store samples in groups of 4. */
4701 vst1q_s32(pDecodedSamples, samples128_0);
4702 pDecodedSamples += 4;
4703 }
4704
4705 /* Make sure we process the last few samples. */
4706 i = (count & ~3);
4707 while (i < (int)count) {
4708 /* Rice extraction. */
4709 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
4710 return DRFLAC_FALSE;
4711 }
4712
4713 /* Rice reconstruction. */
4714 riceParamParts[0] &= riceParamMask;
4715 riceParamParts[0] |= (zeroCountParts[0] << riceParam);
4716 riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
4717
4718 /* Sample reconstruction. */
4719 pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
4720
4721 i += 1;
4722 pDecodedSamples += 1;
4723 }
4724
4725 return DRFLAC_TRUE;
4726 }
4727
4728 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)
4729 {
4730 DRFLAC_ASSERT(bs != NULL);
4731 DRFLAC_ASSERT(pSamplesOut != NULL);
4732
4733 /* 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. */
4734 if (lpcOrder > 0 && lpcOrder <= 12) {
4735 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
4736 return drflac__decode_samples_with_residual__rice__neon_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
4737 } else {
4738 return drflac__decode_samples_with_residual__rice__neon_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
4739 }
4740 } else {
4741 return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4742 }
4743 }
4744 #endif
4745
4746 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)
4747 {
4748 #if defined(DRFLAC_SUPPORT_SSE41)
4749 if (drflac__gIsSSE41Supported) {
4750 return drflac__decode_samples_with_residual__rice__sse41(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4751 } else
4752 #elif defined(DRFLAC_SUPPORT_NEON)
4753 if (drflac__gIsNEONSupported) {
4754 return drflac__decode_samples_with_residual__rice__neon(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4755 } else
4756 #endif
4757 {
4758 /* Scalar fallback. */
4759 #if 0
4760 return drflac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4761 #else
4762 return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4763 #endif
4764 }
4765 }
4766
4767 /* 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. */
4768 static drflac_bool32 drflac__read_and_seek_residual__rice(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam)
4769 {
4770 drflac_uint32 i;
4771
4772 DRFLAC_ASSERT(bs != NULL);
4773
4774 for (i = 0; i < count; ++i) {
4775 if (!drflac__seek_rice_parts(bs, riceParam)) {
4776 return DRFLAC_FALSE;
4777 }
4778 }
4779
4780 return DRFLAC_TRUE;
4781 }
4782
4783 #if defined(__clang__)
4784 __attribute__((no_sanitize("signed-integer-overflow")))
4785 #endif
4786 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)
4787 {
4788 drflac_uint32 i;
4789
4790 DRFLAC_ASSERT(bs != NULL);
4791 DRFLAC_ASSERT(unencodedBitsPerSample <= 31); /* <-- unencodedBitsPerSample is a 5 bit number, so cannot exceed 31. */
4792 DRFLAC_ASSERT(pSamplesOut != NULL);
4793
4794 for (i = 0; i < count; ++i) {
4795 if (unencodedBitsPerSample > 0) {
4796 if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i)) {
4797 return DRFLAC_FALSE;
4798 }
4799 } else {
4800 pSamplesOut[i] = 0;
4801 }
4802
4803 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
4804 pSamplesOut[i] += drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
4805 } else {
4806 pSamplesOut[i] += drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
4807 }
4808 }
4809
4810 return DRFLAC_TRUE;
4811 }
4812
4813
4814 /*
4815 Reads and decodes the residual for the sub-frame the decoder is currently sitting on. This function should be called
4816 when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be ignored. The
4817 <blockSize> and <order> parameters are used to determine how many residual values need to be decoded.
4818 */
4819 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)
4820 {
4821 drflac_uint8 residualMethod;
4822 drflac_uint8 partitionOrder;
4823 drflac_uint32 samplesInPartition;
4824 drflac_uint32 partitionsRemaining;
4825
4826 DRFLAC_ASSERT(bs != NULL);
4827 DRFLAC_ASSERT(blockSize != 0);
4828 DRFLAC_ASSERT(pDecodedSamples != NULL); /* <-- Should we allow NULL, in which case we just seek past the residual rather than do a full decode? */
4829
4830 if (!drflac__read_uint8(bs, 2, &residualMethod)) {
4831 return DRFLAC_FALSE;
4832 }
4833
4834 if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
4835 return DRFLAC_FALSE; /* Unknown or unsupported residual coding method. */
4836 }
4837
4838 /* Ignore the first <order> values. */
4839 pDecodedSamples += lpcOrder;
4840
4841 if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
4842 return DRFLAC_FALSE;
4843 }
4844
4845 /*
4846 From the FLAC spec:
4847 The Rice partition order in a Rice-coded residual section must be less than or equal to 8.
4848 */
4849 if (partitionOrder > 8) {
4850 return DRFLAC_FALSE;
4851 }
4852
4853 /* Validation check. */
4854 if ((blockSize / (1 << partitionOrder)) < lpcOrder) {
4855 return DRFLAC_FALSE;
4856 }
4857
4858 samplesInPartition = (blockSize / (1 << partitionOrder)) - lpcOrder;
4859 partitionsRemaining = (1 << partitionOrder);
4860 for (;;) {
4861 drflac_uint8 riceParam = 0;
4862 if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
4863 if (!drflac__read_uint8(bs, 4, &riceParam)) {
4864 return DRFLAC_FALSE;
4865 }
4866 if (riceParam == 15) {
4867 riceParam = 0xFF;
4868 }
4869 } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
4870 if (!drflac__read_uint8(bs, 5, &riceParam)) {
4871 return DRFLAC_FALSE;
4872 }
4873 if (riceParam == 31) {
4874 riceParam = 0xFF;
4875 }
4876 }
4877
4878 if (riceParam != 0xFF) {
4879 if (!drflac__decode_samples_with_residual__rice(bs, bitsPerSample, samplesInPartition, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
4880 return DRFLAC_FALSE;
4881 }
4882 } else {
4883 drflac_uint8 unencodedBitsPerSample = 0;
4884 if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
4885 return DRFLAC_FALSE;
4886 }
4887
4888 if (!drflac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
4889 return DRFLAC_FALSE;
4890 }
4891 }
4892
4893 pDecodedSamples += samplesInPartition;
4894
4895 if (partitionsRemaining == 1) {
4896 break;
4897 }
4898
4899 partitionsRemaining -= 1;
4900
4901 if (partitionOrder != 0) {
4902 samplesInPartition = blockSize / (1 << partitionOrder);
4903 }
4904 }
4905
4906 return DRFLAC_TRUE;
4907 }
4908
4909 /*
4910 Reads and seeks past the residual for the sub-frame the decoder is currently sitting on. This function should be called
4911 when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be set to 0. The
4912 <blockSize> and <order> parameters are used to determine how many residual values need to be decoded.
4913 */
4914 static drflac_bool32 drflac__read_and_seek_residual(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 order)
4915 {
4916 drflac_uint8 residualMethod;
4917 drflac_uint8 partitionOrder;
4918 drflac_uint32 samplesInPartition;
4919 drflac_uint32 partitionsRemaining;
4920
4921 DRFLAC_ASSERT(bs != NULL);
4922 DRFLAC_ASSERT(blockSize != 0);
4923
4924 if (!drflac__read_uint8(bs, 2, &residualMethod)) {
4925 return DRFLAC_FALSE;
4926 }
4927
4928 if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
4929 return DRFLAC_FALSE; /* Unknown or unsupported residual coding method. */
4930 }
4931
4932 if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
4933 return DRFLAC_FALSE;
4934 }
4935
4936 /*
4937 From the FLAC spec:
4938 The Rice partition order in a Rice-coded residual section must be less than or equal to 8.
4939 */
4940 if (partitionOrder > 8) {
4941 return DRFLAC_FALSE;
4942 }
4943
4944 /* Validation check. */
4945 if ((blockSize / (1 << partitionOrder)) <= order) {
4946 return DRFLAC_FALSE;
4947 }
4948
4949 samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
4950 partitionsRemaining = (1 << partitionOrder);
4951 for (;;)
4952 {
4953 drflac_uint8 riceParam = 0;
4954 if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
4955 if (!drflac__read_uint8(bs, 4, &riceParam)) {
4956 return DRFLAC_FALSE;
4957 }
4958 if (riceParam == 15) {
4959 riceParam = 0xFF;
4960 }
4961 } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
4962 if (!drflac__read_uint8(bs, 5, &riceParam)) {
4963 return DRFLAC_FALSE;
4964 }
4965 if (riceParam == 31) {
4966 riceParam = 0xFF;
4967 }
4968 }
4969
4970 if (riceParam != 0xFF) {
4971 if (!drflac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) {
4972 return DRFLAC_FALSE;
4973 }
4974 } else {
4975 drflac_uint8 unencodedBitsPerSample = 0;
4976 if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
4977 return DRFLAC_FALSE;
4978 }
4979
4980 if (!drflac__seek_bits(bs, unencodedBitsPerSample * samplesInPartition)) {
4981 return DRFLAC_FALSE;
4982 }
4983 }
4984
4985
4986 if (partitionsRemaining == 1) {
4987 break;
4988 }
4989
4990 partitionsRemaining -= 1;
4991 samplesInPartition = blockSize / (1 << partitionOrder);
4992 }
4993
4994 return DRFLAC_TRUE;
4995 }
4996
4997
4998 static drflac_bool32 drflac__decode_samples__constant(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
4999 {
5000 drflac_uint32 i;
5001
5002 /* Only a single sample needs to be decoded here. */
5003 drflac_int32 sample;
5004 if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
5005 return DRFLAC_FALSE;
5006 }
5007
5008 /*
5009 We don't really need to expand this, but it does simplify the process of reading samples. If this becomes a performance issue (unlikely)
5010 we'll want to look at a more efficient way.
5011 */
5012 for (i = 0; i < blockSize; ++i) {
5013 pDecodedSamples[i] = sample;
5014 }
5015
5016 return DRFLAC_TRUE;
5017 }
5018
5019 static drflac_bool32 drflac__decode_samples__verbatim(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
5020 {
5021 drflac_uint32 i;
5022
5023 for (i = 0; i < blockSize; ++i) {
5024 drflac_int32 sample;
5025 if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
5026 return DRFLAC_FALSE;
5027 }
5028
5029 pDecodedSamples[i] = sample;
5030 }
5031
5032 return DRFLAC_TRUE;
5033 }
5034
5035 static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
5036 {
5037 drflac_uint32 i;
5038
5039 static drflac_int32 lpcCoefficientsTable[5][4] = {
5040 {0, 0, 0, 0},
5041 {1, 0, 0, 0},
5042 {2, -1, 0, 0},
5043 {3, -3, 1, 0},
5044 {4, -6, 4, -1}
5045 };
5046
5047 /* Warm up samples and coefficients. */
5048 for (i = 0; i < lpcOrder; ++i) {
5049 drflac_int32 sample;
5050 if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
5051 return DRFLAC_FALSE;
5052 }
5053
5054 pDecodedSamples[i] = sample;
5055 }
5056
5057 if (!drflac__decode_samples_with_residual(bs, subframeBitsPerSample, blockSize, lpcOrder, 0, 4, lpcCoefficientsTable[lpcOrder], pDecodedSamples)) {
5058 return DRFLAC_FALSE;
5059 }
5060
5061 return DRFLAC_TRUE;
5062 }
5063
5064 static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
5065 {
5066 drflac_uint8 i;
5067 drflac_uint8 lpcPrecision;
5068 drflac_int8 lpcShift;
5069 drflac_int32 coefficients[32];
5070
5071 /* Warm up samples. */
5072 for (i = 0; i < lpcOrder; ++i) {
5073 drflac_int32 sample;
5074 if (!drflac__read_int32(bs, bitsPerSample, &sample)) {
5075 return DRFLAC_FALSE;
5076 }
5077
5078 pDecodedSamples[i] = sample;
5079 }
5080
5081 if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
5082 return DRFLAC_FALSE;
5083 }
5084 if (lpcPrecision == 15) {
5085 return DRFLAC_FALSE; /* Invalid. */
5086 }
5087 lpcPrecision += 1;
5088
5089 if (!drflac__read_int8(bs, 5, &lpcShift)) {
5090 return DRFLAC_FALSE;
5091 }
5092
5093 /*
5094 From the FLAC specification:
5095
5096 Quantized linear predictor coefficient shift needed in bits (NOTE: this number is signed two's-complement)
5097
5098 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
5099 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.
5100 */
5101 if (lpcShift < 0) {
5102 return DRFLAC_FALSE;
5103 }
5104
5105 DRFLAC_ZERO_MEMORY(coefficients, sizeof(coefficients));
5106 for (i = 0; i < lpcOrder; ++i) {
5107 if (!drflac__read_int32(bs, lpcPrecision, coefficients + i)) {
5108 return DRFLAC_FALSE;
5109 }
5110 }
5111
5112 if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
5113 return DRFLAC_FALSE;
5114 }
5115
5116 return DRFLAC_TRUE;
5117 }
5118
5119
5120 static drflac_bool32 drflac__read_next_flac_frame_header(drflac_bs* bs, drflac_uint8 streaminfoBitsPerSample, drflac_frame_header* header)
5121 {
5122 const drflac_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000};
5123 const drflac_uint8 bitsPerSampleTable[8] = {0, 8, 12, (drflac_uint8)-1, 16, 20, 24, (drflac_uint8)-1}; /* -1 = reserved. */
5124
5125 DRFLAC_ASSERT(bs != NULL);
5126 DRFLAC_ASSERT(header != NULL);
5127
5128 /* Keep looping until we find a valid sync code. */
5129 for (;;) {
5130 drflac_uint8 crc8 = 0xCE; /* 0xCE = drflac_crc8(0, 0x3FFE, 14); */
5131 drflac_uint8 reserved = 0;
5132 drflac_uint8 blockingStrategy = 0;
5133 drflac_uint8 blockSize = 0;
5134 drflac_uint8 sampleRate = 0;
5135 drflac_uint8 channelAssignment = 0;
5136 drflac_uint8 bitsPerSample = 0;
5137 drflac_bool32 isVariableBlockSize;
5138
5139 if (!drflac__find_and_seek_to_next_sync_code(bs)) {
5140 return DRFLAC_FALSE;
5141 }
5142
5143 if (!drflac__read_uint8(bs, 1, &reserved)) {
5144 return DRFLAC_FALSE;
5145 }
5146 if (reserved == 1) {
5147 continue;
5148 }
5149 crc8 = drflac_crc8(crc8, reserved, 1);
5150
5151 if (!drflac__read_uint8(bs, 1, &blockingStrategy)) {
5152 return DRFLAC_FALSE;
5153 }
5154 crc8 = drflac_crc8(crc8, blockingStrategy, 1);
5155
5156 if (!drflac__read_uint8(bs, 4, &blockSize)) {
5157 return DRFLAC_FALSE;
5158 }
5159 if (blockSize == 0) {
5160 continue;
5161 }
5162 crc8 = drflac_crc8(crc8, blockSize, 4);
5163
5164 if (!drflac__read_uint8(bs, 4, &sampleRate)) {
5165 return DRFLAC_FALSE;
5166 }
5167 crc8 = drflac_crc8(crc8, sampleRate, 4);
5168
5169 if (!drflac__read_uint8(bs, 4, &channelAssignment)) {
5170 return DRFLAC_FALSE;
5171 }
5172 if (channelAssignment > 10) {
5173 continue;
5174 }
5175 crc8 = drflac_crc8(crc8, channelAssignment, 4);
5176
5177 if (!drflac__read_uint8(bs, 3, &bitsPerSample)) {
5178 return DRFLAC_FALSE;
5179 }
5180 if (bitsPerSample == 3 || bitsPerSample == 7) {
5181 continue;
5182 }
5183 crc8 = drflac_crc8(crc8, bitsPerSample, 3);
5184
5185
5186 if (!drflac__read_uint8(bs, 1, &reserved)) {
5187 return DRFLAC_FALSE;
5188 }
5189 if (reserved == 1) {
5190 continue;
5191 }
5192 crc8 = drflac_crc8(crc8, reserved, 1);
5193
5194
5195 isVariableBlockSize = blockingStrategy == 1;
5196 if (isVariableBlockSize) {
5197 drflac_uint64 pcmFrameNumber;
5198 drflac_result result = drflac__read_utf8_coded_number(bs, &pcmFrameNumber, &crc8);
5199 if (result != DRFLAC_SUCCESS) {
5200 if (result == DRFLAC_AT_END) {
5201 return DRFLAC_FALSE;
5202 } else {
5203 continue;
5204 }
5205 }
5206 header->flacFrameNumber = 0;
5207 header->pcmFrameNumber = pcmFrameNumber;
5208 } else {
5209 drflac_uint64 flacFrameNumber = 0;
5210 drflac_result result = drflac__read_utf8_coded_number(bs, &flacFrameNumber, &crc8);
5211 if (result != DRFLAC_SUCCESS) {
5212 if (result == DRFLAC_AT_END) {
5213 return DRFLAC_FALSE;
5214 } else {
5215 continue;
5216 }
5217 }
5218 header->flacFrameNumber = (drflac_uint32)flacFrameNumber; /* <-- Safe cast. */
5219 header->pcmFrameNumber = 0;
5220 }
5221
5222
5223 DRFLAC_ASSERT(blockSize > 0);
5224 if (blockSize == 1) {
5225 header->blockSizeInPCMFrames = 192;
5226 } else if (blockSize <= 5) {
5227 DRFLAC_ASSERT(blockSize >= 2);
5228 header->blockSizeInPCMFrames = 576 * (1 << (blockSize - 2));
5229 } else if (blockSize == 6) {
5230 if (!drflac__read_uint16(bs, 8, &header->blockSizeInPCMFrames)) {
5231 return DRFLAC_FALSE;
5232 }
5233 crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 8);
5234 header->blockSizeInPCMFrames += 1;
5235 } else if (blockSize == 7) {
5236 if (!drflac__read_uint16(bs, 16, &header->blockSizeInPCMFrames)) {
5237 return DRFLAC_FALSE;
5238 }
5239 crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 16);
5240 if (header->blockSizeInPCMFrames == 0xFFFF) {
5241 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. */
5242 }
5243 header->blockSizeInPCMFrames += 1;
5244 } else {
5245 DRFLAC_ASSERT(blockSize >= 8);
5246 header->blockSizeInPCMFrames = 256 * (1 << (blockSize - 8));
5247 }
5248
5249
5250 if (sampleRate <= 11) {
5251 header->sampleRate = sampleRateTable[sampleRate];
5252 } else if (sampleRate == 12) {
5253 if (!drflac__read_uint32(bs, 8, &header->sampleRate)) {
5254 return DRFLAC_FALSE;
5255 }
5256 crc8 = drflac_crc8(crc8, header->sampleRate, 8);
5257 header->sampleRate *= 1000;
5258 } else if (sampleRate == 13) {
5259 if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
5260 return DRFLAC_FALSE;
5261 }
5262 crc8 = drflac_crc8(crc8, header->sampleRate, 16);
5263 } else if (sampleRate == 14) {
5264 if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
5265 return DRFLAC_FALSE;
5266 }
5267 crc8 = drflac_crc8(crc8, header->sampleRate, 16);
5268 header->sampleRate *= 10;
5269 } else {
5270 continue; /* Invalid. Assume an invalid block. */
5271 }
5272
5273
5274 header->channelAssignment = channelAssignment;
5275
5276 header->bitsPerSample = bitsPerSampleTable[bitsPerSample];
5277 if (header->bitsPerSample == 0) {
5278 header->bitsPerSample = streaminfoBitsPerSample;
5279 }
5280
5281 if (header->bitsPerSample != streaminfoBitsPerSample) {
5282 /* If this subframe has a different bitsPerSample then streaminfo or the first frame, reject it */
5283 return DRFLAC_FALSE;
5284 }
5285
5286 if (!drflac__read_uint8(bs, 8, &header->crc8)) {
5287 return DRFLAC_FALSE;
5288 }
5289
5290 #ifndef DR_FLAC_NO_CRC
5291 if (header->crc8 != crc8) {
5292 continue; /* CRC mismatch. Loop back to the top and find the next sync code. */
5293 }
5294 #endif
5295 return DRFLAC_TRUE;
5296 }
5297 }
5298
5299 static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe* pSubframe)
5300 {
5301 drflac_uint8 header;
5302 int type;
5303
5304 if (!drflac__read_uint8(bs, 8, &header)) {
5305 return DRFLAC_FALSE;
5306 }
5307
5308 /* First bit should always be 0. */
5309 if ((header & 0x80) != 0) {
5310 return DRFLAC_FALSE;
5311 }
5312
5313 /*
5314 Default to 0 for the LPC order. It's important that we always set this to 0 for non LPC
5315 and FIXED subframes because we'll be using it in a generic validation check later.
5316 */
5317 pSubframe->lpcOrder = 0;
5318
5319 type = (header & 0x7E) >> 1;
5320 if (type == 0) {
5321 pSubframe->subframeType = DRFLAC_SUBFRAME_CONSTANT;
5322 } else if (type == 1) {
5323 pSubframe->subframeType = DRFLAC_SUBFRAME_VERBATIM;
5324 } else {
5325 if ((type & 0x20) != 0) {
5326 pSubframe->subframeType = DRFLAC_SUBFRAME_LPC;
5327 pSubframe->lpcOrder = (drflac_uint8)(type & 0x1F) + 1;
5328 } else if ((type & 0x08) != 0) {
5329 pSubframe->subframeType = DRFLAC_SUBFRAME_FIXED;
5330 pSubframe->lpcOrder = (drflac_uint8)(type & 0x07);
5331 if (pSubframe->lpcOrder > 4) {
5332 pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
5333 pSubframe->lpcOrder = 0;
5334 }
5335 } else {
5336 pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
5337 }
5338 }
5339
5340 if (pSubframe->subframeType == DRFLAC_SUBFRAME_RESERVED) {
5341 return DRFLAC_FALSE;
5342 }
5343
5344 /* Wasted bits per sample. */
5345 pSubframe->wastedBitsPerSample = 0;
5346 if ((header & 0x01) == 1) {
5347 unsigned int wastedBitsPerSample;
5348 if (!drflac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) {
5349 return DRFLAC_FALSE;
5350 }
5351 pSubframe->wastedBitsPerSample = (drflac_uint8)wastedBitsPerSample + 1;
5352 }
5353
5354 return DRFLAC_TRUE;
5355 }
5356
5357 static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex, drflac_int32* pDecodedSamplesOut)
5358 {
5359 drflac_subframe* pSubframe;
5360 drflac_uint32 subframeBitsPerSample;
5361
5362 DRFLAC_ASSERT(bs != NULL);
5363 DRFLAC_ASSERT(frame != NULL);
5364
5365 pSubframe = frame->subframes + subframeIndex;
5366 if (!drflac__read_subframe_header(bs, pSubframe)) {
5367 return DRFLAC_FALSE;
5368 }
5369
5370 /* Side channels require an extra bit per sample. Took a while to figure that one out... */
5371 subframeBitsPerSample = frame->header.bitsPerSample;
5372 if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
5373 subframeBitsPerSample += 1;
5374 } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
5375 subframeBitsPerSample += 1;
5376 }
5377
5378 if (subframeBitsPerSample > 32) {
5379 /* libFLAC and ffmpeg reject 33-bit subframes as well */
5380 return DRFLAC_FALSE;
5381 }
5382
5383 /* Need to handle wasted bits per sample. */
5384 if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
5385 return DRFLAC_FALSE;
5386 }
5387 subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
5388
5389 pSubframe->pSamplesS32 = pDecodedSamplesOut;
5390
5391 /*
5392 pDecodedSamplesOut will be pointing to a buffer that was allocated with enough memory to store
5393 maxBlockSizeInPCMFrames samples (as specified in the FLAC header). We need to guard against an
5394 overflow here. At a higher level we are checking maxBlockSizeInPCMFrames from the header, but
5395 here we need to do an additional check to ensure this frame's block size fully encompasses any
5396 warmup samples which is determined by the LPC order. For non LPC and FIXED subframes, the LPC
5397 order will be have been set to 0 in drflac__read_subframe_header().
5398 */
5399 if (frame->header.blockSizeInPCMFrames < pSubframe->lpcOrder) {
5400 return DRFLAC_FALSE;
5401 }
5402
5403 switch (pSubframe->subframeType)
5404 {
5405 case DRFLAC_SUBFRAME_CONSTANT:
5406 {
5407 drflac__decode_samples__constant(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
5408 } break;
5409
5410 case DRFLAC_SUBFRAME_VERBATIM:
5411 {
5412 drflac__decode_samples__verbatim(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
5413 } break;
5414
5415 case DRFLAC_SUBFRAME_FIXED:
5416 {
5417 drflac__decode_samples__fixed(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
5418 } break;
5419
5420 case DRFLAC_SUBFRAME_LPC:
5421 {
5422 drflac__decode_samples__lpc(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
5423 } break;
5424
5425 default: return DRFLAC_FALSE;
5426 }
5427
5428 return DRFLAC_TRUE;
5429 }
5430
5431 static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex)
5432 {
5433 drflac_subframe* pSubframe;
5434 drflac_uint32 subframeBitsPerSample;
5435
5436 DRFLAC_ASSERT(bs != NULL);
5437 DRFLAC_ASSERT(frame != NULL);
5438
5439 pSubframe = frame->subframes + subframeIndex;
5440 if (!drflac__read_subframe_header(bs, pSubframe)) {
5441 return DRFLAC_FALSE;
5442 }
5443
5444 /* Side channels require an extra bit per sample. Took a while to figure that one out... */
5445 subframeBitsPerSample = frame->header.bitsPerSample;
5446 if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
5447 subframeBitsPerSample += 1;
5448 } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
5449 subframeBitsPerSample += 1;
5450 }
5451
5452 /* Need to handle wasted bits per sample. */
5453 if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
5454 return DRFLAC_FALSE;
5455 }
5456 subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
5457
5458 pSubframe->pSamplesS32 = NULL;
5459
5460 switch (pSubframe->subframeType)
5461 {
5462 case DRFLAC_SUBFRAME_CONSTANT:
5463 {
5464 if (!drflac__seek_bits(bs, subframeBitsPerSample)) {
5465 return DRFLAC_FALSE;
5466 }
5467 } break;
5468
5469 case DRFLAC_SUBFRAME_VERBATIM:
5470 {
5471 unsigned int bitsToSeek = frame->header.blockSizeInPCMFrames * subframeBitsPerSample;
5472 if (!drflac__seek_bits(bs, bitsToSeek)) {
5473 return DRFLAC_FALSE;
5474 }
5475 } break;
5476
5477 case DRFLAC_SUBFRAME_FIXED:
5478 {
5479 unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
5480 if (!drflac__seek_bits(bs, bitsToSeek)) {
5481 return DRFLAC_FALSE;
5482 }
5483
5484 if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
5485 return DRFLAC_FALSE;
5486 }
5487 } break;
5488
5489 case DRFLAC_SUBFRAME_LPC:
5490 {
5491 drflac_uint8 lpcPrecision;
5492
5493 unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
5494 if (!drflac__seek_bits(bs, bitsToSeek)) {
5495 return DRFLAC_FALSE;
5496 }
5497
5498 if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
5499 return DRFLAC_FALSE;
5500 }
5501 if (lpcPrecision == 15) {
5502 return DRFLAC_FALSE; /* Invalid. */
5503 }
5504 lpcPrecision += 1;
5505
5506
5507 bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5; /* +5 for shift. */
5508 if (!drflac__seek_bits(bs, bitsToSeek)) {
5509 return DRFLAC_FALSE;
5510 }
5511
5512 if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
5513 return DRFLAC_FALSE;
5514 }
5515 } break;
5516
5517 default: return DRFLAC_FALSE;
5518 }
5519
5520 return DRFLAC_TRUE;
5521 }
5522
5523
5524 static DRFLAC_INLINE drflac_uint8 drflac__get_channel_count_from_channel_assignment(drflac_int8 channelAssignment)
5525 {
5526 drflac_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2};
5527
5528 DRFLAC_ASSERT(channelAssignment <= 10);
5529 return lookup[channelAssignment];
5530 }
5531
5532 static drflac_result drflac__decode_flac_frame(drflac* pFlac)
5533 {
5534 int channelCount;
5535 int i;
5536 drflac_uint8 paddingSizeInBits;
5537 drflac_uint16 desiredCRC16;
5538 #ifndef DR_FLAC_NO_CRC
5539 drflac_uint16 actualCRC16;
5540 #endif
5541
5542 /* This function should be called while the stream is sitting on the first byte after the frame header. */
5543 DRFLAC_ZERO_MEMORY(pFlac->currentFLACFrame.subframes, sizeof(pFlac->currentFLACFrame.subframes));
5544
5545 /* The frame block size must never be larger than the maximum block size defined by the FLAC stream. */
5546 if (pFlac->currentFLACFrame.header.blockSizeInPCMFrames > pFlac->maxBlockSizeInPCMFrames) {
5547 return DRFLAC_ERROR;
5548 }
5549
5550 /* The number of channels in the frame must match the channel count from the STREAMINFO block. */
5551 channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
5552 if (channelCount != (int)pFlac->channels) {
5553 return DRFLAC_ERROR;
5554 }
5555
5556 for (i = 0; i < channelCount; ++i) {
5557 if (!drflac__decode_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i, pFlac->pDecodedSamples + (pFlac->currentFLACFrame.header.blockSizeInPCMFrames * i))) {
5558 return DRFLAC_ERROR;
5559 }
5560 }
5561
5562 paddingSizeInBits = (drflac_uint8)(DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7);
5563 if (paddingSizeInBits > 0) {
5564 drflac_uint8 padding = 0;
5565 if (!drflac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding)) {
5566 return DRFLAC_AT_END;
5567 }
5568 }
5569
5570 #ifndef DR_FLAC_NO_CRC
5571 actualCRC16 = drflac__flush_crc16(&pFlac->bs);
5572 #endif
5573 if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
5574 return DRFLAC_AT_END;
5575 }
5576
5577 #ifndef DR_FLAC_NO_CRC
5578 if (actualCRC16 != desiredCRC16) {
5579 return DRFLAC_CRC_MISMATCH; /* CRC mismatch. */
5580 }
5581 #endif
5582
5583 pFlac->currentFLACFrame.pcmFramesRemaining = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
5584
5585 return DRFLAC_SUCCESS;
5586 }
5587
5588 static drflac_result drflac__seek_flac_frame(drflac* pFlac)
5589 {
5590 int channelCount;
5591 int i;
5592 drflac_uint16 desiredCRC16;
5593 #ifndef DR_FLAC_NO_CRC
5594 drflac_uint16 actualCRC16;
5595 #endif
5596
5597 channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
5598 for (i = 0; i < channelCount; ++i) {
5599 if (!drflac__seek_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i)) {
5600 return DRFLAC_ERROR;
5601 }
5602 }
5603
5604 /* Padding. */
5605 if (!drflac__seek_bits(&pFlac->bs, DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7)) {
5606 return DRFLAC_ERROR;
5607 }
5608
5609 /* CRC. */
5610 #ifndef DR_FLAC_NO_CRC
5611 actualCRC16 = drflac__flush_crc16(&pFlac->bs);
5612 #endif
5613 if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
5614 return DRFLAC_AT_END;
5615 }
5616
5617 #ifndef DR_FLAC_NO_CRC
5618 if (actualCRC16 != desiredCRC16) {
5619 return DRFLAC_CRC_MISMATCH; /* CRC mismatch. */
5620 }
5621 #endif
5622
5623 return DRFLAC_SUCCESS;
5624 }
5625
5626 static drflac_bool32 drflac__read_and_decode_next_flac_frame(drflac* pFlac)
5627 {
5628 DRFLAC_ASSERT(pFlac != NULL);
5629
5630 for (;;) {
5631 drflac_result result;
5632
5633 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5634 return DRFLAC_FALSE;
5635 }
5636
5637 result = drflac__decode_flac_frame(pFlac);
5638 if (result != DRFLAC_SUCCESS) {
5639 if (result == DRFLAC_CRC_MISMATCH) {
5640 continue; /* CRC mismatch. Skip to the next frame. */
5641 } else {
5642 return DRFLAC_FALSE;
5643 }
5644 }
5645
5646 return DRFLAC_TRUE;
5647 }
5648 }
5649
5650 static void drflac__get_pcm_frame_range_of_current_flac_frame(drflac* pFlac, drflac_uint64* pFirstPCMFrame, drflac_uint64* pLastPCMFrame)
5651 {
5652 drflac_uint64 firstPCMFrame;
5653 drflac_uint64 lastPCMFrame;
5654
5655 DRFLAC_ASSERT(pFlac != NULL);
5656
5657 firstPCMFrame = pFlac->currentFLACFrame.header.pcmFrameNumber;
5658 if (firstPCMFrame == 0) {
5659 firstPCMFrame = ((drflac_uint64)pFlac->currentFLACFrame.header.flacFrameNumber) * pFlac->maxBlockSizeInPCMFrames;
5660 }
5661
5662 lastPCMFrame = firstPCMFrame + pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
5663 if (lastPCMFrame > 0) {
5664 lastPCMFrame -= 1; /* Needs to be zero based. */
5665 }
5666
5667 if (pFirstPCMFrame) {
5668 *pFirstPCMFrame = firstPCMFrame;
5669 }
5670 if (pLastPCMFrame) {
5671 *pLastPCMFrame = lastPCMFrame;
5672 }
5673 }
5674
5675 static drflac_bool32 drflac__seek_to_first_frame(drflac* pFlac)
5676 {
5677 drflac_bool32 result;
5678
5679 DRFLAC_ASSERT(pFlac != NULL);
5680
5681 result = drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes);
5682
5683 DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
5684 pFlac->currentPCMFrame = 0;
5685
5686 return result;
5687 }
5688
5689 static DRFLAC_INLINE drflac_result drflac__seek_to_next_flac_frame(drflac* pFlac)
5690 {
5691 /* This function should only ever be called while the decoder is sitting on the first byte past the FRAME_HEADER section. */
5692 DRFLAC_ASSERT(pFlac != NULL);
5693 return drflac__seek_flac_frame(pFlac);
5694 }
5695
5696
5697 static drflac_uint64 drflac__seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 pcmFramesToSeek)
5698 {
5699 drflac_uint64 pcmFramesRead = 0;
5700 while (pcmFramesToSeek > 0) {
5701 if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
5702 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
5703 break; /* Couldn't read the next frame, so just break from the loop and return. */
5704 }
5705 } else {
5706 if (pFlac->currentFLACFrame.pcmFramesRemaining > pcmFramesToSeek) {
5707 pcmFramesRead += pcmFramesToSeek;
5708 pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)pcmFramesToSeek; /* <-- Safe cast. Will always be < currentFrame.pcmFramesRemaining < 65536. */
5709 pcmFramesToSeek = 0;
5710 } else {
5711 pcmFramesRead += pFlac->currentFLACFrame.pcmFramesRemaining;
5712 pcmFramesToSeek -= pFlac->currentFLACFrame.pcmFramesRemaining;
5713 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
5714 }
5715 }
5716 }
5717
5718 pFlac->currentPCMFrame += pcmFramesRead;
5719 return pcmFramesRead;
5720 }
5721
5722
5723 static drflac_bool32 drflac__seek_to_pcm_frame__brute_force(drflac* pFlac, drflac_uint64 pcmFrameIndex)
5724 {
5725 drflac_bool32 isMidFrame = DRFLAC_FALSE;
5726 drflac_uint64 runningPCMFrameCount;
5727
5728 DRFLAC_ASSERT(pFlac != NULL);
5729
5730 /* 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. */
5731 if (pcmFrameIndex >= pFlac->currentPCMFrame) {
5732 /* Seeking forward. Need to seek from the current position. */
5733 runningPCMFrameCount = pFlac->currentPCMFrame;
5734
5735 /* The frame header for the first frame may not yet have been read. We need to do that if necessary. */
5736 if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
5737 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5738 return DRFLAC_FALSE;
5739 }
5740 } else {
5741 isMidFrame = DRFLAC_TRUE;
5742 }
5743 } else {
5744 /* Seeking backwards. Need to seek from the start of the file. */
5745 runningPCMFrameCount = 0;
5746
5747 /* Move back to the start. */
5748 if (!drflac__seek_to_first_frame(pFlac)) {
5749 return DRFLAC_FALSE;
5750 }
5751
5752 /* Decode the first frame in preparation for sample-exact seeking below. */
5753 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5754 return DRFLAC_FALSE;
5755 }
5756 }
5757
5758 /*
5759 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
5760 header. If based on the header we can determine that the frame contains the sample, we do a full decode of that frame.
5761 */
5762 for (;;) {
5763 drflac_uint64 pcmFrameCountInThisFLACFrame;
5764 drflac_uint64 firstPCMFrameInFLACFrame = 0;
5765 drflac_uint64 lastPCMFrameInFLACFrame = 0;
5766
5767 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
5768
5769 pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
5770 if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
5771 /*
5772 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
5773 it never existed and keep iterating.
5774 */
5775 drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
5776
5777 if (!isMidFrame) {
5778 drflac_result result = drflac__decode_flac_frame(pFlac);
5779 if (result == DRFLAC_SUCCESS) {
5780 /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
5781 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */
5782 } else {
5783 if (result == DRFLAC_CRC_MISMATCH) {
5784 goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */
5785 } else {
5786 return DRFLAC_FALSE;
5787 }
5788 }
5789 } else {
5790 /* We started seeking mid-frame which means we need to skip the frame decoding part. */
5791 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
5792 }
5793 } else {
5794 /*
5795 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
5796 frame never existed and leave the running sample count untouched.
5797 */
5798 if (!isMidFrame) {
5799 drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
5800 if (result == DRFLAC_SUCCESS) {
5801 runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
5802 } else {
5803 if (result == DRFLAC_CRC_MISMATCH) {
5804 goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */
5805 } else {
5806 return DRFLAC_FALSE;
5807 }
5808 }
5809 } else {
5810 /*
5811 We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with
5812 drflac__seek_to_next_flac_frame() which only works if the decoder is sitting on the byte just after the frame header.
5813 */
5814 runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
5815 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
5816 isMidFrame = DRFLAC_FALSE;
5817 }
5818
5819 /* If we are seeking to the end of the file and we've just hit it, we're done. */
5820 if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
5821 return DRFLAC_TRUE;
5822 }
5823 }
5824
5825 next_iteration:
5826 /* Grab the next frame in preparation for the next iteration. */
5827 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5828 return DRFLAC_FALSE;
5829 }
5830 }
5831 }
5832
5833
5834 #if !defined(DR_FLAC_NO_CRC)
5835 /*
5836 We use an average compression ratio to determine our approximate start location. FLAC files are generally about 50%-70% the size of their
5837 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
5838 location.
5839 */
5840 #define DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO 0.6f
5841
5842 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)
5843 {
5844 DRFLAC_ASSERT(pFlac != NULL);
5845 DRFLAC_ASSERT(pLastSuccessfulSeekOffset != NULL);
5846 DRFLAC_ASSERT(targetByte >= rangeLo);
5847 DRFLAC_ASSERT(targetByte <= rangeHi);
5848
5849 *pLastSuccessfulSeekOffset = pFlac->firstFLACFramePosInBytes;
5850
5851 for (;;) {
5852 /* After rangeLo == rangeHi == targetByte fails, we need to break out. */
5853 drflac_uint64 lastTargetByte = targetByte;
5854
5855 /* 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. */
5856 if (!drflac__seek_to_byte(&pFlac->bs, targetByte)) {
5857 /* If we couldn't even seek to the first byte in the stream we have a problem. Just abandon the whole thing. */
5858 if (targetByte == 0) {
5859 drflac__seek_to_first_frame(pFlac); /* Try to recover. */
5860 return DRFLAC_FALSE;
5861 }
5862
5863 /* Halve the byte location and continue. */
5864 targetByte = rangeLo + ((rangeHi - rangeLo)/2);
5865 rangeHi = targetByte;
5866 } else {
5867 /* Getting here should mean that we have seeked to an appropriate byte. */
5868
5869 /* Clear the details of the FLAC frame so we don't misreport data. */
5870 DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
5871
5872 /*
5873 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
5874 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
5875 so it needs to stay this way for now.
5876 */
5877 #if 1
5878 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
5879 /* Halve the byte location and continue. */
5880 targetByte = rangeLo + ((rangeHi - rangeLo)/2);
5881 rangeHi = targetByte;
5882 } else {
5883 break;
5884 }
5885 #else
5886 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5887 /* Halve the byte location and continue. */
5888 targetByte = rangeLo + ((rangeHi - rangeLo)/2);
5889 rangeHi = targetByte;
5890 } else {
5891 break;
5892 }
5893 #endif
5894 }
5895
5896 /* We already tried this byte and there are no more to try, break out. */
5897 if(targetByte == lastTargetByte) {
5898 return DRFLAC_FALSE;
5899 }
5900 }
5901
5902 /* The current PCM frame needs to be updated based on the frame we just seeked to. */
5903 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
5904
5905 DRFLAC_ASSERT(targetByte <= rangeHi);
5906
5907 *pLastSuccessfulSeekOffset = targetByte;
5908 return DRFLAC_TRUE;
5909 }
5910
5911 static drflac_bool32 drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 offset)
5912 {
5913 /* 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(). */
5914 #if 0
5915 if (drflac__decode_flac_frame(pFlac) != DRFLAC_SUCCESS) {
5916 /* We failed to decode this frame which may be due to it being corrupt. We'll just use the next valid FLAC frame. */
5917 if (drflac__read_and_decode_next_flac_frame(pFlac) == DRFLAC_FALSE) {
5918 return DRFLAC_FALSE;
5919 }
5920 }
5921 #endif
5922
5923 return drflac__seek_forward_by_pcm_frames(pFlac, offset) == offset;
5924 }
5925
5926
5927 static drflac_bool32 drflac__seek_to_pcm_frame__binary_search_internal(drflac* pFlac, drflac_uint64 pcmFrameIndex, drflac_uint64 byteRangeLo, drflac_uint64 byteRangeHi)
5928 {
5929 /* This assumes pFlac->currentPCMFrame is sitting on byteRangeLo upon entry. */
5930
5931 drflac_uint64 targetByte;
5932 drflac_uint64 pcmRangeLo = pFlac->totalPCMFrameCount;
5933 drflac_uint64 pcmRangeHi = 0;
5934 drflac_uint64 lastSuccessfulSeekOffset = (drflac_uint64)-1;
5935 drflac_uint64 closestSeekOffsetBeforeTargetPCMFrame = byteRangeLo;
5936 drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
5937
5938 targetByte = byteRangeLo + (drflac_uint64)(((drflac_int64)((pcmFrameIndex - pFlac->currentPCMFrame) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO);
5939 if (targetByte > byteRangeHi) {
5940 targetByte = byteRangeHi;
5941 }
5942
5943 for (;;) {
5944 if (drflac__seek_to_approximate_flac_frame_to_byte(pFlac, targetByte, byteRangeLo, byteRangeHi, &lastSuccessfulSeekOffset)) {
5945 /* We found a FLAC frame. We need to check if it contains the sample we're looking for. */
5946 drflac_uint64 newPCMRangeLo;
5947 drflac_uint64 newPCMRangeHi;
5948 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &newPCMRangeLo, &newPCMRangeHi);
5949
5950 /* If we selected the same frame, it means we should be pretty close. Just decode the rest. */
5951 if (pcmRangeLo == newPCMRangeLo) {
5952 if (!drflac__seek_to_approximate_flac_frame_to_byte(pFlac, closestSeekOffsetBeforeTargetPCMFrame, closestSeekOffsetBeforeTargetPCMFrame, byteRangeHi, &lastSuccessfulSeekOffset)) {
5953 break; /* Failed to seek to closest frame. */
5954 }
5955
5956 if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
5957 return DRFLAC_TRUE;
5958 } else {
5959 break; /* Failed to seek forward. */
5960 }
5961 }
5962
5963 pcmRangeLo = newPCMRangeLo;
5964 pcmRangeHi = newPCMRangeHi;
5965
5966 if (pcmRangeLo <= pcmFrameIndex && pcmRangeHi >= pcmFrameIndex) {
5967 /* The target PCM frame is in this FLAC frame. */
5968 if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame) ) {
5969 return DRFLAC_TRUE;
5970 } else {
5971 break; /* Failed to seek to FLAC frame. */
5972 }
5973 } else {
5974 const float approxCompressionRatio = (drflac_int64)(lastSuccessfulSeekOffset - pFlac->firstFLACFramePosInBytes) / ((drflac_int64)(pcmRangeLo * pFlac->channels * pFlac->bitsPerSample)/8.0f);
5975
5976 if (pcmRangeLo > pcmFrameIndex) {
5977 /* We seeked too far forward. We need to move our target byte backward and try again. */
5978 byteRangeHi = lastSuccessfulSeekOffset;
5979 if (byteRangeLo > byteRangeHi) {
5980 byteRangeLo = byteRangeHi;
5981 }
5982
5983 targetByte = byteRangeLo + ((byteRangeHi - byteRangeLo) / 2);
5984 if (targetByte < byteRangeLo) {
5985 targetByte = byteRangeLo;
5986 }
5987 } else /*if (pcmRangeHi < pcmFrameIndex)*/ {
5988 /* We didn't seek far enough. We need to move our target byte forward and try again. */
5989
5990 /* If we're close enough we can just seek forward. */
5991 if ((pcmFrameIndex - pcmRangeLo) < seekForwardThreshold) {
5992 if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
5993 return DRFLAC_TRUE;
5994 } else {
5995 break; /* Failed to seek to FLAC frame. */
5996 }
5997 } else {
5998 byteRangeLo = lastSuccessfulSeekOffset;
5999 if (byteRangeHi < byteRangeLo) {
6000 byteRangeHi = byteRangeLo;
6001 }
6002
6003 targetByte = lastSuccessfulSeekOffset + (drflac_uint64)(((drflac_int64)((pcmFrameIndex-pcmRangeLo) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * approxCompressionRatio);
6004 if (targetByte > byteRangeHi) {
6005 targetByte = byteRangeHi;
6006 }
6007
6008 if (closestSeekOffsetBeforeTargetPCMFrame < lastSuccessfulSeekOffset) {
6009 closestSeekOffsetBeforeTargetPCMFrame = lastSuccessfulSeekOffset;
6010 }
6011 }
6012 }
6013 }
6014 } else {
6015 /* Getting here is really bad. We just recover as best we can, but moving to the first frame in the stream, and then abort. */
6016 break;
6017 }
6018 }
6019
6020 drflac__seek_to_first_frame(pFlac); /* <-- Try to recover. */
6021 return DRFLAC_FALSE;
6022 }
6023
6024 static drflac_bool32 drflac__seek_to_pcm_frame__binary_search(drflac* pFlac, drflac_uint64 pcmFrameIndex)
6025 {
6026 drflac_uint64 byteRangeLo;
6027 drflac_uint64 byteRangeHi;
6028 drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
6029
6030 /* Our algorithm currently assumes the FLAC stream is currently sitting at the start. */
6031 if (drflac__seek_to_first_frame(pFlac) == DRFLAC_FALSE) {
6032 return DRFLAC_FALSE;
6033 }
6034
6035 /* If we're close enough to the start, just move to the start and seek forward. */
6036 if (pcmFrameIndex < seekForwardThreshold) {
6037 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFrameIndex) == pcmFrameIndex;
6038 }
6039
6040 /*
6041 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
6042 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.
6043 */
6044 byteRangeLo = pFlac->firstFLACFramePosInBytes;
6045 byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
6046
6047 return drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi);
6048 }
6049 #endif /* !DR_FLAC_NO_CRC */
6050
6051 static drflac_bool32 drflac__seek_to_pcm_frame__seek_table(drflac* pFlac, drflac_uint64 pcmFrameIndex)
6052 {
6053 drflac_uint32 iClosestSeekpoint = 0;
6054 drflac_bool32 isMidFrame = DRFLAC_FALSE;
6055 drflac_uint64 runningPCMFrameCount;
6056 drflac_uint32 iSeekpoint;
6057
6058
6059 DRFLAC_ASSERT(pFlac != NULL);
6060
6061 if (pFlac->pSeekpoints == NULL || pFlac->seekpointCount == 0) {
6062 return DRFLAC_FALSE;
6063 }
6064
6065 /* Do not use the seektable if pcmFramIndex is not coverd by it. */
6066 if (pFlac->pSeekpoints[0].firstPCMFrame > pcmFrameIndex) {
6067 return DRFLAC_FALSE;
6068 }
6069
6070 for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
6071 if (pFlac->pSeekpoints[iSeekpoint].firstPCMFrame >= pcmFrameIndex) {
6072 break;
6073 }
6074
6075 iClosestSeekpoint = iSeekpoint;
6076 }
6077
6078 /* There's been cases where the seek table contains only zeros. We need to do some basic validation on the closest seekpoint. */
6079 if (pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount == 0 || pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount > pFlac->maxBlockSizeInPCMFrames) {
6080 return DRFLAC_FALSE;
6081 }
6082 if (pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame > pFlac->totalPCMFrameCount && pFlac->totalPCMFrameCount > 0) {
6083 return DRFLAC_FALSE;
6084 }
6085
6086 #if !defined(DR_FLAC_NO_CRC)
6087 /* 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. */
6088 if (pFlac->totalPCMFrameCount > 0) {
6089 drflac_uint64 byteRangeLo;
6090 drflac_uint64 byteRangeHi;
6091
6092 byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
6093 byteRangeLo = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset;
6094
6095 /*
6096 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
6097 value for byteRangeHi which will clamp it appropriately.
6098
6099 Note that the next seekpoint must have an offset greater than the closest seekpoint because otherwise our binary search algorithm will break down. There
6100 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.
6101 */
6102 if (iClosestSeekpoint < pFlac->seekpointCount-1) {
6103 drflac_uint32 iNextSeekpoint = iClosestSeekpoint + 1;
6104
6105 /* Basic validation on the seekpoints to ensure they're usable. */
6106 if (pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset >= pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset || pFlac->pSeekpoints[iNextSeekpoint].pcmFrameCount == 0) {
6107 return DRFLAC_FALSE; /* The next seekpoint doesn't look right. The seek table cannot be trusted from here. Abort. */
6108 }
6109
6110 if (pFlac->pSeekpoints[iNextSeekpoint].firstPCMFrame != (((drflac_uint64)0xFFFFFFFF << 32) | 0xFFFFFFFF)) { /* Make sure it's not a placeholder seekpoint. */
6111 byteRangeHi = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset - 1; /* byteRangeHi must be zero based. */
6112 }
6113 }
6114
6115 if (drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
6116 if (drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
6117 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
6118
6119 if (drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi)) {
6120 return DRFLAC_TRUE;
6121 }
6122 }
6123 }
6124 }
6125 #endif /* !DR_FLAC_NO_CRC */
6126
6127 /* Getting here means we need to use a slower algorithm because the binary search method failed or cannot be used. */
6128
6129 /*
6130 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
6131 from the seekpoint's first sample.
6132 */
6133 if (pcmFrameIndex >= pFlac->currentPCMFrame && pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame <= pFlac->currentPCMFrame) {
6134 /* Optimized case. Just seek forward from where we are. */
6135 runningPCMFrameCount = pFlac->currentPCMFrame;
6136
6137 /* The frame header for the first frame may not yet have been read. We need to do that if necessary. */
6138 if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
6139 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
6140 return DRFLAC_FALSE;
6141 }
6142 } else {
6143 isMidFrame = DRFLAC_TRUE;
6144 }
6145 } else {
6146 /* Slower case. Seek to the start of the seekpoint and then seek forward from there. */
6147 runningPCMFrameCount = pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame;
6148
6149 if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
6150 return DRFLAC_FALSE;
6151 }
6152
6153 /* Grab the frame the seekpoint is sitting on in preparation for the sample-exact seeking below. */
6154 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
6155 return DRFLAC_FALSE;
6156 }
6157 }
6158
6159 for (;;) {
6160 drflac_uint64 pcmFrameCountInThisFLACFrame;
6161 drflac_uint64 firstPCMFrameInFLACFrame = 0;
6162 drflac_uint64 lastPCMFrameInFLACFrame = 0;
6163
6164 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
6165
6166 pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
6167 if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
6168 /*
6169 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
6170 it never existed and keep iterating.
6171 */
6172 drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
6173
6174 if (!isMidFrame) {
6175 drflac_result result = drflac__decode_flac_frame(pFlac);
6176 if (result == DRFLAC_SUCCESS) {
6177 /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
6178 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */
6179 } else {
6180 if (result == DRFLAC_CRC_MISMATCH) {
6181 goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */
6182 } else {
6183 return DRFLAC_FALSE;
6184 }
6185 }
6186 } else {
6187 /* We started seeking mid-frame which means we need to skip the frame decoding part. */
6188 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
6189 }
6190 } else {
6191 /*
6192 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
6193 frame never existed and leave the running sample count untouched.
6194 */
6195 if (!isMidFrame) {
6196 drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
6197 if (result == DRFLAC_SUCCESS) {
6198 runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
6199 } else {
6200 if (result == DRFLAC_CRC_MISMATCH) {
6201 goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */
6202 } else {
6203 return DRFLAC_FALSE;
6204 }
6205 }
6206 } else {
6207 /*
6208 We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with
6209 drflac__seek_to_next_flac_frame() which only works if the decoder is sitting on the byte just after the frame header.
6210 */
6211 runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
6212 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
6213 isMidFrame = DRFLAC_FALSE;
6214 }
6215
6216 /* If we are seeking to the end of the file and we've just hit it, we're done. */
6217 if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
6218 return DRFLAC_TRUE;
6219 }
6220 }
6221
6222 next_iteration:
6223 /* Grab the next frame in preparation for the next iteration. */
6224 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
6225 return DRFLAC_FALSE;
6226 }
6227 }
6228 }
6229
6230
6231 #ifndef DR_FLAC_NO_OGG
6232 typedef struct
6233 {
6234 drflac_uint8 capturePattern[4]; /* Should be "OggS" */
6235 drflac_uint8 structureVersion; /* Always 0. */
6236 drflac_uint8 headerType;
6237 drflac_uint64 granulePosition;
6238 drflac_uint32 serialNumber;
6239 drflac_uint32 sequenceNumber;
6240 drflac_uint32 checksum;
6241 drflac_uint8 segmentCount;
6242 drflac_uint8 segmentTable[255];
6243 } drflac_ogg_page_header;
6244 #endif
6245
6246 typedef struct
6247 {
6248 drflac_read_proc onRead;
6249 drflac_seek_proc onSeek;
6250 drflac_tell_proc onTell;
6251 drflac_meta_proc onMeta;
6252 drflac_container container;
6253 void* pUserData;
6254 void* pUserDataMD;
6255 drflac_uint32 sampleRate;
6256 drflac_uint8 channels;
6257 drflac_uint8 bitsPerSample;
6258 drflac_uint64 totalPCMFrameCount;
6259 drflac_uint16 maxBlockSizeInPCMFrames;
6260 drflac_uint64 runningFilePos;
6261 drflac_bool32 hasStreamInfoBlock;
6262 drflac_bool32 hasMetadataBlocks;
6263 drflac_bs bs; /* <-- A bit streamer is required for loading data during initialization. */
6264 drflac_frame_header firstFrameHeader; /* <-- The header of the first frame that was read during relaxed initalization. Only set if there is no STREAMINFO block. */
6265
6266 #ifndef DR_FLAC_NO_OGG
6267 drflac_uint32 oggSerial;
6268 drflac_uint64 oggFirstBytePos;
6269 drflac_ogg_page_header oggBosHeader;
6270 #endif
6271 } drflac_init_info;
6272
6273 static DRFLAC_INLINE void drflac__decode_block_header(drflac_uint32 blockHeader, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
6274 {
6275 blockHeader = drflac__be2host_32(blockHeader);
6276 *isLastBlock = (drflac_uint8)((blockHeader & 0x80000000UL) >> 31);
6277 *blockType = (drflac_uint8)((blockHeader & 0x7F000000UL) >> 24);
6278 *blockSize = (blockHeader & 0x00FFFFFFUL);
6279 }
6280
6281 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)
6282 {
6283 drflac_uint32 blockHeader;
6284
6285 *blockSize = 0;
6286 if (onRead(pUserData, &blockHeader, 4) != 4) {
6287 return DRFLAC_FALSE;
6288 }
6289
6290 drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize);
6291 return DRFLAC_TRUE;
6292 }
6293
6294 static drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, drflac_streaminfo* pStreamInfo)
6295 {
6296 drflac_uint32 blockSizes;
6297 drflac_uint64 frameSizes = 0;
6298 drflac_uint64 importantProps;
6299 drflac_uint8 md5[16];
6300
6301 /* min/max block size. */
6302 if (onRead(pUserData, &blockSizes, 4) != 4) {
6303 return DRFLAC_FALSE;
6304 }
6305
6306 /* min/max frame size. */
6307 if (onRead(pUserData, &frameSizes, 6) != 6) {
6308 return DRFLAC_FALSE;
6309 }
6310
6311 /* Sample rate, channels, bits per sample and total sample count. */
6312 if (onRead(pUserData, &importantProps, 8) != 8) {
6313 return DRFLAC_FALSE;
6314 }
6315
6316 /* MD5 */
6317 if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5)) {
6318 return DRFLAC_FALSE;
6319 }
6320
6321 blockSizes = drflac__be2host_32(blockSizes);
6322 frameSizes = drflac__be2host_64(frameSizes);
6323 importantProps = drflac__be2host_64(importantProps);
6324
6325 pStreamInfo->minBlockSizeInPCMFrames = (drflac_uint16)((blockSizes & 0xFFFF0000) >> 16);
6326 pStreamInfo->maxBlockSizeInPCMFrames = (drflac_uint16) (blockSizes & 0x0000FFFF);
6327 pStreamInfo->minFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 24)) >> 40);
6328 pStreamInfo->maxFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 0)) >> 16);
6329 pStreamInfo->sampleRate = (drflac_uint32)((importantProps & (((drflac_uint64)0x000FFFFF << 16) << 28)) >> 44);
6330 pStreamInfo->channels = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000000E << 16) << 24)) >> 41) + 1;
6331 pStreamInfo->bitsPerSample = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000001F << 16) << 20)) >> 36) + 1;
6332 pStreamInfo->totalPCMFrameCount = ((importantProps & ((((drflac_uint64)0x0000000F << 16) << 16) | 0xFFFFFFFF)));
6333 DRFLAC_COPY_MEMORY(pStreamInfo->md5, md5, sizeof(md5));
6334
6335 return DRFLAC_TRUE;
6336 }
6337
6338
6339 static void* drflac__malloc_default(size_t sz, void* pUserData)
6340 {
6341 (void)pUserData;
6342 return DRFLAC_MALLOC(sz);
6343 }
6344
6345 static void* drflac__realloc_default(void* p, size_t sz, void* pUserData)
6346 {
6347 (void)pUserData;
6348 return DRFLAC_REALLOC(p, sz);
6349 }
6350
6351 static void drflac__free_default(void* p, void* pUserData)
6352 {
6353 (void)pUserData;
6354 DRFLAC_FREE(p);
6355 }
6356
6357
6358 static void* drflac__malloc_from_callbacks(size_t sz, const drflac_allocation_callbacks* pAllocationCallbacks)
6359 {
6360 if (pAllocationCallbacks == NULL) {
6361 return NULL;
6362 }
6363
6364 if (pAllocationCallbacks->onMalloc != NULL) {
6365 return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
6366 }
6367
6368 /* Try using realloc(). */
6369 if (pAllocationCallbacks->onRealloc != NULL) {
6370 return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
6371 }
6372
6373 return NULL;
6374 }
6375
6376 static void* drflac__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drflac_allocation_callbacks* pAllocationCallbacks)
6377 {
6378 if (pAllocationCallbacks == NULL) {
6379 return NULL;
6380 }
6381
6382 if (pAllocationCallbacks->onRealloc != NULL) {
6383 return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
6384 }
6385
6386 /* Try emulating realloc() in terms of malloc()/free(). */
6387 if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
6388 void* p2;
6389
6390 p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
6391 if (p2 == NULL) {
6392 return NULL;
6393 }
6394
6395 if (p != NULL) {
6396 DRFLAC_COPY_MEMORY(p2, p, szOld);
6397 pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
6398 }
6399
6400 return p2;
6401 }
6402
6403 return NULL;
6404 }
6405
6406 static void drflac__free_from_callbacks(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
6407 {
6408 if (p == NULL || pAllocationCallbacks == NULL) {
6409 return;
6410 }
6411
6412 if (pAllocationCallbacks->onFree != NULL) {
6413 pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
6414 }
6415 }
6416
6417
6418 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)
6419 {
6420 /*
6421 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
6422 we'll be sitting on byte 42.
6423 */
6424 drflac_uint64 runningFilePos = 42;
6425 drflac_uint64 seektablePos = 0;
6426 drflac_uint32 seektableSize = 0;
6427
6428 (void)onTell;
6429
6430 for (;;) {
6431 drflac_metadata metadata;
6432 drflac_uint8 isLastBlock = 0;
6433 drflac_uint8 blockType = 0;
6434 drflac_uint32 blockSize;
6435 if (drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize) == DRFLAC_FALSE) {
6436 return DRFLAC_FALSE;
6437 }
6438 runningFilePos += 4;
6439
6440 metadata.type = blockType;
6441 metadata.rawDataSize = 0;
6442 metadata.rawDataOffset = runningFilePos;
6443 metadata.pRawData = NULL;
6444
6445 switch (blockType)
6446 {
6447 case DRFLAC_METADATA_BLOCK_TYPE_APPLICATION:
6448 {
6449 if (blockSize < 4) {
6450 return DRFLAC_FALSE;
6451 }
6452
6453 if (onMeta) {
6454 void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6455 if (pRawData == NULL) {
6456 return DRFLAC_FALSE;
6457 }
6458
6459 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6460 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6461 return DRFLAC_FALSE;
6462 }
6463
6464 metadata.pRawData = pRawData;
6465 metadata.rawDataSize = blockSize;
6466 metadata.data.application.id = drflac__be2host_32(*(drflac_uint32*)pRawData);
6467 metadata.data.application.pData = (const void*)((drflac_uint8*)pRawData + sizeof(drflac_uint32));
6468 metadata.data.application.dataSize = blockSize - sizeof(drflac_uint32);
6469 onMeta(pUserDataMD, &metadata);
6470
6471 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6472 }
6473 } break;
6474
6475 case DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE:
6476 {
6477 seektablePos = runningFilePos;
6478 seektableSize = blockSize;
6479
6480 if (onMeta) {
6481 drflac_uint32 seekpointCount;
6482 drflac_uint32 iSeekpoint;
6483 void* pRawData;
6484
6485 seekpointCount = blockSize/DRFLAC_SEEKPOINT_SIZE_IN_BYTES;
6486
6487 pRawData = drflac__malloc_from_callbacks(seekpointCount * sizeof(drflac_seekpoint), pAllocationCallbacks);
6488 if (pRawData == NULL) {
6489 return DRFLAC_FALSE;
6490 }
6491
6492 /* We need to read seekpoint by seekpoint and do some processing. */
6493 for (iSeekpoint = 0; iSeekpoint < seekpointCount; ++iSeekpoint) {
6494 drflac_seekpoint* pSeekpoint = (drflac_seekpoint*)pRawData + iSeekpoint;
6495
6496 if (onRead(pUserData, pSeekpoint, DRFLAC_SEEKPOINT_SIZE_IN_BYTES) != DRFLAC_SEEKPOINT_SIZE_IN_BYTES) {
6497 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6498 return DRFLAC_FALSE;
6499 }
6500
6501 /* Endian swap. */
6502 pSeekpoint->firstPCMFrame = drflac__be2host_64(pSeekpoint->firstPCMFrame);
6503 pSeekpoint->flacFrameOffset = drflac__be2host_64(pSeekpoint->flacFrameOffset);
6504 pSeekpoint->pcmFrameCount = drflac__be2host_16(pSeekpoint->pcmFrameCount);
6505 }
6506
6507 metadata.pRawData = pRawData;
6508 metadata.rawDataSize = blockSize;
6509 metadata.data.seektable.seekpointCount = seekpointCount;
6510 metadata.data.seektable.pSeekpoints = (const drflac_seekpoint*)pRawData;
6511
6512 onMeta(pUserDataMD, &metadata);
6513
6514 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6515 }
6516 } break;
6517
6518 case DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT:
6519 {
6520 if (blockSize < 8) {
6521 return DRFLAC_FALSE;
6522 }
6523
6524 if (onMeta) {
6525 void* pRawData;
6526 const char* pRunningData;
6527 const char* pRunningDataEnd;
6528 drflac_uint32 i;
6529
6530 pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6531 if (pRawData == NULL) {
6532 return DRFLAC_FALSE;
6533 }
6534
6535 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6536 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6537 return DRFLAC_FALSE;
6538 }
6539
6540 metadata.pRawData = pRawData;
6541 metadata.rawDataSize = blockSize;
6542
6543 pRunningData = (const char*)pRawData;
6544 pRunningDataEnd = (const char*)pRawData + blockSize;
6545
6546 metadata.data.vorbis_comment.vendorLength = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6547
6548 /* Need space for the rest of the block */
6549 if ((pRunningDataEnd - pRunningData) - 4 < (drflac_int64)metadata.data.vorbis_comment.vendorLength) { /* <-- Note the order of operations to avoid overflow to a valid value */
6550 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6551 return DRFLAC_FALSE;
6552 }
6553 metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength;
6554 metadata.data.vorbis_comment.commentCount = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6555
6556 /* Need space for 'commentCount' comments after the block, which at minimum is a drflac_uint32 per comment */
6557 if ((pRunningDataEnd - pRunningData) / sizeof(drflac_uint32) < metadata.data.vorbis_comment.commentCount) { /* <-- Note the order of operations to avoid overflow to a valid value */
6558 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6559 return DRFLAC_FALSE;
6560 }
6561 metadata.data.vorbis_comment.pComments = pRunningData;
6562
6563 /* Check that the comments section is valid before passing it to the callback */
6564 for (i = 0; i < metadata.data.vorbis_comment.commentCount; ++i) {
6565 drflac_uint32 commentLength;
6566
6567 if (pRunningDataEnd - pRunningData < 4) {
6568 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6569 return DRFLAC_FALSE;
6570 }
6571
6572 commentLength = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6573 if (pRunningDataEnd - pRunningData < (drflac_int64)commentLength) { /* <-- Note the order of operations to avoid overflow to a valid value */
6574 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6575 return DRFLAC_FALSE;
6576 }
6577 pRunningData += commentLength;
6578 }
6579
6580 onMeta(pUserDataMD, &metadata);
6581
6582 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6583 }
6584 } break;
6585
6586 case DRFLAC_METADATA_BLOCK_TYPE_CUESHEET:
6587 {
6588 if (blockSize < 396) {
6589 return DRFLAC_FALSE;
6590 }
6591
6592 if (onMeta) {
6593 void* pRawData;
6594 const char* pRunningData;
6595 const char* pRunningDataEnd;
6596 size_t bufferSize;
6597 drflac_uint8 iTrack;
6598 drflac_uint8 iIndex;
6599 void* pTrackData;
6600
6601 /*
6602 This needs to be loaded in two passes. The first pass is used to calculate the size of the memory allocation
6603 we need for storing the necessary data. The second pass will fill that buffer with usable data.
6604 */
6605 pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6606 if (pRawData == NULL) {
6607 return DRFLAC_FALSE;
6608 }
6609
6610 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6611 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6612 return DRFLAC_FALSE;
6613 }
6614
6615 metadata.pRawData = pRawData;
6616 metadata.rawDataSize = blockSize;
6617
6618 pRunningData = (const char*)pRawData;
6619 pRunningDataEnd = (const char*)pRawData + blockSize;
6620
6621 DRFLAC_COPY_MEMORY(metadata.data.cuesheet.catalog, pRunningData, 128); pRunningData += 128;
6622 metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*(const drflac_uint64*)pRunningData); pRunningData += 8;
6623 metadata.data.cuesheet.isCD = (pRunningData[0] & 0x80) != 0; pRunningData += 259;
6624 metadata.data.cuesheet.trackCount = pRunningData[0]; pRunningData += 1;
6625 metadata.data.cuesheet.pTrackData = NULL; /* Will be filled later. */
6626
6627 /* Pass 1: Calculate the size of the buffer for the track data. */
6628 {
6629 const char* pRunningDataSaved = pRunningData; /* Will be restored at the end in preparation for the second pass. */
6630
6631 bufferSize = metadata.data.cuesheet.trackCount * DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES;
6632
6633 for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) {
6634 drflac_uint8 indexCount;
6635 drflac_uint32 indexPointSize;
6636
6637 if (pRunningDataEnd - pRunningData < DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES) {
6638 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6639 return DRFLAC_FALSE;
6640 }
6641
6642 /* Skip to the index point count */
6643 pRunningData += 35;
6644
6645 indexCount = pRunningData[0];
6646 pRunningData += 1;
6647
6648 bufferSize += indexCount * sizeof(drflac_cuesheet_track_index);
6649
6650 /* Quick validation check. */
6651 indexPointSize = indexCount * DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES;
6652 if (pRunningDataEnd - pRunningData < (drflac_int64)indexPointSize) {
6653 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6654 return DRFLAC_FALSE;
6655 }
6656
6657 pRunningData += indexPointSize;
6658 }
6659
6660 pRunningData = pRunningDataSaved;
6661 }
6662
6663 /* Pass 2: Allocate a buffer and fill the data. Validation was done in the step above so can be skipped. */
6664 {
6665 char* pRunningTrackData;
6666
6667 pTrackData = drflac__malloc_from_callbacks(bufferSize, pAllocationCallbacks);
6668 if (pTrackData == NULL) {
6669 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6670 return DRFLAC_FALSE;
6671 }
6672
6673 pRunningTrackData = (char*)pTrackData;
6674
6675 for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) {
6676 drflac_uint8 indexCount;
6677
6678 DRFLAC_COPY_MEMORY(pRunningTrackData, pRunningData, DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES);
6679 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. */
6680 pRunningTrackData += DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1;
6681
6682 /* Grab the index count for the next part. */
6683 indexCount = pRunningData[0];
6684 pRunningData += 1;
6685 pRunningTrackData += 1;
6686
6687 /* Extract each track index. */
6688 for (iIndex = 0; iIndex < indexCount; ++iIndex) {
6689 drflac_cuesheet_track_index* pTrackIndex = (drflac_cuesheet_track_index*)pRunningTrackData;
6690
6691 DRFLAC_COPY_MEMORY(pRunningTrackData, pRunningData, DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES);
6692 pRunningData += DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES;
6693 pRunningTrackData += sizeof(drflac_cuesheet_track_index);
6694
6695 pTrackIndex->offset = drflac__be2host_64(pTrackIndex->offset);
6696 }
6697 }
6698
6699 metadata.data.cuesheet.pTrackData = pTrackData;
6700 }
6701
6702 /* The original data is no longer needed. */
6703 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6704 pRawData = NULL;
6705
6706 onMeta(pUserDataMD, &metadata);
6707
6708 drflac__free_from_callbacks(pTrackData, pAllocationCallbacks);
6709 pTrackData = NULL;
6710 }
6711 } break;
6712
6713 case DRFLAC_METADATA_BLOCK_TYPE_PICTURE:
6714 {
6715 if (blockSize < 32) {
6716 return DRFLAC_FALSE;
6717 }
6718
6719 if (onMeta) {
6720 drflac_bool32 result = DRFLAC_TRUE;
6721 drflac_uint32 blockSizeRemaining = blockSize;
6722 char* pMime = NULL;
6723 char* pDescription = NULL;
6724 void* pPictureData = NULL;
6725
6726 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.type, 4) != 4) {
6727 result = DRFLAC_FALSE;
6728 goto done_flac;
6729 }
6730 blockSizeRemaining -= 4;
6731 metadata.data.picture.type = drflac__be2host_32(metadata.data.picture.type);
6732
6733
6734 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.mimeLength, 4) != 4) {
6735 result = DRFLAC_FALSE;
6736 goto done_flac;
6737 }
6738 blockSizeRemaining -= 4;
6739 metadata.data.picture.mimeLength = drflac__be2host_32(metadata.data.picture.mimeLength);
6740
6741 pMime = (char*)drflac__malloc_from_callbacks(metadata.data.picture.mimeLength + 1, pAllocationCallbacks); /* +1 for null terminator. */
6742 if (pMime == NULL) {
6743 result = DRFLAC_FALSE;
6744 goto done_flac;
6745 }
6746
6747 if (blockSizeRemaining < metadata.data.picture.mimeLength || onRead(pUserData, pMime, metadata.data.picture.mimeLength) != metadata.data.picture.mimeLength) {
6748 result = DRFLAC_FALSE;
6749 goto done_flac;
6750 }
6751 blockSizeRemaining -= metadata.data.picture.mimeLength;
6752 pMime[metadata.data.picture.mimeLength] = '\0'; /* Null terminate for safety. */
6753 metadata.data.picture.mime = (const char*)pMime;
6754
6755
6756 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.descriptionLength, 4) != 4) {
6757 result = DRFLAC_FALSE;
6758 goto done_flac;
6759 }
6760 blockSizeRemaining -= 4;
6761 metadata.data.picture.descriptionLength = drflac__be2host_32(metadata.data.picture.descriptionLength);
6762
6763 pDescription = (char*)drflac__malloc_from_callbacks(metadata.data.picture.descriptionLength + 1, pAllocationCallbacks); /* +1 for null terminator. */
6764 if (pDescription == NULL) {
6765 result = DRFLAC_FALSE;
6766 goto done_flac;
6767 }
6768
6769 if (blockSizeRemaining < metadata.data.picture.descriptionLength || onRead(pUserData, pDescription, metadata.data.picture.descriptionLength) != metadata.data.picture.descriptionLength) {
6770 result = DRFLAC_FALSE;
6771 goto done_flac;
6772 }
6773 blockSizeRemaining -= metadata.data.picture.descriptionLength;
6774 pDescription[metadata.data.picture.descriptionLength] = '\0'; /* Null terminate for safety. */
6775 metadata.data.picture.description = (const char*)pDescription;
6776
6777
6778 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.width, 4) != 4) {
6779 result = DRFLAC_FALSE;
6780 goto done_flac;
6781 }
6782 blockSizeRemaining -= 4;
6783 metadata.data.picture.width = drflac__be2host_32(metadata.data.picture.width);
6784
6785 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.height, 4) != 4) {
6786 result = DRFLAC_FALSE;
6787 goto done_flac;
6788 }
6789 blockSizeRemaining -= 4;
6790 metadata.data.picture.height = drflac__be2host_32(metadata.data.picture.height);
6791
6792 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.colorDepth, 4) != 4) {
6793 result = DRFLAC_FALSE;
6794 goto done_flac;
6795 }
6796 blockSizeRemaining -= 4;
6797 metadata.data.picture.colorDepth = drflac__be2host_32(metadata.data.picture.colorDepth);
6798
6799 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.indexColorCount, 4) != 4) {
6800 result = DRFLAC_FALSE;
6801 goto done_flac;
6802 }
6803 blockSizeRemaining -= 4;
6804 metadata.data.picture.indexColorCount = drflac__be2host_32(metadata.data.picture.indexColorCount);
6805
6806
6807 /* Picture data. */
6808 if (blockSizeRemaining < 4 || onRead(pUserData, &metadata.data.picture.pictureDataSize, 4) != 4) {
6809 result = DRFLAC_FALSE;
6810 goto done_flac;
6811 }
6812 blockSizeRemaining -= 4;
6813 metadata.data.picture.pictureDataSize = drflac__be2host_32(metadata.data.picture.pictureDataSize);
6814
6815 if (blockSizeRemaining < metadata.data.picture.pictureDataSize) {
6816 result = DRFLAC_FALSE;
6817 goto done_flac;
6818 }
6819
6820 /* For the actual image data we want to store the offset to the start of the stream. */
6821 metadata.data.picture.pictureDataOffset = runningFilePos + (blockSize - blockSizeRemaining);
6822
6823 /*
6824 For the allocation of image data, we can allow memory allocation to fail, in which case we just leave
6825 the pointer as null. If it fails, we need to fall back to seeking past the image data.
6826 */
6827 #ifndef DR_FLAC_NO_PICTURE_METADATA_MALLOC
6828 pPictureData = drflac__malloc_from_callbacks(metadata.data.picture.pictureDataSize, pAllocationCallbacks);
6829 if (pPictureData != NULL) {
6830 if (onRead(pUserData, pPictureData, metadata.data.picture.pictureDataSize) != metadata.data.picture.pictureDataSize) {
6831 result = DRFLAC_FALSE;
6832 goto done_flac;
6833 }
6834 } else
6835 #endif
6836 {
6837 /* Allocation failed. We need to seek past the picture data. */
6838 if (!onSeek(pUserData, metadata.data.picture.pictureDataSize, DRFLAC_SEEK_CUR)) {
6839 result = DRFLAC_FALSE;
6840 goto done_flac;
6841 }
6842 }
6843
6844 blockSizeRemaining -= metadata.data.picture.pictureDataSize;
6845 (void)blockSizeRemaining;
6846
6847 metadata.data.picture.pPictureData = (const drflac_uint8*)pPictureData;
6848
6849
6850 /* 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. */
6851 if (metadata.data.picture.pictureDataOffset != 0 || metadata.data.picture.pPictureData != NULL) {
6852 onMeta(pUserDataMD, &metadata);
6853 } else {
6854 /* Don't have a valid offset or data pointer, so just pretend we don't have a picture metadata. */
6855 }
6856
6857 done_flac:
6858 drflac__free_from_callbacks(pMime, pAllocationCallbacks);
6859 drflac__free_from_callbacks(pDescription, pAllocationCallbacks);
6860 drflac__free_from_callbacks(pPictureData, pAllocationCallbacks);
6861
6862 if (result != DRFLAC_TRUE) {
6863 return DRFLAC_FALSE;
6864 }
6865 }
6866 } break;
6867
6868 case DRFLAC_METADATA_BLOCK_TYPE_PADDING:
6869 {
6870 if (onMeta) {
6871 metadata.data.padding.unused = 0;
6872
6873 /* 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. */
6874 if (!onSeek(pUserData, blockSize, DRFLAC_SEEK_CUR)) {
6875 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. */
6876 } else {
6877 onMeta(pUserDataMD, &metadata);
6878 }
6879 }
6880 } break;
6881
6882 case DRFLAC_METADATA_BLOCK_TYPE_INVALID:
6883 {
6884 /* Invalid chunk. Just skip over this one. */
6885 if (onMeta) {
6886 if (!onSeek(pUserData, blockSize, DRFLAC_SEEK_CUR)) {
6887 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. */
6888 }
6889 }
6890 } break;
6891
6892 default:
6893 {
6894 /*
6895 It's an unknown chunk, but not necessarily invalid. There's a chance more metadata blocks might be defined later on, so we
6896 can at the very least report the chunk to the application and let it look at the raw data.
6897 */
6898 if (onMeta) {
6899 void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6900 if (pRawData != NULL) {
6901 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6902 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6903 return DRFLAC_FALSE;
6904 }
6905 } else {
6906 /* Allocation failed. We need to seek past the block. */
6907 if (!onSeek(pUserData, blockSize, DRFLAC_SEEK_CUR)) {
6908 return DRFLAC_FALSE;
6909 }
6910 }
6911
6912 metadata.pRawData = pRawData;
6913 metadata.rawDataSize = blockSize;
6914 onMeta(pUserDataMD, &metadata);
6915
6916 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6917 }
6918 } break;
6919 }
6920
6921 /* 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. */
6922 if (onMeta == NULL && blockSize > 0) {
6923 if (!onSeek(pUserData, blockSize, DRFLAC_SEEK_CUR)) {
6924 isLastBlock = DRFLAC_TRUE;
6925 }
6926 }
6927
6928 runningFilePos += blockSize;
6929 if (isLastBlock) {
6930 break;
6931 }
6932 }
6933
6934 *pSeektablePos = seektablePos;
6935 *pSeekpointCount = seektableSize / DRFLAC_SEEKPOINT_SIZE_IN_BYTES;
6936 *pFirstFramePos = runningFilePos;
6937
6938 return DRFLAC_TRUE;
6939 }
6940
6941 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)
6942 {
6943 /* Pre Condition: The bit stream should be sitting just past the 4-byte id header. */
6944
6945 drflac_uint8 isLastBlock;
6946 drflac_uint8 blockType;
6947 drflac_uint32 blockSize;
6948
6949 (void)onSeek;
6950
6951 pInit->container = drflac_container_native;
6952
6953 /* The first metadata block should be the STREAMINFO block. */
6954 if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
6955 return DRFLAC_FALSE;
6956 }
6957
6958 if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
6959 if (!relaxed) {
6960 /* We're opening in strict mode and the first block is not the STREAMINFO block. Error. */
6961 return DRFLAC_FALSE;
6962 } else {
6963 /*
6964 Relaxed mode. To open from here we need to just find the first frame and set the sample rate, etc. to whatever is defined
6965 for that frame.
6966 */
6967 pInit->hasStreamInfoBlock = DRFLAC_FALSE;
6968 pInit->hasMetadataBlocks = DRFLAC_FALSE;
6969
6970 if (!drflac__read_next_flac_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) {
6971 return DRFLAC_FALSE; /* Couldn't find a frame. */
6972 }
6973
6974 if (pInit->firstFrameHeader.bitsPerSample == 0) {
6975 return DRFLAC_FALSE; /* Failed to initialize because the first frame depends on the STREAMINFO block, which does not exist. */
6976 }
6977
6978 pInit->sampleRate = pInit->firstFrameHeader.sampleRate;
6979 pInit->channels = drflac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment);
6980 pInit->bitsPerSample = pInit->firstFrameHeader.bitsPerSample;
6981 pInit->maxBlockSizeInPCMFrames = 65535; /* <-- See notes here: https://xiph.org/flac/format.html#metadata_block_streaminfo */
6982 return DRFLAC_TRUE;
6983 }
6984 } else {
6985 drflac_streaminfo streaminfo;
6986 if (!drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
6987 return DRFLAC_FALSE;
6988 }
6989
6990 pInit->hasStreamInfoBlock = DRFLAC_TRUE;
6991 pInit->sampleRate = streaminfo.sampleRate;
6992 pInit->channels = streaminfo.channels;
6993 pInit->bitsPerSample = streaminfo.bitsPerSample;
6994 pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
6995 pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames; /* Don't care about the min block size - only the max (used for determining the size of the memory allocation). */
6996 pInit->hasMetadataBlocks = !isLastBlock;
6997
6998 if (onMeta) {
6999 drflac_metadata metadata;
7000 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
7001 metadata.pRawData = NULL;
7002 metadata.rawDataSize = 0;
7003 metadata.data.streaminfo = streaminfo;
7004 onMeta(pUserDataMD, &metadata);
7005 }
7006
7007 return DRFLAC_TRUE;
7008 }
7009 }
7010
7011 #ifndef DR_FLAC_NO_OGG
7012 #define DRFLAC_OGG_MAX_PAGE_SIZE 65307
7013 #define DRFLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199 /* CRC-32 of "OggS". */
7014
7015 typedef enum
7016 {
7017 drflac_ogg_recover_on_crc_mismatch,
7018 drflac_ogg_fail_on_crc_mismatch
7019 } drflac_ogg_crc_mismatch_recovery;
7020
7021 #ifndef DR_FLAC_NO_CRC
7022 static drflac_uint32 drflac__crc32_table[] = {
7023 0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L,
7024 0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L,
7025 0x2608EDB8L, 0x22C9F00FL, 0x2F8AD6D6L, 0x2B4BCB61L,
7026 0x350C9B64L, 0x31CD86D3L, 0x3C8EA00AL, 0x384FBDBDL,
7027 0x4C11DB70L, 0x48D0C6C7L, 0x4593E01EL, 0x4152FDA9L,
7028 0x5F15ADACL, 0x5BD4B01BL, 0x569796C2L, 0x52568B75L,
7029 0x6A1936C8L, 0x6ED82B7FL, 0x639B0DA6L, 0x675A1011L,
7030 0x791D4014L, 0x7DDC5DA3L, 0x709F7B7AL, 0x745E66CDL,
7031 0x9823B6E0L, 0x9CE2AB57L, 0x91A18D8EL, 0x95609039L,
7032 0x8B27C03CL, 0x8FE6DD8BL, 0x82A5FB52L, 0x8664E6E5L,
7033 0xBE2B5B58L, 0xBAEA46EFL, 0xB7A96036L, 0xB3687D81L,
7034 0xAD2F2D84L, 0xA9EE3033L, 0xA4AD16EAL, 0xA06C0B5DL,
7035 0xD4326D90L, 0xD0F37027L, 0xDDB056FEL, 0xD9714B49L,
7036 0xC7361B4CL, 0xC3F706FBL, 0xCEB42022L, 0xCA753D95L,
7037 0xF23A8028L, 0xF6FB9D9FL, 0xFBB8BB46L, 0xFF79A6F1L,
7038 0xE13EF6F4L, 0xE5FFEB43L, 0xE8BCCD9AL, 0xEC7DD02DL,
7039 0x34867077L, 0x30476DC0L, 0x3D044B19L, 0x39C556AEL,
7040 0x278206ABL, 0x23431B1CL, 0x2E003DC5L, 0x2AC12072L,
7041 0x128E9DCFL, 0x164F8078L, 0x1B0CA6A1L, 0x1FCDBB16L,
7042 0x018AEB13L, 0x054BF6A4L, 0x0808D07DL, 0x0CC9CDCAL,
7043 0x7897AB07L, 0x7C56B6B0L, 0x71159069L, 0x75D48DDEL,
7044 0x6B93DDDBL, 0x6F52C06CL, 0x6211E6B5L, 0x66D0FB02L,
7045 0x5E9F46BFL, 0x5A5E5B08L, 0x571D7DD1L, 0x53DC6066L,
7046 0x4D9B3063L, 0x495A2DD4L, 0x44190B0DL, 0x40D816BAL,
7047 0xACA5C697L, 0xA864DB20L, 0xA527FDF9L, 0xA1E6E04EL,
7048 0xBFA1B04BL, 0xBB60ADFCL, 0xB6238B25L, 0xB2E29692L,
7049 0x8AAD2B2FL, 0x8E6C3698L, 0x832F1041L, 0x87EE0DF6L,
7050 0x99A95DF3L, 0x9D684044L, 0x902B669DL, 0x94EA7B2AL,
7051 0xE0B41DE7L, 0xE4750050L, 0xE9362689L, 0xEDF73B3EL,
7052 0xF3B06B3BL, 0xF771768CL, 0xFA325055L, 0xFEF34DE2L,
7053 0xC6BCF05FL, 0xC27DEDE8L, 0xCF3ECB31L, 0xCBFFD686L,
7054 0xD5B88683L, 0xD1799B34L, 0xDC3ABDEDL, 0xD8FBA05AL,
7055 0x690CE0EEL, 0x6DCDFD59L, 0x608EDB80L, 0x644FC637L,
7056 0x7A089632L, 0x7EC98B85L, 0x738AAD5CL, 0x774BB0EBL,
7057 0x4F040D56L, 0x4BC510E1L, 0x46863638L, 0x42472B8FL,
7058 0x5C007B8AL, 0x58C1663DL, 0x558240E4L, 0x51435D53L,
7059 0x251D3B9EL, 0x21DC2629L, 0x2C9F00F0L, 0x285E1D47L,
7060 0x36194D42L, 0x32D850F5L, 0x3F9B762CL, 0x3B5A6B9BL,
7061 0x0315D626L, 0x07D4CB91L, 0x0A97ED48L, 0x0E56F0FFL,
7062 0x1011A0FAL, 0x14D0BD4DL, 0x19939B94L, 0x1D528623L,
7063 0xF12F560EL, 0xF5EE4BB9L, 0xF8AD6D60L, 0xFC6C70D7L,
7064 0xE22B20D2L, 0xE6EA3D65L, 0xEBA91BBCL, 0xEF68060BL,
7065 0xD727BBB6L, 0xD3E6A601L, 0xDEA580D8L, 0xDA649D6FL,
7066 0xC423CD6AL, 0xC0E2D0DDL, 0xCDA1F604L, 0xC960EBB3L,
7067 0xBD3E8D7EL, 0xB9FF90C9L, 0xB4BCB610L, 0xB07DABA7L,
7068 0xAE3AFBA2L, 0xAAFBE615L, 0xA7B8C0CCL, 0xA379DD7BL,
7069 0x9B3660C6L, 0x9FF77D71L, 0x92B45BA8L, 0x9675461FL,
7070 0x8832161AL, 0x8CF30BADL, 0x81B02D74L, 0x857130C3L,
7071 0x5D8A9099L, 0x594B8D2EL, 0x5408ABF7L, 0x50C9B640L,
7072 0x4E8EE645L, 0x4A4FFBF2L, 0x470CDD2BL, 0x43CDC09CL,
7073 0x7B827D21L, 0x7F436096L, 0x7200464FL, 0x76C15BF8L,
7074 0x68860BFDL, 0x6C47164AL, 0x61043093L, 0x65C52D24L,
7075 0x119B4BE9L, 0x155A565EL, 0x18197087L, 0x1CD86D30L,
7076 0x029F3D35L, 0x065E2082L, 0x0B1D065BL, 0x0FDC1BECL,
7077 0x3793A651L, 0x3352BBE6L, 0x3E119D3FL, 0x3AD08088L,
7078 0x2497D08DL, 0x2056CD3AL, 0x2D15EBE3L, 0x29D4F654L,
7079 0xC5A92679L, 0xC1683BCEL, 0xCC2B1D17L, 0xC8EA00A0L,
7080 0xD6AD50A5L, 0xD26C4D12L, 0xDF2F6BCBL, 0xDBEE767CL,
7081 0xE3A1CBC1L, 0xE760D676L, 0xEA23F0AFL, 0xEEE2ED18L,
7082 0xF0A5BD1DL, 0xF464A0AAL, 0xF9278673L, 0xFDE69BC4L,
7083 0x89B8FD09L, 0x8D79E0BEL, 0x803AC667L, 0x84FBDBD0L,
7084 0x9ABC8BD5L, 0x9E7D9662L, 0x933EB0BBL, 0x97FFAD0CL,
7085 0xAFB010B1L, 0xAB710D06L, 0xA6322BDFL, 0xA2F33668L,
7086 0xBCB4666DL, 0xB8757BDAL, 0xB5365D03L, 0xB1F740B4L
7087 };
7088 #endif
7089
7090 static DRFLAC_INLINE drflac_uint32 drflac_crc32_byte(drflac_uint32 crc32, drflac_uint8 data)
7091 {
7092 #ifndef DR_FLAC_NO_CRC
7093 return (crc32 << 8) ^ drflac__crc32_table[(drflac_uint8)((crc32 >> 24) & 0xFF) ^ data];
7094 #else
7095 (void)data;
7096 return crc32;
7097 #endif
7098 }
7099
7100 #if 0
7101 static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint32(drflac_uint32 crc32, drflac_uint32 data)
7102 {
7103 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 24) & 0xFF));
7104 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 16) & 0xFF));
7105 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 8) & 0xFF));
7106 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 0) & 0xFF));
7107 return crc32;
7108 }
7109
7110 static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint64(drflac_uint32 crc32, drflac_uint64 data)
7111 {
7112 crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 32) & 0xFFFFFFFF));
7113 crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 0) & 0xFFFFFFFF));
7114 return crc32;
7115 }
7116 #endif
7117
7118 static DRFLAC_INLINE drflac_uint32 drflac_crc32_buffer(drflac_uint32 crc32, drflac_uint8* pData, drflac_uint32 dataSize)
7119 {
7120 /* This can be optimized. */
7121 drflac_uint32 i;
7122 for (i = 0; i < dataSize; ++i) {
7123 crc32 = drflac_crc32_byte(crc32, pData[i]);
7124 }
7125 return crc32;
7126 }
7127
7128
7129 static DRFLAC_INLINE drflac_bool32 drflac_ogg__is_capture_pattern(drflac_uint8 pattern[4])
7130 {
7131 return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S';
7132 }
7133
7134 static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_header_size(drflac_ogg_page_header* pHeader)
7135 {
7136 return 27 + pHeader->segmentCount;
7137 }
7138
7139 static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_body_size(drflac_ogg_page_header* pHeader)
7140 {
7141 drflac_uint32 pageBodySize = 0;
7142 int i;
7143
7144 for (i = 0; i < pHeader->segmentCount; ++i) {
7145 pageBodySize += pHeader->segmentTable[i];
7146 }
7147
7148 return pageBodySize;
7149 }
7150
7151 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)
7152 {
7153 drflac_uint8 data[23];
7154 drflac_uint32 i;
7155
7156 DRFLAC_ASSERT(*pCRC32 == DRFLAC_OGG_CAPTURE_PATTERN_CRC32);
7157
7158 if (onRead(pUserData, data, 23) != 23) {
7159 return DRFLAC_AT_END;
7160 }
7161 *pBytesRead += 23;
7162
7163 /*
7164 It's not actually used, but set the capture pattern to 'OggS' for completeness. Not doing this will cause static analysers to complain about
7165 us trying to access uninitialized data. We could alternatively just comment out this member of the drflac_ogg_page_header structure, but I
7166 like to have it map to the structure of the underlying data.
7167 */
7168 pHeader->capturePattern[0] = 'O';
7169 pHeader->capturePattern[1] = 'g';
7170 pHeader->capturePattern[2] = 'g';
7171 pHeader->capturePattern[3] = 'S';
7172
7173 pHeader->structureVersion = data[0];
7174 pHeader->headerType = data[1];
7175 DRFLAC_COPY_MEMORY(&pHeader->granulePosition, &data[ 2], 8);
7176 DRFLAC_COPY_MEMORY(&pHeader->serialNumber, &data[10], 4);
7177 DRFLAC_COPY_MEMORY(&pHeader->sequenceNumber, &data[14], 4);
7178 DRFLAC_COPY_MEMORY(&pHeader->checksum, &data[18], 4);
7179 pHeader->segmentCount = data[22];
7180
7181 /* Calculate the CRC. Note that for the calculation the checksum part of the page needs to be set to 0. */
7182 data[18] = 0;
7183 data[19] = 0;
7184 data[20] = 0;
7185 data[21] = 0;
7186
7187 for (i = 0; i < 23; ++i) {
7188 *pCRC32 = drflac_crc32_byte(*pCRC32, data[i]);
7189 }
7190
7191
7192 if (onRead(pUserData, pHeader->segmentTable, pHeader->segmentCount) != pHeader->segmentCount) {
7193 return DRFLAC_AT_END;
7194 }
7195 *pBytesRead += pHeader->segmentCount;
7196
7197 for (i = 0; i < pHeader->segmentCount; ++i) {
7198 *pCRC32 = drflac_crc32_byte(*pCRC32, pHeader->segmentTable[i]);
7199 }
7200
7201 return DRFLAC_SUCCESS;
7202 }
7203
7204 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)
7205 {
7206 drflac_uint8 id[4];
7207
7208 *pBytesRead = 0;
7209
7210 if (onRead(pUserData, id, 4) != 4) {
7211 return DRFLAC_AT_END;
7212 }
7213 *pBytesRead += 4;
7214
7215 /* We need to read byte-by-byte until we find the OggS capture pattern. */
7216 for (;;) {
7217 if (drflac_ogg__is_capture_pattern(id)) {
7218 drflac_result result;
7219
7220 *pCRC32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
7221
7222 result = drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32);
7223 if (result == DRFLAC_SUCCESS) {
7224 return DRFLAC_SUCCESS;
7225 } else {
7226 if (result == DRFLAC_CRC_MISMATCH) {
7227 continue;
7228 } else {
7229 return result;
7230 }
7231 }
7232 } else {
7233 /* The first 4 bytes did not equal the capture pattern. Read the next byte and try again. */
7234 id[0] = id[1];
7235 id[1] = id[2];
7236 id[2] = id[3];
7237 if (onRead(pUserData, &id[3], 1) != 1) {
7238 return DRFLAC_AT_END;
7239 }
7240 *pBytesRead += 1;
7241 }
7242 }
7243 }
7244
7245
7246 /*
7247 The main part of the Ogg encapsulation is the conversion from the physical Ogg bitstream to the native FLAC bitstream. It works
7248 in three general stages: Ogg Physical Bitstream -> Ogg/FLAC Logical Bitstream -> FLAC Native Bitstream. dr_flac is designed
7249 in such a way that the core sections assume everything is delivered in native format. Therefore, for each encapsulation type
7250 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
7251 the physical Ogg bitstream are converted and delivered in native FLAC format.
7252 */
7253 typedef struct
7254 {
7255 drflac_read_proc onRead; /* The original onRead callback from drflac_open() and family. */
7256 drflac_seek_proc onSeek; /* The original onSeek callback from drflac_open() and family. */
7257 drflac_tell_proc onTell; /* The original onTell callback from drflac_open() and family. */
7258 void* pUserData; /* The user data passed on onRead and onSeek. This is the user data that was passed on drflac_open() and family. */
7259 drflac_uint64 currentBytePos; /* The position of the byte we are sitting on in the physical byte stream. Used for efficient seeking. */
7260 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. */
7261 drflac_uint32 serialNumber; /* The serial number of the FLAC audio pages. This is determined by the initial header page that was read during initialization. */
7262 drflac_ogg_page_header bosPageHeader; /* Used for seeking. */
7263 drflac_ogg_page_header currentPageHeader;
7264 drflac_uint32 bytesRemainingInPage;
7265 drflac_uint32 pageDataSize;
7266 drflac_uint8 pageData[DRFLAC_OGG_MAX_PAGE_SIZE];
7267 } drflac_oggbs; /* oggbs = Ogg Bitstream */
7268
7269 static size_t drflac_oggbs__read_physical(drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead)
7270 {
7271 size_t bytesActuallyRead = oggbs->onRead(oggbs->pUserData, bufferOut, bytesToRead);
7272 oggbs->currentBytePos += bytesActuallyRead;
7273
7274 return bytesActuallyRead;
7275 }
7276
7277 static drflac_bool32 drflac_oggbs__seek_physical(drflac_oggbs* oggbs, drflac_uint64 offset, drflac_seek_origin origin)
7278 {
7279 if (origin == DRFLAC_SEEK_SET) {
7280 if (offset <= 0x7FFFFFFF) {
7281 if (!oggbs->onSeek(oggbs->pUserData, (int)offset, DRFLAC_SEEK_SET)) {
7282 return DRFLAC_FALSE;
7283 }
7284 oggbs->currentBytePos = offset;
7285
7286 return DRFLAC_TRUE;
7287 } else {
7288 if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, DRFLAC_SEEK_SET)) {
7289 return DRFLAC_FALSE;
7290 }
7291 oggbs->currentBytePos = offset;
7292
7293 return drflac_oggbs__seek_physical(oggbs, offset - 0x7FFFFFFF, DRFLAC_SEEK_CUR);
7294 }
7295 } else {
7296 while (offset > 0x7FFFFFFF) {
7297 if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, DRFLAC_SEEK_CUR)) {
7298 return DRFLAC_FALSE;
7299 }
7300 oggbs->currentBytePos += 0x7FFFFFFF;
7301 offset -= 0x7FFFFFFF;
7302 }
7303
7304 if (!oggbs->onSeek(oggbs->pUserData, (int)offset, DRFLAC_SEEK_CUR)) { /* <-- Safe cast thanks to the loop above. */
7305 return DRFLAC_FALSE;
7306 }
7307 oggbs->currentBytePos += offset;
7308
7309 return DRFLAC_TRUE;
7310 }
7311 }
7312
7313 static drflac_bool32 drflac_oggbs__goto_next_page(drflac_oggbs* oggbs, drflac_ogg_crc_mismatch_recovery recoveryMethod)
7314 {
7315 drflac_ogg_page_header header;
7316 for (;;) {
7317 drflac_uint32 crc32 = 0;
7318 drflac_uint32 bytesRead;
7319 drflac_uint32 pageBodySize;
7320 #ifndef DR_FLAC_NO_CRC
7321 drflac_uint32 actualCRC32;
7322 #endif
7323
7324 if (drflac_ogg__read_page_header(oggbs->onRead, oggbs->pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
7325 return DRFLAC_FALSE;
7326 }
7327 oggbs->currentBytePos += bytesRead;
7328
7329 pageBodySize = drflac_ogg__get_page_body_size(&header);
7330 if (pageBodySize > DRFLAC_OGG_MAX_PAGE_SIZE) {
7331 continue; /* Invalid page size. Assume it's corrupted and just move to the next page. */
7332 }
7333
7334 if (header.serialNumber != oggbs->serialNumber) {
7335 /* It's not a FLAC page. Skip it. */
7336 if (pageBodySize > 0 && !drflac_oggbs__seek_physical(oggbs, pageBodySize, DRFLAC_SEEK_CUR)) {
7337 return DRFLAC_FALSE;
7338 }
7339 continue;
7340 }
7341
7342
7343 /* 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. */
7344 if (drflac_oggbs__read_physical(oggbs, oggbs->pageData, pageBodySize) != pageBodySize) {
7345 return DRFLAC_FALSE;
7346 }
7347 oggbs->pageDataSize = pageBodySize;
7348
7349 #ifndef DR_FLAC_NO_CRC
7350 actualCRC32 = drflac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize);
7351 if (actualCRC32 != header.checksum) {
7352 if (recoveryMethod == drflac_ogg_recover_on_crc_mismatch) {
7353 continue; /* CRC mismatch. Skip this page. */
7354 } else {
7355 /*
7356 Even though we are failing on a CRC mismatch, we still want our stream to be in a good state. Therefore we
7357 go to the next valid page to ensure we're in a good state, but return false to let the caller know that the
7358 seek did not fully complete.
7359 */
7360 drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch);
7361 return DRFLAC_FALSE;
7362 }
7363 }
7364 #else
7365 (void)recoveryMethod; /* <-- Silence a warning. */
7366 #endif
7367
7368 oggbs->currentPageHeader = header;
7369 oggbs->bytesRemainingInPage = pageBodySize;
7370 return DRFLAC_TRUE;
7371 }
7372 }
7373
7374 /* Function below is unused at the moment, but I might be re-adding it later. */
7375 #if 0
7376 static drflac_uint8 drflac_oggbs__get_current_segment_index(drflac_oggbs* oggbs, drflac_uint8* pBytesRemainingInSeg)
7377 {
7378 drflac_uint32 bytesConsumedInPage = drflac_ogg__get_page_body_size(&oggbs->currentPageHeader) - oggbs->bytesRemainingInPage;
7379 drflac_uint8 iSeg = 0;
7380 drflac_uint32 iByte = 0;
7381 while (iByte < bytesConsumedInPage) {
7382 drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
7383 if (iByte + segmentSize > bytesConsumedInPage) {
7384 break;
7385 } else {
7386 iSeg += 1;
7387 iByte += segmentSize;
7388 }
7389 }
7390
7391 *pBytesRemainingInSeg = oggbs->currentPageHeader.segmentTable[iSeg] - (drflac_uint8)(bytesConsumedInPage - iByte);
7392 return iSeg;
7393 }
7394
7395 static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs)
7396 {
7397 /* 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. */
7398 for (;;) {
7399 drflac_bool32 atEndOfPage = DRFLAC_FALSE;
7400
7401 drflac_uint8 bytesRemainingInSeg;
7402 drflac_uint8 iFirstSeg = drflac_oggbs__get_current_segment_index(oggbs, &bytesRemainingInSeg);
7403
7404 drflac_uint32 bytesToEndOfPacketOrPage = bytesRemainingInSeg;
7405 for (drflac_uint8 iSeg = iFirstSeg; iSeg < oggbs->currentPageHeader.segmentCount; ++iSeg) {
7406 drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
7407 if (segmentSize < 255) {
7408 if (iSeg == oggbs->currentPageHeader.segmentCount-1) {
7409 atEndOfPage = DRFLAC_TRUE;
7410 }
7411
7412 break;
7413 }
7414
7415 bytesToEndOfPacketOrPage += segmentSize;
7416 }
7417
7418 /*
7419 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
7420 want to load the next page and keep searching for the end of the packet.
7421 */
7422 drflac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, DRFLAC_SEEK_CUR);
7423 oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage;
7424
7425 if (atEndOfPage) {
7426 /*
7427 We're potentially at the next packet, but we need to check the next page first to be sure because the packet may
7428 straddle pages.
7429 */
7430 if (!drflac_oggbs__goto_next_page(oggbs)) {
7431 return DRFLAC_FALSE;
7432 }
7433
7434 /* If it's a fresh packet it most likely means we're at the next packet. */
7435 if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
7436 return DRFLAC_TRUE;
7437 }
7438 } else {
7439 /* We're at the next packet. */
7440 return DRFLAC_TRUE;
7441 }
7442 }
7443 }
7444
7445 static drflac_bool32 drflac_oggbs__seek_to_next_frame(drflac_oggbs* oggbs)
7446 {
7447 /* The bitstream should be sitting on the first byte just after the header of the frame. */
7448
7449 /* What we're actually doing here is seeking to the start of the next packet. */
7450 return drflac_oggbs__seek_to_next_packet(oggbs);
7451 }
7452 #endif
7453
7454 static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead)
7455 {
7456 drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
7457 drflac_uint8* pRunningBufferOut = (drflac_uint8*)bufferOut;
7458 size_t bytesRead = 0;
7459
7460 DRFLAC_ASSERT(oggbs != NULL);
7461 DRFLAC_ASSERT(pRunningBufferOut != NULL);
7462
7463 /* Reading is done page-by-page. If we've run out of bytes in the page we need to move to the next one. */
7464 while (bytesRead < bytesToRead) {
7465 size_t bytesRemainingToRead = bytesToRead - bytesRead;
7466
7467 if (oggbs->bytesRemainingInPage >= bytesRemainingToRead) {
7468 DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), bytesRemainingToRead);
7469 bytesRead += bytesRemainingToRead;
7470 oggbs->bytesRemainingInPage -= (drflac_uint32)bytesRemainingToRead;
7471 break;
7472 }
7473
7474 /* If we get here it means some of the requested data is contained in the next pages. */
7475 if (oggbs->bytesRemainingInPage > 0) {
7476 DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage);
7477 bytesRead += oggbs->bytesRemainingInPage;
7478 pRunningBufferOut += oggbs->bytesRemainingInPage;
7479 oggbs->bytesRemainingInPage = 0;
7480 }
7481
7482 DRFLAC_ASSERT(bytesRemainingToRead > 0);
7483 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
7484 break; /* Failed to go to the next page. Might have simply hit the end of the stream. */
7485 }
7486 }
7487
7488 return bytesRead;
7489 }
7490
7491 static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_seek_origin origin)
7492 {
7493 drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
7494 int bytesSeeked = 0;
7495
7496 DRFLAC_ASSERT(oggbs != NULL);
7497 DRFLAC_ASSERT(offset >= 0); /* <-- Never seek backwards. */
7498
7499 /* Seeking is always forward which makes things a lot simpler. */
7500 if (origin == DRFLAC_SEEK_SET) {
7501 if (!drflac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, DRFLAC_SEEK_SET)) {
7502 return DRFLAC_FALSE;
7503 }
7504
7505 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
7506 return DRFLAC_FALSE;
7507 }
7508
7509 return drflac__on_seek_ogg(pUserData, offset, DRFLAC_SEEK_CUR);
7510 } else if (origin == DRFLAC_SEEK_CUR) {
7511 while (bytesSeeked < offset) {
7512 int bytesRemainingToSeek = offset - bytesSeeked;
7513 DRFLAC_ASSERT(bytesRemainingToSeek >= 0);
7514
7515 if (oggbs->bytesRemainingInPage >= (size_t)bytesRemainingToSeek) {
7516 bytesSeeked += bytesRemainingToSeek;
7517 (void)bytesSeeked; /* <-- Silence a dead store warning emitted by Clang Static Analyzer. */
7518 oggbs->bytesRemainingInPage -= bytesRemainingToSeek;
7519 break;
7520 }
7521
7522 /* If we get here it means some of the requested data is contained in the next pages. */
7523 if (oggbs->bytesRemainingInPage > 0) {
7524 bytesSeeked += (int)oggbs->bytesRemainingInPage;
7525 oggbs->bytesRemainingInPage = 0;
7526 }
7527
7528 DRFLAC_ASSERT(bytesRemainingToSeek > 0);
7529 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
7530 /* Failed to go to the next page. We either hit the end of the stream or had a CRC mismatch. */
7531 return DRFLAC_FALSE;
7532 }
7533 }
7534 } else if (origin == DRFLAC_SEEK_END) {
7535 /* Seeking to the end is not supported. */
7536 return DRFLAC_FALSE;
7537 }
7538
7539 return DRFLAC_TRUE;
7540 }
7541
7542 static drflac_bool32 drflac__on_tell_ogg(void* pUserData, drflac_int64* pCursor)
7543 {
7544 /*
7545 Not implemented for Ogg containers because we don't currently track the byte position of the logical bitstream. To support this, we'll need
7546 to track the position in drflac__on_read_ogg and drflac__on_seek_ogg.
7547 */
7548 (void)pUserData;
7549 (void)pCursor;
7550 return DRFLAC_FALSE;
7551 }
7552
7553
7554 static drflac_bool32 drflac_ogg__seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
7555 {
7556 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
7557 drflac_uint64 originalBytePos;
7558 drflac_uint64 runningGranulePosition;
7559 drflac_uint64 runningFrameBytePos;
7560 drflac_uint64 runningPCMFrameCount;
7561
7562 DRFLAC_ASSERT(oggbs != NULL);
7563
7564 originalBytePos = oggbs->currentBytePos; /* For recovery. Points to the OggS identifier. */
7565
7566 /* First seek to the first frame. */
7567 if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes)) {
7568 return DRFLAC_FALSE;
7569 }
7570 oggbs->bytesRemainingInPage = 0;
7571
7572 runningGranulePosition = 0;
7573 for (;;) {
7574 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
7575 drflac_oggbs__seek_physical(oggbs, originalBytePos, DRFLAC_SEEK_SET);
7576 return DRFLAC_FALSE; /* Never did find that sample... */
7577 }
7578
7579 runningFrameBytePos = oggbs->currentBytePos - drflac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize;
7580 if (oggbs->currentPageHeader.granulePosition >= pcmFrameIndex) {
7581 break; /* The sample is somewhere in the previous page. */
7582 }
7583
7584 /*
7585 At this point we know the sample is not in the previous page. It could possibly be in this page. For simplicity we
7586 disregard any pages that do not begin a fresh packet.
7587 */
7588 if ((oggbs->currentPageHeader.headerType & 0x01) == 0) { /* <-- Is it a fresh page? */
7589 if (oggbs->currentPageHeader.segmentTable[0] >= 2) {
7590 drflac_uint8 firstBytesInPage[2];
7591 firstBytesInPage[0] = oggbs->pageData[0];
7592 firstBytesInPage[1] = oggbs->pageData[1];
7593
7594 if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) { /* <-- Does the page begin with a frame's sync code? */
7595 runningGranulePosition = oggbs->currentPageHeader.granulePosition;
7596 }
7597
7598 continue;
7599 }
7600 }
7601 }
7602
7603 /*
7604 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
7605 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
7606 a new frame. This property means that after we've seeked to the page we can immediately start looping over frames until
7607 we find the one containing the target sample.
7608 */
7609 if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, DRFLAC_SEEK_SET)) {
7610 return DRFLAC_FALSE;
7611 }
7612 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
7613 return DRFLAC_FALSE;
7614 }
7615
7616 /*
7617 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
7618 looping over these frames until we find the one containing the sample we're after.
7619 */
7620 runningPCMFrameCount = runningGranulePosition;
7621 for (;;) {
7622 /*
7623 There are two ways to find the sample and seek past irrelevant frames:
7624 1) Use the native FLAC decoder.
7625 2) Use Ogg's framing system.
7626
7627 Both of these options have their own pros and cons. Using the native FLAC decoder is slower because it needs to
7628 do a full decode of the frame. Using Ogg's framing system is faster, but more complicated and involves some code
7629 duplication for the decoding of frame headers.
7630
7631 Another thing to consider is that using the Ogg framing system will perform direct seeking of the physical Ogg
7632 bitstream. This is important to consider because it means we cannot read data from the drflac_bs object using the
7633 standard drflac__*() APIs because that will read in extra data for its own internal caching which in turn breaks
7634 the positioning of the read pointer of the physical Ogg bitstream. Therefore, anything that would normally be read
7635 using the native FLAC decoding APIs, such as drflac__read_next_flac_frame_header(), need to be re-implemented so as to
7636 avoid the use of the drflac_bs object.
7637
7638 Considering these issues, I have decided to use the slower native FLAC decoding method for the following reasons:
7639 1) Seeking is already partially accelerated using Ogg's paging system in the code block above.
7640 2) Seeking in an Ogg encapsulated FLAC stream is probably quite uncommon.
7641 3) Simplicity.
7642 */
7643 drflac_uint64 firstPCMFrameInFLACFrame = 0;
7644 drflac_uint64 lastPCMFrameInFLACFrame = 0;
7645 drflac_uint64 pcmFrameCountInThisFrame;
7646
7647 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
7648 return DRFLAC_FALSE;
7649 }
7650
7651 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
7652
7653 pcmFrameCountInThisFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
7654
7655 /* If we are seeking to the end of the file and we've just hit it, we're done. */
7656 if (pcmFrameIndex == pFlac->totalPCMFrameCount && (runningPCMFrameCount + pcmFrameCountInThisFrame) == pFlac->totalPCMFrameCount) {
7657 drflac_result result = drflac__decode_flac_frame(pFlac);
7658 if (result == DRFLAC_SUCCESS) {
7659 pFlac->currentPCMFrame = pcmFrameIndex;
7660 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
7661 return DRFLAC_TRUE;
7662 } else {
7663 return DRFLAC_FALSE;
7664 }
7665 }
7666
7667 if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFrame)) {
7668 /*
7669 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
7670 it never existed and keep iterating.
7671 */
7672 drflac_result result = drflac__decode_flac_frame(pFlac);
7673 if (result == DRFLAC_SUCCESS) {
7674 /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
7675 drflac_uint64 pcmFramesToDecode = (size_t)(pcmFrameIndex - runningPCMFrameCount); /* <-- Safe cast because the maximum number of samples in a frame is 65535. */
7676 if (pcmFramesToDecode == 0) {
7677 return DRFLAC_TRUE;
7678 }
7679
7680 pFlac->currentPCMFrame = runningPCMFrameCount;
7681
7682 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */
7683 } else {
7684 if (result == DRFLAC_CRC_MISMATCH) {
7685 continue; /* CRC mismatch. Pretend this frame never existed. */
7686 } else {
7687 return DRFLAC_FALSE;
7688 }
7689 }
7690 } else {
7691 /*
7692 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
7693 frame never existed and leave the running sample count untouched.
7694 */
7695 drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
7696 if (result == DRFLAC_SUCCESS) {
7697 runningPCMFrameCount += pcmFrameCountInThisFrame;
7698 } else {
7699 if (result == DRFLAC_CRC_MISMATCH) {
7700 continue; /* CRC mismatch. Pretend this frame never existed. */
7701 } else {
7702 return DRFLAC_FALSE;
7703 }
7704 }
7705 }
7706 }
7707 }
7708
7709
7710
7711 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)
7712 {
7713 drflac_ogg_page_header header;
7714 drflac_uint32 crc32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
7715 drflac_uint32 bytesRead = 0;
7716
7717 /* Pre Condition: The bit stream should be sitting just past the 4-byte OggS capture pattern. */
7718 (void)relaxed;
7719
7720 pInit->container = drflac_container_ogg;
7721 pInit->oggFirstBytePos = 0;
7722
7723 /*
7724 We'll get here if the first 4 bytes of the stream were the OggS capture pattern, however it doesn't necessarily mean the
7725 stream includes FLAC encoded audio. To check for this we need to scan the beginning-of-stream page markers and check if
7726 any match the FLAC specification. Important to keep in mind that the stream may be multiplexed.
7727 */
7728 if (drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
7729 return DRFLAC_FALSE;
7730 }
7731 pInit->runningFilePos += bytesRead;
7732
7733 for (;;) {
7734 int pageBodySize;
7735
7736 /* Break if we're past the beginning of stream page. */
7737 if ((header.headerType & 0x02) == 0) {
7738 return DRFLAC_FALSE;
7739 }
7740
7741 /* Check if it's a FLAC header. */
7742 pageBodySize = drflac_ogg__get_page_body_size(&header);
7743 if (pageBodySize == 51) { /* 51 = the lacing value of the FLAC header packet. */
7744 /* It could be a FLAC page... */
7745 drflac_uint32 bytesRemainingInPage = pageBodySize;
7746 drflac_uint8 packetType;
7747
7748 if (onRead(pUserData, &packetType, 1) != 1) {
7749 return DRFLAC_FALSE;
7750 }
7751
7752 bytesRemainingInPage -= 1;
7753 if (packetType == 0x7F) {
7754 /* Increasingly more likely to be a FLAC page... */
7755 drflac_uint8 sig[4];
7756 if (onRead(pUserData, sig, 4) != 4) {
7757 return DRFLAC_FALSE;
7758 }
7759
7760 bytesRemainingInPage -= 4;
7761 if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') {
7762 /* Almost certainly a FLAC page... */
7763 drflac_uint8 mappingVersion[2];
7764 if (onRead(pUserData, mappingVersion, 2) != 2) {
7765 return DRFLAC_FALSE;
7766 }
7767
7768 if (mappingVersion[0] != 1) {
7769 return DRFLAC_FALSE; /* Only supporting version 1.x of the Ogg mapping. */
7770 }
7771
7772 /*
7773 The next 2 bytes are the non-audio packets, not including this one. We don't care about this because we're going to
7774 be handling it in a generic way based on the serial number and packet types.
7775 */
7776 if (!onSeek(pUserData, 2, DRFLAC_SEEK_CUR)) {
7777 return DRFLAC_FALSE;
7778 }
7779
7780 /* Expecting the native FLAC signature "fLaC". */
7781 if (onRead(pUserData, sig, 4) != 4) {
7782 return DRFLAC_FALSE;
7783 }
7784
7785 if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C') {
7786 /* The remaining data in the page should be the STREAMINFO block. */
7787 drflac_streaminfo streaminfo;
7788 drflac_uint8 isLastBlock;
7789 drflac_uint8 blockType;
7790 drflac_uint32 blockSize;
7791 if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
7792 return DRFLAC_FALSE;
7793 }
7794
7795 if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
7796 return DRFLAC_FALSE; /* Invalid block type. First block must be the STREAMINFO block. */
7797 }
7798
7799 if (drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
7800 /* Success! */
7801 pInit->hasStreamInfoBlock = DRFLAC_TRUE;
7802 pInit->sampleRate = streaminfo.sampleRate;
7803 pInit->channels = streaminfo.channels;
7804 pInit->bitsPerSample = streaminfo.bitsPerSample;
7805 pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
7806 pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames;
7807 pInit->hasMetadataBlocks = !isLastBlock;
7808
7809 if (onMeta) {
7810 drflac_metadata metadata;
7811 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
7812 metadata.pRawData = NULL;
7813 metadata.rawDataSize = 0;
7814 metadata.data.streaminfo = streaminfo;
7815 onMeta(pUserDataMD, &metadata);
7816 }
7817
7818 pInit->runningFilePos += pageBodySize;
7819 pInit->oggFirstBytePos = pInit->runningFilePos - 79; /* Subtracting 79 will place us right on top of the "OggS" identifier of the FLAC bos page. */
7820 pInit->oggSerial = header.serialNumber;
7821 pInit->oggBosHeader = header;
7822 break;
7823 } else {
7824 /* Failed to read STREAMINFO block. Aww, so close... */
7825 return DRFLAC_FALSE;
7826 }
7827 } else {
7828 /* Invalid file. */
7829 return DRFLAC_FALSE;
7830 }
7831 } else {
7832 /* Not a FLAC header. Skip it. */
7833 if (!onSeek(pUserData, bytesRemainingInPage, DRFLAC_SEEK_CUR)) {
7834 return DRFLAC_FALSE;
7835 }
7836 }
7837 } else {
7838 /* Not a FLAC header. Seek past the entire page and move on to the next. */
7839 if (!onSeek(pUserData, bytesRemainingInPage, DRFLAC_SEEK_CUR)) {
7840 return DRFLAC_FALSE;
7841 }
7842 }
7843 } else {
7844 if (!onSeek(pUserData, pageBodySize, DRFLAC_SEEK_CUR)) {
7845 return DRFLAC_FALSE;
7846 }
7847 }
7848
7849 pInit->runningFilePos += pageBodySize;
7850
7851
7852 /* Read the header of the next page. */
7853 if (drflac_ogg__read_page_header(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
7854 return DRFLAC_FALSE;
7855 }
7856 pInit->runningFilePos += bytesRead;
7857 }
7858
7859 /*
7860 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
7861 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
7862 Ogg bistream object.
7863 */
7864 pInit->hasMetadataBlocks = DRFLAC_TRUE; /* <-- Always have at least VORBIS_COMMENT metadata block. */
7865 return DRFLAC_TRUE;
7866 }
7867 #endif
7868
7869 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)
7870 {
7871 drflac_bool32 relaxed;
7872 drflac_uint8 id[4];
7873
7874 if (pInit == NULL || onRead == NULL || onSeek == NULL) { /* <-- onTell is optional. */
7875 return DRFLAC_FALSE;
7876 }
7877
7878 DRFLAC_ZERO_MEMORY(pInit, sizeof(*pInit));
7879 pInit->onRead = onRead;
7880 pInit->onSeek = onSeek;
7881 pInit->onTell = onTell;
7882 pInit->onMeta = onMeta;
7883 pInit->container = container;
7884 pInit->pUserData = pUserData;
7885 pInit->pUserDataMD = pUserDataMD;
7886
7887 pInit->bs.onRead = onRead;
7888 pInit->bs.onSeek = onSeek;
7889 pInit->bs.onTell = onTell;
7890 pInit->bs.pUserData = pUserData;
7891 drflac__reset_cache(&pInit->bs);
7892
7893
7894 /* If the container is explicitly defined then we can try opening in relaxed mode. */
7895 relaxed = container != drflac_container_unknown;
7896
7897 /* Skip over any ID3 tags. */
7898 for (;;) {
7899 if (onRead(pUserData, id, 4) != 4) {
7900 return DRFLAC_FALSE; /* Ran out of data. */
7901 }
7902 pInit->runningFilePos += 4;
7903
7904 if (id[0] == 'I' && id[1] == 'D' && id[2] == '3') {
7905 drflac_uint8 header[6];
7906 drflac_uint8 flags;
7907 drflac_uint32 headerSize;
7908
7909 if (onRead(pUserData, header, 6) != 6) {
7910 return DRFLAC_FALSE; /* Ran out of data. */
7911 }
7912 pInit->runningFilePos += 6;
7913
7914 flags = header[1];
7915
7916 DRFLAC_COPY_MEMORY(&headerSize, header+2, 4);
7917 headerSize = drflac__unsynchsafe_32(drflac__be2host_32(headerSize));
7918 if (flags & 0x10) {
7919 headerSize += 10;
7920 }
7921
7922 if (!onSeek(pUserData, headerSize, DRFLAC_SEEK_CUR)) {
7923 return DRFLAC_FALSE; /* Failed to seek past the tag. */
7924 }
7925 pInit->runningFilePos += headerSize;
7926 } else {
7927 break;
7928 }
7929 }
7930
7931 if (id[0] == 'f' && id[1] == 'L' && id[2] == 'a' && id[3] == 'C') {
7932 return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
7933 }
7934 #ifndef DR_FLAC_NO_OGG
7935 if (id[0] == 'O' && id[1] == 'g' && id[2] == 'g' && id[3] == 'S') {
7936 return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
7937 }
7938 #endif
7939
7940 /* If we get here it means we likely don't have a header. Try opening in relaxed mode, if applicable. */
7941 if (relaxed) {
7942 if (container == drflac_container_native) {
7943 return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
7944 }
7945 #ifndef DR_FLAC_NO_OGG
7946 if (container == drflac_container_ogg) {
7947 return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
7948 }
7949 #endif
7950 }
7951
7952 /* Unsupported container. */
7953 return DRFLAC_FALSE;
7954 }
7955
7956 static void drflac__init_from_info(drflac* pFlac, const drflac_init_info* pInit)
7957 {
7958 DRFLAC_ASSERT(pFlac != NULL);
7959 DRFLAC_ASSERT(pInit != NULL);
7960
7961 DRFLAC_ZERO_MEMORY(pFlac, sizeof(*pFlac));
7962 pFlac->bs = pInit->bs;
7963 pFlac->onMeta = pInit->onMeta;
7964 pFlac->pUserDataMD = pInit->pUserDataMD;
7965 pFlac->maxBlockSizeInPCMFrames = pInit->maxBlockSizeInPCMFrames;
7966 pFlac->sampleRate = pInit->sampleRate;
7967 pFlac->channels = (drflac_uint8)pInit->channels;
7968 pFlac->bitsPerSample = (drflac_uint8)pInit->bitsPerSample;
7969 pFlac->totalPCMFrameCount = pInit->totalPCMFrameCount;
7970 pFlac->container = pInit->container;
7971 }
7972
7973
7974 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)
7975 {
7976 drflac_init_info init;
7977 drflac_uint32 allocationSize;
7978 drflac_uint32 wholeSIMDVectorCountPerChannel;
7979 drflac_uint32 decodedSamplesAllocationSize;
7980 #ifndef DR_FLAC_NO_OGG
7981 drflac_oggbs* pOggbs = NULL;
7982 #endif
7983 drflac_uint64 firstFramePos;
7984 drflac_uint64 seektablePos;
7985 drflac_uint32 seekpointCount;
7986 drflac_allocation_callbacks allocationCallbacks;
7987 drflac* pFlac;
7988
7989 /* CPU support first. */
7990 drflac__init_cpu_caps();
7991
7992 if (!drflac__init_private(&init, onRead, onSeek, onTell, onMeta, container, pUserData, pUserDataMD)) {
7993 return NULL;
7994 }
7995
7996 if (pAllocationCallbacks != NULL) {
7997 allocationCallbacks = *pAllocationCallbacks;
7998 if (allocationCallbacks.onFree == NULL || (allocationCallbacks.onMalloc == NULL && allocationCallbacks.onRealloc == NULL)) {
7999 return NULL; /* Invalid allocation callbacks. */
8000 }
8001 } else {
8002 allocationCallbacks.pUserData = NULL;
8003 allocationCallbacks.onMalloc = drflac__malloc_default;
8004 allocationCallbacks.onRealloc = drflac__realloc_default;
8005 allocationCallbacks.onFree = drflac__free_default;
8006 }
8007
8008
8009 /*
8010 The size of the allocation for the drflac object needs to be large enough to fit the following:
8011 1) The main members of the drflac structure
8012 2) A block of memory large enough to store the decoded samples of the largest frame in the stream
8013 3) If the container is Ogg, a drflac_oggbs object
8014
8015 The complicated part of the allocation is making sure there's enough room the decoded samples, taking into consideration
8016 the different SIMD instruction sets.
8017 */
8018 allocationSize = sizeof(drflac);
8019
8020 /*
8021 The allocation size for decoded frames depends on the number of 32-bit integers that fit inside the largest SIMD vector
8022 we are supporting.
8023 */
8024 if ((init.maxBlockSizeInPCMFrames % (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) == 0) {
8025 wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32)));
8026 } else {
8027 wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) + 1;
8028 }
8029
8030 decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * DRFLAC_MAX_SIMD_VECTOR_SIZE * init.channels;
8031
8032 allocationSize += decodedSamplesAllocationSize;
8033 allocationSize += DRFLAC_MAX_SIMD_VECTOR_SIZE; /* Allocate extra bytes to ensure we have enough for alignment. */
8034
8035 #ifndef DR_FLAC_NO_OGG
8036 /* There's additional data required for Ogg streams. */
8037 if (init.container == drflac_container_ogg) {
8038 allocationSize += sizeof(drflac_oggbs);
8039
8040 pOggbs = (drflac_oggbs*)drflac__malloc_from_callbacks(sizeof(*pOggbs), &allocationCallbacks);
8041 if (pOggbs == NULL) {
8042 return NULL; /*DRFLAC_OUT_OF_MEMORY;*/
8043 }
8044
8045 DRFLAC_ZERO_MEMORY(pOggbs, sizeof(*pOggbs));
8046 pOggbs->onRead = onRead;
8047 pOggbs->onSeek = onSeek;
8048 pOggbs->onTell = onTell;
8049 pOggbs->pUserData = pUserData;
8050 pOggbs->currentBytePos = init.oggFirstBytePos;
8051 pOggbs->firstBytePos = init.oggFirstBytePos;
8052 pOggbs->serialNumber = init.oggSerial;
8053 pOggbs->bosPageHeader = init.oggBosHeader;
8054 pOggbs->bytesRemainingInPage = 0;
8055 }
8056 #endif
8057
8058 /*
8059 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
8060 consist of only a single heap allocation. To this, the size of the seek table needs to be known, which we determine when reading
8061 and decoding the metadata.
8062 */
8063 firstFramePos = 42; /* <-- We know we are at byte 42 at this point. */
8064 seektablePos = 0;
8065 seekpointCount = 0;
8066 if (init.hasMetadataBlocks) {
8067 drflac_read_proc onReadOverride = onRead;
8068 drflac_seek_proc onSeekOverride = onSeek;
8069 drflac_tell_proc onTellOverride = onTell;
8070 void* pUserDataOverride = pUserData;
8071
8072 #ifndef DR_FLAC_NO_OGG
8073 if (init.container == drflac_container_ogg) {
8074 onReadOverride = drflac__on_read_ogg;
8075 onSeekOverride = drflac__on_seek_ogg;
8076 onTellOverride = drflac__on_tell_ogg;
8077 pUserDataOverride = (void*)pOggbs;
8078 }
8079 #endif
8080
8081 if (!drflac__read_and_decode_metadata(onReadOverride, onSeekOverride, onTellOverride, onMeta, pUserDataOverride, pUserDataMD, &firstFramePos, &seektablePos, &seekpointCount, &allocationCallbacks)) {
8082 #ifndef DR_FLAC_NO_OGG
8083 drflac__free_from_callbacks(pOggbs, &allocationCallbacks);
8084 #endif
8085 return NULL;
8086 }
8087
8088 allocationSize += seekpointCount * sizeof(drflac_seekpoint);
8089 }
8090
8091
8092 pFlac = (drflac*)drflac__malloc_from_callbacks(allocationSize, &allocationCallbacks);
8093 if (pFlac == NULL) {
8094 #ifndef DR_FLAC_NO_OGG
8095 drflac__free_from_callbacks(pOggbs, &allocationCallbacks);
8096 #endif
8097 return NULL;
8098 }
8099
8100 drflac__init_from_info(pFlac, &init);
8101 pFlac->allocationCallbacks = allocationCallbacks;
8102 pFlac->pDecodedSamples = (drflac_int32*)drflac_align((size_t)pFlac->pExtraData, DRFLAC_MAX_SIMD_VECTOR_SIZE);
8103
8104 #ifndef DR_FLAC_NO_OGG
8105 if (init.container == drflac_container_ogg) {
8106 drflac_oggbs* pInternalOggbs = (drflac_oggbs*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize + (seekpointCount * sizeof(drflac_seekpoint)));
8107 DRFLAC_COPY_MEMORY(pInternalOggbs, pOggbs, sizeof(*pOggbs));
8108
8109 /* At this point the pOggbs object has been handed over to pInternalOggbs and can be freed. */
8110 drflac__free_from_callbacks(pOggbs, &allocationCallbacks);
8111 pOggbs = NULL;
8112
8113 /* The Ogg bistream needs to be layered on top of the original bitstream. */
8114 pFlac->bs.onRead = drflac__on_read_ogg;
8115 pFlac->bs.onSeek = drflac__on_seek_ogg;
8116 pFlac->bs.onTell = drflac__on_tell_ogg;
8117 pFlac->bs.pUserData = (void*)pInternalOggbs;
8118 pFlac->_oggbs = (void*)pInternalOggbs;
8119 }
8120 #endif
8121
8122 pFlac->firstFLACFramePosInBytes = firstFramePos;
8123
8124 /* 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. */
8125 #ifndef DR_FLAC_NO_OGG
8126 if (init.container == drflac_container_ogg)
8127 {
8128 pFlac->pSeekpoints = NULL;
8129 pFlac->seekpointCount = 0;
8130 }
8131 else
8132 #endif
8133 {
8134 /* If we have a seektable we need to load it now, making sure we move back to where we were previously. */
8135 if (seektablePos != 0) {
8136 pFlac->seekpointCount = seekpointCount;
8137 pFlac->pSeekpoints = (drflac_seekpoint*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize);
8138
8139 DRFLAC_ASSERT(pFlac->bs.onSeek != NULL);
8140 DRFLAC_ASSERT(pFlac->bs.onRead != NULL);
8141
8142 /* Seek to the seektable, then just read directly into our seektable buffer. */
8143 if (pFlac->bs.onSeek(pFlac->bs.pUserData, (int)seektablePos, DRFLAC_SEEK_SET)) {
8144 drflac_uint32 iSeekpoint;
8145
8146 for (iSeekpoint = 0; iSeekpoint < seekpointCount; iSeekpoint += 1) {
8147 if (pFlac->bs.onRead(pFlac->bs.pUserData, pFlac->pSeekpoints + iSeekpoint, DRFLAC_SEEKPOINT_SIZE_IN_BYTES) == DRFLAC_SEEKPOINT_SIZE_IN_BYTES) {
8148 /* Endian swap. */
8149 pFlac->pSeekpoints[iSeekpoint].firstPCMFrame = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].firstPCMFrame);
8150 pFlac->pSeekpoints[iSeekpoint].flacFrameOffset = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].flacFrameOffset);
8151 pFlac->pSeekpoints[iSeekpoint].pcmFrameCount = drflac__be2host_16(pFlac->pSeekpoints[iSeekpoint].pcmFrameCount);
8152 } else {
8153 /* Failed to read the seektable. Pretend we don't have one. */
8154 pFlac->pSeekpoints = NULL;
8155 pFlac->seekpointCount = 0;
8156 break;
8157 }
8158 }
8159
8160 /* We need to seek back to where we were. If this fails it's a critical error. */
8161 if (!pFlac->bs.onSeek(pFlac->bs.pUserData, (int)pFlac->firstFLACFramePosInBytes, DRFLAC_SEEK_SET)) {
8162 drflac__free_from_callbacks(pFlac, &allocationCallbacks);
8163 return NULL;
8164 }
8165 } else {
8166 /* Failed to seek to the seektable. Ominous sign, but for now we can just pretend we don't have one. */
8167 pFlac->pSeekpoints = NULL;
8168 pFlac->seekpointCount = 0;
8169 }
8170 }
8171 }
8172
8173
8174 /*
8175 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
8176 the first frame.
8177 */
8178 if (!init.hasStreamInfoBlock) {
8179 pFlac->currentFLACFrame.header = init.firstFrameHeader;
8180 for (;;) {
8181 drflac_result result = drflac__decode_flac_frame(pFlac);
8182 if (result == DRFLAC_SUCCESS) {
8183 break;
8184 } else {
8185 if (result == DRFLAC_CRC_MISMATCH) {
8186 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
8187 drflac__free_from_callbacks(pFlac, &allocationCallbacks);
8188 return NULL;
8189 }
8190 continue;
8191 } else {
8192 drflac__free_from_callbacks(pFlac, &allocationCallbacks);
8193 return NULL;
8194 }
8195 }
8196 }
8197 }
8198
8199 return pFlac;
8200 }
8201
8202
8203
8204 #ifndef DR_FLAC_NO_STDIO
8205 #include <stdio.h>
8206 #ifndef DR_FLAC_NO_WCHAR
8207 #include <wchar.h> /* For wcslen(), wcsrtombs() */
8208 #endif
8209
8210 /* Errno */
8211 /* 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. */
8212 #include <errno.h>
8213 static drflac_result drflac_result_from_errno(int e)
8214 {
8215 switch (e)
8216 {
8217 case 0: return DRFLAC_SUCCESS;
8218 #ifdef EPERM
8219 case EPERM: return DRFLAC_INVALID_OPERATION;
8220 #endif
8221 #ifdef ENOENT
8222 case ENOENT: return DRFLAC_DOES_NOT_EXIST;
8223 #endif
8224 #ifdef ESRCH
8225 case ESRCH: return DRFLAC_DOES_NOT_EXIST;
8226 #endif
8227 #ifdef EINTR
8228 case EINTR: return DRFLAC_INTERRUPT;
8229 #endif
8230 #ifdef EIO
8231 case EIO: return DRFLAC_IO_ERROR;
8232 #endif
8233 #ifdef ENXIO
8234 case ENXIO: return DRFLAC_DOES_NOT_EXIST;
8235 #endif
8236 #ifdef E2BIG
8237 case E2BIG: return DRFLAC_INVALID_ARGS;
8238 #endif
8239 #ifdef ENOEXEC
8240 case ENOEXEC: return DRFLAC_INVALID_FILE;
8241 #endif
8242 #ifdef EBADF
8243 case EBADF: return DRFLAC_INVALID_FILE;
8244 #endif
8245 #ifdef ECHILD
8246 case ECHILD: return DRFLAC_ERROR;
8247 #endif
8248 #ifdef EAGAIN
8249 case EAGAIN: return DRFLAC_UNAVAILABLE;
8250 #endif
8251 #ifdef ENOMEM
8252 case ENOMEM: return DRFLAC_OUT_OF_MEMORY;
8253 #endif
8254 #ifdef EACCES
8255 case EACCES: return DRFLAC_ACCESS_DENIED;
8256 #endif
8257 #ifdef EFAULT
8258 case EFAULT: return DRFLAC_BAD_ADDRESS;
8259 #endif
8260 #ifdef ENOTBLK
8261 case ENOTBLK: return DRFLAC_ERROR;
8262 #endif
8263 #ifdef EBUSY
8264 case EBUSY: return DRFLAC_BUSY;
8265 #endif
8266 #ifdef EEXIST
8267 case EEXIST: return DRFLAC_ALREADY_EXISTS;
8268 #endif
8269 #ifdef EXDEV
8270 case EXDEV: return DRFLAC_ERROR;
8271 #endif
8272 #ifdef ENODEV
8273 case ENODEV: return DRFLAC_DOES_NOT_EXIST;
8274 #endif
8275 #ifdef ENOTDIR
8276 case ENOTDIR: return DRFLAC_NOT_DIRECTORY;
8277 #endif
8278 #ifdef EISDIR
8279 case EISDIR: return DRFLAC_IS_DIRECTORY;
8280 #endif
8281 #ifdef EINVAL
8282 case EINVAL: return DRFLAC_INVALID_ARGS;
8283 #endif
8284 #ifdef ENFILE
8285 case ENFILE: return DRFLAC_TOO_MANY_OPEN_FILES;
8286 #endif
8287 #ifdef EMFILE
8288 case EMFILE: return DRFLAC_TOO_MANY_OPEN_FILES;
8289 #endif
8290 #ifdef ENOTTY
8291 case ENOTTY: return DRFLAC_INVALID_OPERATION;
8292 #endif
8293 #ifdef ETXTBSY
8294 case ETXTBSY: return DRFLAC_BUSY;
8295 #endif
8296 #ifdef EFBIG
8297 case EFBIG: return DRFLAC_TOO_BIG;
8298 #endif
8299 #ifdef ENOSPC
8300 case ENOSPC: return DRFLAC_NO_SPACE;
8301 #endif
8302 #ifdef ESPIPE
8303 case ESPIPE: return DRFLAC_BAD_SEEK;
8304 #endif
8305 #ifdef EROFS
8306 case EROFS: return DRFLAC_ACCESS_DENIED;
8307 #endif
8308 #ifdef EMLINK
8309 case EMLINK: return DRFLAC_TOO_MANY_LINKS;
8310 #endif
8311 #ifdef EPIPE
8312 case EPIPE: return DRFLAC_BAD_PIPE;
8313 #endif
8314 #ifdef EDOM
8315 case EDOM: return DRFLAC_OUT_OF_RANGE;
8316 #endif
8317 #ifdef ERANGE
8318 case ERANGE: return DRFLAC_OUT_OF_RANGE;
8319 #endif
8320 #ifdef EDEADLK
8321 case EDEADLK: return DRFLAC_DEADLOCK;
8322 #endif
8323 #ifdef ENAMETOOLONG
8324 case ENAMETOOLONG: return DRFLAC_PATH_TOO_LONG;
8325 #endif
8326 #ifdef ENOLCK
8327 case ENOLCK: return DRFLAC_ERROR;
8328 #endif
8329 #ifdef ENOSYS
8330 case ENOSYS: return DRFLAC_NOT_IMPLEMENTED;
8331 #endif
8332 #if defined(ENOTEMPTY) && ENOTEMPTY != EEXIST /* In AIX, ENOTEMPTY and EEXIST use the same value. */
8333 case ENOTEMPTY: return DRFLAC_DIRECTORY_NOT_EMPTY;
8334 #endif
8335 #ifdef ELOOP
8336 case ELOOP: return DRFLAC_TOO_MANY_LINKS;
8337 #endif
8338 #ifdef ENOMSG
8339 case ENOMSG: return DRFLAC_NO_MESSAGE;
8340 #endif
8341 #ifdef EIDRM
8342 case EIDRM: return DRFLAC_ERROR;
8343 #endif
8344 #ifdef ECHRNG
8345 case ECHRNG: return DRFLAC_ERROR;
8346 #endif
8347 #ifdef EL2NSYNC
8348 case EL2NSYNC: return DRFLAC_ERROR;
8349 #endif
8350 #ifdef EL3HLT
8351 case EL3HLT: return DRFLAC_ERROR;
8352 #endif
8353 #ifdef EL3RST
8354 case EL3RST: return DRFLAC_ERROR;
8355 #endif
8356 #ifdef ELNRNG
8357 case ELNRNG: return DRFLAC_OUT_OF_RANGE;
8358 #endif
8359 #ifdef EUNATCH
8360 case EUNATCH: return DRFLAC_ERROR;
8361 #endif
8362 #ifdef ENOCSI
8363 case ENOCSI: return DRFLAC_ERROR;
8364 #endif
8365 #ifdef EL2HLT
8366 case EL2HLT: return DRFLAC_ERROR;
8367 #endif
8368 #ifdef EBADE
8369 case EBADE: return DRFLAC_ERROR;
8370 #endif
8371 #ifdef EBADR
8372 case EBADR: return DRFLAC_ERROR;
8373 #endif
8374 #ifdef EXFULL
8375 case EXFULL: return DRFLAC_ERROR;
8376 #endif
8377 #ifdef ENOANO
8378 case ENOANO: return DRFLAC_ERROR;
8379 #endif
8380 #ifdef EBADRQC
8381 case EBADRQC: return DRFLAC_ERROR;
8382 #endif
8383 #ifdef EBADSLT
8384 case EBADSLT: return DRFLAC_ERROR;
8385 #endif
8386 #ifdef EBFONT
8387 case EBFONT: return DRFLAC_INVALID_FILE;
8388 #endif
8389 #ifdef ENOSTR
8390 case ENOSTR: return DRFLAC_ERROR;
8391 #endif
8392 #ifdef ENODATA
8393 case ENODATA: return DRFLAC_NO_DATA_AVAILABLE;
8394 #endif
8395 #ifdef ETIME
8396 case ETIME: return DRFLAC_TIMEOUT;
8397 #endif
8398 #ifdef ENOSR
8399 case ENOSR: return DRFLAC_NO_DATA_AVAILABLE;
8400 #endif
8401 #ifdef ENONET
8402 case ENONET: return DRFLAC_NO_NETWORK;
8403 #endif
8404 #ifdef ENOPKG
8405 case ENOPKG: return DRFLAC_ERROR;
8406 #endif
8407 #ifdef EREMOTE
8408 case EREMOTE: return DRFLAC_ERROR;
8409 #endif
8410 #ifdef ENOLINK
8411 case ENOLINK: return DRFLAC_ERROR;
8412 #endif
8413 #ifdef EADV
8414 case EADV: return DRFLAC_ERROR;
8415 #endif
8416 #ifdef ESRMNT
8417 case ESRMNT: return DRFLAC_ERROR;
8418 #endif
8419 #ifdef ECOMM
8420 case ECOMM: return DRFLAC_ERROR;
8421 #endif
8422 #ifdef EPROTO
8423 case EPROTO: return DRFLAC_ERROR;
8424 #endif
8425 #ifdef EMULTIHOP
8426 case EMULTIHOP: return DRFLAC_ERROR;
8427 #endif
8428 #ifdef EDOTDOT
8429 case EDOTDOT: return DRFLAC_ERROR;
8430 #endif
8431 #ifdef EBADMSG
8432 case EBADMSG: return DRFLAC_BAD_MESSAGE;
8433 #endif
8434 #ifdef EOVERFLOW
8435 case EOVERFLOW: return DRFLAC_TOO_BIG;
8436 #endif
8437 #ifdef ENOTUNIQ
8438 case ENOTUNIQ: return DRFLAC_NOT_UNIQUE;
8439 #endif
8440 #ifdef EBADFD
8441 case EBADFD: return DRFLAC_ERROR;
8442 #endif
8443 #ifdef EREMCHG
8444 case EREMCHG: return DRFLAC_ERROR;
8445 #endif
8446 #ifdef ELIBACC
8447 case ELIBACC: return DRFLAC_ACCESS_DENIED;
8448 #endif
8449 #ifdef ELIBBAD
8450 case ELIBBAD: return DRFLAC_INVALID_FILE;
8451 #endif
8452 #ifdef ELIBSCN
8453 case ELIBSCN: return DRFLAC_INVALID_FILE;
8454 #endif
8455 #ifdef ELIBMAX
8456 case ELIBMAX: return DRFLAC_ERROR;
8457 #endif
8458 #ifdef ELIBEXEC
8459 case ELIBEXEC: return DRFLAC_ERROR;
8460 #endif
8461 #ifdef EILSEQ
8462 case EILSEQ: return DRFLAC_INVALID_DATA;
8463 #endif
8464 #ifdef ERESTART
8465 case ERESTART: return DRFLAC_ERROR;
8466 #endif
8467 #ifdef ESTRPIPE
8468 case ESTRPIPE: return DRFLAC_ERROR;
8469 #endif
8470 #ifdef EUSERS
8471 case EUSERS: return DRFLAC_ERROR;
8472 #endif
8473 #ifdef ENOTSOCK
8474 case ENOTSOCK: return DRFLAC_NOT_SOCKET;
8475 #endif
8476 #ifdef EDESTADDRREQ
8477 case EDESTADDRREQ: return DRFLAC_NO_ADDRESS;
8478 #endif
8479 #ifdef EMSGSIZE
8480 case EMSGSIZE: return DRFLAC_TOO_BIG;
8481 #endif
8482 #ifdef EPROTOTYPE
8483 case EPROTOTYPE: return DRFLAC_BAD_PROTOCOL;
8484 #endif
8485 #ifdef ENOPROTOOPT
8486 case ENOPROTOOPT: return DRFLAC_PROTOCOL_UNAVAILABLE;
8487 #endif
8488 #ifdef EPROTONOSUPPORT
8489 case EPROTONOSUPPORT: return DRFLAC_PROTOCOL_NOT_SUPPORTED;
8490 #endif
8491 #ifdef ESOCKTNOSUPPORT
8492 case ESOCKTNOSUPPORT: return DRFLAC_SOCKET_NOT_SUPPORTED;
8493 #endif
8494 #ifdef EOPNOTSUPP
8495 case EOPNOTSUPP: return DRFLAC_INVALID_OPERATION;
8496 #endif
8497 #ifdef EPFNOSUPPORT
8498 case EPFNOSUPPORT: return DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED;
8499 #endif
8500 #ifdef EAFNOSUPPORT
8501 case EAFNOSUPPORT: return DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED;
8502 #endif
8503 #ifdef EADDRINUSE
8504 case EADDRINUSE: return DRFLAC_ALREADY_IN_USE;
8505 #endif
8506 #ifdef EADDRNOTAVAIL
8507 case EADDRNOTAVAIL: return DRFLAC_ERROR;
8508 #endif
8509 #ifdef ENETDOWN
8510 case ENETDOWN: return DRFLAC_NO_NETWORK;
8511 #endif
8512 #ifdef ENETUNREACH
8513 case ENETUNREACH: return DRFLAC_NO_NETWORK;
8514 #endif
8515 #ifdef ENETRESET
8516 case ENETRESET: return DRFLAC_NO_NETWORK;
8517 #endif
8518 #ifdef ECONNABORTED
8519 case ECONNABORTED: return DRFLAC_NO_NETWORK;
8520 #endif
8521 #ifdef ECONNRESET
8522 case ECONNRESET: return DRFLAC_CONNECTION_RESET;
8523 #endif
8524 #ifdef ENOBUFS
8525 case ENOBUFS: return DRFLAC_NO_SPACE;
8526 #endif
8527 #ifdef EISCONN
8528 case EISCONN: return DRFLAC_ALREADY_CONNECTED;
8529 #endif
8530 #ifdef ENOTCONN
8531 case ENOTCONN: return DRFLAC_NOT_CONNECTED;
8532 #endif
8533 #ifdef ESHUTDOWN
8534 case ESHUTDOWN: return DRFLAC_ERROR;
8535 #endif
8536 #ifdef ETOOMANYREFS
8537 case ETOOMANYREFS: return DRFLAC_ERROR;
8538 #endif
8539 #ifdef ETIMEDOUT
8540 case ETIMEDOUT: return DRFLAC_TIMEOUT;
8541 #endif
8542 #ifdef ECONNREFUSED
8543 case ECONNREFUSED: return DRFLAC_CONNECTION_REFUSED;
8544 #endif
8545 #ifdef EHOSTDOWN
8546 case EHOSTDOWN: return DRFLAC_NO_HOST;
8547 #endif
8548 #ifdef EHOSTUNREACH
8549 case EHOSTUNREACH: return DRFLAC_NO_HOST;
8550 #endif
8551 #ifdef EALREADY
8552 case EALREADY: return DRFLAC_IN_PROGRESS;
8553 #endif
8554 #ifdef EINPROGRESS
8555 case EINPROGRESS: return DRFLAC_IN_PROGRESS;
8556 #endif
8557 #ifdef ESTALE
8558 case ESTALE: return DRFLAC_INVALID_FILE;
8559 #endif
8560 #ifdef EUCLEAN
8561 case EUCLEAN: return DRFLAC_ERROR;
8562 #endif
8563 #ifdef ENOTNAM
8564 case ENOTNAM: return DRFLAC_ERROR;
8565 #endif
8566 #ifdef ENAVAIL
8567 case ENAVAIL: return DRFLAC_ERROR;
8568 #endif
8569 #ifdef EISNAM
8570 case EISNAM: return DRFLAC_ERROR;
8571 #endif
8572 #ifdef EREMOTEIO
8573 case EREMOTEIO: return DRFLAC_IO_ERROR;
8574 #endif
8575 #ifdef EDQUOT
8576 case EDQUOT: return DRFLAC_NO_SPACE;
8577 #endif
8578 #ifdef ENOMEDIUM
8579 case ENOMEDIUM: return DRFLAC_DOES_NOT_EXIST;
8580 #endif
8581 #ifdef EMEDIUMTYPE
8582 case EMEDIUMTYPE: return DRFLAC_ERROR;
8583 #endif
8584 #ifdef ECANCELED
8585 case ECANCELED: return DRFLAC_CANCELLED;
8586 #endif
8587 #ifdef ENOKEY
8588 case ENOKEY: return DRFLAC_ERROR;
8589 #endif
8590 #ifdef EKEYEXPIRED
8591 case EKEYEXPIRED: return DRFLAC_ERROR;
8592 #endif
8593 #ifdef EKEYREVOKED
8594 case EKEYREVOKED: return DRFLAC_ERROR;
8595 #endif
8596 #ifdef EKEYREJECTED
8597 case EKEYREJECTED: return DRFLAC_ERROR;
8598 #endif
8599 #ifdef EOWNERDEAD
8600 case EOWNERDEAD: return DRFLAC_ERROR;
8601 #endif
8602 #ifdef ENOTRECOVERABLE
8603 case ENOTRECOVERABLE: return DRFLAC_ERROR;
8604 #endif
8605 #ifdef ERFKILL
8606 case ERFKILL: return DRFLAC_ERROR;
8607 #endif
8608 #ifdef EHWPOISON
8609 case EHWPOISON: return DRFLAC_ERROR;
8610 #endif
8611 default: return DRFLAC_ERROR;
8612 }
8613 }
8614 /* End Errno */
8615
8616 /* fopen */
8617 static drflac_result drflac_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
8618 {
8619 #if defined(_MSC_VER) && _MSC_VER >= 1400
8620 errno_t err;
8621 #endif
8622
8623 if (ppFile != NULL) {
8624 *ppFile = NULL; /* Safety. */
8625 }
8626
8627 if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
8628 return DRFLAC_INVALID_ARGS;
8629 }
8630
8631 #if defined(_MSC_VER) && _MSC_VER >= 1400
8632 err = fopen_s(ppFile, pFilePath, pOpenMode);
8633 if (err != 0) {
8634 return drflac_result_from_errno(err);
8635 }
8636 #else
8637 #if defined(_WIN32) || defined(__APPLE__)
8638 *ppFile = fopen(pFilePath, pOpenMode);
8639 #else
8640 #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
8641 *ppFile = fopen64(pFilePath, pOpenMode);
8642 #else
8643 *ppFile = fopen(pFilePath, pOpenMode);
8644 #endif
8645 #endif
8646 if (*ppFile == NULL) {
8647 drflac_result result = drflac_result_from_errno(errno);
8648 if (result == DRFLAC_SUCCESS) {
8649 result = DRFLAC_ERROR; /* Just a safety check to make sure we never ever return success when pFile == NULL. */
8650 }
8651
8652 return result;
8653 }
8654 #endif
8655
8656 return DRFLAC_SUCCESS;
8657 }
8658
8659 /*
8660 _wfopen() isn't always available in all compilation environments.
8661
8662 * Windows only.
8663 * MSVC seems to support it universally as far back as VC6 from what I can tell (haven't checked further back).
8664 * MinGW-64 (both 32- and 64-bit) seems to support it.
8665 * MinGW wraps it in !defined(__STRICT_ANSI__).
8666 * OpenWatcom wraps it in !defined(_NO_EXT_KEYS).
8667
8668 This can be reviewed as compatibility issues arise. The preference is to use _wfopen_s() and _wfopen() as opposed to the wcsrtombs()
8669 fallback, so if you notice your compiler not detecting this properly I'm happy to look at adding support.
8670 */
8671 #if defined(_WIN32)
8672 #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
8673 #define DRFLAC_HAS_WFOPEN
8674 #endif
8675 #endif
8676
8677 #ifndef DR_FLAC_NO_WCHAR
8678 static drflac_result drflac_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const drflac_allocation_callbacks* pAllocationCallbacks)
8679 {
8680 if (ppFile != NULL) {
8681 *ppFile = NULL; /* Safety. */
8682 }
8683
8684 if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
8685 return DRFLAC_INVALID_ARGS;
8686 }
8687
8688 #if defined(DRFLAC_HAS_WFOPEN)
8689 {
8690 /* Use _wfopen() on Windows. */
8691 #if defined(_MSC_VER) && _MSC_VER >= 1400
8692 errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
8693 if (err != 0) {
8694 return drflac_result_from_errno(err);
8695 }
8696 #else
8697 *ppFile = _wfopen(pFilePath, pOpenMode);
8698 if (*ppFile == NULL) {
8699 return drflac_result_from_errno(errno);
8700 }
8701 #endif
8702 (void)pAllocationCallbacks;
8703 }
8704 #else
8705 /*
8706 Use fopen() on anything other than Windows. Requires a conversion. This is annoying because
8707 fopen() is locale specific. The only real way I can think of to do this is with wcsrtombs(). Note
8708 that wcstombs() is apparently not thread-safe because it uses a static global mbstate_t object for
8709 maintaining state. I've checked this with -std=c89 and it works, but if somebody get's a compiler
8710 error I'll look into improving compatibility.
8711 */
8712
8713 /*
8714 Some compilers don't support wchar_t or wcsrtombs() which we're using below. In this case we just
8715 need to abort with an error. If you encounter a compiler lacking such support, add it to this list
8716 and submit a bug report and it'll be added to the library upstream.
8717 */
8718 #if defined(__DJGPP__)
8719 {
8720 /* Nothing to do here. This will fall through to the error check below. */
8721 }
8722 #else
8723 {
8724 mbstate_t mbs;
8725 size_t lenMB;
8726 const wchar_t* pFilePathTemp = pFilePath;
8727 char* pFilePathMB = NULL;
8728 char pOpenModeMB[32] = {0};
8729
8730 /* Get the length first. */
8731 DRFLAC_ZERO_OBJECT(&mbs);
8732 lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
8733 if (lenMB == (size_t)-1) {
8734 return drflac_result_from_errno(errno);
8735 }
8736
8737 pFilePathMB = (char*)drflac__malloc_from_callbacks(lenMB + 1, pAllocationCallbacks);
8738 if (pFilePathMB == NULL) {
8739 return DRFLAC_OUT_OF_MEMORY;
8740 }
8741
8742 pFilePathTemp = pFilePath;
8743 DRFLAC_ZERO_OBJECT(&mbs);
8744 wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
8745
8746 /* The open mode should always consist of ASCII characters so we should be able to do a trivial conversion. */
8747 {
8748 size_t i = 0;
8749 for (;;) {
8750 if (pOpenMode[i] == 0) {
8751 pOpenModeMB[i] = '\0';
8752 break;
8753 }
8754
8755 pOpenModeMB[i] = (char)pOpenMode[i];
8756 i += 1;
8757 }
8758 }
8759
8760 *ppFile = fopen(pFilePathMB, pOpenModeMB);
8761
8762 drflac__free_from_callbacks(pFilePathMB, pAllocationCallbacks);
8763 }
8764 #endif
8765
8766 if (*ppFile == NULL) {
8767 return DRFLAC_ERROR;
8768 }
8769 #endif
8770
8771 return DRFLAC_SUCCESS;
8772 }
8773 #endif
8774 /* End fopen */
8775
8776 static size_t drflac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead)
8777 {
8778 return fread(bufferOut, 1, bytesToRead, (FILE*)pUserData);
8779 }
8780
8781 static drflac_bool32 drflac__on_seek_stdio(void* pUserData, int offset, drflac_seek_origin origin)
8782 {
8783 int whence = SEEK_SET;
8784 if (origin == DRFLAC_SEEK_CUR) {
8785 whence = SEEK_CUR;
8786 } else if (origin == DRFLAC_SEEK_END) {
8787 whence = SEEK_END;
8788 }
8789
8790 return fseek((FILE*)pUserData, offset, whence) == 0;
8791 }
8792
8793 static drflac_bool32 drflac__on_tell_stdio(void* pUserData, drflac_int64* pCursor)
8794 {
8795 FILE* pFileStdio = (FILE*)pUserData;
8796 drflac_int64 result;
8797
8798 /* These were all validated at a higher level. */
8799 DRFLAC_ASSERT(pFileStdio != NULL);
8800 DRFLAC_ASSERT(pCursor != NULL);
8801
8802 #if defined(_WIN32) && !defined(NXDK)
8803 #if defined(_MSC_VER) && _MSC_VER > 1200
8804 result = _ftelli64(pFileStdio);
8805 #else
8806 result = ftell(pFileStdio);
8807 #endif
8808 #else
8809 result = ftell(pFileStdio);
8810 #endif
8811
8812 *pCursor = result;
8813
8814 return DRFLAC_TRUE;
8815 }
8816
8817
8818
8819 DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks)
8820 {
8821 drflac* pFlac;
8822 FILE* pFile;
8823
8824 if (drflac_fopen(&pFile, pFileName, "rb") != DRFLAC_SUCCESS) {
8825 return NULL;
8826 }
8827
8828 pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, drflac__on_tell_stdio, (void*)pFile, pAllocationCallbacks);
8829 if (pFlac == NULL) {
8830 fclose(pFile);
8831 return NULL;
8832 }
8833
8834 return pFlac;
8835 }
8836
8837 #ifndef DR_FLAC_NO_WCHAR
8838 DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks)
8839 {
8840 drflac* pFlac;
8841 FILE* pFile;
8842
8843 if (drflac_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != DRFLAC_SUCCESS) {
8844 return NULL;
8845 }
8846
8847 pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, drflac__on_tell_stdio, (void*)pFile, pAllocationCallbacks);
8848 if (pFlac == NULL) {
8849 fclose(pFile);
8850 return NULL;
8851 }
8852
8853 return pFlac;
8854 }
8855 #endif
8856
8857 DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
8858 {
8859 drflac* pFlac;
8860 FILE* pFile;
8861
8862 if (drflac_fopen(&pFile, pFileName, "rb") != DRFLAC_SUCCESS) {
8863 return NULL;
8864 }
8865
8866 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);
8867 if (pFlac == NULL) {
8868 fclose(pFile);
8869 return pFlac;
8870 }
8871
8872 return pFlac;
8873 }
8874
8875 #ifndef DR_FLAC_NO_WCHAR
8876 DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
8877 {
8878 drflac* pFlac;
8879 FILE* pFile;
8880
8881 if (drflac_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != DRFLAC_SUCCESS) {
8882 return NULL;
8883 }
8884
8885 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);
8886 if (pFlac == NULL) {
8887 fclose(pFile);
8888 return pFlac;
8889 }
8890
8891 return pFlac;
8892 }
8893 #endif
8894 #endif /* DR_FLAC_NO_STDIO */
8895
8896 static size_t drflac__on_read_memory(void* pUserData, void* bufferOut, size_t bytesToRead)
8897 {
8898 drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
8899 size_t bytesRemaining;
8900
8901 DRFLAC_ASSERT(memoryStream != NULL);
8902 DRFLAC_ASSERT(memoryStream->dataSize >= memoryStream->currentReadPos);
8903
8904 bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos;
8905 if (bytesToRead > bytesRemaining) {
8906 bytesToRead = bytesRemaining;
8907 }
8908
8909 if (bytesToRead > 0) {
8910 DRFLAC_COPY_MEMORY(bufferOut, memoryStream->data + memoryStream->currentReadPos, bytesToRead);
8911 memoryStream->currentReadPos += bytesToRead;
8912 }
8913
8914 return bytesToRead;
8915 }
8916
8917 static drflac_bool32 drflac__on_seek_memory(void* pUserData, int offset, drflac_seek_origin origin)
8918 {
8919 drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
8920 drflac_int64 newCursor;
8921
8922 DRFLAC_ASSERT(memoryStream != NULL);
8923
8924 if (origin == DRFLAC_SEEK_SET) {
8925 newCursor = 0;
8926 } else if (origin == DRFLAC_SEEK_CUR) {
8927 newCursor = (drflac_int64)memoryStream->currentReadPos;
8928 } else if (origin == DRFLAC_SEEK_END) {
8929 newCursor = (drflac_int64)memoryStream->dataSize;
8930 } else {
8931 DRFLAC_ASSERT(!"Invalid seek origin");
8932 return DRFLAC_FALSE;
8933 }
8934
8935 newCursor += offset;
8936
8937 if (newCursor < 0) {
8938 return DRFLAC_FALSE; /* Trying to seek prior to the start of the buffer. */
8939 }
8940 if ((size_t)newCursor > memoryStream->dataSize) {
8941 return DRFLAC_FALSE; /* Trying to seek beyond the end of the buffer. */
8942 }
8943
8944 memoryStream->currentReadPos = (size_t)newCursor;
8945
8946 return DRFLAC_TRUE;
8947 }
8948
8949 static drflac_bool32 drflac__on_tell_memory(void* pUserData, drflac_int64* pCursor)
8950 {
8951 drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
8952
8953 DRFLAC_ASSERT(memoryStream != NULL);
8954 DRFLAC_ASSERT(pCursor != NULL);
8955
8956 *pCursor = (drflac_int64)memoryStream->currentReadPos;
8957 return DRFLAC_TRUE;
8958 }
8959
8960 DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks)
8961 {
8962 drflac__memory_stream memoryStream;
8963 drflac* pFlac;
8964
8965 memoryStream.data = (const drflac_uint8*)pData;
8966 memoryStream.dataSize = dataSize;
8967 memoryStream.currentReadPos = 0;
8968 pFlac = drflac_open(drflac__on_read_memory, drflac__on_seek_memory, drflac__on_tell_memory, &memoryStream, pAllocationCallbacks);
8969 if (pFlac == NULL) {
8970 return NULL;
8971 }
8972
8973 pFlac->memoryStream = memoryStream;
8974
8975 /* This is an awful hack... */
8976 #ifndef DR_FLAC_NO_OGG
8977 if (pFlac->container == drflac_container_ogg)
8978 {
8979 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
8980 oggbs->pUserData = &pFlac->memoryStream;
8981 }
8982 else
8983 #endif
8984 {
8985 pFlac->bs.pUserData = &pFlac->memoryStream;
8986 }
8987
8988 return pFlac;
8989 }
8990
8991 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)
8992 {
8993 drflac__memory_stream memoryStream;
8994 drflac* pFlac;
8995
8996 memoryStream.data = (const drflac_uint8*)pData;
8997 memoryStream.dataSize = dataSize;
8998 memoryStream.currentReadPos = 0;
8999 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);
9000 if (pFlac == NULL) {
9001 return NULL;
9002 }
9003
9004 pFlac->memoryStream = memoryStream;
9005
9006 /* This is an awful hack... */
9007 #ifndef DR_FLAC_NO_OGG
9008 if (pFlac->container == drflac_container_ogg)
9009 {
9010 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
9011 oggbs->pUserData = &pFlac->memoryStream;
9012 }
9013 else
9014 #endif
9015 {
9016 pFlac->bs.pUserData = &pFlac->memoryStream;
9017 }
9018
9019 return pFlac;
9020 }
9021
9022
9023
9024 DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_tell_proc onTell, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
9025 {
9026 return drflac_open_with_metadata_private(onRead, onSeek, onTell, NULL, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
9027 }
9028 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)
9029 {
9030 return drflac_open_with_metadata_private(onRead, onSeek, onTell, NULL, container, pUserData, pUserData, pAllocationCallbacks);
9031 }
9032
9033 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)
9034 {
9035 return drflac_open_with_metadata_private(onRead, onSeek, onTell, onMeta, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
9036 }
9037 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)
9038 {
9039 return drflac_open_with_metadata_private(onRead, onSeek, onTell, onMeta, container, pUserData, pUserData, pAllocationCallbacks);
9040 }
9041
9042 DRFLAC_API void drflac_close(drflac* pFlac)
9043 {
9044 if (pFlac == NULL) {
9045 return;
9046 }
9047
9048 #ifndef DR_FLAC_NO_STDIO
9049 /*
9050 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()
9051 was used by looking at the callbacks.
9052 */
9053 if (pFlac->bs.onRead == drflac__on_read_stdio) {
9054 fclose((FILE*)pFlac->bs.pUserData);
9055 }
9056
9057 #ifndef DR_FLAC_NO_OGG
9058 /* Need to clean up Ogg streams a bit differently due to the way the bit streaming is chained. */
9059 if (pFlac->container == drflac_container_ogg) {
9060 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
9061 DRFLAC_ASSERT(pFlac->bs.onRead == drflac__on_read_ogg);
9062
9063 if (oggbs->onRead == drflac__on_read_stdio) {
9064 fclose((FILE*)oggbs->pUserData);
9065 }
9066 }
9067 #endif
9068 #endif
9069
9070 drflac__free_from_callbacks(pFlac, &pFlac->allocationCallbacks);
9071 }
9072
9073
9074 #if 0
9075 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)
9076 {
9077 drflac_uint64 i;
9078 for (i = 0; i < frameCount; ++i) {
9079 drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9080 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9081 drflac_uint32 right = left - side;
9082
9083 pOutputSamples[i*2+0] = (drflac_int32)left;
9084 pOutputSamples[i*2+1] = (drflac_int32)right;
9085 }
9086 }
9087 #endif
9088
9089 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)
9090 {
9091 drflac_uint64 i;
9092 drflac_uint64 frameCount4 = frameCount >> 2;
9093 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9094 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9095 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9096 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9097
9098 for (i = 0; i < frameCount4; ++i) {
9099 drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
9100 drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
9101 drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
9102 drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
9103
9104 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
9105 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
9106 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
9107 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
9108
9109 drflac_uint32 right0 = left0 - side0;
9110 drflac_uint32 right1 = left1 - side1;
9111 drflac_uint32 right2 = left2 - side2;
9112 drflac_uint32 right3 = left3 - side3;
9113
9114 pOutputSamples[i*8+0] = (drflac_int32)left0;
9115 pOutputSamples[i*8+1] = (drflac_int32)right0;
9116 pOutputSamples[i*8+2] = (drflac_int32)left1;
9117 pOutputSamples[i*8+3] = (drflac_int32)right1;
9118 pOutputSamples[i*8+4] = (drflac_int32)left2;
9119 pOutputSamples[i*8+5] = (drflac_int32)right2;
9120 pOutputSamples[i*8+6] = (drflac_int32)left3;
9121 pOutputSamples[i*8+7] = (drflac_int32)right3;
9122 }
9123
9124 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9125 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9126 drflac_uint32 side = pInputSamples1U32[i] << shift1;
9127 drflac_uint32 right = left - side;
9128
9129 pOutputSamples[i*2+0] = (drflac_int32)left;
9130 pOutputSamples[i*2+1] = (drflac_int32)right;
9131 }
9132 }
9133
9134 #if defined(DRFLAC_SUPPORT_SSE2)
9135 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)
9136 {
9137 drflac_uint64 i;
9138 drflac_uint64 frameCount4 = frameCount >> 2;
9139 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9140 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9141 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9142 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9143
9144 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9145
9146 for (i = 0; i < frameCount4; ++i) {
9147 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
9148 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
9149 __m128i right = _mm_sub_epi32(left, side);
9150
9151 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9152 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9153 }
9154
9155 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9156 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9157 drflac_uint32 side = pInputSamples1U32[i] << shift1;
9158 drflac_uint32 right = left - side;
9159
9160 pOutputSamples[i*2+0] = (drflac_int32)left;
9161 pOutputSamples[i*2+1] = (drflac_int32)right;
9162 }
9163 }
9164 #endif
9165
9166 #if defined(DRFLAC_SUPPORT_NEON)
9167 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)
9168 {
9169 drflac_uint64 i;
9170 drflac_uint64 frameCount4 = frameCount >> 2;
9171 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9172 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9173 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9174 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9175 int32x4_t shift0_4;
9176 int32x4_t shift1_4;
9177
9178 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9179
9180 shift0_4 = vdupq_n_s32(shift0);
9181 shift1_4 = vdupq_n_s32(shift1);
9182
9183 for (i = 0; i < frameCount4; ++i) {
9184 uint32x4_t left;
9185 uint32x4_t side;
9186 uint32x4_t right;
9187
9188 left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
9189 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
9190 right = vsubq_u32(left, side);
9191
9192 drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
9193 }
9194
9195 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9196 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9197 drflac_uint32 side = pInputSamples1U32[i] << shift1;
9198 drflac_uint32 right = left - side;
9199
9200 pOutputSamples[i*2+0] = (drflac_int32)left;
9201 pOutputSamples[i*2+1] = (drflac_int32)right;
9202 }
9203 }
9204 #endif
9205
9206 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)
9207 {
9208 #if defined(DRFLAC_SUPPORT_SSE2)
9209 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9210 drflac_read_pcm_frames_s32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9211 } else
9212 #elif defined(DRFLAC_SUPPORT_NEON)
9213 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9214 drflac_read_pcm_frames_s32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9215 } else
9216 #endif
9217 {
9218 /* Scalar fallback. */
9219 #if 0
9220 drflac_read_pcm_frames_s32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9221 #else
9222 drflac_read_pcm_frames_s32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9223 #endif
9224 }
9225 }
9226
9227
9228 #if 0
9229 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)
9230 {
9231 drflac_uint64 i;
9232 for (i = 0; i < frameCount; ++i) {
9233 drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9234 drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9235 drflac_uint32 left = right + side;
9236
9237 pOutputSamples[i*2+0] = (drflac_int32)left;
9238 pOutputSamples[i*2+1] = (drflac_int32)right;
9239 }
9240 }
9241 #endif
9242
9243 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)
9244 {
9245 drflac_uint64 i;
9246 drflac_uint64 frameCount4 = frameCount >> 2;
9247 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9248 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9249 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9250 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9251
9252 for (i = 0; i < frameCount4; ++i) {
9253 drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
9254 drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
9255 drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
9256 drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
9257
9258 drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
9259 drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
9260 drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
9261 drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
9262
9263 drflac_uint32 left0 = right0 + side0;
9264 drflac_uint32 left1 = right1 + side1;
9265 drflac_uint32 left2 = right2 + side2;
9266 drflac_uint32 left3 = right3 + side3;
9267
9268 pOutputSamples[i*8+0] = (drflac_int32)left0;
9269 pOutputSamples[i*8+1] = (drflac_int32)right0;
9270 pOutputSamples[i*8+2] = (drflac_int32)left1;
9271 pOutputSamples[i*8+3] = (drflac_int32)right1;
9272 pOutputSamples[i*8+4] = (drflac_int32)left2;
9273 pOutputSamples[i*8+5] = (drflac_int32)right2;
9274 pOutputSamples[i*8+6] = (drflac_int32)left3;
9275 pOutputSamples[i*8+7] = (drflac_int32)right3;
9276 }
9277
9278 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9279 drflac_uint32 side = pInputSamples0U32[i] << shift0;
9280 drflac_uint32 right = pInputSamples1U32[i] << shift1;
9281 drflac_uint32 left = right + side;
9282
9283 pOutputSamples[i*2+0] = (drflac_int32)left;
9284 pOutputSamples[i*2+1] = (drflac_int32)right;
9285 }
9286 }
9287
9288 #if defined(DRFLAC_SUPPORT_SSE2)
9289 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)
9290 {
9291 drflac_uint64 i;
9292 drflac_uint64 frameCount4 = frameCount >> 2;
9293 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9294 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9295 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9296 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9297
9298 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9299
9300 for (i = 0; i < frameCount4; ++i) {
9301 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
9302 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
9303 __m128i left = _mm_add_epi32(right, side);
9304
9305 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9306 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9307 }
9308
9309 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9310 drflac_uint32 side = pInputSamples0U32[i] << shift0;
9311 drflac_uint32 right = pInputSamples1U32[i] << shift1;
9312 drflac_uint32 left = right + side;
9313
9314 pOutputSamples[i*2+0] = (drflac_int32)left;
9315 pOutputSamples[i*2+1] = (drflac_int32)right;
9316 }
9317 }
9318 #endif
9319
9320 #if defined(DRFLAC_SUPPORT_NEON)
9321 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)
9322 {
9323 drflac_uint64 i;
9324 drflac_uint64 frameCount4 = frameCount >> 2;
9325 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9326 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9327 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9328 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9329 int32x4_t shift0_4;
9330 int32x4_t shift1_4;
9331
9332 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9333
9334 shift0_4 = vdupq_n_s32(shift0);
9335 shift1_4 = vdupq_n_s32(shift1);
9336
9337 for (i = 0; i < frameCount4; ++i) {
9338 uint32x4_t side;
9339 uint32x4_t right;
9340 uint32x4_t left;
9341
9342 side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
9343 right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
9344 left = vaddq_u32(right, side);
9345
9346 drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
9347 }
9348
9349 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9350 drflac_uint32 side = pInputSamples0U32[i] << shift0;
9351 drflac_uint32 right = pInputSamples1U32[i] << shift1;
9352 drflac_uint32 left = right + side;
9353
9354 pOutputSamples[i*2+0] = (drflac_int32)left;
9355 pOutputSamples[i*2+1] = (drflac_int32)right;
9356 }
9357 }
9358 #endif
9359
9360 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)
9361 {
9362 #if defined(DRFLAC_SUPPORT_SSE2)
9363 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9364 drflac_read_pcm_frames_s32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9365 } else
9366 #elif defined(DRFLAC_SUPPORT_NEON)
9367 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9368 drflac_read_pcm_frames_s32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9369 } else
9370 #endif
9371 {
9372 /* Scalar fallback. */
9373 #if 0
9374 drflac_read_pcm_frames_s32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9375 #else
9376 drflac_read_pcm_frames_s32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9377 #endif
9378 }
9379 }
9380
9381
9382 #if 0
9383 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)
9384 {
9385 for (drflac_uint64 i = 0; i < frameCount; ++i) {
9386 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9387 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9388
9389 mid = (mid << 1) | (side & 0x01);
9390
9391 pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
9392 pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
9393 }
9394 }
9395 #endif
9396
9397 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)
9398 {
9399 drflac_uint64 i;
9400 drflac_uint64 frameCount4 = frameCount >> 2;
9401 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9402 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9403 drflac_int32 shift = unusedBitsPerSample;
9404
9405 if (shift > 0) {
9406 shift -= 1;
9407 for (i = 0; i < frameCount4; ++i) {
9408 drflac_uint32 temp0L;
9409 drflac_uint32 temp1L;
9410 drflac_uint32 temp2L;
9411 drflac_uint32 temp3L;
9412 drflac_uint32 temp0R;
9413 drflac_uint32 temp1R;
9414 drflac_uint32 temp2R;
9415 drflac_uint32 temp3R;
9416
9417 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9418 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9419 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9420 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9421
9422 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9423 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9424 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9425 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9426
9427 mid0 = (mid0 << 1) | (side0 & 0x01);
9428 mid1 = (mid1 << 1) | (side1 & 0x01);
9429 mid2 = (mid2 << 1) | (side2 & 0x01);
9430 mid3 = (mid3 << 1) | (side3 & 0x01);
9431
9432 temp0L = (mid0 + side0) << shift;
9433 temp1L = (mid1 + side1) << shift;
9434 temp2L = (mid2 + side2) << shift;
9435 temp3L = (mid3 + side3) << shift;
9436
9437 temp0R = (mid0 - side0) << shift;
9438 temp1R = (mid1 - side1) << shift;
9439 temp2R = (mid2 - side2) << shift;
9440 temp3R = (mid3 - side3) << shift;
9441
9442 pOutputSamples[i*8+0] = (drflac_int32)temp0L;
9443 pOutputSamples[i*8+1] = (drflac_int32)temp0R;
9444 pOutputSamples[i*8+2] = (drflac_int32)temp1L;
9445 pOutputSamples[i*8+3] = (drflac_int32)temp1R;
9446 pOutputSamples[i*8+4] = (drflac_int32)temp2L;
9447 pOutputSamples[i*8+5] = (drflac_int32)temp2R;
9448 pOutputSamples[i*8+6] = (drflac_int32)temp3L;
9449 pOutputSamples[i*8+7] = (drflac_int32)temp3R;
9450 }
9451 } else {
9452 for (i = 0; i < frameCount4; ++i) {
9453 drflac_uint32 temp0L;
9454 drflac_uint32 temp1L;
9455 drflac_uint32 temp2L;
9456 drflac_uint32 temp3L;
9457 drflac_uint32 temp0R;
9458 drflac_uint32 temp1R;
9459 drflac_uint32 temp2R;
9460 drflac_uint32 temp3R;
9461
9462 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9463 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9464 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9465 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9466
9467 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9468 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9469 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9470 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9471
9472 mid0 = (mid0 << 1) | (side0 & 0x01);
9473 mid1 = (mid1 << 1) | (side1 & 0x01);
9474 mid2 = (mid2 << 1) | (side2 & 0x01);
9475 mid3 = (mid3 << 1) | (side3 & 0x01);
9476
9477 temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
9478 temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
9479 temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
9480 temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
9481
9482 temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
9483 temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
9484 temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
9485 temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
9486
9487 pOutputSamples[i*8+0] = (drflac_int32)temp0L;
9488 pOutputSamples[i*8+1] = (drflac_int32)temp0R;
9489 pOutputSamples[i*8+2] = (drflac_int32)temp1L;
9490 pOutputSamples[i*8+3] = (drflac_int32)temp1R;
9491 pOutputSamples[i*8+4] = (drflac_int32)temp2L;
9492 pOutputSamples[i*8+5] = (drflac_int32)temp2R;
9493 pOutputSamples[i*8+6] = (drflac_int32)temp3L;
9494 pOutputSamples[i*8+7] = (drflac_int32)temp3R;
9495 }
9496 }
9497
9498 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9499 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9500 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9501
9502 mid = (mid << 1) | (side & 0x01);
9503
9504 pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
9505 pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
9506 }
9507 }
9508
9509 #if defined(DRFLAC_SUPPORT_SSE2)
9510 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)
9511 {
9512 drflac_uint64 i;
9513 drflac_uint64 frameCount4 = frameCount >> 2;
9514 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9515 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9516 drflac_int32 shift = unusedBitsPerSample;
9517
9518 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9519
9520 if (shift == 0) {
9521 for (i = 0; i < frameCount4; ++i) {
9522 __m128i mid;
9523 __m128i side;
9524 __m128i left;
9525 __m128i right;
9526
9527 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9528 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9529
9530 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
9531
9532 left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
9533 right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
9534
9535 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9536 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9537 }
9538
9539 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9540 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9541 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9542
9543 mid = (mid << 1) | (side & 0x01);
9544
9545 pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
9546 pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
9547 }
9548 } else {
9549 shift -= 1;
9550 for (i = 0; i < frameCount4; ++i) {
9551 __m128i mid;
9552 __m128i side;
9553 __m128i left;
9554 __m128i right;
9555
9556 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9557 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9558
9559 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
9560
9561 left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
9562 right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
9563
9564 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9565 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9566 }
9567
9568 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9569 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9570 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9571
9572 mid = (mid << 1) | (side & 0x01);
9573
9574 pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
9575 pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
9576 }
9577 }
9578 }
9579 #endif
9580
9581 #if defined(DRFLAC_SUPPORT_NEON)
9582 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)
9583 {
9584 drflac_uint64 i;
9585 drflac_uint64 frameCount4 = frameCount >> 2;
9586 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9587 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9588 drflac_int32 shift = unusedBitsPerSample;
9589 int32x4_t wbpsShift0_4; /* wbps = Wasted Bits Per Sample */
9590 int32x4_t wbpsShift1_4; /* wbps = Wasted Bits Per Sample */
9591 uint32x4_t one4;
9592
9593 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9594
9595 wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9596 wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9597 one4 = vdupq_n_u32(1);
9598
9599 if (shift == 0) {
9600 for (i = 0; i < frameCount4; ++i) {
9601 uint32x4_t mid;
9602 uint32x4_t side;
9603 int32x4_t left;
9604 int32x4_t right;
9605
9606 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
9607 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
9608
9609 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
9610
9611 left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
9612 right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
9613
9614 drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
9615 }
9616
9617 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9618 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9619 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9620
9621 mid = (mid << 1) | (side & 0x01);
9622
9623 pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
9624 pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
9625 }
9626 } else {
9627 int32x4_t shift4;
9628
9629 shift -= 1;
9630 shift4 = vdupq_n_s32(shift);
9631
9632 for (i = 0; i < frameCount4; ++i) {
9633 uint32x4_t mid;
9634 uint32x4_t side;
9635 int32x4_t left;
9636 int32x4_t right;
9637
9638 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
9639 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
9640
9641 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
9642
9643 left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
9644 right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
9645
9646 drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
9647 }
9648
9649 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9650 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9651 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9652
9653 mid = (mid << 1) | (side & 0x01);
9654
9655 pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
9656 pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
9657 }
9658 }
9659 }
9660 #endif
9661
9662 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)
9663 {
9664 #if defined(DRFLAC_SUPPORT_SSE2)
9665 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9666 drflac_read_pcm_frames_s32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9667 } else
9668 #elif defined(DRFLAC_SUPPORT_NEON)
9669 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9670 drflac_read_pcm_frames_s32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9671 } else
9672 #endif
9673 {
9674 /* Scalar fallback. */
9675 #if 0
9676 drflac_read_pcm_frames_s32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9677 #else
9678 drflac_read_pcm_frames_s32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9679 #endif
9680 }
9681 }
9682
9683
9684 #if 0
9685 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)
9686 {
9687 for (drflac_uint64 i = 0; i < frameCount; ++i) {
9688 pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample));
9689 pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample));
9690 }
9691 }
9692 #endif
9693
9694 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)
9695 {
9696 drflac_uint64 i;
9697 drflac_uint64 frameCount4 = frameCount >> 2;
9698 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9699 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9700 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9701 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9702
9703 for (i = 0; i < frameCount4; ++i) {
9704 drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
9705 drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
9706 drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
9707 drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
9708
9709 drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
9710 drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
9711 drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
9712 drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
9713
9714 pOutputSamples[i*8+0] = (drflac_int32)tempL0;
9715 pOutputSamples[i*8+1] = (drflac_int32)tempR0;
9716 pOutputSamples[i*8+2] = (drflac_int32)tempL1;
9717 pOutputSamples[i*8+3] = (drflac_int32)tempR1;
9718 pOutputSamples[i*8+4] = (drflac_int32)tempL2;
9719 pOutputSamples[i*8+5] = (drflac_int32)tempR2;
9720 pOutputSamples[i*8+6] = (drflac_int32)tempL3;
9721 pOutputSamples[i*8+7] = (drflac_int32)tempR3;
9722 }
9723
9724 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9725 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
9726 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
9727 }
9728 }
9729
9730 #if defined(DRFLAC_SUPPORT_SSE2)
9731 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)
9732 {
9733 drflac_uint64 i;
9734 drflac_uint64 frameCount4 = frameCount >> 2;
9735 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9736 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9737 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9738 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9739
9740 for (i = 0; i < frameCount4; ++i) {
9741 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
9742 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
9743
9744 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9745 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9746 }
9747
9748 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9749 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
9750 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
9751 }
9752 }
9753 #endif
9754
9755 #if defined(DRFLAC_SUPPORT_NEON)
9756 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)
9757 {
9758 drflac_uint64 i;
9759 drflac_uint64 frameCount4 = frameCount >> 2;
9760 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9761 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9762 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9763 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9764
9765 int32x4_t shift4_0 = vdupq_n_s32(shift0);
9766 int32x4_t shift4_1 = vdupq_n_s32(shift1);
9767
9768 for (i = 0; i < frameCount4; ++i) {
9769 int32x4_t left;
9770 int32x4_t right;
9771
9772 left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift4_0));
9773 right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift4_1));
9774
9775 drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
9776 }
9777
9778 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9779 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
9780 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
9781 }
9782 }
9783 #endif
9784
9785 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)
9786 {
9787 #if defined(DRFLAC_SUPPORT_SSE2)
9788 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9789 drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9790 } else
9791 #elif defined(DRFLAC_SUPPORT_NEON)
9792 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9793 drflac_read_pcm_frames_s32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9794 } else
9795 #endif
9796 {
9797 /* Scalar fallback. */
9798 #if 0
9799 drflac_read_pcm_frames_s32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9800 #else
9801 drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9802 #endif
9803 }
9804 }
9805
9806
9807 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut)
9808 {
9809 drflac_uint64 framesRead;
9810 drflac_uint32 unusedBitsPerSample;
9811
9812 if (pFlac == NULL || framesToRead == 0) {
9813 return 0;
9814 }
9815
9816 if (pBufferOut == NULL) {
9817 return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
9818 }
9819
9820 DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
9821 unusedBitsPerSample = 32 - pFlac->bitsPerSample;
9822
9823 framesRead = 0;
9824 while (framesToRead > 0) {
9825 /* If we've run out of samples in this frame, go to the next. */
9826 if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
9827 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
9828 break; /* Couldn't read the next frame, so just break from the loop and return. */
9829 }
9830 } else {
9831 unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
9832 drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
9833 drflac_uint64 frameCountThisIteration = framesToRead;
9834
9835 if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
9836 frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
9837 }
9838
9839 if (channelCount == 2) {
9840 const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
9841 const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
9842
9843 switch (pFlac->currentFLACFrame.header.channelAssignment)
9844 {
9845 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
9846 {
9847 drflac_read_pcm_frames_s32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
9848 } break;
9849
9850 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
9851 {
9852 drflac_read_pcm_frames_s32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
9853 } break;
9854
9855 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
9856 {
9857 drflac_read_pcm_frames_s32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
9858 } break;
9859
9860 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
9861 default:
9862 {
9863 drflac_read_pcm_frames_s32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
9864 } break;
9865 }
9866 } else {
9867 /* Generic interleaving. */
9868 drflac_uint64 i;
9869 for (i = 0; i < frameCountThisIteration; ++i) {
9870 unsigned int j;
9871 for (j = 0; j < channelCount; ++j) {
9872 pBufferOut[(i*channelCount)+j] = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
9873 }
9874 }
9875 }
9876
9877 framesRead += frameCountThisIteration;
9878 pBufferOut += frameCountThisIteration * channelCount;
9879 framesToRead -= frameCountThisIteration;
9880 pFlac->currentPCMFrame += frameCountThisIteration;
9881 pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
9882 }
9883 }
9884
9885 return framesRead;
9886 }
9887
9888
9889 #if 0
9890 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)
9891 {
9892 drflac_uint64 i;
9893 for (i = 0; i < frameCount; ++i) {
9894 drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9895 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9896 drflac_uint32 right = left - side;
9897
9898 left >>= 16;
9899 right >>= 16;
9900
9901 pOutputSamples[i*2+0] = (drflac_int16)left;
9902 pOutputSamples[i*2+1] = (drflac_int16)right;
9903 }
9904 }
9905 #endif
9906
9907 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)
9908 {
9909 drflac_uint64 i;
9910 drflac_uint64 frameCount4 = frameCount >> 2;
9911 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9912 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9913 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9914 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9915
9916 for (i = 0; i < frameCount4; ++i) {
9917 drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
9918 drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
9919 drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
9920 drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
9921
9922 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
9923 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
9924 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
9925 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
9926
9927 drflac_uint32 right0 = left0 - side0;
9928 drflac_uint32 right1 = left1 - side1;
9929 drflac_uint32 right2 = left2 - side2;
9930 drflac_uint32 right3 = left3 - side3;
9931
9932 left0 >>= 16;
9933 left1 >>= 16;
9934 left2 >>= 16;
9935 left3 >>= 16;
9936
9937 right0 >>= 16;
9938 right1 >>= 16;
9939 right2 >>= 16;
9940 right3 >>= 16;
9941
9942 pOutputSamples[i*8+0] = (drflac_int16)left0;
9943 pOutputSamples[i*8+1] = (drflac_int16)right0;
9944 pOutputSamples[i*8+2] = (drflac_int16)left1;
9945 pOutputSamples[i*8+3] = (drflac_int16)right1;
9946 pOutputSamples[i*8+4] = (drflac_int16)left2;
9947 pOutputSamples[i*8+5] = (drflac_int16)right2;
9948 pOutputSamples[i*8+6] = (drflac_int16)left3;
9949 pOutputSamples[i*8+7] = (drflac_int16)right3;
9950 }
9951
9952 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9953 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9954 drflac_uint32 side = pInputSamples1U32[i] << shift1;
9955 drflac_uint32 right = left - side;
9956
9957 left >>= 16;
9958 right >>= 16;
9959
9960 pOutputSamples[i*2+0] = (drflac_int16)left;
9961 pOutputSamples[i*2+1] = (drflac_int16)right;
9962 }
9963 }
9964
9965 #if defined(DRFLAC_SUPPORT_SSE2)
9966 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)
9967 {
9968 drflac_uint64 i;
9969 drflac_uint64 frameCount4 = frameCount >> 2;
9970 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9971 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9972 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9973 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9974
9975 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9976
9977 for (i = 0; i < frameCount4; ++i) {
9978 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
9979 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
9980 __m128i right = _mm_sub_epi32(left, side);
9981
9982 left = _mm_srai_epi32(left, 16);
9983 right = _mm_srai_epi32(right, 16);
9984
9985 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
9986 }
9987
9988 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9989 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9990 drflac_uint32 side = pInputSamples1U32[i] << shift1;
9991 drflac_uint32 right = left - side;
9992
9993 left >>= 16;
9994 right >>= 16;
9995
9996 pOutputSamples[i*2+0] = (drflac_int16)left;
9997 pOutputSamples[i*2+1] = (drflac_int16)right;
9998 }
9999 }
10000 #endif
10001
10002 #if defined(DRFLAC_SUPPORT_NEON)
10003 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)
10004 {
10005 drflac_uint64 i;
10006 drflac_uint64 frameCount4 = frameCount >> 2;
10007 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10008 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10009 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10010 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10011 int32x4_t shift0_4;
10012 int32x4_t shift1_4;
10013
10014 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10015
10016 shift0_4 = vdupq_n_s32(shift0);
10017 shift1_4 = vdupq_n_s32(shift1);
10018
10019 for (i = 0; i < frameCount4; ++i) {
10020 uint32x4_t left;
10021 uint32x4_t side;
10022 uint32x4_t right;
10023
10024 left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
10025 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
10026 right = vsubq_u32(left, side);
10027
10028 left = vshrq_n_u32(left, 16);
10029 right = vshrq_n_u32(right, 16);
10030
10031 drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
10032 }
10033
10034 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10035 drflac_uint32 left = pInputSamples0U32[i] << shift0;
10036 drflac_uint32 side = pInputSamples1U32[i] << shift1;
10037 drflac_uint32 right = left - side;
10038
10039 left >>= 16;
10040 right >>= 16;
10041
10042 pOutputSamples[i*2+0] = (drflac_int16)left;
10043 pOutputSamples[i*2+1] = (drflac_int16)right;
10044 }
10045 }
10046 #endif
10047
10048 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)
10049 {
10050 #if defined(DRFLAC_SUPPORT_SSE2)
10051 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10052 drflac_read_pcm_frames_s16__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10053 } else
10054 #elif defined(DRFLAC_SUPPORT_NEON)
10055 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10056 drflac_read_pcm_frames_s16__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10057 } else
10058 #endif
10059 {
10060 /* Scalar fallback. */
10061 #if 0
10062 drflac_read_pcm_frames_s16__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10063 #else
10064 drflac_read_pcm_frames_s16__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10065 #endif
10066 }
10067 }
10068
10069
10070 #if 0
10071 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)
10072 {
10073 drflac_uint64 i;
10074 for (i = 0; i < frameCount; ++i) {
10075 drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10076 drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10077 drflac_uint32 left = right + side;
10078
10079 left >>= 16;
10080 right >>= 16;
10081
10082 pOutputSamples[i*2+0] = (drflac_int16)left;
10083 pOutputSamples[i*2+1] = (drflac_int16)right;
10084 }
10085 }
10086 #endif
10087
10088 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)
10089 {
10090 drflac_uint64 i;
10091 drflac_uint64 frameCount4 = frameCount >> 2;
10092 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10093 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10094 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10095 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10096
10097 for (i = 0; i < frameCount4; ++i) {
10098 drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
10099 drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
10100 drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
10101 drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
10102
10103 drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
10104 drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
10105 drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
10106 drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
10107
10108 drflac_uint32 left0 = right0 + side0;
10109 drflac_uint32 left1 = right1 + side1;
10110 drflac_uint32 left2 = right2 + side2;
10111 drflac_uint32 left3 = right3 + side3;
10112
10113 left0 >>= 16;
10114 left1 >>= 16;
10115 left2 >>= 16;
10116 left3 >>= 16;
10117
10118 right0 >>= 16;
10119 right1 >>= 16;
10120 right2 >>= 16;
10121 right3 >>= 16;
10122
10123 pOutputSamples[i*8+0] = (drflac_int16)left0;
10124 pOutputSamples[i*8+1] = (drflac_int16)right0;
10125 pOutputSamples[i*8+2] = (drflac_int16)left1;
10126 pOutputSamples[i*8+3] = (drflac_int16)right1;
10127 pOutputSamples[i*8+4] = (drflac_int16)left2;
10128 pOutputSamples[i*8+5] = (drflac_int16)right2;
10129 pOutputSamples[i*8+6] = (drflac_int16)left3;
10130 pOutputSamples[i*8+7] = (drflac_int16)right3;
10131 }
10132
10133 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10134 drflac_uint32 side = pInputSamples0U32[i] << shift0;
10135 drflac_uint32 right = pInputSamples1U32[i] << shift1;
10136 drflac_uint32 left = right + side;
10137
10138 left >>= 16;
10139 right >>= 16;
10140
10141 pOutputSamples[i*2+0] = (drflac_int16)left;
10142 pOutputSamples[i*2+1] = (drflac_int16)right;
10143 }
10144 }
10145
10146 #if defined(DRFLAC_SUPPORT_SSE2)
10147 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)
10148 {
10149 drflac_uint64 i;
10150 drflac_uint64 frameCount4 = frameCount >> 2;
10151 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10152 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10153 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10154 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10155
10156 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10157
10158 for (i = 0; i < frameCount4; ++i) {
10159 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
10160 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
10161 __m128i left = _mm_add_epi32(right, side);
10162
10163 left = _mm_srai_epi32(left, 16);
10164 right = _mm_srai_epi32(right, 16);
10165
10166 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
10167 }
10168
10169 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10170 drflac_uint32 side = pInputSamples0U32[i] << shift0;
10171 drflac_uint32 right = pInputSamples1U32[i] << shift1;
10172 drflac_uint32 left = right + side;
10173
10174 left >>= 16;
10175 right >>= 16;
10176
10177 pOutputSamples[i*2+0] = (drflac_int16)left;
10178 pOutputSamples[i*2+1] = (drflac_int16)right;
10179 }
10180 }
10181 #endif
10182
10183 #if defined(DRFLAC_SUPPORT_NEON)
10184 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)
10185 {
10186 drflac_uint64 i;
10187 drflac_uint64 frameCount4 = frameCount >> 2;
10188 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10189 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10190 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10191 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10192 int32x4_t shift0_4;
10193 int32x4_t shift1_4;
10194
10195 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10196
10197 shift0_4 = vdupq_n_s32(shift0);
10198 shift1_4 = vdupq_n_s32(shift1);
10199
10200 for (i = 0; i < frameCount4; ++i) {
10201 uint32x4_t side;
10202 uint32x4_t right;
10203 uint32x4_t left;
10204
10205 side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
10206 right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
10207 left = vaddq_u32(right, side);
10208
10209 left = vshrq_n_u32(left, 16);
10210 right = vshrq_n_u32(right, 16);
10211
10212 drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
10213 }
10214
10215 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10216 drflac_uint32 side = pInputSamples0U32[i] << shift0;
10217 drflac_uint32 right = pInputSamples1U32[i] << shift1;
10218 drflac_uint32 left = right + side;
10219
10220 left >>= 16;
10221 right >>= 16;
10222
10223 pOutputSamples[i*2+0] = (drflac_int16)left;
10224 pOutputSamples[i*2+1] = (drflac_int16)right;
10225 }
10226 }
10227 #endif
10228
10229 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)
10230 {
10231 #if defined(DRFLAC_SUPPORT_SSE2)
10232 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10233 drflac_read_pcm_frames_s16__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10234 } else
10235 #elif defined(DRFLAC_SUPPORT_NEON)
10236 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10237 drflac_read_pcm_frames_s16__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10238 } else
10239 #endif
10240 {
10241 /* Scalar fallback. */
10242 #if 0
10243 drflac_read_pcm_frames_s16__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10244 #else
10245 drflac_read_pcm_frames_s16__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10246 #endif
10247 }
10248 }
10249
10250
10251 #if 0
10252 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)
10253 {
10254 for (drflac_uint64 i = 0; i < frameCount; ++i) {
10255 drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10256 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10257
10258 mid = (mid << 1) | (side & 0x01);
10259
10260 pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
10261 pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
10262 }
10263 }
10264 #endif
10265
10266 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)
10267 {
10268 drflac_uint64 i;
10269 drflac_uint64 frameCount4 = frameCount >> 2;
10270 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10271 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10272 drflac_uint32 shift = unusedBitsPerSample;
10273
10274 if (shift > 0) {
10275 shift -= 1;
10276 for (i = 0; i < frameCount4; ++i) {
10277 drflac_uint32 temp0L;
10278 drflac_uint32 temp1L;
10279 drflac_uint32 temp2L;
10280 drflac_uint32 temp3L;
10281 drflac_uint32 temp0R;
10282 drflac_uint32 temp1R;
10283 drflac_uint32 temp2R;
10284 drflac_uint32 temp3R;
10285
10286 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10287 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10288 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10289 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10290
10291 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10292 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10293 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10294 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10295
10296 mid0 = (mid0 << 1) | (side0 & 0x01);
10297 mid1 = (mid1 << 1) | (side1 & 0x01);
10298 mid2 = (mid2 << 1) | (side2 & 0x01);
10299 mid3 = (mid3 << 1) | (side3 & 0x01);
10300
10301 temp0L = (mid0 + side0) << shift;
10302 temp1L = (mid1 + side1) << shift;
10303 temp2L = (mid2 + side2) << shift;
10304 temp3L = (mid3 + side3) << shift;
10305
10306 temp0R = (mid0 - side0) << shift;
10307 temp1R = (mid1 - side1) << shift;
10308 temp2R = (mid2 - side2) << shift;
10309 temp3R = (mid3 - side3) << shift;
10310
10311 temp0L >>= 16;
10312 temp1L >>= 16;
10313 temp2L >>= 16;
10314 temp3L >>= 16;
10315
10316 temp0R >>= 16;
10317 temp1R >>= 16;
10318 temp2R >>= 16;
10319 temp3R >>= 16;
10320
10321 pOutputSamples[i*8+0] = (drflac_int16)temp0L;
10322 pOutputSamples[i*8+1] = (drflac_int16)temp0R;
10323 pOutputSamples[i*8+2] = (drflac_int16)temp1L;
10324 pOutputSamples[i*8+3] = (drflac_int16)temp1R;
10325 pOutputSamples[i*8+4] = (drflac_int16)temp2L;
10326 pOutputSamples[i*8+5] = (drflac_int16)temp2R;
10327 pOutputSamples[i*8+6] = (drflac_int16)temp3L;
10328 pOutputSamples[i*8+7] = (drflac_int16)temp3R;
10329 }
10330 } else {
10331 for (i = 0; i < frameCount4; ++i) {
10332 drflac_uint32 temp0L;
10333 drflac_uint32 temp1L;
10334 drflac_uint32 temp2L;
10335 drflac_uint32 temp3L;
10336 drflac_uint32 temp0R;
10337 drflac_uint32 temp1R;
10338 drflac_uint32 temp2R;
10339 drflac_uint32 temp3R;
10340
10341 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10342 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10343 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10344 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10345
10346 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10347 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10348 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10349 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10350
10351 mid0 = (mid0 << 1) | (side0 & 0x01);
10352 mid1 = (mid1 << 1) | (side1 & 0x01);
10353 mid2 = (mid2 << 1) | (side2 & 0x01);
10354 mid3 = (mid3 << 1) | (side3 & 0x01);
10355
10356 temp0L = ((drflac_int32)(mid0 + side0) >> 1);
10357 temp1L = ((drflac_int32)(mid1 + side1) >> 1);
10358 temp2L = ((drflac_int32)(mid2 + side2) >> 1);
10359 temp3L = ((drflac_int32)(mid3 + side3) >> 1);
10360
10361 temp0R = ((drflac_int32)(mid0 - side0) >> 1);
10362 temp1R = ((drflac_int32)(mid1 - side1) >> 1);
10363 temp2R = ((drflac_int32)(mid2 - side2) >> 1);
10364 temp3R = ((drflac_int32)(mid3 - side3) >> 1);
10365
10366 temp0L >>= 16;
10367 temp1L >>= 16;
10368 temp2L >>= 16;
10369 temp3L >>= 16;
10370
10371 temp0R >>= 16;
10372 temp1R >>= 16;
10373 temp2R >>= 16;
10374 temp3R >>= 16;
10375
10376 pOutputSamples[i*8+0] = (drflac_int16)temp0L;
10377 pOutputSamples[i*8+1] = (drflac_int16)temp0R;
10378 pOutputSamples[i*8+2] = (drflac_int16)temp1L;
10379 pOutputSamples[i*8+3] = (drflac_int16)temp1R;
10380 pOutputSamples[i*8+4] = (drflac_int16)temp2L;
10381 pOutputSamples[i*8+5] = (drflac_int16)temp2R;
10382 pOutputSamples[i*8+6] = (drflac_int16)temp3L;
10383 pOutputSamples[i*8+7] = (drflac_int16)temp3R;
10384 }
10385 }
10386
10387 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10388 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10389 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10390
10391 mid = (mid << 1) | (side & 0x01);
10392
10393 pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
10394 pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
10395 }
10396 }
10397
10398 #if defined(DRFLAC_SUPPORT_SSE2)
10399 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)
10400 {
10401 drflac_uint64 i;
10402 drflac_uint64 frameCount4 = frameCount >> 2;
10403 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10404 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10405 drflac_uint32 shift = unusedBitsPerSample;
10406
10407 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10408
10409 if (shift == 0) {
10410 for (i = 0; i < frameCount4; ++i) {
10411 __m128i mid;
10412 __m128i side;
10413 __m128i left;
10414 __m128i right;
10415
10416 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10417 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10418
10419 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
10420
10421 left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
10422 right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
10423
10424 left = _mm_srai_epi32(left, 16);
10425 right = _mm_srai_epi32(right, 16);
10426
10427 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
10428 }
10429
10430 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10431 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10432 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10433
10434 mid = (mid << 1) | (side & 0x01);
10435
10436 pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
10437 pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
10438 }
10439 } else {
10440 shift -= 1;
10441 for (i = 0; i < frameCount4; ++i) {
10442 __m128i mid;
10443 __m128i side;
10444 __m128i left;
10445 __m128i right;
10446
10447 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10448 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10449
10450 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
10451
10452 left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
10453 right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
10454
10455 left = _mm_srai_epi32(left, 16);
10456 right = _mm_srai_epi32(right, 16);
10457
10458 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
10459 }
10460
10461 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10462 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10463 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10464
10465 mid = (mid << 1) | (side & 0x01);
10466
10467 pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
10468 pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
10469 }
10470 }
10471 }
10472 #endif
10473
10474 #if defined(DRFLAC_SUPPORT_NEON)
10475 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)
10476 {
10477 drflac_uint64 i;
10478 drflac_uint64 frameCount4 = frameCount >> 2;
10479 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10480 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10481 drflac_uint32 shift = unusedBitsPerSample;
10482 int32x4_t wbpsShift0_4; /* wbps = Wasted Bits Per Sample */
10483 int32x4_t wbpsShift1_4; /* wbps = Wasted Bits Per Sample */
10484
10485 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10486
10487 wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10488 wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10489
10490 if (shift == 0) {
10491 for (i = 0; i < frameCount4; ++i) {
10492 uint32x4_t mid;
10493 uint32x4_t side;
10494 int32x4_t left;
10495 int32x4_t right;
10496
10497 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
10498 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
10499
10500 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
10501
10502 left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
10503 right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
10504
10505 left = vshrq_n_s32(left, 16);
10506 right = vshrq_n_s32(right, 16);
10507
10508 drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
10509 }
10510
10511 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10512 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10513 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10514
10515 mid = (mid << 1) | (side & 0x01);
10516
10517 pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
10518 pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
10519 }
10520 } else {
10521 int32x4_t shift4;
10522
10523 shift -= 1;
10524 shift4 = vdupq_n_s32(shift);
10525
10526 for (i = 0; i < frameCount4; ++i) {
10527 uint32x4_t mid;
10528 uint32x4_t side;
10529 int32x4_t left;
10530 int32x4_t right;
10531
10532 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
10533 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
10534
10535 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
10536
10537 left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
10538 right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
10539
10540 left = vshrq_n_s32(left, 16);
10541 right = vshrq_n_s32(right, 16);
10542
10543 drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
10544 }
10545
10546 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10547 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10548 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10549
10550 mid = (mid << 1) | (side & 0x01);
10551
10552 pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
10553 pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
10554 }
10555 }
10556 }
10557 #endif
10558
10559 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)
10560 {
10561 #if defined(DRFLAC_SUPPORT_SSE2)
10562 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10563 drflac_read_pcm_frames_s16__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10564 } else
10565 #elif defined(DRFLAC_SUPPORT_NEON)
10566 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10567 drflac_read_pcm_frames_s16__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10568 } else
10569 #endif
10570 {
10571 /* Scalar fallback. */
10572 #if 0
10573 drflac_read_pcm_frames_s16__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10574 #else
10575 drflac_read_pcm_frames_s16__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10576 #endif
10577 }
10578 }
10579
10580
10581 #if 0
10582 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)
10583 {
10584 for (drflac_uint64 i = 0; i < frameCount; ++i) {
10585 pOutputSamples[i*2+0] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) >> 16);
10586 pOutputSamples[i*2+1] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) >> 16);
10587 }
10588 }
10589 #endif
10590
10591 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)
10592 {
10593 drflac_uint64 i;
10594 drflac_uint64 frameCount4 = frameCount >> 2;
10595 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10596 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10597 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10598 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10599
10600 for (i = 0; i < frameCount4; ++i) {
10601 drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
10602 drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
10603 drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
10604 drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
10605
10606 drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
10607 drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
10608 drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
10609 drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
10610
10611 tempL0 >>= 16;
10612 tempL1 >>= 16;
10613 tempL2 >>= 16;
10614 tempL3 >>= 16;
10615
10616 tempR0 >>= 16;
10617 tempR1 >>= 16;
10618 tempR2 >>= 16;
10619 tempR3 >>= 16;
10620
10621 pOutputSamples[i*8+0] = (drflac_int16)tempL0;
10622 pOutputSamples[i*8+1] = (drflac_int16)tempR0;
10623 pOutputSamples[i*8+2] = (drflac_int16)tempL1;
10624 pOutputSamples[i*8+3] = (drflac_int16)tempR1;
10625 pOutputSamples[i*8+4] = (drflac_int16)tempL2;
10626 pOutputSamples[i*8+5] = (drflac_int16)tempR2;
10627 pOutputSamples[i*8+6] = (drflac_int16)tempL3;
10628 pOutputSamples[i*8+7] = (drflac_int16)tempR3;
10629 }
10630
10631 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10632 pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
10633 pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
10634 }
10635 }
10636
10637 #if defined(DRFLAC_SUPPORT_SSE2)
10638 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)
10639 {
10640 drflac_uint64 i;
10641 drflac_uint64 frameCount4 = frameCount >> 2;
10642 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10643 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10644 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10645 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10646
10647 for (i = 0; i < frameCount4; ++i) {
10648 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
10649 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
10650
10651 left = _mm_srai_epi32(left, 16);
10652 right = _mm_srai_epi32(right, 16);
10653
10654 /* 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. */
10655 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
10656 }
10657
10658 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10659 pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
10660 pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
10661 }
10662 }
10663 #endif
10664
10665 #if defined(DRFLAC_SUPPORT_NEON)
10666 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)
10667 {
10668 drflac_uint64 i;
10669 drflac_uint64 frameCount4 = frameCount >> 2;
10670 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10671 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10672 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10673 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10674
10675 int32x4_t shift0_4 = vdupq_n_s32(shift0);
10676 int32x4_t shift1_4 = vdupq_n_s32(shift1);
10677
10678 for (i = 0; i < frameCount4; ++i) {
10679 int32x4_t left;
10680 int32x4_t right;
10681
10682 left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
10683 right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
10684
10685 left = vshrq_n_s32(left, 16);
10686 right = vshrq_n_s32(right, 16);
10687
10688 drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
10689 }
10690
10691 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10692 pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
10693 pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
10694 }
10695 }
10696 #endif
10697
10698 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)
10699 {
10700 #if defined(DRFLAC_SUPPORT_SSE2)
10701 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10702 drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10703 } else
10704 #elif defined(DRFLAC_SUPPORT_NEON)
10705 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10706 drflac_read_pcm_frames_s16__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10707 } else
10708 #endif
10709 {
10710 /* Scalar fallback. */
10711 #if 0
10712 drflac_read_pcm_frames_s16__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10713 #else
10714 drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10715 #endif
10716 }
10717 }
10718
10719 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut)
10720 {
10721 drflac_uint64 framesRead;
10722 drflac_uint32 unusedBitsPerSample;
10723
10724 if (pFlac == NULL || framesToRead == 0) {
10725 return 0;
10726 }
10727
10728 if (pBufferOut == NULL) {
10729 return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
10730 }
10731
10732 DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
10733 unusedBitsPerSample = 32 - pFlac->bitsPerSample;
10734
10735 framesRead = 0;
10736 while (framesToRead > 0) {
10737 /* If we've run out of samples in this frame, go to the next. */
10738 if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
10739 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
10740 break; /* Couldn't read the next frame, so just break from the loop and return. */
10741 }
10742 } else {
10743 unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
10744 drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
10745 drflac_uint64 frameCountThisIteration = framesToRead;
10746
10747 if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
10748 frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
10749 }
10750
10751 if (channelCount == 2) {
10752 const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
10753 const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
10754
10755 switch (pFlac->currentFLACFrame.header.channelAssignment)
10756 {
10757 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
10758 {
10759 drflac_read_pcm_frames_s16__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
10760 } break;
10761
10762 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
10763 {
10764 drflac_read_pcm_frames_s16__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
10765 } break;
10766
10767 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
10768 {
10769 drflac_read_pcm_frames_s16__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
10770 } break;
10771
10772 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
10773 default:
10774 {
10775 drflac_read_pcm_frames_s16__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
10776 } break;
10777 }
10778 } else {
10779 /* Generic interleaving. */
10780 drflac_uint64 i;
10781 for (i = 0; i < frameCountThisIteration; ++i) {
10782 unsigned int j;
10783 for (j = 0; j < channelCount; ++j) {
10784 drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
10785 pBufferOut[(i*channelCount)+j] = (drflac_int16)(sampleS32 >> 16);
10786 }
10787 }
10788 }
10789
10790 framesRead += frameCountThisIteration;
10791 pBufferOut += frameCountThisIteration * channelCount;
10792 framesToRead -= frameCountThisIteration;
10793 pFlac->currentPCMFrame += frameCountThisIteration;
10794 pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
10795 }
10796 }
10797
10798 return framesRead;
10799 }
10800
10801
10802 #if 0
10803 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)
10804 {
10805 drflac_uint64 i;
10806 for (i = 0; i < frameCount; ++i) {
10807 drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10808 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10809 drflac_uint32 right = left - side;
10810
10811 pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0);
10812 pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
10813 }
10814 }
10815 #endif
10816
10817 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)
10818 {
10819 drflac_uint64 i;
10820 drflac_uint64 frameCount4 = frameCount >> 2;
10821 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10822 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10823 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10824 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10825
10826 float factor = 1 / 2147483648.0;
10827
10828 for (i = 0; i < frameCount4; ++i) {
10829 drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
10830 drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
10831 drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
10832 drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
10833
10834 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
10835 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
10836 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
10837 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
10838
10839 drflac_uint32 right0 = left0 - side0;
10840 drflac_uint32 right1 = left1 - side1;
10841 drflac_uint32 right2 = left2 - side2;
10842 drflac_uint32 right3 = left3 - side3;
10843
10844 pOutputSamples[i*8+0] = (drflac_int32)left0 * factor;
10845 pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
10846 pOutputSamples[i*8+2] = (drflac_int32)left1 * factor;
10847 pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
10848 pOutputSamples[i*8+4] = (drflac_int32)left2 * factor;
10849 pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
10850 pOutputSamples[i*8+6] = (drflac_int32)left3 * factor;
10851 pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
10852 }
10853
10854 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10855 drflac_uint32 left = pInputSamples0U32[i] << shift0;
10856 drflac_uint32 side = pInputSamples1U32[i] << shift1;
10857 drflac_uint32 right = left - side;
10858
10859 pOutputSamples[i*2+0] = (drflac_int32)left * factor;
10860 pOutputSamples[i*2+1] = (drflac_int32)right * factor;
10861 }
10862 }
10863
10864 #if defined(DRFLAC_SUPPORT_SSE2)
10865 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)
10866 {
10867 drflac_uint64 i;
10868 drflac_uint64 frameCount4 = frameCount >> 2;
10869 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10870 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10871 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
10872 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
10873 __m128 factor;
10874
10875 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10876
10877 factor = _mm_set1_ps(1.0f / 8388608.0f);
10878
10879 for (i = 0; i < frameCount4; ++i) {
10880 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
10881 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
10882 __m128i right = _mm_sub_epi32(left, side);
10883 __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
10884 __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
10885
10886 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
10887 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
10888 }
10889
10890 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10891 drflac_uint32 left = pInputSamples0U32[i] << shift0;
10892 drflac_uint32 side = pInputSamples1U32[i] << shift1;
10893 drflac_uint32 right = left - side;
10894
10895 pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
10896 pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
10897 }
10898 }
10899 #endif
10900
10901 #if defined(DRFLAC_SUPPORT_NEON)
10902 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)
10903 {
10904 drflac_uint64 i;
10905 drflac_uint64 frameCount4 = frameCount >> 2;
10906 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10907 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10908 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
10909 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
10910 float32x4_t factor4;
10911 int32x4_t shift0_4;
10912 int32x4_t shift1_4;
10913
10914 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10915
10916 factor4 = vdupq_n_f32(1.0f / 8388608.0f);
10917 shift0_4 = vdupq_n_s32(shift0);
10918 shift1_4 = vdupq_n_s32(shift1);
10919
10920 for (i = 0; i < frameCount4; ++i) {
10921 uint32x4_t left;
10922 uint32x4_t side;
10923 uint32x4_t right;
10924 float32x4_t leftf;
10925 float32x4_t rightf;
10926
10927 left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
10928 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
10929 right = vsubq_u32(left, side);
10930 leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
10931 rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
10932
10933 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
10934 }
10935
10936 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10937 drflac_uint32 left = pInputSamples0U32[i] << shift0;
10938 drflac_uint32 side = pInputSamples1U32[i] << shift1;
10939 drflac_uint32 right = left - side;
10940
10941 pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
10942 pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
10943 }
10944 }
10945 #endif
10946
10947 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)
10948 {
10949 #if defined(DRFLAC_SUPPORT_SSE2)
10950 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10951 drflac_read_pcm_frames_f32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10952 } else
10953 #elif defined(DRFLAC_SUPPORT_NEON)
10954 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10955 drflac_read_pcm_frames_f32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10956 } else
10957 #endif
10958 {
10959 /* Scalar fallback. */
10960 #if 0
10961 drflac_read_pcm_frames_f32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10962 #else
10963 drflac_read_pcm_frames_f32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10964 #endif
10965 }
10966 }
10967
10968
10969 #if 0
10970 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)
10971 {
10972 drflac_uint64 i;
10973 for (i = 0; i < frameCount; ++i) {
10974 drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10975 drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10976 drflac_uint32 left = right + side;
10977
10978 pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0);
10979 pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
10980 }
10981 }
10982 #endif
10983
10984 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)
10985 {
10986 drflac_uint64 i;
10987 drflac_uint64 frameCount4 = frameCount >> 2;
10988 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10989 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10990 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10991 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10992 float factor = 1 / 2147483648.0;
10993
10994 for (i = 0; i < frameCount4; ++i) {
10995 drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
10996 drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
10997 drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
10998 drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
10999
11000 drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
11001 drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
11002 drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
11003 drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
11004
11005 drflac_uint32 left0 = right0 + side0;
11006 drflac_uint32 left1 = right1 + side1;
11007 drflac_uint32 left2 = right2 + side2;
11008 drflac_uint32 left3 = right3 + side3;
11009
11010 pOutputSamples[i*8+0] = (drflac_int32)left0 * factor;
11011 pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
11012 pOutputSamples[i*8+2] = (drflac_int32)left1 * factor;
11013 pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
11014 pOutputSamples[i*8+4] = (drflac_int32)left2 * factor;
11015 pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
11016 pOutputSamples[i*8+6] = (drflac_int32)left3 * factor;
11017 pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
11018 }
11019
11020 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11021 drflac_uint32 side = pInputSamples0U32[i] << shift0;
11022 drflac_uint32 right = pInputSamples1U32[i] << shift1;
11023 drflac_uint32 left = right + side;
11024
11025 pOutputSamples[i*2+0] = (drflac_int32)left * factor;
11026 pOutputSamples[i*2+1] = (drflac_int32)right * factor;
11027 }
11028 }
11029
11030 #if defined(DRFLAC_SUPPORT_SSE2)
11031 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)
11032 {
11033 drflac_uint64 i;
11034 drflac_uint64 frameCount4 = frameCount >> 2;
11035 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11036 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11037 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
11038 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
11039 __m128 factor;
11040
11041 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
11042
11043 factor = _mm_set1_ps(1.0f / 8388608.0f);
11044
11045 for (i = 0; i < frameCount4; ++i) {
11046 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
11047 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
11048 __m128i left = _mm_add_epi32(right, side);
11049 __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
11050 __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
11051
11052 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
11053 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
11054 }
11055
11056 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11057 drflac_uint32 side = pInputSamples0U32[i] << shift0;
11058 drflac_uint32 right = pInputSamples1U32[i] << shift1;
11059 drflac_uint32 left = right + side;
11060
11061 pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
11062 pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
11063 }
11064 }
11065 #endif
11066
11067 #if defined(DRFLAC_SUPPORT_NEON)
11068 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)
11069 {
11070 drflac_uint64 i;
11071 drflac_uint64 frameCount4 = frameCount >> 2;
11072 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11073 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11074 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
11075 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
11076 float32x4_t factor4;
11077 int32x4_t shift0_4;
11078 int32x4_t shift1_4;
11079
11080 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
11081
11082 factor4 = vdupq_n_f32(1.0f / 8388608.0f);
11083 shift0_4 = vdupq_n_s32(shift0);
11084 shift1_4 = vdupq_n_s32(shift1);
11085
11086 for (i = 0; i < frameCount4; ++i) {
11087 uint32x4_t side;
11088 uint32x4_t right;
11089 uint32x4_t left;
11090 float32x4_t leftf;
11091 float32x4_t rightf;
11092
11093 side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
11094 right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
11095 left = vaddq_u32(right, side);
11096 leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
11097 rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
11098
11099 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
11100 }
11101
11102 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11103 drflac_uint32 side = pInputSamples0U32[i] << shift0;
11104 drflac_uint32 right = pInputSamples1U32[i] << shift1;
11105 drflac_uint32 left = right + side;
11106
11107 pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
11108 pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
11109 }
11110 }
11111 #endif
11112
11113 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)
11114 {
11115 #if defined(DRFLAC_SUPPORT_SSE2)
11116 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
11117 drflac_read_pcm_frames_f32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11118 } else
11119 #elif defined(DRFLAC_SUPPORT_NEON)
11120 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
11121 drflac_read_pcm_frames_f32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11122 } else
11123 #endif
11124 {
11125 /* Scalar fallback. */
11126 #if 0
11127 drflac_read_pcm_frames_f32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11128 #else
11129 drflac_read_pcm_frames_f32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11130 #endif
11131 }
11132 }
11133
11134
11135 #if 0
11136 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)
11137 {
11138 for (drflac_uint64 i = 0; i < frameCount; ++i) {
11139 drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11140 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11141
11142 mid = (mid << 1) | (side & 0x01);
11143
11144 pOutputSamples[i*2+0] = (float)((((drflac_int32)(mid + side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
11145 pOutputSamples[i*2+1] = (float)((((drflac_int32)(mid - side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
11146 }
11147 }
11148 #endif
11149
11150 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)
11151 {
11152 drflac_uint64 i;
11153 drflac_uint64 frameCount4 = frameCount >> 2;
11154 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11155 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11156 drflac_uint32 shift = unusedBitsPerSample;
11157 float factor = 1 / 2147483648.0;
11158
11159 if (shift > 0) {
11160 shift -= 1;
11161 for (i = 0; i < frameCount4; ++i) {
11162 drflac_uint32 temp0L;
11163 drflac_uint32 temp1L;
11164 drflac_uint32 temp2L;
11165 drflac_uint32 temp3L;
11166 drflac_uint32 temp0R;
11167 drflac_uint32 temp1R;
11168 drflac_uint32 temp2R;
11169 drflac_uint32 temp3R;
11170
11171 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11172 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11173 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11174 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11175
11176 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11177 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11178 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11179 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11180
11181 mid0 = (mid0 << 1) | (side0 & 0x01);
11182 mid1 = (mid1 << 1) | (side1 & 0x01);
11183 mid2 = (mid2 << 1) | (side2 & 0x01);
11184 mid3 = (mid3 << 1) | (side3 & 0x01);
11185
11186 temp0L = (mid0 + side0) << shift;
11187 temp1L = (mid1 + side1) << shift;
11188 temp2L = (mid2 + side2) << shift;
11189 temp3L = (mid3 + side3) << shift;
11190
11191 temp0R = (mid0 - side0) << shift;
11192 temp1R = (mid1 - side1) << shift;
11193 temp2R = (mid2 - side2) << shift;
11194 temp3R = (mid3 - side3) << shift;
11195
11196 pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
11197 pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
11198 pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
11199 pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
11200 pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
11201 pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
11202 pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
11203 pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
11204 }
11205 } else {
11206 for (i = 0; i < frameCount4; ++i) {
11207 drflac_uint32 temp0L;
11208 drflac_uint32 temp1L;
11209 drflac_uint32 temp2L;
11210 drflac_uint32 temp3L;
11211 drflac_uint32 temp0R;
11212 drflac_uint32 temp1R;
11213 drflac_uint32 temp2R;
11214 drflac_uint32 temp3R;
11215
11216 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11217 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11218 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11219 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11220
11221 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11222 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11223 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11224 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11225
11226 mid0 = (mid0 << 1) | (side0 & 0x01);
11227 mid1 = (mid1 << 1) | (side1 & 0x01);
11228 mid2 = (mid2 << 1) | (side2 & 0x01);
11229 mid3 = (mid3 << 1) | (side3 & 0x01);
11230
11231 temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
11232 temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
11233 temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
11234 temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
11235
11236 temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
11237 temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
11238 temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
11239 temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
11240
11241 pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
11242 pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
11243 pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
11244 pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
11245 pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
11246 pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
11247 pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
11248 pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
11249 }
11250 }
11251
11252 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11253 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11254 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11255
11256 mid = (mid << 1) | (side & 0x01);
11257
11258 pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) * factor;
11259 pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) * factor;
11260 }
11261 }
11262
11263 #if defined(DRFLAC_SUPPORT_SSE2)
11264 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)
11265 {
11266 drflac_uint64 i;
11267 drflac_uint64 frameCount4 = frameCount >> 2;
11268 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11269 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11270 drflac_uint32 shift = unusedBitsPerSample - 8;
11271 float factor;
11272 __m128 factor128;
11273
11274 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
11275
11276 factor = 1.0f / 8388608.0f;
11277 factor128 = _mm_set1_ps(factor);
11278
11279 if (shift == 0) {
11280 for (i = 0; i < frameCount4; ++i) {
11281 __m128i mid;
11282 __m128i side;
11283 __m128i tempL;
11284 __m128i tempR;
11285 __m128 leftf;
11286 __m128 rightf;
11287
11288 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
11289 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
11290
11291 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
11292
11293 tempL = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
11294 tempR = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
11295
11296 leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
11297 rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
11298
11299 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
11300 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
11301 }
11302
11303 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11304 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11305 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11306
11307 mid = (mid << 1) | (side & 0x01);
11308
11309 pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
11310 pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
11311 }
11312 } else {
11313 shift -= 1;
11314 for (i = 0; i < frameCount4; ++i) {
11315 __m128i mid;
11316 __m128i side;
11317 __m128i tempL;
11318 __m128i tempR;
11319 __m128 leftf;
11320 __m128 rightf;
11321
11322 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
11323 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
11324
11325 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
11326
11327 tempL = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
11328 tempR = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
11329
11330 leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
11331 rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
11332
11333 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
11334 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
11335 }
11336
11337 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11338 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11339 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11340
11341 mid = (mid << 1) | (side & 0x01);
11342
11343 pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
11344 pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
11345 }
11346 }
11347 }
11348 #endif
11349
11350 #if defined(DRFLAC_SUPPORT_NEON)
11351 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)
11352 {
11353 drflac_uint64 i;
11354 drflac_uint64 frameCount4 = frameCount >> 2;
11355 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11356 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11357 drflac_uint32 shift = unusedBitsPerSample - 8;
11358 float factor;
11359 float32x4_t factor4;
11360 int32x4_t shift4;
11361 int32x4_t wbps0_4; /* Wasted Bits Per Sample */
11362 int32x4_t wbps1_4; /* Wasted Bits Per Sample */
11363
11364 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
11365
11366 factor = 1.0f / 8388608.0f;
11367 factor4 = vdupq_n_f32(factor);
11368 wbps0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
11369 wbps1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
11370
11371 if (shift == 0) {
11372 for (i = 0; i < frameCount4; ++i) {
11373 int32x4_t lefti;
11374 int32x4_t righti;
11375 float32x4_t leftf;
11376 float32x4_t rightf;
11377
11378 uint32x4_t mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
11379 uint32x4_t side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
11380
11381 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
11382
11383 lefti = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
11384 righti = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
11385
11386 leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
11387 rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
11388
11389 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
11390 }
11391
11392 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11393 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11394 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11395
11396 mid = (mid << 1) | (side & 0x01);
11397
11398 pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
11399 pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
11400 }
11401 } else {
11402 shift -= 1;
11403 shift4 = vdupq_n_s32(shift);
11404 for (i = 0; i < frameCount4; ++i) {
11405 uint32x4_t mid;
11406 uint32x4_t side;
11407 int32x4_t lefti;
11408 int32x4_t righti;
11409 float32x4_t leftf;
11410 float32x4_t rightf;
11411
11412 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
11413 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
11414
11415 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
11416
11417 lefti = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
11418 righti = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
11419
11420 leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
11421 rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
11422
11423 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
11424 }
11425
11426 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11427 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11428 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11429
11430 mid = (mid << 1) | (side & 0x01);
11431
11432 pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
11433 pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
11434 }
11435 }
11436 }
11437 #endif
11438
11439 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)
11440 {
11441 #if defined(DRFLAC_SUPPORT_SSE2)
11442 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
11443 drflac_read_pcm_frames_f32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11444 } else
11445 #elif defined(DRFLAC_SUPPORT_NEON)
11446 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
11447 drflac_read_pcm_frames_f32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11448 } else
11449 #endif
11450 {
11451 /* Scalar fallback. */
11452 #if 0
11453 drflac_read_pcm_frames_f32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11454 #else
11455 drflac_read_pcm_frames_f32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11456 #endif
11457 }
11458 }
11459
11460 #if 0
11461 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)
11462 {
11463 for (drflac_uint64 i = 0; i < frameCount; ++i) {
11464 pOutputSamples[i*2+0] = (float)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) / 2147483648.0);
11465 pOutputSamples[i*2+1] = (float)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) / 2147483648.0);
11466 }
11467 }
11468 #endif
11469
11470 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)
11471 {
11472 drflac_uint64 i;
11473 drflac_uint64 frameCount4 = frameCount >> 2;
11474 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11475 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11476 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11477 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11478 float factor = 1 / 2147483648.0;
11479
11480 for (i = 0; i < frameCount4; ++i) {
11481 drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
11482 drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
11483 drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
11484 drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
11485
11486 drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
11487 drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
11488 drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
11489 drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
11490
11491 pOutputSamples[i*8+0] = (drflac_int32)tempL0 * factor;
11492 pOutputSamples[i*8+1] = (drflac_int32)tempR0 * factor;
11493 pOutputSamples[i*8+2] = (drflac_int32)tempL1 * factor;
11494 pOutputSamples[i*8+3] = (drflac_int32)tempR1 * factor;
11495 pOutputSamples[i*8+4] = (drflac_int32)tempL2 * factor;
11496 pOutputSamples[i*8+5] = (drflac_int32)tempR2 * factor;
11497 pOutputSamples[i*8+6] = (drflac_int32)tempL3 * factor;
11498 pOutputSamples[i*8+7] = (drflac_int32)tempR3 * factor;
11499 }
11500
11501 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11502 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
11503 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
11504 }
11505 }
11506
11507 #if defined(DRFLAC_SUPPORT_SSE2)
11508 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)
11509 {
11510 drflac_uint64 i;
11511 drflac_uint64 frameCount4 = frameCount >> 2;
11512 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11513 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11514 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
11515 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
11516
11517 float factor = 1.0f / 8388608.0f;
11518 __m128 factor128 = _mm_set1_ps(factor);
11519
11520 for (i = 0; i < frameCount4; ++i) {
11521 __m128i lefti;
11522 __m128i righti;
11523 __m128 leftf;
11524 __m128 rightf;
11525
11526 lefti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
11527 righti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
11528
11529 leftf = _mm_mul_ps(_mm_cvtepi32_ps(lefti), factor128);
11530 rightf = _mm_mul_ps(_mm_cvtepi32_ps(righti), factor128);
11531
11532 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
11533 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
11534 }
11535
11536 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11537 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
11538 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
11539 }
11540 }
11541 #endif
11542
11543 #if defined(DRFLAC_SUPPORT_NEON)
11544 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)
11545 {
11546 drflac_uint64 i;
11547 drflac_uint64 frameCount4 = frameCount >> 2;
11548 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11549 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11550 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
11551 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
11552
11553 float factor = 1.0f / 8388608.0f;
11554 float32x4_t factor4 = vdupq_n_f32(factor);
11555 int32x4_t shift0_4 = vdupq_n_s32(shift0);
11556 int32x4_t shift1_4 = vdupq_n_s32(shift1);
11557
11558 for (i = 0; i < frameCount4; ++i) {
11559 int32x4_t lefti;
11560 int32x4_t righti;
11561 float32x4_t leftf;
11562 float32x4_t rightf;
11563
11564 lefti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
11565 righti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
11566
11567 leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
11568 rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
11569
11570 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
11571 }
11572
11573 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11574 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
11575 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
11576 }
11577 }
11578 #endif
11579
11580 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)
11581 {
11582 #if defined(DRFLAC_SUPPORT_SSE2)
11583 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
11584 drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11585 } else
11586 #elif defined(DRFLAC_SUPPORT_NEON)
11587 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
11588 drflac_read_pcm_frames_f32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11589 } else
11590 #endif
11591 {
11592 /* Scalar fallback. */
11593 #if 0
11594 drflac_read_pcm_frames_f32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11595 #else
11596 drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11597 #endif
11598 }
11599 }
11600
11601 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut)
11602 {
11603 drflac_uint64 framesRead;
11604 drflac_uint32 unusedBitsPerSample;
11605
11606 if (pFlac == NULL || framesToRead == 0) {
11607 return 0;
11608 }
11609
11610 if (pBufferOut == NULL) {
11611 return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
11612 }
11613
11614 DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
11615 unusedBitsPerSample = 32 - pFlac->bitsPerSample;
11616
11617 framesRead = 0;
11618 while (framesToRead > 0) {
11619 /* If we've run out of samples in this frame, go to the next. */
11620 if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
11621 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
11622 break; /* Couldn't read the next frame, so just break from the loop and return. */
11623 }
11624 } else {
11625 unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
11626 drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
11627 drflac_uint64 frameCountThisIteration = framesToRead;
11628
11629 if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
11630 frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
11631 }
11632
11633 if (channelCount == 2) {
11634 const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
11635 const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
11636
11637 switch (pFlac->currentFLACFrame.header.channelAssignment)
11638 {
11639 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
11640 {
11641 drflac_read_pcm_frames_f32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
11642 } break;
11643
11644 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
11645 {
11646 drflac_read_pcm_frames_f32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
11647 } break;
11648
11649 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
11650 {
11651 drflac_read_pcm_frames_f32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
11652 } break;
11653
11654 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
11655 default:
11656 {
11657 drflac_read_pcm_frames_f32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
11658 } break;
11659 }
11660 } else {
11661 /* Generic interleaving. */
11662 drflac_uint64 i;
11663 for (i = 0; i < frameCountThisIteration; ++i) {
11664 unsigned int j;
11665 for (j = 0; j < channelCount; ++j) {
11666 drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
11667 pBufferOut[(i*channelCount)+j] = (float)(sampleS32 / 2147483648.0);
11668 }
11669 }
11670 }
11671
11672 framesRead += frameCountThisIteration;
11673 pBufferOut += frameCountThisIteration * channelCount;
11674 framesToRead -= frameCountThisIteration;
11675 pFlac->currentPCMFrame += frameCountThisIteration;
11676 pFlac->currentFLACFrame.pcmFramesRemaining -= (unsigned int)frameCountThisIteration;
11677 }
11678 }
11679
11680 return framesRead;
11681 }
11682
11683
11684 DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
11685 {
11686 if (pFlac == NULL) {
11687 return DRFLAC_FALSE;
11688 }
11689
11690 /* Don't do anything if we're already on the seek point. */
11691 if (pFlac->currentPCMFrame == pcmFrameIndex) {
11692 return DRFLAC_TRUE;
11693 }
11694
11695 /*
11696 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
11697 when the decoder was opened.
11698 */
11699 if (pFlac->firstFLACFramePosInBytes == 0) {
11700 return DRFLAC_FALSE;
11701 }
11702
11703 if (pcmFrameIndex == 0) {
11704 pFlac->currentPCMFrame = 0;
11705 return drflac__seek_to_first_frame(pFlac);
11706 } else {
11707 drflac_bool32 wasSuccessful = DRFLAC_FALSE;
11708 drflac_uint64 originalPCMFrame = pFlac->currentPCMFrame;
11709
11710 /* Clamp the sample to the end. */
11711 if (pcmFrameIndex > pFlac->totalPCMFrameCount) {
11712 pcmFrameIndex = pFlac->totalPCMFrameCount;
11713 }
11714
11715 /* If the target sample and the current sample are in the same frame we just move the position forward. */
11716 if (pcmFrameIndex > pFlac->currentPCMFrame) {
11717 /* Forward. */
11718 drflac_uint32 offset = (drflac_uint32)(pcmFrameIndex - pFlac->currentPCMFrame);
11719 if (pFlac->currentFLACFrame.pcmFramesRemaining > offset) {
11720 pFlac->currentFLACFrame.pcmFramesRemaining -= offset;
11721 pFlac->currentPCMFrame = pcmFrameIndex;
11722 return DRFLAC_TRUE;
11723 }
11724 } else {
11725 /* Backward. */
11726 drflac_uint32 offsetAbs = (drflac_uint32)(pFlac->currentPCMFrame - pcmFrameIndex);
11727 drflac_uint32 currentFLACFramePCMFrameCount = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
11728 drflac_uint32 currentFLACFramePCMFramesConsumed = currentFLACFramePCMFrameCount - pFlac->currentFLACFrame.pcmFramesRemaining;
11729 if (currentFLACFramePCMFramesConsumed > offsetAbs) {
11730 pFlac->currentFLACFrame.pcmFramesRemaining += offsetAbs;
11731 pFlac->currentPCMFrame = pcmFrameIndex;
11732 return DRFLAC_TRUE;
11733 }
11734 }
11735
11736 /*
11737 Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so
11738 we'll instead use Ogg's natural seeking facility.
11739 */
11740 #ifndef DR_FLAC_NO_OGG
11741 if (pFlac->container == drflac_container_ogg)
11742 {
11743 wasSuccessful = drflac_ogg__seek_to_pcm_frame(pFlac, pcmFrameIndex);
11744 }
11745 else
11746 #endif
11747 {
11748 /* First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower. */
11749 if (/*!wasSuccessful && */!pFlac->_noSeekTableSeek) {
11750 wasSuccessful = drflac__seek_to_pcm_frame__seek_table(pFlac, pcmFrameIndex);
11751 }
11752
11753 #if !defined(DR_FLAC_NO_CRC)
11754 /* Fall back to binary search if seek table seeking fails. This requires the length of the stream to be known. */
11755 if (!wasSuccessful && !pFlac->_noBinarySearchSeek && pFlac->totalPCMFrameCount > 0) {
11756 wasSuccessful = drflac__seek_to_pcm_frame__binary_search(pFlac, pcmFrameIndex);
11757 }
11758 #endif
11759
11760 /* Fall back to brute force if all else fails. */
11761 if (!wasSuccessful && !pFlac->_noBruteForceSeek) {
11762 wasSuccessful = drflac__seek_to_pcm_frame__brute_force(pFlac, pcmFrameIndex);
11763 }
11764 }
11765
11766 if (wasSuccessful) {
11767 pFlac->currentPCMFrame = pcmFrameIndex;
11768 } else {
11769 /* Seek failed. Try putting the decoder back to it's original state. */
11770 if (drflac_seek_to_pcm_frame(pFlac, originalPCMFrame) == DRFLAC_FALSE) {
11771 /* Failed to seek back to the original PCM frame. Fall back to 0. */
11772 drflac_seek_to_pcm_frame(pFlac, 0);
11773 }
11774 }
11775
11776 return wasSuccessful;
11777 }
11778 }
11779
11780
11781
11782 /* High Level APIs */
11783
11784 /* SIZE_MAX */
11785 #if defined(SIZE_MAX)
11786 #define DRFLAC_SIZE_MAX SIZE_MAX
11787 #else
11788 #if defined(DRFLAC_64BIT)
11789 #define DRFLAC_SIZE_MAX ((drflac_uint64)0xFFFFFFFFFFFFFFFF)
11790 #else
11791 #define DRFLAC_SIZE_MAX 0xFFFFFFFF
11792 #endif
11793 #endif
11794 /* End SIZE_MAX */
11795
11796
11797 /* Using a macro as the definition of the drflac__full_decode_and_close_*() API family. Sue me. */
11798 #define DRFLAC_DEFINE_FULL_READ_AND_CLOSE(extension, type) \
11799 static type* drflac__full_read_and_close_ ## extension (drflac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut)\
11800 { \
11801 type* pSampleData = NULL; \
11802 drflac_uint64 totalPCMFrameCount; \
11803 type buffer[4096]; \
11804 drflac_uint64 pcmFramesRead; \
11805 size_t sampleDataBufferSize = sizeof(buffer); \
11806 \
11807 DRFLAC_ASSERT(pFlac != NULL); \
11808 \
11809 totalPCMFrameCount = 0; \
11810 \
11811 pSampleData = (type*)drflac__malloc_from_callbacks(sampleDataBufferSize, &pFlac->allocationCallbacks); \
11812 if (pSampleData == NULL) { \
11813 goto on_error; \
11814 } \
11815 \
11816 while ((pcmFramesRead = (drflac_uint64)drflac_read_pcm_frames_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0])/pFlac->channels, buffer)) > 0) { \
11817 if (((totalPCMFrameCount + pcmFramesRead) * pFlac->channels * sizeof(type)) > sampleDataBufferSize) { \
11818 type* pNewSampleData; \
11819 size_t newSampleDataBufferSize; \
11820 \
11821 newSampleDataBufferSize = sampleDataBufferSize * 2; \
11822 pNewSampleData = (type*)drflac__realloc_from_callbacks(pSampleData, newSampleDataBufferSize, sampleDataBufferSize, &pFlac->allocationCallbacks); \
11823 if (pNewSampleData == NULL) { \
11824 drflac__free_from_callbacks(pSampleData, &pFlac->allocationCallbacks); \
11825 goto on_error; \
11826 } \
11827 \
11828 sampleDataBufferSize = newSampleDataBufferSize; \
11829 pSampleData = pNewSampleData; \
11830 } \
11831 \
11832 DRFLAC_COPY_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), buffer, (size_t)(pcmFramesRead*pFlac->channels*sizeof(type))); \
11833 totalPCMFrameCount += pcmFramesRead; \
11834 } \
11835 \
11836 /* At this point everything should be decoded, but we just want to fill the unused part buffer with silence - need to \
11837 protect those ears from random noise! */ \
11838 DRFLAC_ZERO_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), (size_t)(sampleDataBufferSize - totalPCMFrameCount*pFlac->channels*sizeof(type))); \
11839 \
11840 if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \
11841 if (channelsOut) *channelsOut = pFlac->channels; \
11842 if (totalPCMFrameCountOut) *totalPCMFrameCountOut = totalPCMFrameCount; \
11843 \
11844 drflac_close(pFlac); \
11845 return pSampleData; \
11846 \
11847 on_error: \
11848 drflac_close(pFlac); \
11849 return NULL; \
11850 }
11851
11852 DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s32, drflac_int32)
11853 DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s16, drflac_int16)
11854 DRFLAC_DEFINE_FULL_READ_AND_CLOSE(f32, float)
11855
11856 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)
11857 {
11858 drflac* pFlac;
11859
11860 if (channelsOut) {
11861 *channelsOut = 0;
11862 }
11863 if (sampleRateOut) {
11864 *sampleRateOut = 0;
11865 }
11866 if (totalPCMFrameCountOut) {
11867 *totalPCMFrameCountOut = 0;
11868 }
11869
11870 pFlac = drflac_open(onRead, onSeek, onTell, pUserData, pAllocationCallbacks);
11871 if (pFlac == NULL) {
11872 return NULL;
11873 }
11874
11875 return drflac__full_read_and_close_s32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
11876 }
11877
11878 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)
11879 {
11880 drflac* pFlac;
11881
11882 if (channelsOut) {
11883 *channelsOut = 0;
11884 }
11885 if (sampleRateOut) {
11886 *sampleRateOut = 0;
11887 }
11888 if (totalPCMFrameCountOut) {
11889 *totalPCMFrameCountOut = 0;
11890 }
11891
11892 pFlac = drflac_open(onRead, onSeek, onTell, pUserData, pAllocationCallbacks);
11893 if (pFlac == NULL) {
11894 return NULL;
11895 }
11896
11897 return drflac__full_read_and_close_s16(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
11898 }
11899
11900 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)
11901 {
11902 drflac* pFlac;
11903
11904 if (channelsOut) {
11905 *channelsOut = 0;
11906 }
11907 if (sampleRateOut) {
11908 *sampleRateOut = 0;
11909 }
11910 if (totalPCMFrameCountOut) {
11911 *totalPCMFrameCountOut = 0;
11912 }
11913
11914 pFlac = drflac_open(onRead, onSeek, onTell, pUserData, pAllocationCallbacks);
11915 if (pFlac == NULL) {
11916 return NULL;
11917 }
11918
11919 return drflac__full_read_and_close_f32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
11920 }
11921
11922 #ifndef DR_FLAC_NO_STDIO
11923 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)
11924 {
11925 drflac* pFlac;
11926
11927 if (sampleRate) {
11928 *sampleRate = 0;
11929 }
11930 if (channels) {
11931 *channels = 0;
11932 }
11933 if (totalPCMFrameCount) {
11934 *totalPCMFrameCount = 0;
11935 }
11936
11937 pFlac = drflac_open_file(filename, pAllocationCallbacks);
11938 if (pFlac == NULL) {
11939 return NULL;
11940 }
11941
11942 return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
11943 }
11944
11945 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)
11946 {
11947 drflac* pFlac;
11948
11949 if (sampleRate) {
11950 *sampleRate = 0;
11951 }
11952 if (channels) {
11953 *channels = 0;
11954 }
11955 if (totalPCMFrameCount) {
11956 *totalPCMFrameCount = 0;
11957 }
11958
11959 pFlac = drflac_open_file(filename, pAllocationCallbacks);
11960 if (pFlac == NULL) {
11961 return NULL;
11962 }
11963
11964 return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
11965 }
11966
11967 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)
11968 {
11969 drflac* pFlac;
11970
11971 if (sampleRate) {
11972 *sampleRate = 0;
11973 }
11974 if (channels) {
11975 *channels = 0;
11976 }
11977 if (totalPCMFrameCount) {
11978 *totalPCMFrameCount = 0;
11979 }
11980
11981 pFlac = drflac_open_file(filename, pAllocationCallbacks);
11982 if (pFlac == NULL) {
11983 return NULL;
11984 }
11985
11986 return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
11987 }
11988 #endif
11989
11990 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)
11991 {
11992 drflac* pFlac;
11993
11994 if (sampleRate) {
11995 *sampleRate = 0;
11996 }
11997 if (channels) {
11998 *channels = 0;
11999 }
12000 if (totalPCMFrameCount) {
12001 *totalPCMFrameCount = 0;
12002 }
12003
12004 pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
12005 if (pFlac == NULL) {
12006 return NULL;
12007 }
12008
12009 return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
12010 }
12011
12012 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)
12013 {
12014 drflac* pFlac;
12015
12016 if (sampleRate) {
12017 *sampleRate = 0;
12018 }
12019 if (channels) {
12020 *channels = 0;
12021 }
12022 if (totalPCMFrameCount) {
12023 *totalPCMFrameCount = 0;
12024 }
12025
12026 pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
12027 if (pFlac == NULL) {
12028 return NULL;
12029 }
12030
12031 return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
12032 }
12033
12034 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)
12035 {
12036 drflac* pFlac;
12037
12038 if (sampleRate) {
12039 *sampleRate = 0;
12040 }
12041 if (channels) {
12042 *channels = 0;
12043 }
12044 if (totalPCMFrameCount) {
12045 *totalPCMFrameCount = 0;
12046 }
12047
12048 pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
12049 if (pFlac == NULL) {
12050 return NULL;
12051 }
12052
12053 return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
12054 }
12055
12056
12057 DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
12058 {
12059 if (pAllocationCallbacks != NULL) {
12060 drflac__free_from_callbacks(p, pAllocationCallbacks);
12061 } else {
12062 drflac__free_default(p, NULL);
12063 }
12064 }
12065
12066
12067
12068
12069 DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments)
12070 {
12071 if (pIter == NULL) {
12072 return;
12073 }
12074
12075 pIter->countRemaining = commentCount;
12076 pIter->pRunningData = (const char*)pComments;
12077 }
12078
12079 DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut)
12080 {
12081 drflac_int32 length;
12082 const char* pComment;
12083
12084 /* Safety. */
12085 if (pCommentLengthOut) {
12086 *pCommentLengthOut = 0;
12087 }
12088
12089 if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
12090 return NULL;
12091 }
12092
12093 length = drflac__le2host_32_ptr_unaligned(pIter->pRunningData);
12094 pIter->pRunningData += 4;
12095
12096 pComment = pIter->pRunningData;
12097 pIter->pRunningData += length;
12098 pIter->countRemaining -= 1;
12099
12100 if (pCommentLengthOut) {
12101 *pCommentLengthOut = length;
12102 }
12103
12104 return pComment;
12105 }
12106
12107
12108
12109
12110 DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData)
12111 {
12112 if (pIter == NULL) {
12113 return;
12114 }
12115
12116 pIter->countRemaining = trackCount;
12117 pIter->pRunningData = (const char*)pTrackData;
12118 }
12119
12120 DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack)
12121 {
12122 drflac_cuesheet_track cuesheetTrack;
12123 const char* pRunningData;
12124 drflac_uint64 offsetHi;
12125 drflac_uint64 offsetLo;
12126
12127 if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
12128 return DRFLAC_FALSE;
12129 }
12130
12131 pRunningData = pIter->pRunningData;
12132
12133 offsetHi = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
12134 offsetLo = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
12135 cuesheetTrack.offset = offsetLo | (offsetHi << 32);
12136 cuesheetTrack.trackNumber = pRunningData[0]; pRunningData += 1;
12137 DRFLAC_COPY_MEMORY(cuesheetTrack.ISRC, pRunningData, sizeof(cuesheetTrack.ISRC)); pRunningData += 12;
12138 cuesheetTrack.isAudio = (pRunningData[0] & 0x80) != 0;
12139 cuesheetTrack.preEmphasis = (pRunningData[0] & 0x40) != 0; pRunningData += 14;
12140 cuesheetTrack.indexCount = pRunningData[0]; pRunningData += 1;
12141 cuesheetTrack.pIndexPoints = (const drflac_cuesheet_track_index*)pRunningData; pRunningData += cuesheetTrack.indexCount * sizeof(drflac_cuesheet_track_index);
12142
12143 pIter->pRunningData = pRunningData;
12144 pIter->countRemaining -= 1;
12145
12146 if (pCuesheetTrack) {
12147 *pCuesheetTrack = cuesheetTrack;
12148 }
12149
12150 return DRFLAC_TRUE;
12151 }
12152
12153 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
12154 #pragma GCC diagnostic pop
12155 #endif
12156 #endif /* dr_flac_c */
12157 #endif /* DR_FLAC_IMPLEMENTATION */
12158
12159
12160 /*
12161 REVISION HISTORY
12162 ================
12163 v0.13.3 - 2026-01-17
12164 - Fix a compiler compatibility issue with some inlined assembly.
12165 - Fix a compilation warning.
12166
12167 v0.13.2 - 2025-12-02
12168 - Improve robustness of the parsing of picture metadata to improve support for memory constrained embedded devices.
12169 - Fix a warning about an assigned by unused variable.
12170 - Improvements to drflac_open_and_read_pcm_frames_*() and family to avoid excessively large memory allocations from malformed files.
12171
12172 v0.13.1 - 2025-09-10
12173 - Fix an error with the NXDK build.
12174
12175 v0.13.0 - 2025-07-23
12176 - API CHANGE: Seek origin enums have been renamed to match the naming convention used by other dr_libs libraries:
12177 - drflac_seek_origin_start -> DRFLAC_SEEK_SET
12178 - drflac_seek_origin_current -> DRFLAC_SEEK_CUR
12179 - DRFLAC_SEEK_END (new)
12180 - 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.
12181 - API CHANGE: An `onTell` callback has been added to the following functions:
12182 - drflac_open()
12183 - drflac_open_relaxed()
12184 - drflac_open_with_metadata()
12185 - drflac_open_with_metadata_relaxed()
12186 - drflac_open_and_read_pcm_frames_s32()
12187 - drflac_open_and_read_pcm_frames_s16()
12188 - drflac_open_and_read_pcm_frames_f32()
12189 - Fix compilation for AIX OS.
12190
12191 v0.12.43 - 2024-12-17
12192 - Fix a possible buffer overflow during decoding.
12193 - Improve detection of ARM64EC
12194
12195 v0.12.42 - 2023-11-02
12196 - Fix build for ARMv6-M.
12197 - Fix a compilation warning with GCC.
12198
12199 v0.12.41 - 2023-06-17
12200 - Fix an incorrect date in revision history. No functional change.
12201
12202 v0.12.40 - 2023-05-22
12203 - Minor code restructure. No functional change.
12204
12205 v0.12.39 - 2022-09-17
12206 - Fix compilation with DJGPP.
12207 - Fix compilation error with Visual Studio 2019 and the ARM build.
12208 - Fix an error with SSE 4.1 detection.
12209 - Add support for disabling wchar_t with DR_WAV_NO_WCHAR.
12210 - Improve compatibility with compilers which lack support for explicit struct packing.
12211 - Improve compatibility with low-end and embedded hardware by reducing the amount of stack
12212 allocation when loading an Ogg encapsulated file.
12213
12214 v0.12.38 - 2022-04-10
12215 - Fix compilation error on older versions of GCC.
12216
12217 v0.12.37 - 2022-02-12
12218 - Improve ARM detection.
12219
12220 v0.12.36 - 2022-02-07
12221 - Fix a compilation error with the ARM build.
12222
12223 v0.12.35 - 2022-02-06
12224 - Fix a bug due to underestimating the amount of precision required for the prediction stage.
12225 - Fix some bugs found from fuzz testing.
12226
12227 v0.12.34 - 2022-01-07
12228 - Fix some misalignment bugs when reading metadata.
12229
12230 v0.12.33 - 2021-12-22
12231 - Fix a bug with seeking when the seek table does not start at PCM frame 0.
12232
12233 v0.12.32 - 2021-12-11
12234 - Fix a warning with Clang.
12235
12236 v0.12.31 - 2021-08-16
12237 - Silence some warnings.
12238
12239 v0.12.30 - 2021-07-31
12240 - Fix platform detection for ARM64.
12241
12242 v0.12.29 - 2021-04-02
12243 - Fix a bug where the running PCM frame index is set to an invalid value when over-seeking.
12244 - Fix a decoding error due to an incorrect validation check.
12245
12246 v0.12.28 - 2021-02-21
12247 - Fix a warning due to referencing _MSC_VER when it is undefined.
12248
12249 v0.12.27 - 2021-01-31
12250 - Fix a static analysis warning.
12251
12252 v0.12.26 - 2021-01-17
12253 - Fix a compilation warning due to _BSD_SOURCE being deprecated.
12254
12255 v0.12.25 - 2020-12-26
12256 - Update documentation.
12257
12258 v0.12.24 - 2020-11-29
12259 - Fix ARM64/NEON detection when compiling with MSVC.
12260
12261 v0.12.23 - 2020-11-21
12262 - Fix compilation with OpenWatcom.
12263
12264 v0.12.22 - 2020-11-01
12265 - Fix an error with the previous release.
12266
12267 v0.12.21 - 2020-11-01
12268 - Fix a possible deadlock when seeking.
12269 - Improve compiler support for older versions of GCC.
12270
12271 v0.12.20 - 2020-09-08
12272 - Fix a compilation error on older compilers.
12273
12274 v0.12.19 - 2020-08-30
12275 - Fix a bug due to an undefined 32-bit shift.
12276
12277 v0.12.18 - 2020-08-14
12278 - Fix a crash when compiling with clang-cl.
12279
12280 v0.12.17 - 2020-08-02
12281 - Simplify sized types.
12282
12283 v0.12.16 - 2020-07-25
12284 - Fix a compilation warning.
12285
12286 v0.12.15 - 2020-07-06
12287 - Check for negative LPC shifts and return an error.
12288
12289 v0.12.14 - 2020-06-23
12290 - Add include guard for the implementation section.
12291
12292 v0.12.13 - 2020-05-16
12293 - Add compile-time and run-time version querying.
12294 - DRFLAC_VERSION_MINOR
12295 - DRFLAC_VERSION_MAJOR
12296 - DRFLAC_VERSION_REVISION
12297 - DRFLAC_VERSION_STRING
12298 - drflac_version()
12299 - drflac_version_string()
12300
12301 v0.12.12 - 2020-04-30
12302 - Fix compilation errors with VC6.
12303
12304 v0.12.11 - 2020-04-19
12305 - Fix some pedantic warnings.
12306 - Fix some undefined behaviour warnings.
12307
12308 v0.12.10 - 2020-04-10
12309 - Fix some bugs when trying to seek with an invalid seek table.
12310
12311 v0.12.9 - 2020-04-05
12312 - Fix warnings.
12313
12314 v0.12.8 - 2020-04-04
12315 - Add drflac_open_file_w() and drflac_open_file_with_metadata_w().
12316 - Fix some static analysis warnings.
12317 - Minor documentation updates.
12318
12319 v0.12.7 - 2020-03-14
12320 - Fix compilation errors with VC6.
12321
12322 v0.12.6 - 2020-03-07
12323 - Fix compilation error with Visual Studio .NET 2003.
12324
12325 v0.12.5 - 2020-01-30
12326 - Silence some static analysis warnings.
12327
12328 v0.12.4 - 2020-01-29
12329 - Silence some static analysis warnings.
12330
12331 v0.12.3 - 2019-12-02
12332 - Fix some warnings when compiling with GCC and the -Og flag.
12333 - Fix a crash in out-of-memory situations.
12334 - Fix potential integer overflow bug.
12335 - Fix some static analysis warnings.
12336 - Fix a possible crash when using custom memory allocators without a custom realloc() implementation.
12337 - Fix a bug with binary search seeking where the bits per sample is not a multiple of 8.
12338
12339 v0.12.2 - 2019-10-07
12340 - Internal code clean up.
12341
12342 v0.12.1 - 2019-09-29
12343 - Fix some Clang Static Analyzer warnings.
12344 - Fix an unused variable warning.
12345
12346 v0.12.0 - 2019-09-23
12347 - API CHANGE: Add support for user defined memory allocation routines. This system allows the program to specify their own memory allocation
12348 routines with a user data pointer for client-specific contextual data. This adds an extra parameter to the end of the following APIs:
12349 - drflac_open()
12350 - drflac_open_relaxed()
12351 - drflac_open_with_metadata()
12352 - drflac_open_with_metadata_relaxed()
12353 - drflac_open_file()
12354 - drflac_open_file_with_metadata()
12355 - drflac_open_memory()
12356 - drflac_open_memory_with_metadata()
12357 - drflac_open_and_read_pcm_frames_s32()
12358 - drflac_open_and_read_pcm_frames_s16()
12359 - drflac_open_and_read_pcm_frames_f32()
12360 - drflac_open_file_and_read_pcm_frames_s32()
12361 - drflac_open_file_and_read_pcm_frames_s16()
12362 - drflac_open_file_and_read_pcm_frames_f32()
12363 - drflac_open_memory_and_read_pcm_frames_s32()
12364 - drflac_open_memory_and_read_pcm_frames_s16()
12365 - drflac_open_memory_and_read_pcm_frames_f32()
12366 Set this extra parameter to NULL to use defaults which is the same as the previous behaviour. Setting this NULL will use
12367 DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE.
12368 - Remove deprecated APIs:
12369 - drflac_read_s32()
12370 - drflac_read_s16()
12371 - drflac_read_f32()
12372 - drflac_seek_to_sample()
12373 - drflac_open_and_decode_s32()
12374 - drflac_open_and_decode_s16()
12375 - drflac_open_and_decode_f32()
12376 - drflac_open_and_decode_file_s32()
12377 - drflac_open_and_decode_file_s16()
12378 - drflac_open_and_decode_file_f32()
12379 - drflac_open_and_decode_memory_s32()
12380 - drflac_open_and_decode_memory_s16()
12381 - drflac_open_and_decode_memory_f32()
12382 - Remove drflac.totalSampleCount which is now replaced with drflac.totalPCMFrameCount. You can emulate drflac.totalSampleCount
12383 by doing pFlac->totalPCMFrameCount*pFlac->channels.
12384 - Rename drflac.currentFrame to drflac.currentFLACFrame to remove ambiguity with PCM frames.
12385 - Fix errors when seeking to the end of a stream.
12386 - Optimizations to seeking.
12387 - SSE improvements and optimizations.
12388 - ARM NEON optimizations.
12389 - Optimizations to drflac_read_pcm_frames_s16().
12390 - Optimizations to drflac_read_pcm_frames_s32().
12391
12392 v0.11.10 - 2019-06-26
12393 - Fix a compiler error.
12394
12395 v0.11.9 - 2019-06-16
12396 - Silence some ThreadSanitizer warnings.
12397
12398 v0.11.8 - 2019-05-21
12399 - Fix warnings.
12400
12401 v0.11.7 - 2019-05-06
12402 - C89 fixes.
12403
12404 v0.11.6 - 2019-05-05
12405 - Add support for C89.
12406 - Fix a compiler warning when CRC is disabled.
12407 - Change license to choice of public domain or MIT-0.
12408
12409 v0.11.5 - 2019-04-19
12410 - Fix a compiler error with GCC.
12411
12412 v0.11.4 - 2019-04-17
12413 - Fix some warnings with GCC when compiling with -std=c99.
12414
12415 v0.11.3 - 2019-04-07
12416 - Silence warnings with GCC.
12417
12418 v0.11.2 - 2019-03-10
12419 - Fix a warning.
12420
12421 v0.11.1 - 2019-02-17
12422 - Fix a potential bug with seeking.
12423
12424 v0.11.0 - 2018-12-16
12425 - API CHANGE: Deprecated drflac_read_s32(), drflac_read_s16() and drflac_read_f32() and replaced them with
12426 drflac_read_pcm_frames_s32(), drflac_read_pcm_frames_s16() and drflac_read_pcm_frames_f32(). The new APIs take
12427 and return PCM frame counts instead of sample counts. To upgrade you will need to change the input count by
12428 dividing it by the channel count, and then do the same with the return value.
12429 - API_CHANGE: Deprecated drflac_seek_to_sample() and replaced with drflac_seek_to_pcm_frame(). Same rules as
12430 the changes to drflac_read_*() apply.
12431 - API CHANGE: Deprecated drflac_open_and_decode_*() and replaced with drflac_open_*_and_read_*(). Same rules as
12432 the changes to drflac_read_*() apply.
12433 - Optimizations.
12434
12435 v0.10.0 - 2018-09-11
12436 - Remove the DR_FLAC_NO_WIN32_IO option and the Win32 file IO functionality. If you need to use Win32 file IO you
12437 need to do it yourself via the callback API.
12438 - Fix the clang build.
12439 - Fix undefined behavior.
12440 - Fix errors with CUESHEET metdata blocks.
12441 - Add an API for iterating over each cuesheet track in the CUESHEET metadata block. This works the same way as the
12442 Vorbis comment API.
12443 - Other miscellaneous bug fixes, mostly relating to invalid FLAC streams.
12444 - Minor optimizations.
12445
12446 v0.9.11 - 2018-08-29
12447 - Fix a bug with sample reconstruction.
12448
12449 v0.9.10 - 2018-08-07
12450 - Improve 64-bit detection.
12451
12452 v0.9.9 - 2018-08-05
12453 - Fix C++ build on older versions of GCC.
12454
12455 v0.9.8 - 2018-07-24
12456 - Fix compilation errors.
12457
12458 v0.9.7 - 2018-07-05
12459 - Fix a warning.
12460
12461 v0.9.6 - 2018-06-29
12462 - Fix some typos.
12463
12464 v0.9.5 - 2018-06-23
12465 - Fix some warnings.
12466
12467 v0.9.4 - 2018-06-14
12468 - Optimizations to seeking.
12469 - Clean up.
12470
12471 v0.9.3 - 2018-05-22
12472 - Bug fix.
12473
12474 v0.9.2 - 2018-05-12
12475 - Fix a compilation error due to a missing break statement.
12476
12477 v0.9.1 - 2018-04-29
12478 - Fix compilation error with Clang.
12479
12480 v0.9 - 2018-04-24
12481 - Fix Clang build.
12482 - Start using major.minor.revision versioning.
12483
12484 v0.8g - 2018-04-19
12485 - Fix build on non-x86/x64 architectures.
12486
12487 v0.8f - 2018-02-02
12488 - Stop pretending to support changing rate/channels mid stream.
12489
12490 v0.8e - 2018-02-01
12491 - Fix a crash when the block size of a frame is larger than the maximum block size defined by the FLAC stream.
12492 - Fix a crash the the Rice partition order is invalid.
12493
12494 v0.8d - 2017-09-22
12495 - Add support for decoding streams with ID3 tags. ID3 tags are just skipped.
12496
12497 v0.8c - 2017-09-07
12498 - Fix warning on non-x86/x64 architectures.
12499
12500 v0.8b - 2017-08-19
12501 - Fix build on non-x86/x64 architectures.
12502
12503 v0.8a - 2017-08-13
12504 - A small optimization for the Clang build.
12505
12506 v0.8 - 2017-08-12
12507 - API CHANGE: Rename dr_* types to drflac_*.
12508 - Optimizations. This brings dr_flac back to about the same class of efficiency as the reference implementation.
12509 - Add support for custom implementations of malloc(), realloc(), etc.
12510 - Add CRC checking to Ogg encapsulated streams.
12511 - Fix VC++ 6 build. This is only for the C++ compiler. The C compiler is not currently supported.
12512 - Bug fixes.
12513
12514 v0.7 - 2017-07-23
12515 - Add support for opening a stream without a header block. To do this, use drflac_open_relaxed() / drflac_open_with_metadata_relaxed().
12516
12517 v0.6 - 2017-07-22
12518 - Add support for recovering from invalid frames. With this change, dr_flac will simply skip over invalid frames as if they
12519 never existed. Frames are checked against their sync code, the CRC-8 of the frame header and the CRC-16 of the whole frame.
12520
12521 v0.5 - 2017-07-16
12522 - Fix typos.
12523 - Change drflac_bool* types to unsigned.
12524 - Add CRC checking. This makes dr_flac slower, but can be disabled with #define DR_FLAC_NO_CRC.
12525
12526 v0.4f - 2017-03-10
12527 - Fix a couple of bugs with the bitstreaming code.
12528
12529 v0.4e - 2017-02-17
12530 - Fix some warnings.
12531
12532 v0.4d - 2016-12-26
12533 - Add support for 32-bit floating-point PCM decoding.
12534 - Use drflac_int* and drflac_uint* sized types to improve compiler support.
12535 - Minor improvements to documentation.
12536
12537 v0.4c - 2016-12-26
12538 - Add support for signed 16-bit integer PCM decoding.
12539
12540 v0.4b - 2016-10-23
12541 - A minor change to drflac_bool8 and drflac_bool32 types.
12542
12543 v0.4a - 2016-10-11
12544 - Rename drBool32 to drflac_bool32 for styling consistency.
12545
12546 v0.4 - 2016-09-29
12547 - API/ABI CHANGE: Use fixed size 32-bit booleans instead of the built-in bool type.
12548 - API CHANGE: Rename drflac_open_and_decode*() to drflac_open_and_decode*_s32().
12549 - API CHANGE: Swap the order of "channels" and "sampleRate" parameters in drflac_open_and_decode*(). Rationale for this is to
12550 keep it consistent with drflac_audio.
12551
12552 v0.3f - 2016-09-21
12553 - Fix a warning with GCC.
12554
12555 v0.3e - 2016-09-18
12556 - Fixed a bug where GCC 4.3+ was not getting properly identified.
12557 - Fixed a few typos.
12558 - Changed date formats to ISO 8601 (YYYY-MM-DD).
12559
12560 v0.3d - 2016-06-11
12561 - Minor clean up.
12562
12563 v0.3c - 2016-05-28
12564 - Fixed compilation error.
12565
12566 v0.3b - 2016-05-16
12567 - Fixed Linux/GCC build.
12568 - Updated documentation.
12569
12570 v0.3a - 2016-05-15
12571 - Minor fixes to documentation.
12572
12573 v0.3 - 2016-05-11
12574 - Optimizations. Now at about parity with the reference implementation on 32-bit builds.
12575 - Lots of clean up.
12576
12577 v0.2b - 2016-05-10
12578 - Bug fixes.
12579
12580 v0.2a - 2016-05-10
12581 - Made drflac_open_and_decode() more robust.
12582 - Removed an unused debugging variable
12583
12584 v0.2 - 2016-05-09
12585 - Added support for Ogg encapsulation.
12586 - API CHANGE. Have the onSeek callback take a third argument which specifies whether or not the seek
12587 should be relative to the start or the current position. Also changes the seeking rules such that
12588 seeking offsets will never be negative.
12589 - Have drflac_open_and_decode() fail gracefully if the stream has an unknown total sample count.
12590
12591 v0.1b - 2016-05-07
12592 - Properly close the file handle in drflac_open_file() and family when the decoder fails to initialize.
12593 - Removed a stale comment.
12594
12595 v0.1a - 2016-05-05
12596 - Minor formatting changes.
12597 - Fixed a warning on the GCC build.
12598
12599 v0.1 - 2016-05-03
12600 - Initial versioned release.
12601 */
12602
12603 /*
12604 This software is available as a choice of the following licenses. Choose
12605 whichever you prefer.
12606
12607 ===============================================================================
12608 ALTERNATIVE 1 - Public Domain (www.unlicense.org)
12609 ===============================================================================
12610 This is free and unencumbered software released into the public domain.
12611
12612 Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
12613 software, either in source code form or as a compiled binary, for any purpose,
12614 commercial or non-commercial, and by any means.
12615
12616 In jurisdictions that recognize copyright laws, the author or authors of this
12617 software dedicate any and all copyright interest in the software to the public
12618 domain. We make this dedication for the benefit of the public at large and to
12619 the detriment of our heirs and successors. We intend this dedication to be an
12620 overt act of relinquishment in perpetuity of all present and future rights to
12621 this software under copyright law.
12622
12623 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12624 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12625 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12626 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
12627 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
12628 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12629
12630 For more information, please refer to <http://unlicense.org/>
12631
12632 ===============================================================================
12633 ALTERNATIVE 2 - MIT No Attribution
12634 ===============================================================================
12635 Copyright 2023 David Reid
12636
12637 Permission is hereby granted, free of charge, to any person obtaining a copy of
12638 this software and associated documentation files (the "Software"), to deal in
12639 the Software without restriction, including without limitation the rights to
12640 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
12641 of the Software, and to permit persons to whom the Software is furnished to do
12642 so.
12643
12644 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12645 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12646 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12647 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12648 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12649 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
12650 SOFTWARE.
12651 */