Debian Codegraph @

SDL_audiolib/3rdparty/dr_libs/dr_flac.h

raw symbols SCIP
1 /*
2 FLAC audio decoder. Choice of public domain or MIT-0. See license statements at the end of this file.
3 dr_flac - v0.12.38 - 2022-04-10
4
5 David Reid - [email protected]
6
7 GitHub: https://github.com/mackron/dr_libs
8 */
9
10 /*
11 RELEASE NOTES - v0.12.0
12 =======================
13 Version 0.12.0 has breaking API changes including changes to the existing API and the removal of deprecated APIs.
14
15
16 Improved Client-Defined Memory Allocation
17 -----------------------------------------
18 The main change with this release is the addition of a more flexible way of implementing custom memory allocation routines. The
19 existing system of DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE are still in place and will be used by default when no custom
20 allocation callbacks are specified.
21
22 To use the new system, you pass in a pointer to a drflac_allocation_callbacks object to drflac_open() and family, like this:
23
24 void* my_malloc(size_t sz, void* pUserData)
25 {
26 return malloc(sz);
27 }
28 void* my_realloc(void* p, size_t sz, void* pUserData)
29 {
30 return realloc(p, sz);
31 }
32 void my_free(void* p, void* pUserData)
33 {
34 free(p);
35 }
36
37 ...
38
39 drflac_allocation_callbacks allocationCallbacks;
40 allocationCallbacks.pUserData = &myData;
41 allocationCallbacks.onMalloc = my_malloc;
42 allocationCallbacks.onRealloc = my_realloc;
43 allocationCallbacks.onFree = my_free;
44 drflac* pFlac = drflac_open_file("my_file.flac", &allocationCallbacks);
45
46 The advantage of this new system is that it allows you to specify user data which will be passed in to the allocation routines.
47
48 Passing in null for the allocation callbacks object will cause dr_flac to use defaults which is the same as DRFLAC_MALLOC,
49 DRFLAC_REALLOC and DRFLAC_FREE and the equivalent of how it worked in previous versions.
50
51 Every API that opens a drflac object now takes this extra parameter. These include the following:
52
53 drflac_open()
54 drflac_open_relaxed()
55 drflac_open_with_metadata()
56 drflac_open_with_metadata_relaxed()
57 drflac_open_file()
58 drflac_open_file_with_metadata()
59 drflac_open_memory()
60 drflac_open_memory_with_metadata()
61 drflac_open_and_read_pcm_frames_s32()
62 drflac_open_and_read_pcm_frames_s16()
63 drflac_open_and_read_pcm_frames_f32()
64 drflac_open_file_and_read_pcm_frames_s32()
65 drflac_open_file_and_read_pcm_frames_s16()
66 drflac_open_file_and_read_pcm_frames_f32()
67 drflac_open_memory_and_read_pcm_frames_s32()
68 drflac_open_memory_and_read_pcm_frames_s16()
69 drflac_open_memory_and_read_pcm_frames_f32()
70
71
72
73 Optimizations
74 -------------
75 Seeking performance has been greatly improved. A new binary search based seeking algorithm has been introduced which significantly
76 improves performance over the brute force method which was used when no seek table was present. Seek table based seeking also takes
77 advantage of the new binary search seeking system to further improve performance there as well. Note that this depends on CRC which
78 means it will be disabled when DR_FLAC_NO_CRC is used.
79
80 The SSE4.1 pipeline has been cleaned up and optimized. You should see some improvements with decoding speed of 24-bit files in
81 particular. 16-bit streams should also see some improvement.
82
83 drflac_read_pcm_frames_s16() has been optimized. Previously this sat on top of drflac_read_pcm_frames_s32() and performed it's s32
84 to s16 conversion in a second pass. This is now all done in a single pass. This includes SSE2 and ARM NEON optimized paths.
85
86 A minor optimization has been implemented for drflac_read_pcm_frames_s32(). This will now use an SSE2 optimized pipeline for stereo
87 channel reconstruction which is the last part of the decoding process.
88
89 The ARM build has seen a few improvements. The CLZ (count leading zeroes) and REV (byte swap) instructions are now used when
90 compiling with GCC and Clang which is achieved using inline assembly. The CLZ instruction requires ARM architecture version 5 at
91 compile time and the REV instruction requires ARM architecture version 6.
92
93 An ARM NEON optimized pipeline has been implemented. To enable this you'll need to add -mfpu=neon to the command line when compiling.
94
95
96 Removed APIs
97 ------------
98 The following APIs were deprecated in version 0.11.0 and have been completely removed in version 0.12.0:
99
100 drflac_read_s32() -> drflac_read_pcm_frames_s32()
101 drflac_read_s16() -> drflac_read_pcm_frames_s16()
102 drflac_read_f32() -> drflac_read_pcm_frames_f32()
103 drflac_seek_to_sample() -> drflac_seek_to_pcm_frame()
104 drflac_open_and_decode_s32() -> drflac_open_and_read_pcm_frames_s32()
105 drflac_open_and_decode_s16() -> drflac_open_and_read_pcm_frames_s16()
106 drflac_open_and_decode_f32() -> drflac_open_and_read_pcm_frames_f32()
107 drflac_open_and_decode_file_s32() -> drflac_open_file_and_read_pcm_frames_s32()
108 drflac_open_and_decode_file_s16() -> drflac_open_file_and_read_pcm_frames_s16()
109 drflac_open_and_decode_file_f32() -> drflac_open_file_and_read_pcm_frames_f32()
110 drflac_open_and_decode_memory_s32() -> drflac_open_memory_and_read_pcm_frames_s32()
111 drflac_open_and_decode_memory_s16() -> drflac_open_memory_and_read_pcm_frames_s16()
112 drflac_open_and_decode_memory_f32() -> drflac_open_memroy_and_read_pcm_frames_f32()
113
114 Prior versions of dr_flac operated on a per-sample basis whereas now it operates on PCM frames. The removed APIs all relate
115 to the old per-sample APIs. You now need to use the "pcm_frame" versions.
116 */
117
118
119 /*
120 Introduction
121 ============
122 dr_flac is a single file library. To use it, do something like the following in one .c file.
123
124 ```c
125 #define DR_FLAC_IMPLEMENTATION
126 #include "dr_flac.h"
127 ```
128
129 You can then #include this file in other parts of the program as you would with any other header file. To decode audio data, do something like the following:
130
131 ```c
132 drflac* pFlac = drflac_open_file("MySong.flac", NULL);
133 if (pFlac == NULL) {
134 // Failed to open FLAC file
135 }
136
137 drflac_int32* pSamples = malloc(pFlac->totalPCMFrameCount * pFlac->channels * sizeof(drflac_int32));
138 drflac_uint64 numberOfInterleavedSamplesActuallyRead = drflac_read_pcm_frames_s32(pFlac, pFlac->totalPCMFrameCount, pSamples);
139 ```
140
141 The drflac object represents the decoder. It is a transparent type so all the information you need, such as the number of channels and the bits per sample,
142 should be directly accessible - just make sure you don't change their values. Samples are always output as interleaved signed 32-bit PCM. In the example above
143 a native FLAC stream was opened, however dr_flac has seamless support for Ogg encapsulated FLAC streams as well.
144
145 You do not need to decode the entire stream in one go - you just specify how many samples you'd like at any given time and the decoder will give you as many
146 samples as it can, up to the amount requested. Later on when you need the next batch of samples, just call it again. Example:
147
148 ```c
149 while (drflac_read_pcm_frames_s32(pFlac, chunkSizeInPCMFrames, pChunkSamples) > 0) {
150 do_something();
151 }
152 ```
153
154 You can seek to a specific PCM frame with `drflac_seek_to_pcm_frame()`.
155
156 If you just want to quickly decode an entire FLAC file in one go you can do something like this:
157
158 ```c
159 unsigned int channels;
160 unsigned int sampleRate;
161 drflac_uint64 totalPCMFrameCount;
162 drflac_int32* pSampleData = drflac_open_file_and_read_pcm_frames_s32("MySong.flac", &channels, &sampleRate, &totalPCMFrameCount, NULL);
163 if (pSampleData == NULL) {
164 // Failed to open and decode FLAC file.
165 }
166
167 ...
168
169 drflac_free(pSampleData, NULL);
170 ```
171
172 You can read samples as signed 16-bit integer and 32-bit floating-point PCM with the *_s16() and *_f32() family of APIs respectively, but note that these
173 should be considered lossy.
174
175
176 If you need access to metadata (album art, etc.), use `drflac_open_with_metadata()`, `drflac_open_file_with_metdata()` or `drflac_open_memory_with_metadata()`.
177 The rationale for keeping these APIs separate is that they're slightly slower than the normal versions and also just a little bit harder to use. dr_flac
178 reports metadata to the application through the use of a callback, and every metadata block is reported before `drflac_open_with_metdata()` returns.
179
180 The main opening APIs (`drflac_open()`, etc.) will fail if the header is not present. The presents a problem in certain scenarios such as broadcast style
181 streams or internet radio where the header may not be present because the user has started playback mid-stream. To handle this, use the relaxed APIs:
182
183 `drflac_open_relaxed()`
184 `drflac_open_with_metadata_relaxed()`
185
186 It is not recommended to use these APIs for file based streams because a missing header would usually indicate a corrupt or perverse file. In addition, these
187 APIs can take a long time to initialize because they may need to spend a lot of time finding the first frame.
188
189
190
191 Build Options
192 =============
193 #define these options before including this file.
194
195 #define DR_FLAC_NO_STDIO
196 Disable `drflac_open_file()` and family.
197
198 #define DR_FLAC_NO_OGG
199 Disables support for Ogg/FLAC streams.
200
201 #define DR_FLAC_BUFFER_SIZE <number>
202 Defines the size of the internal buffer to store data from onRead(). This buffer is used to reduce the number of calls back to the client for more data.
203 Larger values means more memory, but better performance. My tests show diminishing returns after about 4KB (which is the default). Consider reducing this if
204 you have a very efficient implementation of onRead(), or increase it if it's very inefficient. Must be a multiple of 8.
205
206 #define DR_FLAC_NO_CRC
207 Disables CRC checks. This will offer a performance boost when CRC is unnecessary. This will disable binary search seeking. When seeking, the seek table will
208 be used if available. Otherwise the seek will be performed using brute force.
209
210 #define DR_FLAC_NO_SIMD
211 Disables SIMD optimizations (SSE on x86/x64 architectures, NEON on ARM architectures). Use this if you are having compatibility issues with your compiler.
212
213
214
215 Notes
216 =====
217 - dr_flac does not support changing the sample rate nor channel count mid stream.
218 - dr_flac is not thread-safe, but its APIs can be called from any thread so long as you do your own synchronization.
219 - When using Ogg encapsulation, a corrupted metadata block will result in `drflac_open_with_metadata()` and `drflac_open()` returning inconsistent samples due
220 to differences in corrupted stream recorvery logic between the two APIs.
221 */
222
223 #ifndef dr_flac_h
224 #define dr_flac_h
225
226 #ifdef __cplusplus
227 extern "C" {
228 #endif
229
230 #define DRFLAC_STRINGIFY(x) #x
231 #define DRFLAC_XSTRINGIFY(x) DRFLAC_STRINGIFY(x)
232
233 #define DRFLAC_VERSION_MAJOR 0
234 #define DRFLAC_VERSION_MINOR 12
235 #define DRFLAC_VERSION_REVISION 38
236 #define DRFLAC_VERSION_STRING DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MAJOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MINOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_REVISION)
237
238 #include <stddef.h> /* For size_t. */
239
240 /* Sized types. */
241 typedef signed char drflac_int8;
242 typedef unsigned char drflac_uint8;
243 typedef signed short drflac_int16;
244 typedef unsigned short drflac_uint16;
245 typedef signed int drflac_int32;
246 typedef unsigned int drflac_uint32;
247 #if defined(_MSC_VER) && !defined(__clang__)
248 typedef signed __int64 drflac_int64;
249 typedef unsigned __int64 drflac_uint64;
250 #else
251 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
252 #pragma GCC diagnostic push
253 #pragma GCC diagnostic ignored "-Wlong-long"
254 #if defined(__clang__)
255 #pragma GCC diagnostic ignored "-Wc++11-long-long"
256 #endif
257 #endif
258 typedef signed long long drflac_int64;
259 typedef unsigned long long drflac_uint64;
260 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
261 #pragma GCC diagnostic pop
262 #endif
263 #endif
264 #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__)
265 typedef drflac_uint64 drflac_uintptr;
266 #else
267 typedef drflac_uint32 drflac_uintptr;
268 #endif
269 typedef drflac_uint8 drflac_bool8;
270 typedef drflac_uint32 drflac_bool32;
271 #define DRFLAC_TRUE 1
272 #define DRFLAC_FALSE 0
273
274 #if !defined(DRFLAC_API)
275 #if defined(DRFLAC_DLL)
276 #if defined(_WIN32)
277 #define DRFLAC_DLL_IMPORT __declspec(dllimport)
278 #define DRFLAC_DLL_EXPORT __declspec(dllexport)
279 #define DRFLAC_DLL_PRIVATE static
280 #else
281 #if defined(__GNUC__) && __GNUC__ >= 4
282 #define DRFLAC_DLL_IMPORT __attribute__((visibility("default")))
283 #define DRFLAC_DLL_EXPORT __attribute__((visibility("default")))
284 #define DRFLAC_DLL_PRIVATE __attribute__((visibility("hidden")))
285 #else
286 #define DRFLAC_DLL_IMPORT
287 #define DRFLAC_DLL_EXPORT
288 #define DRFLAC_DLL_PRIVATE static
289 #endif
290 #endif
291
292 #if defined(DR_FLAC_IMPLEMENTATION) || defined(DRFLAC_IMPLEMENTATION)
293 #define DRFLAC_API DRFLAC_DLL_EXPORT
294 #else
295 #define DRFLAC_API DRFLAC_DLL_IMPORT
296 #endif
297 #define DRFLAC_PRIVATE DRFLAC_DLL_PRIVATE
298 #else
299 #define DRFLAC_API extern
300 #define DRFLAC_PRIVATE static
301 #endif
302 #endif
303
304 #if defined(_MSC_VER) && _MSC_VER >= 1700 /* Visual Studio 2012 */
305 #define DRFLAC_DEPRECATED __declspec(deprecated)
306 #elif (defined(__GNUC__) && __GNUC__ >= 4) /* GCC 4 */
307 #define DRFLAC_DEPRECATED __attribute__((deprecated))
308 #elif defined(__has_feature) /* Clang */
309 #if __has_feature(attribute_deprecated)
310 #define DRFLAC_DEPRECATED __attribute__((deprecated))
311 #else
312 #define DRFLAC_DEPRECATED
313 #endif
314 #else
315 #define DRFLAC_DEPRECATED
316 #endif
317
318 DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision);
319 DRFLAC_API const char* drflac_version_string(void);
320
321 /*
322 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,
323 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.
324 */
325 #ifndef DR_FLAC_BUFFER_SIZE
326 #define DR_FLAC_BUFFER_SIZE 4096
327 #endif
328
329 /* Check if we can enable 64-bit optimizations. */
330 #if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
331 #define DRFLAC_64BIT
332 #endif
333
334 #ifdef DRFLAC_64BIT
335 typedef drflac_uint64 drflac_cache_t;
336 #else
337 typedef drflac_uint32 drflac_cache_t;
338 #endif
339
340 /* The various metadata block types. */
341 #define DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO 0
342 #define DRFLAC_METADATA_BLOCK_TYPE_PADDING 1
343 #define DRFLAC_METADATA_BLOCK_TYPE_APPLICATION 2
344 #define DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE 3
345 #define DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT 4
346 #define DRFLAC_METADATA_BLOCK_TYPE_CUESHEET 5
347 #define DRFLAC_METADATA_BLOCK_TYPE_PICTURE 6
348 #define DRFLAC_METADATA_BLOCK_TYPE_INVALID 127
349
350 /* The various picture types specified in the PICTURE block. */
351 #define DRFLAC_PICTURE_TYPE_OTHER 0
352 #define DRFLAC_PICTURE_TYPE_FILE_ICON 1
353 #define DRFLAC_PICTURE_TYPE_OTHER_FILE_ICON 2
354 #define DRFLAC_PICTURE_TYPE_COVER_FRONT 3
355 #define DRFLAC_PICTURE_TYPE_COVER_BACK 4
356 #define DRFLAC_PICTURE_TYPE_LEAFLET_PAGE 5
357 #define DRFLAC_PICTURE_TYPE_MEDIA 6
358 #define DRFLAC_PICTURE_TYPE_LEAD_ARTIST 7
359 #define DRFLAC_PICTURE_TYPE_ARTIST 8
360 #define DRFLAC_PICTURE_TYPE_CONDUCTOR 9
361 #define DRFLAC_PICTURE_TYPE_BAND 10
362 #define DRFLAC_PICTURE_TYPE_COMPOSER 11
363 #define DRFLAC_PICTURE_TYPE_LYRICIST 12
364 #define DRFLAC_PICTURE_TYPE_RECORDING_LOCATION 13
365 #define DRFLAC_PICTURE_TYPE_DURING_RECORDING 14
366 #define DRFLAC_PICTURE_TYPE_DURING_PERFORMANCE 15
367 #define DRFLAC_PICTURE_TYPE_SCREEN_CAPTURE 16
368 #define DRFLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH 17
369 #define DRFLAC_PICTURE_TYPE_ILLUSTRATION 18
370 #define DRFLAC_PICTURE_TYPE_BAND_LOGOTYPE 19
371 #define DRFLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE 20
372
373 typedef enum
374 {
375 drflac_container_native,
376 drflac_container_ogg,
377 drflac_container_unknown
378 } drflac_container;
379
380 typedef enum
381 {
382 drflac_seek_origin_start,
383 drflac_seek_origin_current
384 } drflac_seek_origin;
385
386 /* Packing is important on this structure because we map this directly to the raw data within the SEEKTABLE metadata block. */
387 #pragma pack(2)
388 typedef struct
389 {
390 drflac_uint64 firstPCMFrame;
391 drflac_uint64 flacFrameOffset; /* The offset from the first byte of the header of the first frame. */
392 drflac_uint16 pcmFrameCount;
393 } drflac_seekpoint;
394 #pragma pack()
395
396 typedef struct
397 {
398 drflac_uint16 minBlockSizeInPCMFrames;
399 drflac_uint16 maxBlockSizeInPCMFrames;
400 drflac_uint32 minFrameSizeInPCMFrames;
401 drflac_uint32 maxFrameSizeInPCMFrames;
402 drflac_uint32 sampleRate;
403 drflac_uint8 channels;
404 drflac_uint8 bitsPerSample;
405 drflac_uint64 totalPCMFrameCount;
406 drflac_uint8 md5[16];
407 } drflac_streaminfo;
408
409 typedef struct
410 {
411 /*
412 The metadata type. Use this to know how to interpret the data below. Will be set to one of the
413 DRFLAC_METADATA_BLOCK_TYPE_* tokens.
414 */
415 drflac_uint32 type;
416
417 /*
418 A pointer to the raw data. This points to a temporary buffer so don't hold on to it. It's best to
419 not modify the contents of this buffer. Use the structures below for more meaningful and structured
420 information about the metadata. It's possible for this to be null.
421 */
422 const void* pRawData;
423
424 /* The size in bytes of the block and the buffer pointed to by pRawData if it's non-NULL. */
425 drflac_uint32 rawDataSize;
426
427 union
428 {
429 drflac_streaminfo streaminfo;
430
431 struct
432 {
433 int unused;
434 } padding;
435
436 struct
437 {
438 drflac_uint32 id;
439 const void* pData;
440 drflac_uint32 dataSize;
441 } application;
442
443 struct
444 {
445 drflac_uint32 seekpointCount;
446 const drflac_seekpoint* pSeekpoints;
447 } seektable;
448
449 struct
450 {
451 drflac_uint32 vendorLength;
452 const char* vendor;
453 drflac_uint32 commentCount;
454 const void* pComments;
455 } vorbis_comment;
456
457 struct
458 {
459 char catalog[128];
460 drflac_uint64 leadInSampleCount;
461 drflac_bool32 isCD;
462 drflac_uint8 trackCount;
463 const void* pTrackData;
464 } cuesheet;
465
466 struct
467 {
468 drflac_uint32 type;
469 drflac_uint32 mimeLength;
470 const char* mime;
471 drflac_uint32 descriptionLength;
472 const char* description;
473 drflac_uint32 width;
474 drflac_uint32 height;
475 drflac_uint32 colorDepth;
476 drflac_uint32 indexColorCount;
477 drflac_uint32 pictureDataSize;
478 const drflac_uint8* pPictureData;
479 } picture;
480 } data;
481 } drflac_metadata;
482
483
484 /*
485 Callback for when data needs to be read from the client.
486
487
488 Parameters
489 ----------
490 pUserData (in)
491 The user data that was passed to drflac_open() and family.
492
493 pBufferOut (out)
494 The output buffer.
495
496 bytesToRead (in)
497 The number of bytes to read.
498
499
500 Return Value
501 ------------
502 The number of bytes actually read.
503
504
505 Remarks
506 -------
507 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
508 you have reached the end of the stream.
509 */
510 typedef size_t (* drflac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
511
512 /*
513 Callback for when data needs to be seeked.
514
515
516 Parameters
517 ----------
518 pUserData (in)
519 The user data that was passed to drflac_open() and family.
520
521 offset (in)
522 The number of bytes to move, relative to the origin. Will never be negative.
523
524 origin (in)
525 The origin of the seek - the current position or the start of the stream.
526
527
528 Return Value
529 ------------
530 Whether or not the seek was successful.
531
532
533 Remarks
534 -------
535 The offset will never be negative. Whether or not it is relative to the beginning or current position is determined by the "origin" parameter which will be
536 either drflac_seek_origin_start or drflac_seek_origin_current.
537
538 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
539 and handled by returning DRFLAC_FALSE.
540 */
541 typedef drflac_bool32 (* drflac_seek_proc)(void* pUserData, int offset, drflac_seek_origin origin);
542
543 /*
544 Callback for when a metadata block is read.
545
546
547 Parameters
548 ----------
549 pUserData (in)
550 The user data that was passed to drflac_open() and family.
551
552 pMetadata (in)
553 A pointer to a structure containing the data of the metadata block.
554
555
556 Remarks
557 -------
558 Use pMetadata->type to determine which metadata block is being handled and how to read the data. This
559 will be set to one of the DRFLAC_METADATA_BLOCK_TYPE_* tokens.
560 */
561 typedef void (* drflac_meta_proc)(void* pUserData, drflac_metadata* pMetadata);
562
563
564 typedef struct
565 {
566 void* pUserData;
567 void* (* onMalloc)(size_t sz, void* pUserData);
568 void* (* onRealloc)(void* p, size_t sz, void* pUserData);
569 void (* onFree)(void* p, void* pUserData);
570 } drflac_allocation_callbacks;
571
572 /* Structure for internal use. Only used for decoders opened with drflac_open_memory. */
573 typedef struct
574 {
575 const drflac_uint8* data;
576 size_t dataSize;
577 size_t currentReadPos;
578 } drflac__memory_stream;
579
580 /* Structure for internal use. Used for bit streaming. */
581 typedef struct
582 {
583 /* The function to call when more data needs to be read. */
584 drflac_read_proc onRead;
585
586 /* The function to call when the current read position needs to be moved. */
587 drflac_seek_proc onSeek;
588
589 /* The user data to pass around to onRead and onSeek. */
590 void* pUserData;
591
592
593 /*
594 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
595 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
596 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).
597 */
598 size_t unalignedByteCount;
599
600 /* The content of the unaligned bytes. */
601 drflac_cache_t unalignedCache;
602
603 /* The index of the next valid cache line in the "L2" cache. */
604 drflac_uint32 nextL2Line;
605
606 /* The number of bits that have been consumed by the cache. This is used to determine how many valid bits are remaining. */
607 drflac_uint32 consumedBits;
608
609 /*
610 The cached data which was most recently read from the client. There are two levels of cache. Data flows as such:
611 Client -> L2 -> L1. The L2 -> L1 movement is aligned and runs on a fast path in just a few instructions.
612 */
613 drflac_cache_t cacheL2[DR_FLAC_BUFFER_SIZE/sizeof(drflac_cache_t)];
614 drflac_cache_t cache;
615
616 /*
617 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
618 is reset to 0 at the beginning of each frame.
619 */
620 drflac_uint16 crc16;
621 drflac_cache_t crc16Cache; /* A cache for optimizing CRC calculations. This is filled when when the L1 cache is reloaded. */
622 drflac_uint32 crc16CacheIgnoredBytes; /* The number of bytes to ignore when updating the CRC-16 from the CRC-16 cache. */
623 } drflac_bs;
624
625 typedef struct
626 {
627 /* The type of the subframe: SUBFRAME_CONSTANT, SUBFRAME_VERBATIM, SUBFRAME_FIXED or SUBFRAME_LPC. */
628 drflac_uint8 subframeType;
629
630 /* The number of wasted bits per sample as specified by the sub-frame header. */
631 drflac_uint8 wastedBitsPerSample;
632
633 /* The order to use for the prediction stage for SUBFRAME_FIXED and SUBFRAME_LPC. */
634 drflac_uint8 lpcOrder;
635
636 /* A pointer to the buffer containing the decoded samples in the subframe. This pointer is an offset from drflac::pExtraData. */
637 drflac_int32* pSamplesS32;
638 } drflac_subframe;
639
640 typedef struct
641 {
642 /*
643 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
644 always be set to 0. This is 64-bit because the decoded PCM frame number will be 36 bits.
645 */
646 drflac_uint64 pcmFrameNumber;
647
648 /*
649 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
650 is 32-bit because in fixed block sizes, the maximum frame number will be 31 bits.
651 */
652 drflac_uint32 flacFrameNumber;
653
654 /* The sample rate of this frame. */
655 drflac_uint32 sampleRate;
656
657 /* The number of PCM frames in each sub-frame within this frame. */
658 drflac_uint16 blockSizeInPCMFrames;
659
660 /*
661 The channel assignment of this frame. This is not always set to the channel count. If interchannel decorrelation is being used this
662 will be set to DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE, DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE or DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE.
663 */
664 drflac_uint8 channelAssignment;
665
666 /* The number of bits per sample within this frame. */
667 drflac_uint8 bitsPerSample;
668
669 /* The frame's CRC. */
670 drflac_uint8 crc8;
671 } drflac_frame_header;
672
673 typedef struct
674 {
675 /* The header. */
676 drflac_frame_header header;
677
678 /*
679 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,
680 this will be decremented. When it reaches 0, the decoder will see this frame as fully consumed and load the next frame.
681 */
682 drflac_uint32 pcmFramesRemaining;
683
684 /* The list of sub-frames within the frame. There is one sub-frame for each channel, and there's a maximum of 8 channels. */
685 drflac_subframe subframes[8];
686 } drflac_frame;
687
688 typedef struct
689 {
690 /* The function to call when a metadata block is read. */
691 drflac_meta_proc onMeta;
692
693 /* The user data posted to the metadata callback function. */
694 void* pUserDataMD;
695
696 /* Memory allocation callbacks. */
697 drflac_allocation_callbacks allocationCallbacks;
698
699
700 /* The sample rate. Will be set to something like 44100. */
701 drflac_uint32 sampleRate;
702
703 /*
704 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
705 value specified in the STREAMINFO block.
706 */
707 drflac_uint8 channels;
708
709 /* The bits per sample. Will be set to something like 16, 24, etc. */
710 drflac_uint8 bitsPerSample;
711
712 /* The maximum block size, in samples. This number represents the number of samples in each channel (not combined). */
713 drflac_uint16 maxBlockSizeInPCMFrames;
714
715 /*
716 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
717 the total PCM frame count is unknown. Likely the case with streams like internet radio.
718 */
719 drflac_uint64 totalPCMFrameCount;
720
721
722 /* The container type. This is set based on whether or not the decoder was opened from a native or Ogg stream. */
723 drflac_container container;
724
725 /* The number of seekpoints in the seektable. */
726 drflac_uint32 seekpointCount;
727
728
729 /* Information about the frame the decoder is currently sitting on. */
730 drflac_frame currentFLACFrame;
731
732
733 /* The index of the PCM frame the decoder is currently sitting on. This is only used for seeking. */
734 drflac_uint64 currentPCMFrame;
735
736 /* The position of the first FLAC frame in the stream. This is only ever used for seeking. */
737 drflac_uint64 firstFLACFramePosInBytes;
738
739
740 /* A hack to avoid a malloc() when opening a decoder with drflac_open_memory(). */
741 drflac__memory_stream memoryStream;
742
743
744 /* A pointer to the decoded sample data. This is an offset of pExtraData. */
745 drflac_int32* pDecodedSamples;
746
747 /* A pointer to the seek table. This is an offset of pExtraData, or NULL if there is no seek table. */
748 drflac_seekpoint* pSeekpoints;
749
750 /* Internal use only. Only used with Ogg containers. Points to a drflac_oggbs object. This is an offset of pExtraData. */
751 void* _oggbs;
752
753 /* Internal use only. Used for profiling and testing different seeking modes. */
754 drflac_bool32 _noSeekTableSeek : 1;
755 drflac_bool32 _noBinarySearchSeek : 1;
756 drflac_bool32 _noBruteForceSeek : 1;
757
758 /* The bit streamer. The raw FLAC data is fed through this object. */
759 drflac_bs bs;
760
761 /* Variable length extra data. We attach this to the end of the object so we can avoid unnecessary mallocs. */
762 drflac_uint8 pExtraData[1];
763 } drflac;
764
765
766 /*
767 Opens a FLAC decoder.
768
769
770 Parameters
771 ----------
772 onRead (in)
773 The function to call when data needs to be read from the client.
774
775 onSeek (in)
776 The function to call when the read position of the client data needs to move.
777
778 pUserData (in, optional)
779 A pointer to application defined data that will be passed to onRead and onSeek.
780
781 pAllocationCallbacks (in, optional)
782 A pointer to application defined callbacks for managing memory allocations.
783
784
785 Return Value
786 ------------
787 Returns a pointer to an object representing the decoder.
788
789
790 Remarks
791 -------
792 Close the decoder with `drflac_close()`.
793
794 `pAllocationCallbacks` can be NULL in which case it will use `DRFLAC_MALLOC`, `DRFLAC_REALLOC` and `DRFLAC_FREE`.
795
796 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
797 without any manual intervention. Ogg encapsulation also works with multiplexed streams which basically means it can play FLAC encoded audio tracks in videos.
798
799 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
800 from a block of memory respectively.
801
802 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.
803
804 Use `drflac_open_with_metadata()` if you need access to metadata.
805
806
807 Seek Also
808 ---------
809 drflac_open_file()
810 drflac_open_memory()
811 drflac_open_with_metadata()
812 drflac_close()
813 */
814 DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
815
816 /*
817 Opens a FLAC stream with relaxed validation of the header block.
818
819
820 Parameters
821 ----------
822 onRead (in)
823 The function to call when data needs to be read from the client.
824
825 onSeek (in)
826 The function to call when the read position of the client data needs to move.
827
828 container (in)
829 Whether or not the FLAC stream is encapsulated using standard FLAC encapsulation or Ogg encapsulation.
830
831 pUserData (in, optional)
832 A pointer to application defined data that will be passed to onRead and onSeek.
833
834 pAllocationCallbacks (in, optional)
835 A pointer to application defined callbacks for managing memory allocations.
836
837
838 Return Value
839 ------------
840 A pointer to an object representing the decoder.
841
842
843 Remarks
844 -------
845 The same as drflac_open(), except attempts to open the stream even when a header block is not present.
846
847 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`
848 as that is for internal use only.
849
850 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,
851 force your `onRead` callback to return 0, which dr_flac will use as an indicator that the end of the stream was found.
852
853 Use `drflac_open_with_metadata_relaxed()` if you need access to metadata.
854 */
855 DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
856
857 /*
858 Opens a FLAC decoder and notifies the caller of the metadata chunks (album art, etc.).
859
860
861 Parameters
862 ----------
863 onRead (in)
864 The function to call when data needs to be read from the client.
865
866 onSeek (in)
867 The function to call when the read position of the client data needs to move.
868
869 onMeta (in)
870 The function to call for every metadata block.
871
872 pUserData (in, optional)
873 A pointer to application defined data that will be passed to onRead, onSeek and onMeta.
874
875 pAllocationCallbacks (in, optional)
876 A pointer to application defined callbacks for managing memory allocations.
877
878
879 Return Value
880 ------------
881 A pointer to an object representing the decoder.
882
883
884 Remarks
885 -------
886 Close the decoder with `drflac_close()`.
887
888 `pAllocationCallbacks` can be NULL in which case it will use `DRFLAC_MALLOC`, `DRFLAC_REALLOC` and `DRFLAC_FREE`.
889
890 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
891 metadata block except for STREAMINFO and PADDING blocks.
892
893 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
894 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
895 the different metadata types.
896
897 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.
898
899 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
900 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
901 metadata block, whereas `drflac_open()` will simply seek past it (for the sake of efficiency). This inconsistency can result in different samples being
902 returned depending on whether or not the stream is being opened with metadata.
903
904
905 Seek Also
906 ---------
907 drflac_open_file_with_metadata()
908 drflac_open_memory_with_metadata()
909 drflac_open()
910 drflac_close()
911 */
912 DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
913
914 /*
915 The same as drflac_open_with_metadata(), except attempts to open the stream even when a header block is not present.
916
917 See Also
918 --------
919 drflac_open_with_metadata()
920 drflac_open_relaxed()
921 */
922 DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
923
924 /*
925 Closes the given FLAC decoder.
926
927
928 Parameters
929 ----------
930 pFlac (in)
931 The decoder to close.
932
933
934 Remarks
935 -------
936 This will destroy the decoder object.
937
938
939 See Also
940 --------
941 drflac_open()
942 drflac_open_with_metadata()
943 drflac_open_file()
944 drflac_open_file_w()
945 drflac_open_file_with_metadata()
946 drflac_open_file_with_metadata_w()
947 drflac_open_memory()
948 drflac_open_memory_with_metadata()
949 */
950 DRFLAC_API void drflac_close(drflac* pFlac);
951
952
953 /*
954 Reads sample data from the given FLAC decoder, output as interleaved signed 32-bit PCM.
955
956
957 Parameters
958 ----------
959 pFlac (in)
960 The decoder.
961
962 framesToRead (in)
963 The number of PCM frames to read.
964
965 pBufferOut (out, optional)
966 A pointer to the buffer that will receive the decoded samples.
967
968
969 Return Value
970 ------------
971 Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end.
972
973
974 Remarks
975 -------
976 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.
977 */
978 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut);
979
980
981 /*
982 Reads sample data from the given FLAC decoder, output as interleaved signed 16-bit PCM.
983
984
985 Parameters
986 ----------
987 pFlac (in)
988 The decoder.
989
990 framesToRead (in)
991 The number of PCM frames to read.
992
993 pBufferOut (out, optional)
994 A pointer to the buffer that will receive the decoded samples.
995
996
997 Return Value
998 ------------
999 Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end.
1000
1001
1002 Remarks
1003 -------
1004 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.
1005
1006 Note that this is lossy for streams where the bits per sample is larger than 16.
1007 */
1008 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut);
1009
1010 /*
1011 Reads sample data from the given FLAC decoder, output as interleaved 32-bit floating point PCM.
1012
1013
1014 Parameters
1015 ----------
1016 pFlac (in)
1017 The decoder.
1018
1019 framesToRead (in)
1020 The number of PCM frames to read.
1021
1022 pBufferOut (out, optional)
1023 A pointer to the buffer that will receive the decoded samples.
1024
1025
1026 Return Value
1027 ------------
1028 Returns the number of PCM frames actually read. If the return value is less than `framesToRead` it has reached the end.
1029
1030
1031 Remarks
1032 -------
1033 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.
1034
1035 Note that this should be considered lossy due to the nature of floating point numbers not being able to exactly represent every possible number.
1036 */
1037 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut);
1038
1039 /*
1040 Seeks to the PCM frame at the given index.
1041
1042
1043 Parameters
1044 ----------
1045 pFlac (in)
1046 The decoder.
1047
1048 pcmFrameIndex (in)
1049 The index of the PCM frame to seek to. See notes below.
1050
1051
1052 Return Value
1053 -------------
1054 `DRFLAC_TRUE` if successful; `DRFLAC_FALSE` otherwise.
1055 */
1056 DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex);
1057
1058
1059
1060 #ifndef DR_FLAC_NO_STDIO
1061 /*
1062 Opens a FLAC decoder from the file at the given path.
1063
1064
1065 Parameters
1066 ----------
1067 pFileName (in)
1068 The path of the file to open, either absolute or relative to the current directory.
1069
1070 pAllocationCallbacks (in, optional)
1071 A pointer to application defined callbacks for managing memory allocations.
1072
1073
1074 Return Value
1075 ------------
1076 A pointer to an object representing the decoder.
1077
1078
1079 Remarks
1080 -------
1081 Close the decoder with drflac_close().
1082
1083
1084 Remarks
1085 -------
1086 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
1087 at any given time, so keep this mind if you have many decoders open at the same time.
1088
1089
1090 See Also
1091 --------
1092 drflac_open_file_with_metadata()
1093 drflac_open()
1094 drflac_close()
1095 */
1096 DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
1097 DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
1098
1099 /*
1100 Opens a FLAC decoder from the file at the given path and notifies the caller of the metadata chunks (album art, etc.)
1101
1102
1103 Parameters
1104 ----------
1105 pFileName (in)
1106 The path of the file to open, either absolute or relative to the current directory.
1107
1108 pAllocationCallbacks (in, optional)
1109 A pointer to application defined callbacks for managing memory allocations.
1110
1111 onMeta (in)
1112 The callback to fire for each metadata block.
1113
1114 pUserData (in)
1115 A pointer to the user data to pass to the metadata callback.
1116
1117 pAllocationCallbacks (in)
1118 A pointer to application defined callbacks for managing memory allocations.
1119
1120
1121 Remarks
1122 -------
1123 Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
1124
1125
1126 See Also
1127 --------
1128 drflac_open_with_metadata()
1129 drflac_open()
1130 drflac_close()
1131 */
1132 DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
1133 DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
1134 #endif
1135
1136 /*
1137 Opens a FLAC decoder from a pre-allocated block of memory
1138
1139
1140 Parameters
1141 ----------
1142 pData (in)
1143 A pointer to the raw encoded FLAC data.
1144
1145 dataSize (in)
1146 The size in bytes of `data`.
1147
1148 pAllocationCallbacks (in)
1149 A pointer to application defined callbacks for managing memory allocations.
1150
1151
1152 Return Value
1153 ------------
1154 A pointer to an object representing the decoder.
1155
1156
1157 Remarks
1158 -------
1159 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.
1160
1161
1162 See Also
1163 --------
1164 drflac_open()
1165 drflac_close()
1166 */
1167 DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks);
1168
1169 /*
1170 Opens a FLAC decoder from a pre-allocated block of memory and notifies the caller of the metadata chunks (album art, etc.)
1171
1172
1173 Parameters
1174 ----------
1175 pData (in)
1176 A pointer to the raw encoded FLAC data.
1177
1178 dataSize (in)
1179 The size in bytes of `data`.
1180
1181 onMeta (in)
1182 The callback to fire for each metadata block.
1183
1184 pUserData (in)
1185 A pointer to the user data to pass to the metadata callback.
1186
1187 pAllocationCallbacks (in)
1188 A pointer to application defined callbacks for managing memory allocations.
1189
1190
1191 Remarks
1192 -------
1193 Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled.
1194
1195
1196 See Also
1197 -------
1198 drflac_open_with_metadata()
1199 drflac_open()
1200 drflac_close()
1201 */
1202 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);
1203
1204
1205
1206 /* High Level APIs */
1207
1208 /*
1209 Opens a FLAC stream from the given callbacks and fully decodes it in a single operation. The return value is a
1210 pointer to the sample data as interleaved signed 32-bit PCM. The returned data must be freed with drflac_free().
1211
1212 You can pass in custom memory allocation callbacks via the pAllocationCallbacks parameter. This can be NULL in which
1213 case it will use DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE.
1214
1215 Sometimes a FLAC file won't keep track of the total sample count. In this situation the function will continuously
1216 read samples into a dynamically sized buffer on the heap until no samples are left.
1217
1218 Do not call this function on a broadcast type of stream (like internet radio streams and whatnot).
1219 */
1220 DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1221
1222 /* Same as drflac_open_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */
1223 DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1224
1225 /* Same as drflac_open_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */
1226 DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
1227
1228 #ifndef DR_FLAC_NO_STDIO
1229 /* Same as drflac_open_and_read_pcm_frames_s32() except opens the decoder from a file. */
1230 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);
1231
1232 /* Same as drflac_open_file_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */
1233 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);
1234
1235 /* Same as drflac_open_file_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */
1236 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);
1237 #endif
1238
1239 /* Same as drflac_open_and_read_pcm_frames_s32() except opens the decoder from a block of memory. */
1240 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);
1241
1242 /* Same as drflac_open_memory_and_read_pcm_frames_s32(), except returns signed 16-bit integer samples. */
1243 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);
1244
1245 /* Same as drflac_open_memory_and_read_pcm_frames_s32(), except returns 32-bit floating-point samples. */
1246 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);
1247
1248 /*
1249 Frees memory that was allocated internally by dr_flac.
1250
1251 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.
1252 */
1253 DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks);
1254
1255
1256 /* Structure representing an iterator for vorbis comments in a VORBIS_COMMENT metadata block. */
1257 typedef struct
1258 {
1259 drflac_uint32 countRemaining;
1260 const char* pRunningData;
1261 } drflac_vorbis_comment_iterator;
1262
1263 /*
1264 Initializes a vorbis comment iterator. This can be used for iterating over the vorbis comments in a VORBIS_COMMENT
1265 metadata block.
1266 */
1267 DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments);
1268
1269 /*
1270 Goes to the next vorbis comment in the given iterator. If null is returned it means there are no more comments. The
1271 returned string is NOT null terminated.
1272 */
1273 DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut);
1274
1275
1276 /* Structure representing an iterator for cuesheet tracks in a CUESHEET metadata block. */
1277 typedef struct
1278 {
1279 drflac_uint32 countRemaining;
1280 const char* pRunningData;
1281 } drflac_cuesheet_track_iterator;
1282
1283 /* Packing is important on this structure because we map this directly to the raw data within the CUESHEET metadata block. */
1284 #pragma pack(4)
1285 typedef struct
1286 {
1287 drflac_uint64 offset;
1288 drflac_uint8 index;
1289 drflac_uint8 reserved[3];
1290 } drflac_cuesheet_track_index;
1291 #pragma pack()
1292
1293 typedef struct
1294 {
1295 drflac_uint64 offset;
1296 drflac_uint8 trackNumber;
1297 char ISRC[12];
1298 drflac_bool8 isAudio;
1299 drflac_bool8 preEmphasis;
1300 drflac_uint8 indexCount;
1301 const drflac_cuesheet_track_index* pIndexPoints;
1302 } drflac_cuesheet_track;
1303
1304 /*
1305 Initializes a cuesheet track iterator. This can be used for iterating over the cuesheet tracks in a CUESHEET metadata
1306 block.
1307 */
1308 DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData);
1309
1310 /* Goes to the next cuesheet track in the given iterator. If DRFLAC_FALSE is returned it means there are no more comments. */
1311 DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack);
1312
1313
1314 #ifdef __cplusplus
1315 }
1316 #endif
1317 #endif /* dr_flac_h */
1318
1319
1320 /************************************************************************************************************************************************************
1321 ************************************************************************************************************************************************************
1322
1323 IMPLEMENTATION
1324
1325 ************************************************************************************************************************************************************
1326 ************************************************************************************************************************************************************/
1327 #if defined(DR_FLAC_IMPLEMENTATION) || defined(DRFLAC_IMPLEMENTATION)
1328 #ifndef dr_flac_c
1329 #define dr_flac_c
1330
1331 /* Disable some annoying warnings. */
1332 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
1333 #pragma GCC diagnostic push
1334 #if __GNUC__ >= 7
1335 #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
1336 #endif
1337 #endif
1338
1339 #ifdef __linux__
1340 #ifndef _BSD_SOURCE
1341 #define _BSD_SOURCE
1342 #endif
1343 #ifndef _DEFAULT_SOURCE
1344 #define _DEFAULT_SOURCE
1345 #endif
1346 #ifndef __USE_BSD
1347 #define __USE_BSD
1348 #endif
1349 #include <endian.h>
1350 #endif
1351
1352 #include <stdlib.h>
1353 #include <string.h>
1354
1355 #ifdef _MSC_VER
1356 #define DRFLAC_INLINE __forceinline
1357 #elif defined(__GNUC__)
1358 /*
1359 I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when
1360 the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some
1361 case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the
1362 command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue
1363 I am using "__inline__" only when we're compiling in strict ANSI mode.
1364 */
1365 #if defined(__STRICT_ANSI__)
1366 #define DRFLAC_GNUC_INLINE_HINT __inline__
1367 #else
1368 #define DRFLAC_GNUC_INLINE_HINT inline
1369 #endif
1370
1371 #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
1372 #define DRFLAC_INLINE DRFLAC_GNUC_INLINE_HINT __attribute__((always_inline))
1373 #else
1374 #define DRFLAC_INLINE DRFLAC_GNUC_INLINE_HINT
1375 #endif
1376 #elif defined(__WATCOMC__)
1377 #define DRFLAC_INLINE __inline
1378 #else
1379 #define DRFLAC_INLINE
1380 #endif
1381
1382 /* CPU architecture. */
1383 #if defined(__x86_64__) || defined(_M_X64)
1384 #define DRFLAC_X64
1385 #elif defined(__i386) || defined(_M_IX86)
1386 #define DRFLAC_X86
1387 #elif defined(__arm__) || defined(_M_ARM) || defined(__arm64) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
1388 #define DRFLAC_ARM
1389 #endif
1390
1391 /*
1392 Intrinsics Support
1393
1394 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
1395
1396 "error: shift must be an immediate"
1397
1398 Unfortuantely dr_flac depends on this for a few things so we're just going to disable SSE on GCC 4.2 and below.
1399 */
1400 #if !defined(DR_FLAC_NO_SIMD)
1401 #if defined(DRFLAC_X64) || defined(DRFLAC_X86)
1402 #if defined(_MSC_VER) && !defined(__clang__)
1403 /* MSVC. */
1404 #if _MSC_VER >= 1400 && !defined(DRFLAC_NO_SSE2) /* 2005 */
1405 #define DRFLAC_SUPPORT_SSE2
1406 #endif
1407 #if _MSC_VER >= 1600 && !defined(DRFLAC_NO_SSE41) /* 2010 */
1408 #define DRFLAC_SUPPORT_SSE41
1409 #endif
1410 #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)))
1411 /* Assume GNUC-style. */
1412 #if defined(__SSE2__) && !defined(DRFLAC_NO_SSE2)
1413 #define DRFLAC_SUPPORT_SSE2
1414 #endif
1415 #if defined(__SSE4_1__) && !defined(DRFLAC_NO_SSE41)
1416 #define DRFLAC_SUPPORT_SSE41
1417 #endif
1418 #endif
1419
1420 /* If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. */
1421 #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
1422 #if !defined(DRFLAC_SUPPORT_SSE2) && !defined(DRFLAC_NO_SSE2) && __has_include(<emmintrin.h>)
1423 #define DRFLAC_SUPPORT_SSE2
1424 #endif
1425 #if !defined(DRFLAC_SUPPORT_SSE41) && !defined(DRFLAC_NO_SSE41) && __has_include(<smmintrin.h>)
1426 #define DRFLAC_SUPPORT_SSE41
1427 #endif
1428 #endif
1429
1430 #if defined(DRFLAC_SUPPORT_SSE41)
1431 #include <smmintrin.h>
1432 #elif defined(DRFLAC_SUPPORT_SSE2)
1433 #include <emmintrin.h>
1434 #endif
1435 #endif
1436
1437 #if defined(DRFLAC_ARM)
1438 #if !defined(DRFLAC_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
1439 #define DRFLAC_SUPPORT_NEON
1440 #include <arm_neon.h>
1441 #endif
1442 #endif
1443 #endif
1444
1445 /* Compile-time CPU feature support. */
1446 #if !defined(DR_FLAC_NO_SIMD) && (defined(DRFLAC_X86) || defined(DRFLAC_X64))
1447 #if defined(_MSC_VER) && !defined(__clang__)
1448 #if _MSC_VER >= 1400
1449 #include <intrin.h>
1450 static void drflac__cpuid(int info[4], int fid)
1451 {
1452 __cpuid(info, fid);
1453 }
1454 #else
1455 #define DRFLAC_NO_CPUID
1456 #endif
1457 #else
1458 #if defined(__GNUC__) || defined(__clang__)
1459 static void drflac__cpuid(int info[4], int fid)
1460 {
1461 /*
1462 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
1463 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
1464 supporting different assembly dialects.
1465
1466 What's basically happening is that we're saving and restoring the ebx register manually.
1467 */
1468 #if defined(DRFLAC_X86) && defined(__PIC__)
1469 __asm__ __volatile__ (
1470 "xchg{l} {%%}ebx, %k1;"
1471 "cpuid;"
1472 "xchg{l} {%%}ebx, %k1;"
1473 : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
1474 );
1475 #else
1476 __asm__ __volatile__ (
1477 "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
1478 );
1479 #endif
1480 }
1481 #else
1482 #define DRFLAC_NO_CPUID
1483 #endif
1484 #endif
1485 #else
1486 #define DRFLAC_NO_CPUID
1487 #endif
1488
1489 static DRFLAC_INLINE drflac_bool32 drflac_has_sse2(void)
1490 {
1491 #if defined(DRFLAC_SUPPORT_SSE2)
1492 #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE2)
1493 #if defined(DRFLAC_X64)
1494 return DRFLAC_TRUE; /* 64-bit targets always support SSE2. */
1495 #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)
1496 return DRFLAC_TRUE; /* If the compiler is allowed to freely generate SSE2 code we can assume support. */
1497 #else
1498 #if defined(DRFLAC_NO_CPUID)
1499 return DRFLAC_FALSE;
1500 #else
1501 int info[4];
1502 drflac__cpuid(info, 1);
1503 return (info[3] & (1 << 26)) != 0;
1504 #endif
1505 #endif
1506 #else
1507 return DRFLAC_FALSE; /* SSE2 is only supported on x86 and x64 architectures. */
1508 #endif
1509 #else
1510 return DRFLAC_FALSE; /* No compiler support. */
1511 #endif
1512 }
1513
1514 static DRFLAC_INLINE drflac_bool32 drflac_has_sse41(void)
1515 {
1516 #if defined(DRFLAC_SUPPORT_SSE41)
1517 #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE41)
1518 #if defined(DRFLAC_X64)
1519 return DRFLAC_TRUE; /* 64-bit targets always support SSE4.1. */
1520 #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE4_1__)
1521 return DRFLAC_TRUE; /* If the compiler is allowed to freely generate SSE41 code we can assume support. */
1522 #else
1523 #if defined(DRFLAC_NO_CPUID)
1524 return DRFLAC_FALSE;
1525 #else
1526 int info[4];
1527 drflac__cpuid(info, 1);
1528 return (info[2] & (1 << 19)) != 0;
1529 #endif
1530 #endif
1531 #else
1532 return DRFLAC_FALSE; /* SSE41 is only supported on x86 and x64 architectures. */
1533 #endif
1534 #else
1535 return DRFLAC_FALSE; /* No compiler support. */
1536 #endif
1537 }
1538
1539
1540 #if defined(_MSC_VER) && _MSC_VER >= 1500 && (defined(DRFLAC_X86) || defined(DRFLAC_X64)) && !defined(__clang__)
1541 #define DRFLAC_HAS_LZCNT_INTRINSIC
1542 #elif (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
1543 #define DRFLAC_HAS_LZCNT_INTRINSIC
1544 #elif defined(__clang__)
1545 #if defined(__has_builtin)
1546 #if __has_builtin(__builtin_clzll) || __has_builtin(__builtin_clzl)
1547 #define DRFLAC_HAS_LZCNT_INTRINSIC
1548 #endif
1549 #endif
1550 #endif
1551
1552 #if defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(__clang__)
1553 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
1554 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
1555 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
1556 #elif defined(__clang__)
1557 #if defined(__has_builtin)
1558 #if __has_builtin(__builtin_bswap16)
1559 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
1560 #endif
1561 #if __has_builtin(__builtin_bswap32)
1562 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
1563 #endif
1564 #if __has_builtin(__builtin_bswap64)
1565 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
1566 #endif
1567 #endif
1568 #elif defined(__GNUC__)
1569 #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
1570 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
1571 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
1572 #endif
1573 #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
1574 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
1575 #endif
1576 #elif defined(__WATCOMC__) && defined(__386__)
1577 #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
1578 #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
1579 #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
1580 extern __inline drflac_uint16 _watcom_bswap16(drflac_uint16);
1581 extern __inline drflac_uint32 _watcom_bswap32(drflac_uint32);
1582 extern __inline drflac_uint64 _watcom_bswap64(drflac_uint64);
1583 #pragma aux _watcom_bswap16 = \
1584 "xchg al, ah" \
1585 parm [ax] \
1586 modify [ax];
1587 #pragma aux _watcom_bswap32 = \
1588 "bswap eax" \
1589 parm [eax] \
1590 modify [eax];
1591 #pragma aux _watcom_bswap64 = \
1592 "bswap eax" \
1593 "bswap edx" \
1594 "xchg eax,edx" \
1595 parm [eax edx] \
1596 modify [eax edx];
1597 #endif
1598
1599
1600 /* Standard library stuff. */
1601 #ifndef DRFLAC_ASSERT
1602 #include <assert.h>
1603 #define DRFLAC_ASSERT(expression) assert(expression)
1604 #endif
1605 #ifndef DRFLAC_MALLOC
1606 #define DRFLAC_MALLOC(sz) malloc((sz))
1607 #endif
1608 #ifndef DRFLAC_REALLOC
1609 #define DRFLAC_REALLOC(p, sz) realloc((p), (sz))
1610 #endif
1611 #ifndef DRFLAC_FREE
1612 #define DRFLAC_FREE(p) free((p))
1613 #endif
1614 #ifndef DRFLAC_COPY_MEMORY
1615 #define DRFLAC_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
1616 #endif
1617 #ifndef DRFLAC_ZERO_MEMORY
1618 #define DRFLAC_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
1619 #endif
1620 #ifndef DRFLAC_ZERO_OBJECT
1621 #define DRFLAC_ZERO_OBJECT(p) DRFLAC_ZERO_MEMORY((p), sizeof(*(p)))
1622 #endif
1623
1624 #define DRFLAC_MAX_SIMD_VECTOR_SIZE 64 /* 64 for AVX-512 in the future. */
1625
1626 typedef drflac_int32 drflac_result;
1627 #define DRFLAC_SUCCESS 0
1628 #define DRFLAC_ERROR -1 /* A generic error. */
1629 #define DRFLAC_INVALID_ARGS -2
1630 #define DRFLAC_INVALID_OPERATION -3
1631 #define DRFLAC_OUT_OF_MEMORY -4
1632 #define DRFLAC_OUT_OF_RANGE -5
1633 #define DRFLAC_ACCESS_DENIED -6
1634 #define DRFLAC_DOES_NOT_EXIST -7
1635 #define DRFLAC_ALREADY_EXISTS -8
1636 #define DRFLAC_TOO_MANY_OPEN_FILES -9
1637 #define DRFLAC_INVALID_FILE -10
1638 #define DRFLAC_TOO_BIG -11
1639 #define DRFLAC_PATH_TOO_LONG -12
1640 #define DRFLAC_NAME_TOO_LONG -13
1641 #define DRFLAC_NOT_DIRECTORY -14
1642 #define DRFLAC_IS_DIRECTORY -15
1643 #define DRFLAC_DIRECTORY_NOT_EMPTY -16
1644 #define DRFLAC_END_OF_FILE -17
1645 #define DRFLAC_NO_SPACE -18
1646 #define DRFLAC_BUSY -19
1647 #define DRFLAC_IO_ERROR -20
1648 #define DRFLAC_INTERRUPT -21
1649 #define DRFLAC_UNAVAILABLE -22
1650 #define DRFLAC_ALREADY_IN_USE -23
1651 #define DRFLAC_BAD_ADDRESS -24
1652 #define DRFLAC_BAD_SEEK -25
1653 #define DRFLAC_BAD_PIPE -26
1654 #define DRFLAC_DEADLOCK -27
1655 #define DRFLAC_TOO_MANY_LINKS -28
1656 #define DRFLAC_NOT_IMPLEMENTED -29
1657 #define DRFLAC_NO_MESSAGE -30
1658 #define DRFLAC_BAD_MESSAGE -31
1659 #define DRFLAC_NO_DATA_AVAILABLE -32
1660 #define DRFLAC_INVALID_DATA -33
1661 #define DRFLAC_TIMEOUT -34
1662 #define DRFLAC_NO_NETWORK -35
1663 #define DRFLAC_NOT_UNIQUE -36
1664 #define DRFLAC_NOT_SOCKET -37
1665 #define DRFLAC_NO_ADDRESS -38
1666 #define DRFLAC_BAD_PROTOCOL -39
1667 #define DRFLAC_PROTOCOL_UNAVAILABLE -40
1668 #define DRFLAC_PROTOCOL_NOT_SUPPORTED -41
1669 #define DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED -42
1670 #define DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED -43
1671 #define DRFLAC_SOCKET_NOT_SUPPORTED -44
1672 #define DRFLAC_CONNECTION_RESET -45
1673 #define DRFLAC_ALREADY_CONNECTED -46
1674 #define DRFLAC_NOT_CONNECTED -47
1675 #define DRFLAC_CONNECTION_REFUSED -48
1676 #define DRFLAC_NO_HOST -49
1677 #define DRFLAC_IN_PROGRESS -50
1678 #define DRFLAC_CANCELLED -51
1679 #define DRFLAC_MEMORY_ALREADY_MAPPED -52
1680 #define DRFLAC_AT_END -53
1681 #define DRFLAC_CRC_MISMATCH -128
1682
1683 #define DRFLAC_SUBFRAME_CONSTANT 0
1684 #define DRFLAC_SUBFRAME_VERBATIM 1
1685 #define DRFLAC_SUBFRAME_FIXED 8
1686 #define DRFLAC_SUBFRAME_LPC 32
1687 #define DRFLAC_SUBFRAME_RESERVED 255
1688
1689 #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE 0
1690 #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 1
1691
1692 #define DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT 0
1693 #define DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE 8
1694 #define DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE 9
1695 #define DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE 10
1696
1697 #define drflac_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
1698
1699
1700 DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision)
1701 {
1702 if (pMajor) {
1703 *pMajor = DRFLAC_VERSION_MAJOR;
1704 }
1705
1706 if (pMinor) {
1707 *pMinor = DRFLAC_VERSION_MINOR;
1708 }
1709
1710 if (pRevision) {
1711 *pRevision = DRFLAC_VERSION_REVISION;
1712 }
1713 }
1714
1715 DRFLAC_API const char* drflac_version_string(void)
1716 {
1717 return DRFLAC_VERSION_STRING;
1718 }
1719
1720
1721 /* CPU caps. */
1722 #if defined(__has_feature)
1723 #if __has_feature(thread_sanitizer)
1724 #define DRFLAC_NO_THREAD_SANITIZE __attribute__((no_sanitize("thread")))
1725 #else
1726 #define DRFLAC_NO_THREAD_SANITIZE
1727 #endif
1728 #else
1729 #define DRFLAC_NO_THREAD_SANITIZE
1730 #endif
1731
1732 #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
1733 static drflac_bool32 drflac__gIsLZCNTSupported = DRFLAC_FALSE;
1734 #endif
1735
1736 #ifndef DRFLAC_NO_CPUID
1737 static drflac_bool32 drflac__gIsSSE2Supported = DRFLAC_FALSE;
1738 static drflac_bool32 drflac__gIsSSE41Supported = DRFLAC_FALSE;
1739
1740 /*
1741 I've had a bug report that Clang's ThreadSanitizer presents a warning in this function. Having reviewed this, this does
1742 actually make sense. However, since CPU caps should never differ for a running process, I don't think the trade off of
1743 complicating internal API's by passing around CPU caps versus just disabling the warnings is worthwhile. I'm therefore
1744 just going to disable these warnings. This is disabled via the DRFLAC_NO_THREAD_SANITIZE attribute.
1745 */
1746 DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void)
1747 {
1748 static drflac_bool32 isCPUCapsInitialized = DRFLAC_FALSE;
1749
1750 if (!isCPUCapsInitialized) {
1751 /* LZCNT */
1752 #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
1753 int info[4] = {0};
1754 drflac__cpuid(info, 0x80000001);
1755 drflac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0;
1756 #endif
1757
1758 /* SSE2 */
1759 drflac__gIsSSE2Supported = drflac_has_sse2();
1760
1761 /* SSE4.1 */
1762 drflac__gIsSSE41Supported = drflac_has_sse41();
1763
1764 /* Initialized. */
1765 isCPUCapsInitialized = DRFLAC_TRUE;
1766 }
1767 }
1768 #else
1769 static drflac_bool32 drflac__gIsNEONSupported = DRFLAC_FALSE;
1770
1771 static DRFLAC_INLINE drflac_bool32 drflac__has_neon(void)
1772 {
1773 #if defined(DRFLAC_SUPPORT_NEON)
1774 #if defined(DRFLAC_ARM) && !defined(DRFLAC_NO_NEON)
1775 #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
1776 return DRFLAC_TRUE; /* If the compiler is allowed to freely generate NEON code we can assume support. */
1777 #else
1778 /* TODO: Runtime check. */
1779 return DRFLAC_FALSE;
1780 #endif
1781 #else
1782 return DRFLAC_FALSE; /* NEON is only supported on ARM architectures. */
1783 #endif
1784 #else
1785 return DRFLAC_FALSE; /* No compiler support. */
1786 #endif
1787 }
1788
1789 DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void)
1790 {
1791 drflac__gIsNEONSupported = drflac__has_neon();
1792
1793 #if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
1794 drflac__gIsLZCNTSupported = DRFLAC_TRUE;
1795 #endif
1796 }
1797 #endif
1798
1799
1800 /* Endian Management */
1801 static DRFLAC_INLINE drflac_bool32 drflac__is_little_endian(void)
1802 {
1803 #if defined(DRFLAC_X86) || defined(DRFLAC_X64)
1804 return DRFLAC_TRUE;
1805 #elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
1806 return DRFLAC_TRUE;
1807 #else
1808 int n = 1;
1809 return (*(char*)&n) == 1;
1810 #endif
1811 }
1812
1813 static DRFLAC_INLINE drflac_uint16 drflac__swap_endian_uint16(drflac_uint16 n)
1814 {
1815 #ifdef DRFLAC_HAS_BYTESWAP16_INTRINSIC
1816 #if defined(_MSC_VER) && !defined(__clang__)
1817 return _byteswap_ushort(n);
1818 #elif defined(__GNUC__) || defined(__clang__)
1819 return __builtin_bswap16(n);
1820 #elif defined(__WATCOMC__) && defined(__386__)
1821 return _watcom_bswap16(n);
1822 #else
1823 #error "This compiler does not support the byte swap intrinsic."
1824 #endif
1825 #else
1826 return ((n & 0xFF00) >> 8) |
1827 ((n & 0x00FF) << 8);
1828 #endif
1829 }
1830
1831 static DRFLAC_INLINE drflac_uint32 drflac__swap_endian_uint32(drflac_uint32 n)
1832 {
1833 #ifdef DRFLAC_HAS_BYTESWAP32_INTRINSIC
1834 #if defined(_MSC_VER) && !defined(__clang__)
1835 return _byteswap_ulong(n);
1836 #elif defined(__GNUC__) || defined(__clang__)
1837 #if defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(DRFLAC_64BIT) /* <-- 64-bit inline assembly has not been tested, so disabling for now. */
1838 /* Inline assembly optimized implementation for ARM. In my testing, GCC does not generate optimized code with __builtin_bswap32(). */
1839 drflac_uint32 r;
1840 __asm__ __volatile__ (
1841 #if defined(DRFLAC_64BIT)
1842 "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! */
1843 #else
1844 "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
1845 #endif
1846 );
1847 return r;
1848 #else
1849 return __builtin_bswap32(n);
1850 #endif
1851 #elif defined(__WATCOMC__) && defined(__386__)
1852 return _watcom_bswap32(n);
1853 #else
1854 #error "This compiler does not support the byte swap intrinsic."
1855 #endif
1856 #else
1857 return ((n & 0xFF000000) >> 24) |
1858 ((n & 0x00FF0000) >> 8) |
1859 ((n & 0x0000FF00) << 8) |
1860 ((n & 0x000000FF) << 24);
1861 #endif
1862 }
1863
1864 static DRFLAC_INLINE drflac_uint64 drflac__swap_endian_uint64(drflac_uint64 n)
1865 {
1866 #ifdef DRFLAC_HAS_BYTESWAP64_INTRINSIC
1867 #if defined(_MSC_VER) && !defined(__clang__)
1868 return _byteswap_uint64(n);
1869 #elif defined(__GNUC__) || defined(__clang__)
1870 return __builtin_bswap64(n);
1871 #elif defined(__WATCOMC__) && defined(__386__)
1872 return _watcom_bswap64(n);
1873 #else
1874 #error "This compiler does not support the byte swap intrinsic."
1875 #endif
1876 #else
1877 /* Weird "<< 32" bitshift is required for C89 because it doesn't support 64-bit constants. Should be optimized out by a good compiler. */
1878 return ((n & ((drflac_uint64)0xFF000000 << 32)) >> 56) |
1879 ((n & ((drflac_uint64)0x00FF0000 << 32)) >> 40) |
1880 ((n & ((drflac_uint64)0x0000FF00 << 32)) >> 24) |
1881 ((n & ((drflac_uint64)0x000000FF << 32)) >> 8) |
1882 ((n & ((drflac_uint64)0xFF000000 )) << 8) |
1883 ((n & ((drflac_uint64)0x00FF0000 )) << 24) |
1884 ((n & ((drflac_uint64)0x0000FF00 )) << 40) |
1885 ((n & ((drflac_uint64)0x000000FF )) << 56);
1886 #endif
1887 }
1888
1889
1890 static DRFLAC_INLINE drflac_uint16 drflac__be2host_16(drflac_uint16 n)
1891 {
1892 if (drflac__is_little_endian()) {
1893 return drflac__swap_endian_uint16(n);
1894 }
1895
1896 return n;
1897 }
1898
1899 static DRFLAC_INLINE drflac_uint32 drflac__be2host_32(drflac_uint32 n)
1900 {
1901 if (drflac__is_little_endian()) {
1902 return drflac__swap_endian_uint32(n);
1903 }
1904
1905 return n;
1906 }
1907
1908 static DRFLAC_INLINE drflac_uint32 drflac__be2host_32_ptr_unaligned(const void* pData)
1909 {
1910 const drflac_uint8* pNum = (drflac_uint8*)pData;
1911 return *(pNum) << 24 | *(pNum+1) << 16 | *(pNum+2) << 8 | *(pNum+3);
1912 }
1913
1914 static DRFLAC_INLINE drflac_uint64 drflac__be2host_64(drflac_uint64 n)
1915 {
1916 if (drflac__is_little_endian()) {
1917 return drflac__swap_endian_uint64(n);
1918 }
1919
1920 return n;
1921 }
1922
1923
1924 static DRFLAC_INLINE drflac_uint32 drflac__le2host_32(drflac_uint32 n)
1925 {
1926 if (!drflac__is_little_endian()) {
1927 return drflac__swap_endian_uint32(n);
1928 }
1929
1930 return n;
1931 }
1932
1933 static DRFLAC_INLINE drflac_uint32 drflac__le2host_32_ptr_unaligned(const void* pData)
1934 {
1935 const drflac_uint8* pNum = (drflac_uint8*)pData;
1936 return *pNum | *(pNum+1) << 8 | *(pNum+2) << 16 | *(pNum+3) << 24;
1937 }
1938
1939
1940 static DRFLAC_INLINE drflac_uint32 drflac__unsynchsafe_32(drflac_uint32 n)
1941 {
1942 drflac_uint32 result = 0;
1943 result |= (n & 0x7F000000) >> 3;
1944 result |= (n & 0x007F0000) >> 2;
1945 result |= (n & 0x00007F00) >> 1;
1946 result |= (n & 0x0000007F) >> 0;
1947
1948 return result;
1949 }
1950
1951
1952
1953 /* The CRC code below is based on this document: http://zlib.net/crc_v3.txt */
1954 static drflac_uint8 drflac__crc8_table[] = {
1955 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
1956 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
1957 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
1958 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
1959 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
1960 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
1961 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
1962 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
1963 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
1964 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
1965 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
1966 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
1967 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
1968 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
1969 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
1970 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
1971 };
1972
1973 static drflac_uint16 drflac__crc16_table[] = {
1974 0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
1975 0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022,
1976 0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072,
1977 0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041,
1978 0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2,
1979 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1,
1980 0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1,
1981 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
1982 0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192,
1983 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1,
1984 0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1,
1985 0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2,
1986 0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151,
1987 0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162,
1988 0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132,
1989 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101,
1990 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312,
1991 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
1992 0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371,
1993 0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342,
1994 0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1,
1995 0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
1996 0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2,
1997 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381,
1998 0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291,
1999 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2,
2000 0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2,
2001 0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1,
2002 0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252,
2003 0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261,
2004 0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231,
2005 0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202
2006 };
2007
2008 static DRFLAC_INLINE drflac_uint8 drflac_crc8_byte(drflac_uint8 crc, drflac_uint8 data)
2009 {
2010 return drflac__crc8_table[crc ^ data];
2011 }
2012
2013 static DRFLAC_INLINE drflac_uint8 drflac_crc8(drflac_uint8 crc, drflac_uint32 data, drflac_uint32 count)
2014 {
2015 #ifdef DR_FLAC_NO_CRC
2016 (void)crc;
2017 (void)data;
2018 (void)count;
2019 return 0;
2020 #else
2021 #if 0
2022 /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc8(crc, 0, 8);") */
2023 drflac_uint8 p = 0x07;
2024 for (int i = count-1; i >= 0; --i) {
2025 drflac_uint8 bit = (data & (1 << i)) >> i;
2026 if (crc & 0x80) {
2027 crc = ((crc << 1) | bit) ^ p;
2028 } else {
2029 crc = ((crc << 1) | bit);
2030 }
2031 }
2032 return crc;
2033 #else
2034 drflac_uint32 wholeBytes;
2035 drflac_uint32 leftoverBits;
2036 drflac_uint64 leftoverDataMask;
2037
2038 static drflac_uint64 leftoverDataMaskTable[8] = {
2039 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
2040 };
2041
2042 DRFLAC_ASSERT(count <= 32);
2043
2044 wholeBytes = count >> 3;
2045 leftoverBits = count - (wholeBytes*8);
2046 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
2047
2048 switch (wholeBytes) {
2049 case 4: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
2050 case 3: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
2051 case 2: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
2052 case 1: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
2053 case 0: if (leftoverBits > 0) crc = (drflac_uint8)((crc << leftoverBits) ^ drflac__crc8_table[(crc >> (8 - leftoverBits)) ^ (data & leftoverDataMask)]);
2054 }
2055 return crc;
2056 #endif
2057 #endif
2058 }
2059
2060 static DRFLAC_INLINE drflac_uint16 drflac_crc16_byte(drflac_uint16 crc, drflac_uint8 data)
2061 {
2062 return (crc << 8) ^ drflac__crc16_table[(drflac_uint8)(crc >> 8) ^ data];
2063 }
2064
2065 static DRFLAC_INLINE drflac_uint16 drflac_crc16_cache(drflac_uint16 crc, drflac_cache_t data)
2066 {
2067 #ifdef DRFLAC_64BIT
2068 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
2069 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
2070 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
2071 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
2072 #endif
2073 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
2074 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
2075 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF));
2076 crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF));
2077
2078 return crc;
2079 }
2080
2081 static DRFLAC_INLINE drflac_uint16 drflac_crc16_bytes(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 byteCount)
2082 {
2083 switch (byteCount)
2084 {
2085 #ifdef DRFLAC_64BIT
2086 case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
2087 case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
2088 case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
2089 case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
2090 #endif
2091 case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
2092 case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
2093 case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF));
2094 case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF));
2095 }
2096
2097 return crc;
2098 }
2099
2100 #if 0
2101 static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac_uint32 data, drflac_uint32 count)
2102 {
2103 #ifdef DR_FLAC_NO_CRC
2104 (void)crc;
2105 (void)data;
2106 (void)count;
2107 return 0;
2108 #else
2109 #if 0
2110 /* REFERENCE (use of this implementation requires an explicit flush by doing "drflac_crc16(crc, 0, 16);") */
2111 drflac_uint16 p = 0x8005;
2112 for (int i = count-1; i >= 0; --i) {
2113 drflac_uint16 bit = (data & (1ULL << i)) >> i;
2114 if (r & 0x8000) {
2115 r = ((r << 1) | bit) ^ p;
2116 } else {
2117 r = ((r << 1) | bit);
2118 }
2119 }
2120
2121 return crc;
2122 #else
2123 drflac_uint32 wholeBytes;
2124 drflac_uint32 leftoverBits;
2125 drflac_uint64 leftoverDataMask;
2126
2127 static drflac_uint64 leftoverDataMaskTable[8] = {
2128 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
2129 };
2130
2131 DRFLAC_ASSERT(count <= 64);
2132
2133 wholeBytes = count >> 3;
2134 leftoverBits = count & 7;
2135 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
2136
2137 switch (wholeBytes) {
2138 default:
2139 case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
2140 case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
2141 case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
2142 case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
2143 case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
2144 }
2145 return crc;
2146 #endif
2147 #endif
2148 }
2149
2150 static DRFLAC_INLINE drflac_uint16 drflac_crc16__64bit(drflac_uint16 crc, drflac_uint64 data, drflac_uint32 count)
2151 {
2152 #ifdef DR_FLAC_NO_CRC
2153 (void)crc;
2154 (void)data;
2155 (void)count;
2156 return 0;
2157 #else
2158 drflac_uint32 wholeBytes;
2159 drflac_uint32 leftoverBits;
2160 drflac_uint64 leftoverDataMask;
2161
2162 static drflac_uint64 leftoverDataMaskTable[8] = {
2163 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
2164 };
2165
2166 DRFLAC_ASSERT(count <= 64);
2167
2168 wholeBytes = count >> 3;
2169 leftoverBits = count & 7;
2170 leftoverDataMask = leftoverDataMaskTable[leftoverBits];
2171
2172 switch (wholeBytes) {
2173 default:
2174 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. */
2175 case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 << 32) << leftoverBits)) >> (48 + leftoverBits)));
2176 case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 << 32) << leftoverBits)) >> (40 + leftoverBits)));
2177 case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF << 32) << leftoverBits)) >> (32 + leftoverBits)));
2178 case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 ) << leftoverBits)) >> (24 + leftoverBits)));
2179 case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 ) << leftoverBits)) >> (16 + leftoverBits)));
2180 case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 ) << leftoverBits)) >> ( 8 + leftoverBits)));
2181 case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF ) << leftoverBits)) >> ( 0 + leftoverBits)));
2182 case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
2183 }
2184 return crc;
2185 #endif
2186 }
2187
2188
2189 static DRFLAC_INLINE drflac_uint16 drflac_crc16(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 count)
2190 {
2191 #ifdef DRFLAC_64BIT
2192 return drflac_crc16__64bit(crc, data, count);
2193 #else
2194 return drflac_crc16__32bit(crc, data, count);
2195 #endif
2196 }
2197 #endif
2198
2199
2200 #ifdef DRFLAC_64BIT
2201 #define drflac__be2host__cache_line drflac__be2host_64
2202 #else
2203 #define drflac__be2host__cache_line drflac__be2host_32
2204 #endif
2205
2206 /*
2207 BIT READING ATTEMPT #2
2208
2209 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
2210 on the most significant bit. It uses the notion of an L1 and L2 cache (borrowed from CPU architecture), where the L1 cache
2211 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
2212 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
2213 from onRead() is read into.
2214 */
2215 #define DRFLAC_CACHE_L1_SIZE_BYTES(bs) (sizeof((bs)->cache))
2216 #define DRFLAC_CACHE_L1_SIZE_BITS(bs) (sizeof((bs)->cache)*8)
2217 #define DRFLAC_CACHE_L1_BITS_REMAINING(bs) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (bs)->consumedBits)
2218 #define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~((~(drflac_cache_t)0) >> (_bitCount)))
2219 #define DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount))
2220 #define DRFLAC_CACHE_L1_SELECT(bs, _bitCount) (((bs)->cache) & DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount))
2221 #define DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)))
2222 #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)))
2223 #define DRFLAC_CACHE_L2_SIZE_BYTES(bs) (sizeof((bs)->cacheL2))
2224 #define DRFLAC_CACHE_L2_LINE_COUNT(bs) (DRFLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0]))
2225 #define DRFLAC_CACHE_L2_LINES_REMAINING(bs) (DRFLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line)
2226
2227
2228 #ifndef DR_FLAC_NO_CRC
2229 static DRFLAC_INLINE void drflac__reset_crc16(drflac_bs* bs)
2230 {
2231 bs->crc16 = 0;
2232 bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
2233 }
2234
2235 static DRFLAC_INLINE void drflac__update_crc16(drflac_bs* bs)
2236 {
2237 if (bs->crc16CacheIgnoredBytes == 0) {
2238 bs->crc16 = drflac_crc16_cache(bs->crc16, bs->crc16Cache);
2239 } else {
2240 bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache, DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bs->crc16CacheIgnoredBytes);
2241 bs->crc16CacheIgnoredBytes = 0;
2242 }
2243 }
2244
2245 static DRFLAC_INLINE drflac_uint16 drflac__flush_crc16(drflac_bs* bs)
2246 {
2247 /* We should never be flushing in a situation where we are not aligned on a byte boundary. */
2248 DRFLAC_ASSERT((DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7) == 0);
2249
2250 /*
2251 The bits that were read from the L1 cache need to be accumulated. The number of bytes needing to be accumulated is determined
2252 by the number of bits that have been consumed.
2253 */
2254 if (DRFLAC_CACHE_L1_BITS_REMAINING(bs) == 0) {
2255 drflac__update_crc16(bs);
2256 } else {
2257 /* We only accumulate the consumed bits. */
2258 bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache >> DRFLAC_CACHE_L1_BITS_REMAINING(bs), (bs->consumedBits >> 3) - bs->crc16CacheIgnoredBytes);
2259
2260 /*
2261 The bits that we just accumulated should never be accumulated again. We need to keep track of how many bytes were accumulated
2262 so we can handle that later.
2263 */
2264 bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
2265 }
2266
2267 return bs->crc16;
2268 }
2269 #endif
2270
2271 static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs)
2272 {
2273 size_t bytesRead;
2274 size_t alignedL1LineCount;
2275
2276 /* Fast path. Try loading straight from L2. */
2277 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
2278 bs->cache = bs->cacheL2[bs->nextL2Line++];
2279 return DRFLAC_TRUE;
2280 }
2281
2282 /*
2283 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
2284 any left.
2285 */
2286 if (bs->unalignedByteCount > 0) {
2287 return DRFLAC_FALSE; /* If we have any unaligned bytes it means there's no more aligned bytes left in the client. */
2288 }
2289
2290 bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, DRFLAC_CACHE_L2_SIZE_BYTES(bs));
2291
2292 bs->nextL2Line = 0;
2293 if (bytesRead == DRFLAC_CACHE_L2_SIZE_BYTES(bs)) {
2294 bs->cache = bs->cacheL2[bs->nextL2Line++];
2295 return DRFLAC_TRUE;
2296 }
2297
2298
2299 /*
2300 If we get here it means we were unable to retrieve enough data to fill the entire L2 cache. It probably
2301 means we've just reached the end of the file. We need to move the valid data down to the end of the buffer
2302 and adjust the index of the next line accordingly. Also keep in mind that the L2 cache must be aligned to
2303 the size of the L1 so we'll need to seek backwards by any misaligned bytes.
2304 */
2305 alignedL1LineCount = bytesRead / DRFLAC_CACHE_L1_SIZE_BYTES(bs);
2306
2307 /* We need to keep track of any unaligned bytes for later use. */
2308 bs->unalignedByteCount = bytesRead - (alignedL1LineCount * DRFLAC_CACHE_L1_SIZE_BYTES(bs));
2309 if (bs->unalignedByteCount > 0) {
2310 bs->unalignedCache = bs->cacheL2[alignedL1LineCount];
2311 }
2312
2313 if (alignedL1LineCount > 0) {
2314 size_t offset = DRFLAC_CACHE_L2_LINE_COUNT(bs) - alignedL1LineCount;
2315 size_t i;
2316 for (i = alignedL1LineCount; i > 0; --i) {
2317 bs->cacheL2[i-1 + offset] = bs->cacheL2[i-1];
2318 }
2319
2320 bs->nextL2Line = (drflac_uint32)offset;
2321 bs->cache = bs->cacheL2[bs->nextL2Line++];
2322 return DRFLAC_TRUE;
2323 } else {
2324 /* If we get into this branch it means we weren't able to load any L1-aligned data. */
2325 bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs);
2326 return DRFLAC_FALSE;
2327 }
2328 }
2329
2330 static drflac_bool32 drflac__reload_cache(drflac_bs* bs)
2331 {
2332 size_t bytesRead;
2333
2334 #ifndef DR_FLAC_NO_CRC
2335 drflac__update_crc16(bs);
2336 #endif
2337
2338 /* Fast path. Try just moving the next value in the L2 cache to the L1 cache. */
2339 if (drflac__reload_l1_cache_from_l2(bs)) {
2340 bs->cache = drflac__be2host__cache_line(bs->cache);
2341 bs->consumedBits = 0;
2342 #ifndef DR_FLAC_NO_CRC
2343 bs->crc16Cache = bs->cache;
2344 #endif
2345 return DRFLAC_TRUE;
2346 }
2347
2348 /* Slow path. */
2349
2350 /*
2351 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
2352 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
2353 data from the unaligned cache.
2354 */
2355 bytesRead = bs->unalignedByteCount;
2356 if (bytesRead == 0) {
2357 bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); /* <-- The stream has been exhausted, so marked the bits as consumed. */
2358 return DRFLAC_FALSE;
2359 }
2360
2361 DRFLAC_ASSERT(bytesRead < DRFLAC_CACHE_L1_SIZE_BYTES(bs));
2362 bs->consumedBits = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bytesRead) * 8;
2363
2364 bs->cache = drflac__be2host__cache_line(bs->unalignedCache);
2365 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. */
2366 bs->unalignedByteCount = 0; /* <-- At this point the unaligned bytes have been moved into the cache and we thus have no more unaligned bytes. */
2367
2368 #ifndef DR_FLAC_NO_CRC
2369 bs->crc16Cache = bs->cache >> bs->consumedBits;
2370 bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
2371 #endif
2372 return DRFLAC_TRUE;
2373 }
2374
2375 static void drflac__reset_cache(drflac_bs* bs)
2376 {
2377 bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs); /* <-- This clears the L2 cache. */
2378 bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs); /* <-- This clears the L1 cache. */
2379 bs->cache = 0;
2380 bs->unalignedByteCount = 0; /* <-- This clears the trailing unaligned bytes. */
2381 bs->unalignedCache = 0;
2382
2383 #ifndef DR_FLAC_NO_CRC
2384 bs->crc16Cache = 0;
2385 bs->crc16CacheIgnoredBytes = 0;
2386 #endif
2387 }
2388
2389
2390 static DRFLAC_INLINE drflac_bool32 drflac__read_uint32(drflac_bs* bs, unsigned int bitCount, drflac_uint32* pResultOut)
2391 {
2392 DRFLAC_ASSERT(bs != NULL);
2393 DRFLAC_ASSERT(pResultOut != NULL);
2394 DRFLAC_ASSERT(bitCount > 0);
2395 DRFLAC_ASSERT(bitCount <= 32);
2396
2397 if (bs->consumedBits == DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
2398 if (!drflac__reload_cache(bs)) {
2399 return DRFLAC_FALSE;
2400 }
2401 }
2402
2403 if (bitCount <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2404 /*
2405 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
2406 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
2407 more optimal solution for this.
2408 */
2409 #ifdef DRFLAC_64BIT
2410 *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
2411 bs->consumedBits += bitCount;
2412 bs->cache <<= bitCount;
2413 #else
2414 if (bitCount < DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
2415 *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
2416 bs->consumedBits += bitCount;
2417 bs->cache <<= bitCount;
2418 } else {
2419 /* Cannot shift by 32-bits, so need to do it differently. */
2420 *pResultOut = (drflac_uint32)bs->cache;
2421 bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);
2422 bs->cache = 0;
2423 }
2424 #endif
2425
2426 return DRFLAC_TRUE;
2427 } else {
2428 /* 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. */
2429 drflac_uint32 bitCountHi = DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2430 drflac_uint32 bitCountLo = bitCount - bitCountHi;
2431 drflac_uint32 resultHi;
2432
2433 DRFLAC_ASSERT(bitCountHi > 0);
2434 DRFLAC_ASSERT(bitCountHi < 32);
2435 resultHi = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountHi);
2436
2437 if (!drflac__reload_cache(bs)) {
2438 return DRFLAC_FALSE;
2439 }
2440 if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2441 /* This happens when we get to end of stream */
2442 return DRFLAC_FALSE;
2443 }
2444
2445 *pResultOut = (resultHi << bitCountLo) | (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo);
2446 bs->consumedBits += bitCountLo;
2447 bs->cache <<= bitCountLo;
2448 return DRFLAC_TRUE;
2449 }
2450 }
2451
2452 static drflac_bool32 drflac__read_int32(drflac_bs* bs, unsigned int bitCount, drflac_int32* pResult)
2453 {
2454 drflac_uint32 result;
2455
2456 DRFLAC_ASSERT(bs != NULL);
2457 DRFLAC_ASSERT(pResult != NULL);
2458 DRFLAC_ASSERT(bitCount > 0);
2459 DRFLAC_ASSERT(bitCount <= 32);
2460
2461 if (!drflac__read_uint32(bs, bitCount, &result)) {
2462 return DRFLAC_FALSE;
2463 }
2464
2465 /* Do not attempt to shift by 32 as it's undefined. */
2466 if (bitCount < 32) {
2467 drflac_uint32 signbit;
2468 signbit = ((result >> (bitCount-1)) & 0x01);
2469 result |= (~signbit + 1) << bitCount;
2470 }
2471
2472 *pResult = (drflac_int32)result;
2473 return DRFLAC_TRUE;
2474 }
2475
2476 #ifdef DRFLAC_64BIT
2477 static drflac_bool32 drflac__read_uint64(drflac_bs* bs, unsigned int bitCount, drflac_uint64* pResultOut)
2478 {
2479 drflac_uint32 resultHi;
2480 drflac_uint32 resultLo;
2481
2482 DRFLAC_ASSERT(bitCount <= 64);
2483 DRFLAC_ASSERT(bitCount > 32);
2484
2485 if (!drflac__read_uint32(bs, bitCount - 32, &resultHi)) {
2486 return DRFLAC_FALSE;
2487 }
2488
2489 if (!drflac__read_uint32(bs, 32, &resultLo)) {
2490 return DRFLAC_FALSE;
2491 }
2492
2493 *pResultOut = (((drflac_uint64)resultHi) << 32) | ((drflac_uint64)resultLo);
2494 return DRFLAC_TRUE;
2495 }
2496 #endif
2497
2498 /* Function below is unused, but leaving it here in case I need to quickly add it again. */
2499 #if 0
2500 static drflac_bool32 drflac__read_int64(drflac_bs* bs, unsigned int bitCount, drflac_int64* pResultOut)
2501 {
2502 drflac_uint64 result;
2503 drflac_uint64 signbit;
2504
2505 DRFLAC_ASSERT(bitCount <= 64);
2506
2507 if (!drflac__read_uint64(bs, bitCount, &result)) {
2508 return DRFLAC_FALSE;
2509 }
2510
2511 signbit = ((result >> (bitCount-1)) & 0x01);
2512 result |= (~signbit + 1) << bitCount;
2513
2514 *pResultOut = (drflac_int64)result;
2515 return DRFLAC_TRUE;
2516 }
2517 #endif
2518
2519 static drflac_bool32 drflac__read_uint16(drflac_bs* bs, unsigned int bitCount, drflac_uint16* pResult)
2520 {
2521 drflac_uint32 result;
2522
2523 DRFLAC_ASSERT(bs != NULL);
2524 DRFLAC_ASSERT(pResult != NULL);
2525 DRFLAC_ASSERT(bitCount > 0);
2526 DRFLAC_ASSERT(bitCount <= 16);
2527
2528 if (!drflac__read_uint32(bs, bitCount, &result)) {
2529 return DRFLAC_FALSE;
2530 }
2531
2532 *pResult = (drflac_uint16)result;
2533 return DRFLAC_TRUE;
2534 }
2535
2536 #if 0
2537 static drflac_bool32 drflac__read_int16(drflac_bs* bs, unsigned int bitCount, drflac_int16* pResult)
2538 {
2539 drflac_int32 result;
2540
2541 DRFLAC_ASSERT(bs != NULL);
2542 DRFLAC_ASSERT(pResult != NULL);
2543 DRFLAC_ASSERT(bitCount > 0);
2544 DRFLAC_ASSERT(bitCount <= 16);
2545
2546 if (!drflac__read_int32(bs, bitCount, &result)) {
2547 return DRFLAC_FALSE;
2548 }
2549
2550 *pResult = (drflac_int16)result;
2551 return DRFLAC_TRUE;
2552 }
2553 #endif
2554
2555 static drflac_bool32 drflac__read_uint8(drflac_bs* bs, unsigned int bitCount, drflac_uint8* pResult)
2556 {
2557 drflac_uint32 result;
2558
2559 DRFLAC_ASSERT(bs != NULL);
2560 DRFLAC_ASSERT(pResult != NULL);
2561 DRFLAC_ASSERT(bitCount > 0);
2562 DRFLAC_ASSERT(bitCount <= 8);
2563
2564 if (!drflac__read_uint32(bs, bitCount, &result)) {
2565 return DRFLAC_FALSE;
2566 }
2567
2568 *pResult = (drflac_uint8)result;
2569 return DRFLAC_TRUE;
2570 }
2571
2572 static drflac_bool32 drflac__read_int8(drflac_bs* bs, unsigned int bitCount, drflac_int8* pResult)
2573 {
2574 drflac_int32 result;
2575
2576 DRFLAC_ASSERT(bs != NULL);
2577 DRFLAC_ASSERT(pResult != NULL);
2578 DRFLAC_ASSERT(bitCount > 0);
2579 DRFLAC_ASSERT(bitCount <= 8);
2580
2581 if (!drflac__read_int32(bs, bitCount, &result)) {
2582 return DRFLAC_FALSE;
2583 }
2584
2585 *pResult = (drflac_int8)result;
2586 return DRFLAC_TRUE;
2587 }
2588
2589
2590 static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek)
2591 {
2592 if (bitsToSeek <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2593 bs->consumedBits += (drflac_uint32)bitsToSeek;
2594 bs->cache <<= bitsToSeek;
2595 return DRFLAC_TRUE;
2596 } else {
2597 /* It straddles the cached data. This function isn't called too frequently so I'm favouring simplicity here. */
2598 bitsToSeek -= DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2599 bs->consumedBits += DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2600 bs->cache = 0;
2601
2602 /* Simple case. Seek in groups of the same number as bits that fit within a cache line. */
2603 #ifdef DRFLAC_64BIT
2604 while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
2605 drflac_uint64 bin;
2606 if (!drflac__read_uint64(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
2607 return DRFLAC_FALSE;
2608 }
2609 bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
2610 }
2611 #else
2612 while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
2613 drflac_uint32 bin;
2614 if (!drflac__read_uint32(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
2615 return DRFLAC_FALSE;
2616 }
2617 bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
2618 }
2619 #endif
2620
2621 /* Whole leftover bytes. */
2622 while (bitsToSeek >= 8) {
2623 drflac_uint8 bin;
2624 if (!drflac__read_uint8(bs, 8, &bin)) {
2625 return DRFLAC_FALSE;
2626 }
2627 bitsToSeek -= 8;
2628 }
2629
2630 /* Leftover bits. */
2631 if (bitsToSeek > 0) {
2632 drflac_uint8 bin;
2633 if (!drflac__read_uint8(bs, (drflac_uint32)bitsToSeek, &bin)) {
2634 return DRFLAC_FALSE;
2635 }
2636 bitsToSeek = 0; /* <-- Necessary for the assert below. */
2637 }
2638
2639 DRFLAC_ASSERT(bitsToSeek == 0);
2640 return DRFLAC_TRUE;
2641 }
2642 }
2643
2644
2645 /* 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. */
2646 static drflac_bool32 drflac__find_and_seek_to_next_sync_code(drflac_bs* bs)
2647 {
2648 DRFLAC_ASSERT(bs != NULL);
2649
2650 /*
2651 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
2652 thing to do is align to the next byte.
2653 */
2654 if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
2655 return DRFLAC_FALSE;
2656 }
2657
2658 for (;;) {
2659 drflac_uint8 hi;
2660
2661 #ifndef DR_FLAC_NO_CRC
2662 drflac__reset_crc16(bs);
2663 #endif
2664
2665 if (!drflac__read_uint8(bs, 8, &hi)) {
2666 return DRFLAC_FALSE;
2667 }
2668
2669 if (hi == 0xFF) {
2670 drflac_uint8 lo;
2671 if (!drflac__read_uint8(bs, 6, &lo)) {
2672 return DRFLAC_FALSE;
2673 }
2674
2675 if (lo == 0x3E) {
2676 return DRFLAC_TRUE;
2677 } else {
2678 if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
2679 return DRFLAC_FALSE;
2680 }
2681 }
2682 }
2683 }
2684
2685 /* Should never get here. */
2686 /*return DRFLAC_FALSE;*/
2687 }
2688
2689
2690 #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
2691 #define DRFLAC_IMPLEMENT_CLZ_LZCNT
2692 #endif
2693 #if defined(_MSC_VER) && _MSC_VER >= 1400 && (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(__clang__)
2694 #define DRFLAC_IMPLEMENT_CLZ_MSVC
2695 #endif
2696 #if defined(__WATCOMC__) && defined(__386__)
2697 #define DRFLAC_IMPLEMENT_CLZ_WATCOM
2698 #endif
2699
2700 static DRFLAC_INLINE drflac_uint32 drflac__clz_software(drflac_cache_t x)
2701 {
2702 drflac_uint32 n;
2703 static drflac_uint32 clz_table_4[] = {
2704 0,
2705 4,
2706 3, 3,
2707 2, 2, 2, 2,
2708 1, 1, 1, 1, 1, 1, 1, 1
2709 };
2710
2711 if (x == 0) {
2712 return sizeof(x)*8;
2713 }
2714
2715 n = clz_table_4[x >> (sizeof(x)*8 - 4)];
2716 if (n == 0) {
2717 #ifdef DRFLAC_64BIT
2718 if ((x & ((drflac_uint64)0xFFFFFFFF << 32)) == 0) { n = 32; x <<= 32; }
2719 if ((x & ((drflac_uint64)0xFFFF0000 << 32)) == 0) { n += 16; x <<= 16; }
2720 if ((x & ((drflac_uint64)0xFF000000 << 32)) == 0) { n += 8; x <<= 8; }
2721 if ((x & ((drflac_uint64)0xF0000000 << 32)) == 0) { n += 4; x <<= 4; }
2722 #else
2723 if ((x & 0xFFFF0000) == 0) { n = 16; x <<= 16; }
2724 if ((x & 0xFF000000) == 0) { n += 8; x <<= 8; }
2725 if ((x & 0xF0000000) == 0) { n += 4; x <<= 4; }
2726 #endif
2727 n += clz_table_4[x >> (sizeof(x)*8 - 4)];
2728 }
2729
2730 return n - 1;
2731 }
2732
2733 #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
2734 static DRFLAC_INLINE drflac_bool32 drflac__is_lzcnt_supported(void)
2735 {
2736 /* Fast compile time check for ARM. */
2737 #if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
2738 return DRFLAC_TRUE;
2739 #else
2740 /* If the compiler itself does not support the intrinsic then we'll need to return false. */
2741 #ifdef DRFLAC_HAS_LZCNT_INTRINSIC
2742 return drflac__gIsLZCNTSupported;
2743 #else
2744 return DRFLAC_FALSE;
2745 #endif
2746 #endif
2747 }
2748
2749 static DRFLAC_INLINE drflac_uint32 drflac__clz_lzcnt(drflac_cache_t x)
2750 {
2751 /*
2752 It's critical for competitive decoding performance that this function be highly optimal. With MSVC we can use the __lzcnt64() and __lzcnt() intrinsics
2753 to achieve good performance, however on GCC and Clang it's a little bit more annoying. The __builtin_clzl() and __builtin_clzll() intrinsics leave
2754 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
2755 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
2756 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
2757 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
2758 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
2759 getting clobbered?
2760
2761 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
2762 assembly rules for `clang-cl`. If somebody can identify an error in dr_flac's inlined assembly I'm happy to get that fixed.
2763
2764 Fortunately there is an easy workaround for this. Clang implements MSVC-specific intrinsics for compatibility. It also defines _MSC_VER for extra
2765 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
2766 to know how to fix the inlined assembly for correctness sake, however.
2767 */
2768
2769 #if defined(_MSC_VER) /*&& !defined(__clang__)*/ /* <-- Intentionally wanting Clang to use the MSVC __lzcnt64/__lzcnt intrinsics due to above ^. */
2770 #ifdef DRFLAC_64BIT
2771 return (drflac_uint32)__lzcnt64(x);
2772 #else
2773 return (drflac_uint32)__lzcnt(x);
2774 #endif
2775 #else
2776 #if defined(__GNUC__) || defined(__clang__)
2777 #if defined(DRFLAC_X64)
2778 {
2779 drflac_uint64 r;
2780 __asm__ __volatile__ (
2781 "lzcnt{ %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
2782 );
2783
2784 return (drflac_uint32)r;
2785 }
2786 #elif defined(DRFLAC_X86)
2787 {
2788 drflac_uint32 r;
2789 __asm__ __volatile__ (
2790 "lzcnt{l %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
2791 );
2792
2793 return r;
2794 }
2795 #elif defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) && !defined(DRFLAC_64BIT) /* <-- I haven't tested 64-bit inline assembly, so only enabling this for the 32-bit build for now. */
2796 {
2797 unsigned int r;
2798 __asm__ __volatile__ (
2799 #if defined(DRFLAC_64BIT)
2800 "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! */
2801 #else
2802 "clz %[out], %[in]" : [out]"=r"(r) : [in]"r"(x)
2803 #endif
2804 );
2805
2806 return r;
2807 }
2808 #else
2809 if (x == 0) {
2810 return sizeof(x)*8;
2811 }
2812 #ifdef DRFLAC_64BIT
2813 return (drflac_uint32)__builtin_clzll((drflac_uint64)x);
2814 #else
2815 return (drflac_uint32)__builtin_clzl((drflac_uint32)x);
2816 #endif
2817 #endif
2818 #else
2819 /* Unsupported compiler. */
2820 #error "This compiler does not support the lzcnt intrinsic."
2821 #endif
2822 #endif
2823 }
2824 #endif
2825
2826 #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
2827 #include <intrin.h> /* For BitScanReverse(). */
2828
2829 static DRFLAC_INLINE drflac_uint32 drflac__clz_msvc(drflac_cache_t x)
2830 {
2831 drflac_uint32 n;
2832
2833 if (x == 0) {
2834 return sizeof(x)*8;
2835 }
2836
2837 #ifdef DRFLAC_64BIT
2838 _BitScanReverse64((unsigned long*)&n, x);
2839 #else
2840 _BitScanReverse((unsigned long*)&n, x);
2841 #endif
2842 return sizeof(x)*8 - n - 1;
2843 }
2844 #endif
2845
2846 #ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM
2847 static __inline drflac_uint32 drflac__clz_watcom (drflac_uint32);
2848 #pragma aux drflac__clz_watcom = \
2849 "bsr eax, eax" \
2850 "xor eax, 31" \
2851 parm [eax] nomemory \
2852 value [eax] \
2853 modify exact [eax] nomemory;
2854 #endif
2855
2856 static DRFLAC_INLINE drflac_uint32 drflac__clz(drflac_cache_t x)
2857 {
2858 #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
2859 if (drflac__is_lzcnt_supported()) {
2860 return drflac__clz_lzcnt(x);
2861 } else
2862 #endif
2863 {
2864 #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
2865 return drflac__clz_msvc(x);
2866 #elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM)
2867 return (x == 0) ? sizeof(x)*8 : drflac__clz_watcom(x);
2868 #else
2869 return drflac__clz_software(x);
2870 #endif
2871 }
2872 }
2873
2874
2875 static DRFLAC_INLINE drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsigned int* pOffsetOut)
2876 {
2877 drflac_uint32 zeroCounter = 0;
2878 drflac_uint32 setBitOffsetPlus1;
2879
2880 while (bs->cache == 0) {
2881 zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
2882 if (!drflac__reload_cache(bs)) {
2883 return DRFLAC_FALSE;
2884 }
2885 }
2886
2887 if (bs->cache == 1) {
2888 /* Not catching this would lead to undefined behaviour: a shift of a 32-bit number by 32 or more is undefined */
2889 *pOffsetOut = zeroCounter + (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs) - 1;
2890 if (!drflac__reload_cache(bs)) {
2891 return DRFLAC_FALSE;
2892 }
2893
2894 return DRFLAC_TRUE;
2895 }
2896
2897 setBitOffsetPlus1 = drflac__clz(bs->cache);
2898 setBitOffsetPlus1 += 1;
2899
2900 if (setBitOffsetPlus1 > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
2901 /* This happens when we get to end of stream */
2902 return DRFLAC_FALSE;
2903 }
2904
2905 bs->consumedBits += setBitOffsetPlus1;
2906 bs->cache <<= setBitOffsetPlus1;
2907
2908 *pOffsetOut = zeroCounter + setBitOffsetPlus1 - 1;
2909 return DRFLAC_TRUE;
2910 }
2911
2912
2913
2914 static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFromStart)
2915 {
2916 DRFLAC_ASSERT(bs != NULL);
2917 DRFLAC_ASSERT(offsetFromStart > 0);
2918
2919 /*
2920 Seeking from the start is not quite as trivial as it sounds because the onSeek callback takes a signed 32-bit integer (which
2921 is intentional because it simplifies the implementation of the onSeek callbacks), however offsetFromStart is unsigned 64-bit.
2922 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.
2923 */
2924 if (offsetFromStart > 0x7FFFFFFF) {
2925 drflac_uint64 bytesRemaining = offsetFromStart;
2926 if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start)) {
2927 return DRFLAC_FALSE;
2928 }
2929 bytesRemaining -= 0x7FFFFFFF;
2930
2931 while (bytesRemaining > 0x7FFFFFFF) {
2932 if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current)) {
2933 return DRFLAC_FALSE;
2934 }
2935 bytesRemaining -= 0x7FFFFFFF;
2936 }
2937
2938 if (bytesRemaining > 0) {
2939 if (!bs->onSeek(bs->pUserData, (int)bytesRemaining, drflac_seek_origin_current)) {
2940 return DRFLAC_FALSE;
2941 }
2942 }
2943 } else {
2944 if (!bs->onSeek(bs->pUserData, (int)offsetFromStart, drflac_seek_origin_start)) {
2945 return DRFLAC_FALSE;
2946 }
2947 }
2948
2949 /* The cache should be reset to force a reload of fresh data from the client. */
2950 drflac__reset_cache(bs);
2951 return DRFLAC_TRUE;
2952 }
2953
2954
2955 static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64* pNumberOut, drflac_uint8* pCRCOut)
2956 {
2957 drflac_uint8 crc;
2958 drflac_uint64 result;
2959 drflac_uint8 utf8[7] = {0};
2960 int byteCount;
2961 int i;
2962
2963 DRFLAC_ASSERT(bs != NULL);
2964 DRFLAC_ASSERT(pNumberOut != NULL);
2965 DRFLAC_ASSERT(pCRCOut != NULL);
2966
2967 crc = *pCRCOut;
2968
2969 if (!drflac__read_uint8(bs, 8, utf8)) {
2970 *pNumberOut = 0;
2971 return DRFLAC_AT_END;
2972 }
2973 crc = drflac_crc8(crc, utf8[0], 8);
2974
2975 if ((utf8[0] & 0x80) == 0) {
2976 *pNumberOut = utf8[0];
2977 *pCRCOut = crc;
2978 return DRFLAC_SUCCESS;
2979 }
2980
2981 /*byteCount = 1;*/
2982 if ((utf8[0] & 0xE0) == 0xC0) {
2983 byteCount = 2;
2984 } else if ((utf8[0] & 0xF0) == 0xE0) {
2985 byteCount = 3;
2986 } else if ((utf8[0] & 0xF8) == 0xF0) {
2987 byteCount = 4;
2988 } else if ((utf8[0] & 0xFC) == 0xF8) {
2989 byteCount = 5;
2990 } else if ((utf8[0] & 0xFE) == 0xFC) {
2991 byteCount = 6;
2992 } else if ((utf8[0] & 0xFF) == 0xFE) {
2993 byteCount = 7;
2994 } else {
2995 *pNumberOut = 0;
2996 return DRFLAC_CRC_MISMATCH; /* Bad UTF-8 encoding. */
2997 }
2998
2999 /* Read extra bytes. */
3000 DRFLAC_ASSERT(byteCount > 1);
3001
3002 result = (drflac_uint64)(utf8[0] & (0xFF >> (byteCount + 1)));
3003 for (i = 1; i < byteCount; ++i) {
3004 if (!drflac__read_uint8(bs, 8, utf8 + i)) {
3005 *pNumberOut = 0;
3006 return DRFLAC_AT_END;
3007 }
3008 crc = drflac_crc8(crc, utf8[i], 8);
3009
3010 result = (result << 6) | (utf8[i] & 0x3F);
3011 }
3012
3013 *pNumberOut = result;
3014 *pCRCOut = crc;
3015 return DRFLAC_SUCCESS;
3016 }
3017
3018
3019 static DRFLAC_INLINE drflac_uint32 drflac__ilog2_u32(drflac_uint32 x)
3020 {
3021 #if 1 /* Needs optimizing. */
3022 drflac_uint32 result = 0;
3023 while (x > 0) {
3024 result += 1;
3025 x >>= 1;
3026 }
3027
3028 return result;
3029 #endif
3030 }
3031
3032 static DRFLAC_INLINE drflac_bool32 drflac__use_64_bit_prediction(drflac_uint32 bitsPerSample, drflac_uint32 order, drflac_uint32 precision)
3033 {
3034 /* https://web.archive.org/web/20220205005724/https://github.com/ietf-wg-cellar/flac-specification/blob/37a49aa48ba4ba12e8757badfc59c0df35435fec/rfc_backmatter.md */
3035 return bitsPerSample + precision + drflac__ilog2_u32(order) > 32;
3036 }
3037
3038
3039 /*
3040 The next two functions are responsible for calculating the prediction.
3041
3042 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
3043 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.
3044 */
3045 #if defined(__clang__)
3046 __attribute__((no_sanitize("signed-integer-overflow")))
3047 #endif
3048 static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_32(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
3049 {
3050 drflac_int32 prediction = 0;
3051
3052 DRFLAC_ASSERT(order <= 32);
3053
3054 /* 32-bit version. */
3055
3056 /* VC++ optimizes this to a single jmp. I've not yet verified this for other compilers. */
3057 switch (order)
3058 {
3059 case 32: prediction += coefficients[31] * pDecodedSamples[-32];
3060 case 31: prediction += coefficients[30] * pDecodedSamples[-31];
3061 case 30: prediction += coefficients[29] * pDecodedSamples[-30];
3062 case 29: prediction += coefficients[28] * pDecodedSamples[-29];
3063 case 28: prediction += coefficients[27] * pDecodedSamples[-28];
3064 case 27: prediction += coefficients[26] * pDecodedSamples[-27];
3065 case 26: prediction += coefficients[25] * pDecodedSamples[-26];
3066 case 25: prediction += coefficients[24] * pDecodedSamples[-25];
3067 case 24: prediction += coefficients[23] * pDecodedSamples[-24];
3068 case 23: prediction += coefficients[22] * pDecodedSamples[-23];
3069 case 22: prediction += coefficients[21] * pDecodedSamples[-22];
3070 case 21: prediction += coefficients[20] * pDecodedSamples[-21];
3071 case 20: prediction += coefficients[19] * pDecodedSamples[-20];
3072 case 19: prediction += coefficients[18] * pDecodedSamples[-19];
3073 case 18: prediction += coefficients[17] * pDecodedSamples[-18];
3074 case 17: prediction += coefficients[16] * pDecodedSamples[-17];
3075 case 16: prediction += coefficients[15] * pDecodedSamples[-16];
3076 case 15: prediction += coefficients[14] * pDecodedSamples[-15];
3077 case 14: prediction += coefficients[13] * pDecodedSamples[-14];
3078 case 13: prediction += coefficients[12] * pDecodedSamples[-13];
3079 case 12: prediction += coefficients[11] * pDecodedSamples[-12];
3080 case 11: prediction += coefficients[10] * pDecodedSamples[-11];
3081 case 10: prediction += coefficients[ 9] * pDecodedSamples[-10];
3082 case 9: prediction += coefficients[ 8] * pDecodedSamples[- 9];
3083 case 8: prediction += coefficients[ 7] * pDecodedSamples[- 8];
3084 case 7: prediction += coefficients[ 6] * pDecodedSamples[- 7];
3085 case 6: prediction += coefficients[ 5] * pDecodedSamples[- 6];
3086 case 5: prediction += coefficients[ 4] * pDecodedSamples[- 5];
3087 case 4: prediction += coefficients[ 3] * pDecodedSamples[- 4];
3088 case 3: prediction += coefficients[ 2] * pDecodedSamples[- 3];
3089 case 2: prediction += coefficients[ 1] * pDecodedSamples[- 2];
3090 case 1: prediction += coefficients[ 0] * pDecodedSamples[- 1];
3091 }
3092
3093 return (drflac_int32)(prediction >> shift);
3094 }
3095
3096 static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
3097 {
3098 drflac_int64 prediction;
3099
3100 DRFLAC_ASSERT(order <= 32);
3101
3102 /* 64-bit version. */
3103
3104 /* This method is faster on the 32-bit build when compiling with VC++. See note below. */
3105 #ifndef DRFLAC_64BIT
3106 if (order == 8)
3107 {
3108 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3109 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3110 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3111 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3112 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3113 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3114 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3115 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3116 }
3117 else if (order == 7)
3118 {
3119 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3120 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3121 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3122 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3123 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3124 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3125 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3126 }
3127 else if (order == 3)
3128 {
3129 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3130 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3131 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3132 }
3133 else if (order == 6)
3134 {
3135 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3136 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3137 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3138 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3139 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3140 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3141 }
3142 else if (order == 5)
3143 {
3144 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3145 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3146 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3147 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3148 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3149 }
3150 else if (order == 4)
3151 {
3152 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3153 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3154 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3155 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3156 }
3157 else if (order == 12)
3158 {
3159 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3160 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3161 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3162 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3163 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3164 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3165 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3166 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3167 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3168 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
3169 prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
3170 prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
3171 }
3172 else if (order == 2)
3173 {
3174 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3175 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3176 }
3177 else if (order == 1)
3178 {
3179 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3180 }
3181 else if (order == 10)
3182 {
3183 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3184 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3185 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3186 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3187 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3188 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3189 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3190 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3191 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3192 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
3193 }
3194 else if (order == 9)
3195 {
3196 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3197 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3198 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3199 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3200 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3201 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3202 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3203 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3204 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3205 }
3206 else if (order == 11)
3207 {
3208 prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
3209 prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
3210 prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
3211 prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
3212 prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
3213 prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
3214 prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
3215 prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
3216 prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
3217 prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
3218 prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
3219 }
3220 else
3221 {
3222 int j;
3223
3224 prediction = 0;
3225 for (j = 0; j < (int)order; ++j) {
3226 prediction += coefficients[j] * (drflac_int64)pDecodedSamples[-j-1];
3227 }
3228 }
3229 #endif
3230
3231 /*
3232 VC++ optimizes this to a single jmp instruction, but only the 64-bit build. The 32-bit build generates less efficient code for some
3233 reason. The ugly version above is faster so we'll just switch between the two depending on the target platform.
3234 */
3235 #ifdef DRFLAC_64BIT
3236 prediction = 0;
3237 switch (order)
3238 {
3239 case 32: prediction += coefficients[31] * (drflac_int64)pDecodedSamples[-32];
3240 case 31: prediction += coefficients[30] * (drflac_int64)pDecodedSamples[-31];
3241 case 30: prediction += coefficients[29] * (drflac_int64)pDecodedSamples[-30];
3242 case 29: prediction += coefficients[28] * (drflac_int64)pDecodedSamples[-29];
3243 case 28: prediction += coefficients[27] * (drflac_int64)pDecodedSamples[-28];
3244 case 27: prediction += coefficients[26] * (drflac_int64)pDecodedSamples[-27];
3245 case 26: prediction += coefficients[25] * (drflac_int64)pDecodedSamples[-26];
3246 case 25: prediction += coefficients[24] * (drflac_int64)pDecodedSamples[-25];
3247 case 24: prediction += coefficients[23] * (drflac_int64)pDecodedSamples[-24];
3248 case 23: prediction += coefficients[22] * (drflac_int64)pDecodedSamples[-23];
3249 case 22: prediction += coefficients[21] * (drflac_int64)pDecodedSamples[-22];
3250 case 21: prediction += coefficients[20] * (drflac_int64)pDecodedSamples[-21];
3251 case 20: prediction += coefficients[19] * (drflac_int64)pDecodedSamples[-20];
3252 case 19: prediction += coefficients[18] * (drflac_int64)pDecodedSamples[-19];
3253 case 18: prediction += coefficients[17] * (drflac_int64)pDecodedSamples[-18];
3254 case 17: prediction += coefficients[16] * (drflac_int64)pDecodedSamples[-17];
3255 case 16: prediction += coefficients[15] * (drflac_int64)pDecodedSamples[-16];
3256 case 15: prediction += coefficients[14] * (drflac_int64)pDecodedSamples[-15];
3257 case 14: prediction += coefficients[13] * (drflac_int64)pDecodedSamples[-14];
3258 case 13: prediction += coefficients[12] * (drflac_int64)pDecodedSamples[-13];
3259 case 12: prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
3260 case 11: prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
3261 case 10: prediction += coefficients[ 9] * (drflac_int64)pDecodedSamples[-10];
3262 case 9: prediction += coefficients[ 8] * (drflac_int64)pDecodedSamples[- 9];
3263 case 8: prediction += coefficients[ 7] * (drflac_int64)pDecodedSamples[- 8];
3264 case 7: prediction += coefficients[ 6] * (drflac_int64)pDecodedSamples[- 7];
3265 case 6: prediction += coefficients[ 5] * (drflac_int64)pDecodedSamples[- 6];
3266 case 5: prediction += coefficients[ 4] * (drflac_int64)pDecodedSamples[- 5];
3267 case 4: prediction += coefficients[ 3] * (drflac_int64)pDecodedSamples[- 4];
3268 case 3: prediction += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 3];
3269 case 2: prediction += coefficients[ 1] * (drflac_int64)pDecodedSamples[- 2];
3270 case 1: prediction += coefficients[ 0] * (drflac_int64)pDecodedSamples[- 1];
3271 }
3272 #endif
3273
3274 return (drflac_int32)(prediction >> shift);
3275 }
3276
3277
3278 #if 0
3279 /*
3280 Reference implementation for reading and decoding samples with residual. This is intentionally left unoptimized for the
3281 sake of readability and should only be used as a reference.
3282 */
3283 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)
3284 {
3285 drflac_uint32 i;
3286
3287 DRFLAC_ASSERT(bs != NULL);
3288 DRFLAC_ASSERT(pSamplesOut != NULL);
3289
3290 for (i = 0; i < count; ++i) {
3291 drflac_uint32 zeroCounter = 0;
3292 for (;;) {
3293 drflac_uint8 bit;
3294 if (!drflac__read_uint8(bs, 1, &bit)) {
3295 return DRFLAC_FALSE;
3296 }
3297
3298 if (bit == 0) {
3299 zeroCounter += 1;
3300 } else {
3301 break;
3302 }
3303 }
3304
3305 drflac_uint32 decodedRice;
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 decodedRice |= (zeroCounter << riceParam);
3315 if ((decodedRice & 0x01)) {
3316 decodedRice = ~(decodedRice >> 1);
3317 } else {
3318 decodedRice = (decodedRice >> 1);
3319 }
3320
3321
3322 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
3323 pSamplesOut[i] = decodedRice + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
3324 } else {
3325 pSamplesOut[i] = decodedRice + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
3326 }
3327 }
3328
3329 return DRFLAC_TRUE;
3330 }
3331 #endif
3332
3333 #if 0
3334 static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
3335 {
3336 drflac_uint32 zeroCounter = 0;
3337 drflac_uint32 decodedRice;
3338
3339 for (;;) {
3340 drflac_uint8 bit;
3341 if (!drflac__read_uint8(bs, 1, &bit)) {
3342 return DRFLAC_FALSE;
3343 }
3344
3345 if (bit == 0) {
3346 zeroCounter += 1;
3347 } else {
3348 break;
3349 }
3350 }
3351
3352 if (riceParam > 0) {
3353 if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
3354 return DRFLAC_FALSE;
3355 }
3356 } else {
3357 decodedRice = 0;
3358 }
3359
3360 *pZeroCounterOut = zeroCounter;
3361 *pRiceParamPartOut = decodedRice;
3362 return DRFLAC_TRUE;
3363 }
3364 #endif
3365
3366 #if 0
3367 static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
3368 {
3369 drflac_cache_t riceParamMask;
3370 drflac_uint32 zeroCounter;
3371 drflac_uint32 setBitOffsetPlus1;
3372 drflac_uint32 riceParamPart;
3373 drflac_uint32 riceLength;
3374
3375 DRFLAC_ASSERT(riceParam > 0); /* <-- riceParam should never be 0. drflac__read_rice_parts__param_equals_zero() should be used instead for this case. */
3376
3377 riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParam);
3378
3379 zeroCounter = 0;
3380 while (bs->cache == 0) {
3381 zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
3382 if (!drflac__reload_cache(bs)) {
3383 return DRFLAC_FALSE;
3384 }
3385 }
3386
3387 setBitOffsetPlus1 = drflac__clz(bs->cache);
3388 zeroCounter += setBitOffsetPlus1;
3389 setBitOffsetPlus1 += 1;
3390
3391 riceLength = setBitOffsetPlus1 + riceParam;
3392 if (riceLength < DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3393 riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength));
3394
3395 bs->consumedBits += riceLength;
3396 bs->cache <<= riceLength;
3397 } else {
3398 drflac_uint32 bitCountLo;
3399 drflac_cache_t resultHi;
3400
3401 bs->consumedBits += riceLength;
3402 bs->cache <<= setBitOffsetPlus1 & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1); /* <-- Equivalent to "if (setBitOffsetPlus1 < DRFLAC_CACHE_L1_SIZE_BITS(bs)) { bs->cache <<= setBitOffsetPlus1; }" */
3403
3404 /* 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. */
3405 bitCountLo = bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs);
3406 resultHi = DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, riceParam); /* <-- Use DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE() if ever this function allows riceParam=0. */
3407
3408 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3409 #ifndef DR_FLAC_NO_CRC
3410 drflac__update_crc16(bs);
3411 #endif
3412 bs->cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3413 bs->consumedBits = 0;
3414 #ifndef DR_FLAC_NO_CRC
3415 bs->crc16Cache = bs->cache;
3416 #endif
3417 } else {
3418 /* Slow path. We need to fetch more data from the client. */
3419 if (!drflac__reload_cache(bs)) {
3420 return DRFLAC_FALSE;
3421 }
3422 if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3423 /* This happens when we get to end of stream */
3424 return DRFLAC_FALSE;
3425 }
3426 }
3427
3428 riceParamPart = (drflac_uint32)(resultHi | DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo));
3429
3430 bs->consumedBits += bitCountLo;
3431 bs->cache <<= bitCountLo;
3432 }
3433
3434 pZeroCounterOut[0] = zeroCounter;
3435 pRiceParamPartOut[0] = riceParamPart;
3436
3437 return DRFLAC_TRUE;
3438 }
3439 #endif
3440
3441 static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts_x1(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
3442 {
3443 drflac_uint32 riceParamPlus1 = riceParam + 1;
3444 /*drflac_cache_t riceParamPlus1Mask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParamPlus1);*/
3445 drflac_uint32 riceParamPlus1Shift = DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPlus1);
3446 drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
3447
3448 /*
3449 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
3450 no idea how this will work in practice...
3451 */
3452 drflac_cache_t bs_cache = bs->cache;
3453 drflac_uint32 bs_consumedBits = bs->consumedBits;
3454
3455 /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */
3456 drflac_uint32 lzcount = drflac__clz(bs_cache);
3457 if (lzcount < sizeof(bs_cache)*8) {
3458 pZeroCounterOut[0] = lzcount;
3459
3460 /*
3461 It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting
3462 this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled
3463 outside of this function at a higher level.
3464 */
3465 extract_rice_param_part:
3466 bs_cache <<= lzcount;
3467 bs_consumedBits += lzcount;
3468
3469 if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
3470 /* Getting here means the rice parameter part is wholly contained within the current cache line. */
3471 pRiceParamPartOut[0] = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
3472 bs_cache <<= riceParamPlus1;
3473 bs_consumedBits += riceParamPlus1;
3474 } else {
3475 drflac_uint32 riceParamPartHi;
3476 drflac_uint32 riceParamPartLo;
3477 drflac_uint32 riceParamPartLoBitCount;
3478
3479 /*
3480 Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache
3481 line, reload the cache, and then combine it with the head of the next cache line.
3482 */
3483
3484 /* Grab the high part of the rice parameter part. */
3485 riceParamPartHi = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
3486
3487 /* Before reloading the cache we need to grab the size in bits of the low part. */
3488 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
3489 DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
3490
3491 /* Now reload the cache. */
3492 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3493 #ifndef DR_FLAC_NO_CRC
3494 drflac__update_crc16(bs);
3495 #endif
3496 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3497 bs_consumedBits = riceParamPartLoBitCount;
3498 #ifndef DR_FLAC_NO_CRC
3499 bs->crc16Cache = bs_cache;
3500 #endif
3501 } else {
3502 /* Slow path. We need to fetch more data from the client. */
3503 if (!drflac__reload_cache(bs)) {
3504 return DRFLAC_FALSE;
3505 }
3506 if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3507 /* This happens when we get to end of stream */
3508 return DRFLAC_FALSE;
3509 }
3510
3511 bs_cache = bs->cache;
3512 bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
3513 }
3514
3515 /* We should now have enough information to construct the rice parameter part. */
3516 riceParamPartLo = (drflac_uint32)(bs_cache >> (DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPartLoBitCount)));
3517 pRiceParamPartOut[0] = riceParamPartHi | riceParamPartLo;
3518
3519 bs_cache <<= riceParamPartLoBitCount;
3520 }
3521 } else {
3522 /*
3523 Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call
3524 to drflac__clz() and we need to reload the cache.
3525 */
3526 drflac_uint32 zeroCounter = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BITS(bs) - bs_consumedBits);
3527 for (;;) {
3528 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3529 #ifndef DR_FLAC_NO_CRC
3530 drflac__update_crc16(bs);
3531 #endif
3532 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3533 bs_consumedBits = 0;
3534 #ifndef DR_FLAC_NO_CRC
3535 bs->crc16Cache = bs_cache;
3536 #endif
3537 } else {
3538 /* Slow path. We need to fetch more data from the client. */
3539 if (!drflac__reload_cache(bs)) {
3540 return DRFLAC_FALSE;
3541 }
3542
3543 bs_cache = bs->cache;
3544 bs_consumedBits = bs->consumedBits;
3545 }
3546
3547 lzcount = drflac__clz(bs_cache);
3548 zeroCounter += lzcount;
3549
3550 if (lzcount < sizeof(bs_cache)*8) {
3551 break;
3552 }
3553 }
3554
3555 pZeroCounterOut[0] = zeroCounter;
3556 goto extract_rice_param_part;
3557 }
3558
3559 /* Make sure the cache is restored at the end of it all. */
3560 bs->cache = bs_cache;
3561 bs->consumedBits = bs_consumedBits;
3562
3563 return DRFLAC_TRUE;
3564 }
3565
3566 static DRFLAC_INLINE drflac_bool32 drflac__seek_rice_parts(drflac_bs* bs, drflac_uint8 riceParam)
3567 {
3568 drflac_uint32 riceParamPlus1 = riceParam + 1;
3569 drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
3570
3571 /*
3572 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
3573 no idea how this will work in practice...
3574 */
3575 drflac_cache_t bs_cache = bs->cache;
3576 drflac_uint32 bs_consumedBits = bs->consumedBits;
3577
3578 /* The first thing to do is find the first unset bit. Most likely a bit will be set in the current cache line. */
3579 drflac_uint32 lzcount = drflac__clz(bs_cache);
3580 if (lzcount < sizeof(bs_cache)*8) {
3581 /*
3582 It is most likely that the riceParam part (which comes after the zero counter) is also on this cache line. When extracting
3583 this, we include the set bit from the unary coded part because it simplifies cache management. This bit will be handled
3584 outside of this function at a higher level.
3585 */
3586 extract_rice_param_part:
3587 bs_cache <<= lzcount;
3588 bs_consumedBits += lzcount;
3589
3590 if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
3591 /* Getting here means the rice parameter part is wholly contained within the current cache line. */
3592 bs_cache <<= riceParamPlus1;
3593 bs_consumedBits += riceParamPlus1;
3594 } else {
3595 /*
3596 Getting here means the rice parameter part straddles the cache line. We need to read from the tail of the current cache
3597 line, reload the cache, and then combine it with the head of the next cache line.
3598 */
3599
3600 /* Before reloading the cache we need to grab the size in bits of the low part. */
3601 drflac_uint32 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
3602 DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
3603
3604 /* Now reload the cache. */
3605 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3606 #ifndef DR_FLAC_NO_CRC
3607 drflac__update_crc16(bs);
3608 #endif
3609 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3610 bs_consumedBits = riceParamPartLoBitCount;
3611 #ifndef DR_FLAC_NO_CRC
3612 bs->crc16Cache = bs_cache;
3613 #endif
3614 } else {
3615 /* Slow path. We need to fetch more data from the client. */
3616 if (!drflac__reload_cache(bs)) {
3617 return DRFLAC_FALSE;
3618 }
3619
3620 if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
3621 /* This happens when we get to end of stream */
3622 return DRFLAC_FALSE;
3623 }
3624
3625 bs_cache = bs->cache;
3626 bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
3627 }
3628
3629 bs_cache <<= riceParamPartLoBitCount;
3630 }
3631 } else {
3632 /*
3633 Getting here means there are no bits set on the cache line. This is a less optimal case because we just wasted a call
3634 to drflac__clz() and we need to reload the cache.
3635 */
3636 for (;;) {
3637 if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
3638 #ifndef DR_FLAC_NO_CRC
3639 drflac__update_crc16(bs);
3640 #endif
3641 bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
3642 bs_consumedBits = 0;
3643 #ifndef DR_FLAC_NO_CRC
3644 bs->crc16Cache = bs_cache;
3645 #endif
3646 } else {
3647 /* Slow path. We need to fetch more data from the client. */
3648 if (!drflac__reload_cache(bs)) {
3649 return DRFLAC_FALSE;
3650 }
3651
3652 bs_cache = bs->cache;
3653 bs_consumedBits = bs->consumedBits;
3654 }
3655
3656 lzcount = drflac__clz(bs_cache);
3657 if (lzcount < sizeof(bs_cache)*8) {
3658 break;
3659 }
3660 }
3661
3662 goto extract_rice_param_part;
3663 }
3664
3665 /* Make sure the cache is restored at the end of it all. */
3666 bs->cache = bs_cache;
3667 bs->consumedBits = bs_consumedBits;
3668
3669 return DRFLAC_TRUE;
3670 }
3671
3672
3673 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)
3674 {
3675 drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
3676 drflac_uint32 zeroCountPart0;
3677 drflac_uint32 riceParamPart0;
3678 drflac_uint32 riceParamMask;
3679 drflac_uint32 i;
3680
3681 DRFLAC_ASSERT(bs != NULL);
3682 DRFLAC_ASSERT(pSamplesOut != NULL);
3683
3684 (void)bitsPerSample;
3685 (void)order;
3686 (void)shift;
3687 (void)coefficients;
3688
3689 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
3690
3691 i = 0;
3692 while (i < count) {
3693 /* Rice extraction. */
3694 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
3695 return DRFLAC_FALSE;
3696 }
3697
3698 /* Rice reconstruction. */
3699 riceParamPart0 &= riceParamMask;
3700 riceParamPart0 |= (zeroCountPart0 << riceParam);
3701 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3702
3703 pSamplesOut[i] = riceParamPart0;
3704
3705 i += 1;
3706 }
3707
3708 return DRFLAC_TRUE;
3709 }
3710
3711 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)
3712 {
3713 drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
3714 drflac_uint32 zeroCountPart0 = 0;
3715 drflac_uint32 zeroCountPart1 = 0;
3716 drflac_uint32 zeroCountPart2 = 0;
3717 drflac_uint32 zeroCountPart3 = 0;
3718 drflac_uint32 riceParamPart0 = 0;
3719 drflac_uint32 riceParamPart1 = 0;
3720 drflac_uint32 riceParamPart2 = 0;
3721 drflac_uint32 riceParamPart3 = 0;
3722 drflac_uint32 riceParamMask;
3723 const drflac_int32* pSamplesOutEnd;
3724 drflac_uint32 i;
3725
3726 DRFLAC_ASSERT(bs != NULL);
3727 DRFLAC_ASSERT(pSamplesOut != NULL);
3728
3729 if (lpcOrder == 0) {
3730 return drflac__decode_samples_with_residual__rice__scalar_zeroorder(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
3731 }
3732
3733 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
3734 pSamplesOutEnd = pSamplesOut + (count & ~3);
3735
3736 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
3737 while (pSamplesOut < pSamplesOutEnd) {
3738 /*
3739 Rice extraction. It's faster to do this one at a time against local variables than it is to use the x4 version
3740 against an array. Not sure why, but perhaps it's making more efficient use of registers?
3741 */
3742 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
3743 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
3744 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
3745 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
3746 return DRFLAC_FALSE;
3747 }
3748
3749 riceParamPart0 &= riceParamMask;
3750 riceParamPart1 &= riceParamMask;
3751 riceParamPart2 &= riceParamMask;
3752 riceParamPart3 &= riceParamMask;
3753
3754 riceParamPart0 |= (zeroCountPart0 << riceParam);
3755 riceParamPart1 |= (zeroCountPart1 << riceParam);
3756 riceParamPart2 |= (zeroCountPart2 << riceParam);
3757 riceParamPart3 |= (zeroCountPart3 << riceParam);
3758
3759 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3760 riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
3761 riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
3762 riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
3763
3764 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3765 pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
3766 pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
3767 pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
3768
3769 pSamplesOut += 4;
3770 }
3771 } else {
3772 while (pSamplesOut < pSamplesOutEnd) {
3773 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
3774 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
3775 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
3776 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
3777 return DRFLAC_FALSE;
3778 }
3779
3780 riceParamPart0 &= riceParamMask;
3781 riceParamPart1 &= riceParamMask;
3782 riceParamPart2 &= riceParamMask;
3783 riceParamPart3 &= riceParamMask;
3784
3785 riceParamPart0 |= (zeroCountPart0 << riceParam);
3786 riceParamPart1 |= (zeroCountPart1 << riceParam);
3787 riceParamPart2 |= (zeroCountPart2 << riceParam);
3788 riceParamPart3 |= (zeroCountPart3 << riceParam);
3789
3790 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3791 riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
3792 riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
3793 riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
3794
3795 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3796 pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
3797 pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
3798 pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
3799
3800 pSamplesOut += 4;
3801 }
3802 }
3803
3804 i = (count & ~3);
3805 while (i < count) {
3806 /* Rice extraction. */
3807 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
3808 return DRFLAC_FALSE;
3809 }
3810
3811 /* Rice reconstruction. */
3812 riceParamPart0 &= riceParamMask;
3813 riceParamPart0 |= (zeroCountPart0 << riceParam);
3814 riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
3815 /*riceParamPart0 = (riceParamPart0 >> 1) ^ (~(riceParamPart0 & 0x01) + 1);*/
3816
3817 /* Sample reconstruction. */
3818 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
3819 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3820 } else {
3821 pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
3822 }
3823
3824 i += 1;
3825 pSamplesOut += 1;
3826 }
3827
3828 return DRFLAC_TRUE;
3829 }
3830
3831 #if defined(DRFLAC_SUPPORT_SSE2)
3832 static DRFLAC_INLINE __m128i drflac__mm_packs_interleaved_epi32(__m128i a, __m128i b)
3833 {
3834 __m128i r;
3835
3836 /* Pack. */
3837 r = _mm_packs_epi32(a, b);
3838
3839 /* a3a2 a1a0 b3b2 b1b0 -> a3a2 b3b2 a1a0 b1b0 */
3840 r = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 1, 2, 0));
3841
3842 /* a3a2 b3b2 a1a0 b1b0 -> a3b3 a2b2 a1b1 a0b0 */
3843 r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
3844 r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
3845
3846 return r;
3847 }
3848 #endif
3849
3850 #if defined(DRFLAC_SUPPORT_SSE41)
3851 static DRFLAC_INLINE __m128i drflac__mm_not_si128(__m128i a)
3852 {
3853 return _mm_xor_si128(a, _mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128()));
3854 }
3855
3856 static DRFLAC_INLINE __m128i drflac__mm_hadd_epi32(__m128i x)
3857 {
3858 __m128i x64 = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
3859 __m128i x32 = _mm_shufflelo_epi16(x64, _MM_SHUFFLE(1, 0, 3, 2));
3860 return _mm_add_epi32(x64, x32);
3861 }
3862
3863 static DRFLAC_INLINE __m128i drflac__mm_hadd_epi64(__m128i x)
3864 {
3865 return _mm_add_epi64(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
3866 }
3867
3868 static DRFLAC_INLINE __m128i drflac__mm_srai_epi64(__m128i x, int count)
3869 {
3870 /*
3871 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
3872 is shifted with zero bits, whereas the right side is shifted with sign bits.
3873 */
3874 __m128i lo = _mm_srli_epi64(x, count);
3875 __m128i hi = _mm_srai_epi32(x, count);
3876
3877 hi = _mm_and_si128(hi, _mm_set_epi32(0xFFFFFFFF, 0, 0xFFFFFFFF, 0)); /* The high part needs to have the low part cleared. */
3878
3879 return _mm_or_si128(lo, hi);
3880 }
3881
3882 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)
3883 {
3884 int i;
3885 drflac_uint32 riceParamMask;
3886 drflac_int32* pDecodedSamples = pSamplesOut;
3887 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
3888 drflac_uint32 zeroCountParts0 = 0;
3889 drflac_uint32 zeroCountParts1 = 0;
3890 drflac_uint32 zeroCountParts2 = 0;
3891 drflac_uint32 zeroCountParts3 = 0;
3892 drflac_uint32 riceParamParts0 = 0;
3893 drflac_uint32 riceParamParts1 = 0;
3894 drflac_uint32 riceParamParts2 = 0;
3895 drflac_uint32 riceParamParts3 = 0;
3896 __m128i coefficients128_0;
3897 __m128i coefficients128_4;
3898 __m128i coefficients128_8;
3899 __m128i samples128_0;
3900 __m128i samples128_4;
3901 __m128i samples128_8;
3902 __m128i riceParamMask128;
3903
3904 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
3905
3906 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
3907 riceParamMask128 = _mm_set1_epi32(riceParamMask);
3908
3909 /* Pre-load. */
3910 coefficients128_0 = _mm_setzero_si128();
3911 coefficients128_4 = _mm_setzero_si128();
3912 coefficients128_8 = _mm_setzero_si128();
3913
3914 samples128_0 = _mm_setzero_si128();
3915 samples128_4 = _mm_setzero_si128();
3916 samples128_8 = _mm_setzero_si128();
3917
3918 /*
3919 Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
3920 what's available in the input buffers. It would be convenient to use a fall-through switch to do this, but this results
3921 in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
3922 so I think there's opportunity for this to be simplified.
3923 */
3924 #if 1
3925 {
3926 int runningOrder = order;
3927
3928 /* 0 - 3. */
3929 if (runningOrder >= 4) {
3930 coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
3931 samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
3932 runningOrder -= 4;
3933 } else {
3934 switch (runningOrder) {
3935 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;
3936 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;
3937 case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
3938 }
3939 runningOrder = 0;
3940 }
3941
3942 /* 4 - 7 */
3943 if (runningOrder >= 4) {
3944 coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
3945 samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
3946 runningOrder -= 4;
3947 } else {
3948 switch (runningOrder) {
3949 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;
3950 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;
3951 case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
3952 }
3953 runningOrder = 0;
3954 }
3955
3956 /* 8 - 11 */
3957 if (runningOrder == 4) {
3958 coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
3959 samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
3960 runningOrder -= 4;
3961 } else {
3962 switch (runningOrder) {
3963 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;
3964 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;
3965 case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
3966 }
3967 runningOrder = 0;
3968 }
3969
3970 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
3971 coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
3972 coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
3973 coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
3974 }
3975 #else
3976 /* This causes strict-aliasing warnings with GCC. */
3977 switch (order)
3978 {
3979 case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
3980 case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
3981 case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
3982 case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
3983 case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
3984 case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
3985 case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
3986 case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
3987 case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
3988 case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
3989 case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
3990 case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
3991 }
3992 #endif
3993
3994 /* For this version we are doing one sample at a time. */
3995 while (pDecodedSamples < pDecodedSamplesEnd) {
3996 __m128i prediction128;
3997 __m128i zeroCountPart128;
3998 __m128i riceParamPart128;
3999
4000 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
4001 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
4002 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
4003 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
4004 return DRFLAC_FALSE;
4005 }
4006
4007 zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
4008 riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
4009
4010 riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
4011 riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
4012 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 */
4013 /*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... */
4014
4015 if (order <= 4) {
4016 for (i = 0; i < 4; i += 1) {
4017 prediction128 = _mm_mullo_epi32(coefficients128_0, samples128_0);
4018
4019 /* Horizontal add and shift. */
4020 prediction128 = drflac__mm_hadd_epi32(prediction128);
4021 prediction128 = _mm_srai_epi32(prediction128, shift);
4022 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
4023
4024 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
4025 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
4026 }
4027 } else if (order <= 8) {
4028 for (i = 0; i < 4; i += 1) {
4029 prediction128 = _mm_mullo_epi32(coefficients128_4, samples128_4);
4030 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
4031
4032 /* Horizontal add and shift. */
4033 prediction128 = drflac__mm_hadd_epi32(prediction128);
4034 prediction128 = _mm_srai_epi32(prediction128, shift);
4035 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
4036
4037 samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
4038 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
4039 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
4040 }
4041 } else {
4042 for (i = 0; i < 4; i += 1) {
4043 prediction128 = _mm_mullo_epi32(coefficients128_8, samples128_8);
4044 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_4, samples128_4));
4045 prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
4046
4047 /* Horizontal add and shift. */
4048 prediction128 = drflac__mm_hadd_epi32(prediction128);
4049 prediction128 = _mm_srai_epi32(prediction128, shift);
4050 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
4051
4052 samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
4053 samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
4054 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
4055 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
4056 }
4057 }
4058
4059 /* We store samples in groups of 4. */
4060 _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
4061 pDecodedSamples += 4;
4062 }
4063
4064 /* Make sure we process the last few samples. */
4065 i = (count & ~3);
4066 while (i < (int)count) {
4067 /* Rice extraction. */
4068 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
4069 return DRFLAC_FALSE;
4070 }
4071
4072 /* Rice reconstruction. */
4073 riceParamParts0 &= riceParamMask;
4074 riceParamParts0 |= (zeroCountParts0 << riceParam);
4075 riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
4076
4077 /* Sample reconstruction. */
4078 pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
4079
4080 i += 1;
4081 pDecodedSamples += 1;
4082 }
4083
4084 return DRFLAC_TRUE;
4085 }
4086
4087 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)
4088 {
4089 int i;
4090 drflac_uint32 riceParamMask;
4091 drflac_int32* pDecodedSamples = pSamplesOut;
4092 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
4093 drflac_uint32 zeroCountParts0 = 0;
4094 drflac_uint32 zeroCountParts1 = 0;
4095 drflac_uint32 zeroCountParts2 = 0;
4096 drflac_uint32 zeroCountParts3 = 0;
4097 drflac_uint32 riceParamParts0 = 0;
4098 drflac_uint32 riceParamParts1 = 0;
4099 drflac_uint32 riceParamParts2 = 0;
4100 drflac_uint32 riceParamParts3 = 0;
4101 __m128i coefficients128_0;
4102 __m128i coefficients128_4;
4103 __m128i coefficients128_8;
4104 __m128i samples128_0;
4105 __m128i samples128_4;
4106 __m128i samples128_8;
4107 __m128i prediction128;
4108 __m128i riceParamMask128;
4109
4110 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
4111
4112 DRFLAC_ASSERT(order <= 12);
4113
4114 riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
4115 riceParamMask128 = _mm_set1_epi32(riceParamMask);
4116
4117 prediction128 = _mm_setzero_si128();
4118
4119 /* Pre-load. */
4120 coefficients128_0 = _mm_setzero_si128();
4121 coefficients128_4 = _mm_setzero_si128();
4122 coefficients128_8 = _mm_setzero_si128();
4123
4124 samples128_0 = _mm_setzero_si128();
4125 samples128_4 = _mm_setzero_si128();
4126 samples128_8 = _mm_setzero_si128();
4127
4128 #if 1
4129 {
4130 int runningOrder = order;
4131
4132 /* 0 - 3. */
4133 if (runningOrder >= 4) {
4134 coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
4135 samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
4136 runningOrder -= 4;
4137 } else {
4138 switch (runningOrder) {
4139 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;
4140 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;
4141 case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
4142 }
4143 runningOrder = 0;
4144 }
4145
4146 /* 4 - 7 */
4147 if (runningOrder >= 4) {
4148 coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
4149 samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
4150 runningOrder -= 4;
4151 } else {
4152 switch (runningOrder) {
4153 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;
4154 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;
4155 case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
4156 }
4157 runningOrder = 0;
4158 }
4159
4160 /* 8 - 11 */
4161 if (runningOrder == 4) {
4162 coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
4163 samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
4164 runningOrder -= 4;
4165 } else {
4166 switch (runningOrder) {
4167 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;
4168 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;
4169 case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
4170 }
4171 runningOrder = 0;
4172 }
4173
4174 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
4175 coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
4176 coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
4177 coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
4178 }
4179 #else
4180 switch (order)
4181 {
4182 case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
4183 case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
4184 case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
4185 case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
4186 case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
4187 case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
4188 case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
4189 case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
4190 case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
4191 case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
4192 case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
4193 case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
4194 }
4195 #endif
4196
4197 /* For this version we are doing one sample at a time. */
4198 while (pDecodedSamples < pDecodedSamplesEnd) {
4199 __m128i zeroCountPart128;
4200 __m128i riceParamPart128;
4201
4202 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
4203 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
4204 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
4205 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
4206 return DRFLAC_FALSE;
4207 }
4208
4209 zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
4210 riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
4211
4212 riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
4213 riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
4214 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)));
4215
4216 for (i = 0; i < 4; i += 1) {
4217 prediction128 = _mm_xor_si128(prediction128, prediction128); /* Reset to 0. */
4218
4219 switch (order)
4220 {
4221 case 12:
4222 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))));
4223 case 10:
4224 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))));
4225 case 8:
4226 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))));
4227 case 6:
4228 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))));
4229 case 4:
4230 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))));
4231 case 2:
4232 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))));
4233 }
4234
4235 /* Horizontal add and shift. */
4236 prediction128 = drflac__mm_hadd_epi64(prediction128);
4237 prediction128 = drflac__mm_srai_epi64(prediction128, shift);
4238 prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
4239
4240 /* Our value should be sitting in prediction128[0]. We need to combine this with our SSE samples. */
4241 samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
4242 samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
4243 samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
4244
4245 /* Slide our rice parameter down so that the value in position 0 contains the next one to process. */
4246 riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
4247 }
4248
4249 /* We store samples in groups of 4. */
4250 _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
4251 pDecodedSamples += 4;
4252 }
4253
4254 /* Make sure we process the last few samples. */
4255 i = (count & ~3);
4256 while (i < (int)count) {
4257 /* Rice extraction. */
4258 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
4259 return DRFLAC_FALSE;
4260 }
4261
4262 /* Rice reconstruction. */
4263 riceParamParts0 &= riceParamMask;
4264 riceParamParts0 |= (zeroCountParts0 << riceParam);
4265 riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
4266
4267 /* Sample reconstruction. */
4268 pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
4269
4270 i += 1;
4271 pDecodedSamples += 1;
4272 }
4273
4274 return DRFLAC_TRUE;
4275 }
4276
4277 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)
4278 {
4279 DRFLAC_ASSERT(bs != NULL);
4280 DRFLAC_ASSERT(pSamplesOut != NULL);
4281
4282 /* 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. */
4283 if (lpcOrder > 0 && lpcOrder <= 12) {
4284 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
4285 return drflac__decode_samples_with_residual__rice__sse41_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
4286 } else {
4287 return drflac__decode_samples_with_residual__rice__sse41_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
4288 }
4289 } else {
4290 return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4291 }
4292 }
4293 #endif
4294
4295 #if defined(DRFLAC_SUPPORT_NEON)
4296 static DRFLAC_INLINE void drflac__vst2q_s32(drflac_int32* p, int32x4x2_t x)
4297 {
4298 vst1q_s32(p+0, x.val[0]);
4299 vst1q_s32(p+4, x.val[1]);
4300 }
4301
4302 static DRFLAC_INLINE void drflac__vst2q_u32(drflac_uint32* p, uint32x4x2_t x)
4303 {
4304 vst1q_u32(p+0, x.val[0]);
4305 vst1q_u32(p+4, x.val[1]);
4306 }
4307
4308 static DRFLAC_INLINE void drflac__vst2q_f32(float* p, float32x4x2_t x)
4309 {
4310 vst1q_f32(p+0, x.val[0]);
4311 vst1q_f32(p+4, x.val[1]);
4312 }
4313
4314 static DRFLAC_INLINE void drflac__vst2q_s16(drflac_int16* p, int16x4x2_t x)
4315 {
4316 vst1q_s16(p, vcombine_s16(x.val[0], x.val[1]));
4317 }
4318
4319 static DRFLAC_INLINE void drflac__vst2q_u16(drflac_uint16* p, uint16x4x2_t x)
4320 {
4321 vst1q_u16(p, vcombine_u16(x.val[0], x.val[1]));
4322 }
4323
4324 static DRFLAC_INLINE int32x4_t drflac__vdupq_n_s32x4(drflac_int32 x3, drflac_int32 x2, drflac_int32 x1, drflac_int32 x0)
4325 {
4326 drflac_int32 x[4];
4327 x[3] = x3;
4328 x[2] = x2;
4329 x[1] = x1;
4330 x[0] = x0;
4331 return vld1q_s32(x);
4332 }
4333
4334 static DRFLAC_INLINE int32x4_t drflac__valignrq_s32_1(int32x4_t a, int32x4_t b)
4335 {
4336 /* Equivalent to SSE's _mm_alignr_epi8(a, b, 4) */
4337
4338 /* Reference */
4339 /*return drflac__vdupq_n_s32x4(
4340 vgetq_lane_s32(a, 0),
4341 vgetq_lane_s32(b, 3),
4342 vgetq_lane_s32(b, 2),
4343 vgetq_lane_s32(b, 1)
4344 );*/
4345
4346 return vextq_s32(b, a, 1);
4347 }
4348
4349 static DRFLAC_INLINE uint32x4_t drflac__valignrq_u32_1(uint32x4_t a, uint32x4_t b)
4350 {
4351 /* Equivalent to SSE's _mm_alignr_epi8(a, b, 4) */
4352
4353 /* Reference */
4354 /*return drflac__vdupq_n_s32x4(
4355 vgetq_lane_s32(a, 0),
4356 vgetq_lane_s32(b, 3),
4357 vgetq_lane_s32(b, 2),
4358 vgetq_lane_s32(b, 1)
4359 );*/
4360
4361 return vextq_u32(b, a, 1);
4362 }
4363
4364 static DRFLAC_INLINE int32x2_t drflac__vhaddq_s32(int32x4_t x)
4365 {
4366 /* The sum must end up in position 0. */
4367
4368 /* Reference */
4369 /*return vdupq_n_s32(
4370 vgetq_lane_s32(x, 3) +
4371 vgetq_lane_s32(x, 2) +
4372 vgetq_lane_s32(x, 1) +
4373 vgetq_lane_s32(x, 0)
4374 );*/
4375
4376 int32x2_t r = vadd_s32(vget_high_s32(x), vget_low_s32(x));
4377 return vpadd_s32(r, r);
4378 }
4379
4380 static DRFLAC_INLINE int64x1_t drflac__vhaddq_s64(int64x2_t x)
4381 {
4382 return vadd_s64(vget_high_s64(x), vget_low_s64(x));
4383 }
4384
4385 static DRFLAC_INLINE int32x4_t drflac__vrevq_s32(int32x4_t x)
4386 {
4387 /* Reference */
4388 /*return drflac__vdupq_n_s32x4(
4389 vgetq_lane_s32(x, 0),
4390 vgetq_lane_s32(x, 1),
4391 vgetq_lane_s32(x, 2),
4392 vgetq_lane_s32(x, 3)
4393 );*/
4394
4395 return vrev64q_s32(vcombine_s32(vget_high_s32(x), vget_low_s32(x)));
4396 }
4397
4398 static DRFLAC_INLINE int32x4_t drflac__vnotq_s32(int32x4_t x)
4399 {
4400 return veorq_s32(x, vdupq_n_s32(0xFFFFFFFF));
4401 }
4402
4403 static DRFLAC_INLINE uint32x4_t drflac__vnotq_u32(uint32x4_t x)
4404 {
4405 return veorq_u32(x, vdupq_n_u32(0xFFFFFFFF));
4406 }
4407
4408 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)
4409 {
4410 int i;
4411 drflac_uint32 riceParamMask;
4412 drflac_int32* pDecodedSamples = pSamplesOut;
4413 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
4414 drflac_uint32 zeroCountParts[4];
4415 drflac_uint32 riceParamParts[4];
4416 int32x4_t coefficients128_0;
4417 int32x4_t coefficients128_4;
4418 int32x4_t coefficients128_8;
4419 int32x4_t samples128_0;
4420 int32x4_t samples128_4;
4421 int32x4_t samples128_8;
4422 uint32x4_t riceParamMask128;
4423 int32x4_t riceParam128;
4424 int32x2_t shift64;
4425 uint32x4_t one128;
4426
4427 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
4428
4429 riceParamMask = ~((~0UL) << riceParam);
4430 riceParamMask128 = vdupq_n_u32(riceParamMask);
4431
4432 riceParam128 = vdupq_n_s32(riceParam);
4433 shift64 = vdup_n_s32(-shift); /* Negate the shift because we'll be doing a variable shift using vshlq_s32(). */
4434 one128 = vdupq_n_u32(1);
4435
4436 /*
4437 Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
4438 what's available in the input buffers. It would be conenient to use a fall-through switch to do this, but this results
4439 in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
4440 so I think there's opportunity for this to be simplified.
4441 */
4442 {
4443 int runningOrder = order;
4444 drflac_int32 tempC[4] = {0, 0, 0, 0};
4445 drflac_int32 tempS[4] = {0, 0, 0, 0};
4446
4447 /* 0 - 3. */
4448 if (runningOrder >= 4) {
4449 coefficients128_0 = vld1q_s32(coefficients + 0);
4450 samples128_0 = vld1q_s32(pSamplesOut - 4);
4451 runningOrder -= 4;
4452 } else {
4453 switch (runningOrder) {
4454 case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3]; /* fallthrough */
4455 case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2]; /* fallthrough */
4456 case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1]; /* fallthrough */
4457 }
4458
4459 coefficients128_0 = vld1q_s32(tempC);
4460 samples128_0 = vld1q_s32(tempS);
4461 runningOrder = 0;
4462 }
4463
4464 /* 4 - 7 */
4465 if (runningOrder >= 4) {
4466 coefficients128_4 = vld1q_s32(coefficients + 4);
4467 samples128_4 = vld1q_s32(pSamplesOut - 8);
4468 runningOrder -= 4;
4469 } else {
4470 switch (runningOrder) {
4471 case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7]; /* fallthrough */
4472 case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6]; /* fallthrough */
4473 case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5]; /* fallthrough */
4474 }
4475
4476 coefficients128_4 = vld1q_s32(tempC);
4477 samples128_4 = vld1q_s32(tempS);
4478 runningOrder = 0;
4479 }
4480
4481 /* 8 - 11 */
4482 if (runningOrder == 4) {
4483 coefficients128_8 = vld1q_s32(coefficients + 8);
4484 samples128_8 = vld1q_s32(pSamplesOut - 12);
4485 runningOrder -= 4;
4486 } else {
4487 switch (runningOrder) {
4488 case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11]; /* fallthrough */
4489 case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10]; /* fallthrough */
4490 case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9]; /* fallthrough */
4491 }
4492
4493 coefficients128_8 = vld1q_s32(tempC);
4494 samples128_8 = vld1q_s32(tempS);
4495 runningOrder = 0;
4496 }
4497
4498 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
4499 coefficients128_0 = drflac__vrevq_s32(coefficients128_0);
4500 coefficients128_4 = drflac__vrevq_s32(coefficients128_4);
4501 coefficients128_8 = drflac__vrevq_s32(coefficients128_8);
4502 }
4503
4504 /* For this version we are doing one sample at a time. */
4505 while (pDecodedSamples < pDecodedSamplesEnd) {
4506 int32x4_t prediction128;
4507 int32x2_t prediction64;
4508 uint32x4_t zeroCountPart128;
4509 uint32x4_t riceParamPart128;
4510
4511 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
4512 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
4513 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
4514 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
4515 return DRFLAC_FALSE;
4516 }
4517
4518 zeroCountPart128 = vld1q_u32(zeroCountParts);
4519 riceParamPart128 = vld1q_u32(riceParamParts);
4520
4521 riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
4522 riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
4523 riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
4524
4525 if (order <= 4) {
4526 for (i = 0; i < 4; i += 1) {
4527 prediction128 = vmulq_s32(coefficients128_0, samples128_0);
4528
4529 /* Horizontal add and shift. */
4530 prediction64 = drflac__vhaddq_s32(prediction128);
4531 prediction64 = vshl_s32(prediction64, shift64);
4532 prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
4533
4534 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
4535 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
4536 }
4537 } else if (order <= 8) {
4538 for (i = 0; i < 4; i += 1) {
4539 prediction128 = vmulq_s32(coefficients128_4, samples128_4);
4540 prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
4541
4542 /* Horizontal add and shift. */
4543 prediction64 = drflac__vhaddq_s32(prediction128);
4544 prediction64 = vshl_s32(prediction64, shift64);
4545 prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
4546
4547 samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
4548 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
4549 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
4550 }
4551 } else {
4552 for (i = 0; i < 4; i += 1) {
4553 prediction128 = vmulq_s32(coefficients128_8, samples128_8);
4554 prediction128 = vmlaq_s32(prediction128, coefficients128_4, samples128_4);
4555 prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
4556
4557 /* Horizontal add and shift. */
4558 prediction64 = drflac__vhaddq_s32(prediction128);
4559 prediction64 = vshl_s32(prediction64, shift64);
4560 prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
4561
4562 samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8);
4563 samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
4564 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
4565 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
4566 }
4567 }
4568
4569 /* We store samples in groups of 4. */
4570 vst1q_s32(pDecodedSamples, samples128_0);
4571 pDecodedSamples += 4;
4572 }
4573
4574 /* Make sure we process the last few samples. */
4575 i = (count & ~3);
4576 while (i < (int)count) {
4577 /* Rice extraction. */
4578 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
4579 return DRFLAC_FALSE;
4580 }
4581
4582 /* Rice reconstruction. */
4583 riceParamParts[0] &= riceParamMask;
4584 riceParamParts[0] |= (zeroCountParts[0] << riceParam);
4585 riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
4586
4587 /* Sample reconstruction. */
4588 pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
4589
4590 i += 1;
4591 pDecodedSamples += 1;
4592 }
4593
4594 return DRFLAC_TRUE;
4595 }
4596
4597 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)
4598 {
4599 int i;
4600 drflac_uint32 riceParamMask;
4601 drflac_int32* pDecodedSamples = pSamplesOut;
4602 drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
4603 drflac_uint32 zeroCountParts[4];
4604 drflac_uint32 riceParamParts[4];
4605 int32x4_t coefficients128_0;
4606 int32x4_t coefficients128_4;
4607 int32x4_t coefficients128_8;
4608 int32x4_t samples128_0;
4609 int32x4_t samples128_4;
4610 int32x4_t samples128_8;
4611 uint32x4_t riceParamMask128;
4612 int32x4_t riceParam128;
4613 int64x1_t shift64;
4614 uint32x4_t one128;
4615
4616 const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
4617
4618 riceParamMask = ~((~0UL) << riceParam);
4619 riceParamMask128 = vdupq_n_u32(riceParamMask);
4620
4621 riceParam128 = vdupq_n_s32(riceParam);
4622 shift64 = vdup_n_s64(-shift); /* Negate the shift because we'll be doing a variable shift using vshlq_s32(). */
4623 one128 = vdupq_n_u32(1);
4624
4625 /*
4626 Pre-loading the coefficients and prior samples is annoying because we need to ensure we don't try reading more than
4627 what's available in the input buffers. It would be convenient to use a fall-through switch to do this, but this results
4628 in strict aliasing warnings with GCC. To work around this I'm just doing something hacky. This feels a bit convoluted
4629 so I think there's opportunity for this to be simplified.
4630 */
4631 {
4632 int runningOrder = order;
4633 drflac_int32 tempC[4] = {0, 0, 0, 0};
4634 drflac_int32 tempS[4] = {0, 0, 0, 0};
4635
4636 /* 0 - 3. */
4637 if (runningOrder >= 4) {
4638 coefficients128_0 = vld1q_s32(coefficients + 0);
4639 samples128_0 = vld1q_s32(pSamplesOut - 4);
4640 runningOrder -= 4;
4641 } else {
4642 switch (runningOrder) {
4643 case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3]; /* fallthrough */
4644 case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2]; /* fallthrough */
4645 case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1]; /* fallthrough */
4646 }
4647
4648 coefficients128_0 = vld1q_s32(tempC);
4649 samples128_0 = vld1q_s32(tempS);
4650 runningOrder = 0;
4651 }
4652
4653 /* 4 - 7 */
4654 if (runningOrder >= 4) {
4655 coefficients128_4 = vld1q_s32(coefficients + 4);
4656 samples128_4 = vld1q_s32(pSamplesOut - 8);
4657 runningOrder -= 4;
4658 } else {
4659 switch (runningOrder) {
4660 case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7]; /* fallthrough */
4661 case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6]; /* fallthrough */
4662 case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5]; /* fallthrough */
4663 }
4664
4665 coefficients128_4 = vld1q_s32(tempC);
4666 samples128_4 = vld1q_s32(tempS);
4667 runningOrder = 0;
4668 }
4669
4670 /* 8 - 11 */
4671 if (runningOrder == 4) {
4672 coefficients128_8 = vld1q_s32(coefficients + 8);
4673 samples128_8 = vld1q_s32(pSamplesOut - 12);
4674 runningOrder -= 4;
4675 } else {
4676 switch (runningOrder) {
4677 case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11]; /* fallthrough */
4678 case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10]; /* fallthrough */
4679 case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9]; /* fallthrough */
4680 }
4681
4682 coefficients128_8 = vld1q_s32(tempC);
4683 samples128_8 = vld1q_s32(tempS);
4684 runningOrder = 0;
4685 }
4686
4687 /* Coefficients need to be shuffled for our streaming algorithm below to work. Samples are already in the correct order from the loading routine above. */
4688 coefficients128_0 = drflac__vrevq_s32(coefficients128_0);
4689 coefficients128_4 = drflac__vrevq_s32(coefficients128_4);
4690 coefficients128_8 = drflac__vrevq_s32(coefficients128_8);
4691 }
4692
4693 /* For this version we are doing one sample at a time. */
4694 while (pDecodedSamples < pDecodedSamplesEnd) {
4695 int64x2_t prediction128;
4696 uint32x4_t zeroCountPart128;
4697 uint32x4_t riceParamPart128;
4698
4699 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
4700 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
4701 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
4702 !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
4703 return DRFLAC_FALSE;
4704 }
4705
4706 zeroCountPart128 = vld1q_u32(zeroCountParts);
4707 riceParamPart128 = vld1q_u32(riceParamParts);
4708
4709 riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
4710 riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
4711 riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
4712
4713 for (i = 0; i < 4; i += 1) {
4714 int64x1_t prediction64;
4715
4716 prediction128 = veorq_s64(prediction128, prediction128); /* Reset to 0. */
4717 switch (order)
4718 {
4719 case 12:
4720 case 11: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_8), vget_low_s32(samples128_8)));
4721 case 10:
4722 case 9: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_8), vget_high_s32(samples128_8)));
4723 case 8:
4724 case 7: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_4), vget_low_s32(samples128_4)));
4725 case 6:
4726 case 5: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_4), vget_high_s32(samples128_4)));
4727 case 4:
4728 case 3: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_0), vget_low_s32(samples128_0)));
4729 case 2:
4730 case 1: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_0), vget_high_s32(samples128_0)));
4731 }
4732
4733 /* Horizontal add and shift. */
4734 prediction64 = drflac__vhaddq_s64(prediction128);
4735 prediction64 = vshl_s64(prediction64, shift64);
4736 prediction64 = vadd_s64(prediction64, vdup_n_s64(vgetq_lane_u32(riceParamPart128, 0)));
4737
4738 /* Our value should be sitting in prediction64[0]. We need to combine this with our SSE samples. */
4739 samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8);
4740 samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
4741 samples128_0 = drflac__valignrq_s32_1(vcombine_s32(vreinterpret_s32_s64(prediction64), vdup_n_s32(0)), samples128_0);
4742
4743 /* Slide our rice parameter down so that the value in position 0 contains the next one to process. */
4744 riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
4745 }
4746
4747 /* We store samples in groups of 4. */
4748 vst1q_s32(pDecodedSamples, samples128_0);
4749 pDecodedSamples += 4;
4750 }
4751
4752 /* Make sure we process the last few samples. */
4753 i = (count & ~3);
4754 while (i < (int)count) {
4755 /* Rice extraction. */
4756 if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
4757 return DRFLAC_FALSE;
4758 }
4759
4760 /* Rice reconstruction. */
4761 riceParamParts[0] &= riceParamMask;
4762 riceParamParts[0] |= (zeroCountParts[0] << riceParam);
4763 riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
4764
4765 /* Sample reconstruction. */
4766 pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
4767
4768 i += 1;
4769 pDecodedSamples += 1;
4770 }
4771
4772 return DRFLAC_TRUE;
4773 }
4774
4775 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)
4776 {
4777 DRFLAC_ASSERT(bs != NULL);
4778 DRFLAC_ASSERT(pSamplesOut != NULL);
4779
4780 /* 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. */
4781 if (lpcOrder > 0 && lpcOrder <= 12) {
4782 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
4783 return drflac__decode_samples_with_residual__rice__neon_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
4784 } else {
4785 return drflac__decode_samples_with_residual__rice__neon_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
4786 }
4787 } else {
4788 return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4789 }
4790 }
4791 #endif
4792
4793 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)
4794 {
4795 #if defined(DRFLAC_SUPPORT_SSE41)
4796 if (drflac__gIsSSE41Supported) {
4797 return drflac__decode_samples_with_residual__rice__sse41(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4798 } else
4799 #elif defined(DRFLAC_SUPPORT_NEON)
4800 if (drflac__gIsNEONSupported) {
4801 return drflac__decode_samples_with_residual__rice__neon(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4802 } else
4803 #endif
4804 {
4805 /* Scalar fallback. */
4806 #if 0
4807 return drflac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4808 #else
4809 return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
4810 #endif
4811 }
4812 }
4813
4814 /* 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. */
4815 static drflac_bool32 drflac__read_and_seek_residual__rice(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam)
4816 {
4817 drflac_uint32 i;
4818
4819 DRFLAC_ASSERT(bs != NULL);
4820
4821 for (i = 0; i < count; ++i) {
4822 if (!drflac__seek_rice_parts(bs, riceParam)) {
4823 return DRFLAC_FALSE;
4824 }
4825 }
4826
4827 return DRFLAC_TRUE;
4828 }
4829
4830 #if defined(__clang__)
4831 __attribute__((no_sanitize("signed-integer-overflow")))
4832 #endif
4833 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)
4834 {
4835 drflac_uint32 i;
4836
4837 DRFLAC_ASSERT(bs != NULL);
4838 DRFLAC_ASSERT(unencodedBitsPerSample <= 31); /* <-- unencodedBitsPerSample is a 5 bit number, so cannot exceed 31. */
4839 DRFLAC_ASSERT(pSamplesOut != NULL);
4840
4841 for (i = 0; i < count; ++i) {
4842 if (unencodedBitsPerSample > 0) {
4843 if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i)) {
4844 return DRFLAC_FALSE;
4845 }
4846 } else {
4847 pSamplesOut[i] = 0;
4848 }
4849
4850 if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
4851 pSamplesOut[i] += drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
4852 } else {
4853 pSamplesOut[i] += drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
4854 }
4855 }
4856
4857 return DRFLAC_TRUE;
4858 }
4859
4860
4861 /*
4862 Reads and decodes the residual for the sub-frame the decoder is currently sitting on. This function should be called
4863 when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be ignored. The
4864 <blockSize> and <order> parameters are used to determine how many residual values need to be decoded.
4865 */
4866 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)
4867 {
4868 drflac_uint8 residualMethod;
4869 drflac_uint8 partitionOrder;
4870 drflac_uint32 samplesInPartition;
4871 drflac_uint32 partitionsRemaining;
4872
4873 DRFLAC_ASSERT(bs != NULL);
4874 DRFLAC_ASSERT(blockSize != 0);
4875 DRFLAC_ASSERT(pDecodedSamples != NULL); /* <-- Should we allow NULL, in which case we just seek past the residual rather than do a full decode? */
4876
4877 if (!drflac__read_uint8(bs, 2, &residualMethod)) {
4878 return DRFLAC_FALSE;
4879 }
4880
4881 if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
4882 return DRFLAC_FALSE; /* Unknown or unsupported residual coding method. */
4883 }
4884
4885 /* Ignore the first <order> values. */
4886 pDecodedSamples += lpcOrder;
4887
4888 if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
4889 return DRFLAC_FALSE;
4890 }
4891
4892 /*
4893 From the FLAC spec:
4894 The Rice partition order in a Rice-coded residual section must be less than or equal to 8.
4895 */
4896 if (partitionOrder > 8) {
4897 return DRFLAC_FALSE;
4898 }
4899
4900 /* Validation check. */
4901 if ((blockSize / (1 << partitionOrder)) < lpcOrder) {
4902 return DRFLAC_FALSE;
4903 }
4904
4905 samplesInPartition = (blockSize / (1 << partitionOrder)) - lpcOrder;
4906 partitionsRemaining = (1 << partitionOrder);
4907 for (;;) {
4908 drflac_uint8 riceParam = 0;
4909 if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
4910 if (!drflac__read_uint8(bs, 4, &riceParam)) {
4911 return DRFLAC_FALSE;
4912 }
4913 if (riceParam == 15) {
4914 riceParam = 0xFF;
4915 }
4916 } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
4917 if (!drflac__read_uint8(bs, 5, &riceParam)) {
4918 return DRFLAC_FALSE;
4919 }
4920 if (riceParam == 31) {
4921 riceParam = 0xFF;
4922 }
4923 }
4924
4925 if (riceParam != 0xFF) {
4926 if (!drflac__decode_samples_with_residual__rice(bs, bitsPerSample, samplesInPartition, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
4927 return DRFLAC_FALSE;
4928 }
4929 } else {
4930 drflac_uint8 unencodedBitsPerSample = 0;
4931 if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
4932 return DRFLAC_FALSE;
4933 }
4934
4935 if (!drflac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
4936 return DRFLAC_FALSE;
4937 }
4938 }
4939
4940 pDecodedSamples += samplesInPartition;
4941
4942 if (partitionsRemaining == 1) {
4943 break;
4944 }
4945
4946 partitionsRemaining -= 1;
4947
4948 if (partitionOrder != 0) {
4949 samplesInPartition = blockSize / (1 << partitionOrder);
4950 }
4951 }
4952
4953 return DRFLAC_TRUE;
4954 }
4955
4956 /*
4957 Reads and seeks past the residual for the sub-frame the decoder is currently sitting on. This function should be called
4958 when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be set to 0. The
4959 <blockSize> and <order> parameters are used to determine how many residual values need to be decoded.
4960 */
4961 static drflac_bool32 drflac__read_and_seek_residual(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 order)
4962 {
4963 drflac_uint8 residualMethod;
4964 drflac_uint8 partitionOrder;
4965 drflac_uint32 samplesInPartition;
4966 drflac_uint32 partitionsRemaining;
4967
4968 DRFLAC_ASSERT(bs != NULL);
4969 DRFLAC_ASSERT(blockSize != 0);
4970
4971 if (!drflac__read_uint8(bs, 2, &residualMethod)) {
4972 return DRFLAC_FALSE;
4973 }
4974
4975 if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
4976 return DRFLAC_FALSE; /* Unknown or unsupported residual coding method. */
4977 }
4978
4979 if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
4980 return DRFLAC_FALSE;
4981 }
4982
4983 /*
4984 From the FLAC spec:
4985 The Rice partition order in a Rice-coded residual section must be less than or equal to 8.
4986 */
4987 if (partitionOrder > 8) {
4988 return DRFLAC_FALSE;
4989 }
4990
4991 /* Validation check. */
4992 if ((blockSize / (1 << partitionOrder)) <= order) {
4993 return DRFLAC_FALSE;
4994 }
4995
4996 samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
4997 partitionsRemaining = (1 << partitionOrder);
4998 for (;;)
4999 {
5000 drflac_uint8 riceParam = 0;
5001 if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
5002 if (!drflac__read_uint8(bs, 4, &riceParam)) {
5003 return DRFLAC_FALSE;
5004 }
5005 if (riceParam == 15) {
5006 riceParam = 0xFF;
5007 }
5008 } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
5009 if (!drflac__read_uint8(bs, 5, &riceParam)) {
5010 return DRFLAC_FALSE;
5011 }
5012 if (riceParam == 31) {
5013 riceParam = 0xFF;
5014 }
5015 }
5016
5017 if (riceParam != 0xFF) {
5018 if (!drflac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) {
5019 return DRFLAC_FALSE;
5020 }
5021 } else {
5022 drflac_uint8 unencodedBitsPerSample = 0;
5023 if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
5024 return DRFLAC_FALSE;
5025 }
5026
5027 if (!drflac__seek_bits(bs, unencodedBitsPerSample * samplesInPartition)) {
5028 return DRFLAC_FALSE;
5029 }
5030 }
5031
5032
5033 if (partitionsRemaining == 1) {
5034 break;
5035 }
5036
5037 partitionsRemaining -= 1;
5038 samplesInPartition = blockSize / (1 << partitionOrder);
5039 }
5040
5041 return DRFLAC_TRUE;
5042 }
5043
5044
5045 static drflac_bool32 drflac__decode_samples__constant(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
5046 {
5047 drflac_uint32 i;
5048
5049 /* Only a single sample needs to be decoded here. */
5050 drflac_int32 sample;
5051 if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
5052 return DRFLAC_FALSE;
5053 }
5054
5055 /*
5056 We don't really need to expand this, but it does simplify the process of reading samples. If this becomes a performance issue (unlikely)
5057 we'll want to look at a more efficient way.
5058 */
5059 for (i = 0; i < blockSize; ++i) {
5060 pDecodedSamples[i] = sample;
5061 }
5062
5063 return DRFLAC_TRUE;
5064 }
5065
5066 static drflac_bool32 drflac__decode_samples__verbatim(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
5067 {
5068 drflac_uint32 i;
5069
5070 for (i = 0; i < blockSize; ++i) {
5071 drflac_int32 sample;
5072 if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
5073 return DRFLAC_FALSE;
5074 }
5075
5076 pDecodedSamples[i] = sample;
5077 }
5078
5079 return DRFLAC_TRUE;
5080 }
5081
5082 static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
5083 {
5084 drflac_uint32 i;
5085
5086 static drflac_int32 lpcCoefficientsTable[5][4] = {
5087 {0, 0, 0, 0},
5088 {1, 0, 0, 0},
5089 {2, -1, 0, 0},
5090 {3, -3, 1, 0},
5091 {4, -6, 4, -1}
5092 };
5093
5094 /* Warm up samples and coefficients. */
5095 for (i = 0; i < lpcOrder; ++i) {
5096 drflac_int32 sample;
5097 if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
5098 return DRFLAC_FALSE;
5099 }
5100
5101 pDecodedSamples[i] = sample;
5102 }
5103
5104 if (!drflac__decode_samples_with_residual(bs, subframeBitsPerSample, blockSize, lpcOrder, 0, 4, lpcCoefficientsTable[lpcOrder], pDecodedSamples)) {
5105 return DRFLAC_FALSE;
5106 }
5107
5108 return DRFLAC_TRUE;
5109 }
5110
5111 static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
5112 {
5113 drflac_uint8 i;
5114 drflac_uint8 lpcPrecision;
5115 drflac_int8 lpcShift;
5116 drflac_int32 coefficients[32];
5117
5118 /* Warm up samples. */
5119 for (i = 0; i < lpcOrder; ++i) {
5120 drflac_int32 sample;
5121 if (!drflac__read_int32(bs, bitsPerSample, &sample)) {
5122 return DRFLAC_FALSE;
5123 }
5124
5125 pDecodedSamples[i] = sample;
5126 }
5127
5128 if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
5129 return DRFLAC_FALSE;
5130 }
5131 if (lpcPrecision == 15) {
5132 return DRFLAC_FALSE; /* Invalid. */
5133 }
5134 lpcPrecision += 1;
5135
5136 if (!drflac__read_int8(bs, 5, &lpcShift)) {
5137 return DRFLAC_FALSE;
5138 }
5139
5140 /*
5141 From the FLAC specification:
5142
5143 Quantized linear predictor coefficient shift needed in bits (NOTE: this number is signed two's-complement)
5144
5145 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
5146 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.
5147 */
5148 if (lpcShift < 0) {
5149 return DRFLAC_FALSE;
5150 }
5151
5152 DRFLAC_ZERO_MEMORY(coefficients, sizeof(coefficients));
5153 for (i = 0; i < lpcOrder; ++i) {
5154 if (!drflac__read_int32(bs, lpcPrecision, coefficients + i)) {
5155 return DRFLAC_FALSE;
5156 }
5157 }
5158
5159 if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
5160 return DRFLAC_FALSE;
5161 }
5162
5163 return DRFLAC_TRUE;
5164 }
5165
5166
5167 static drflac_bool32 drflac__read_next_flac_frame_header(drflac_bs* bs, drflac_uint8 streaminfoBitsPerSample, drflac_frame_header* header)
5168 {
5169 const drflac_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000};
5170 const drflac_uint8 bitsPerSampleTable[8] = {0, 8, 12, (drflac_uint8)-1, 16, 20, 24, (drflac_uint8)-1}; /* -1 = reserved. */
5171
5172 DRFLAC_ASSERT(bs != NULL);
5173 DRFLAC_ASSERT(header != NULL);
5174
5175 /* Keep looping until we find a valid sync code. */
5176 for (;;) {
5177 drflac_uint8 crc8 = 0xCE; /* 0xCE = drflac_crc8(0, 0x3FFE, 14); */
5178 drflac_uint8 reserved = 0;
5179 drflac_uint8 blockingStrategy = 0;
5180 drflac_uint8 blockSize = 0;
5181 drflac_uint8 sampleRate = 0;
5182 drflac_uint8 channelAssignment = 0;
5183 drflac_uint8 bitsPerSample = 0;
5184 drflac_bool32 isVariableBlockSize;
5185
5186 if (!drflac__find_and_seek_to_next_sync_code(bs)) {
5187 return DRFLAC_FALSE;
5188 }
5189
5190 if (!drflac__read_uint8(bs, 1, &reserved)) {
5191 return DRFLAC_FALSE;
5192 }
5193 if (reserved == 1) {
5194 continue;
5195 }
5196 crc8 = drflac_crc8(crc8, reserved, 1);
5197
5198 if (!drflac__read_uint8(bs, 1, &blockingStrategy)) {
5199 return DRFLAC_FALSE;
5200 }
5201 crc8 = drflac_crc8(crc8, blockingStrategy, 1);
5202
5203 if (!drflac__read_uint8(bs, 4, &blockSize)) {
5204 return DRFLAC_FALSE;
5205 }
5206 if (blockSize == 0) {
5207 continue;
5208 }
5209 crc8 = drflac_crc8(crc8, blockSize, 4);
5210
5211 if (!drflac__read_uint8(bs, 4, &sampleRate)) {
5212 return DRFLAC_FALSE;
5213 }
5214 crc8 = drflac_crc8(crc8, sampleRate, 4);
5215
5216 if (!drflac__read_uint8(bs, 4, &channelAssignment)) {
5217 return DRFLAC_FALSE;
5218 }
5219 if (channelAssignment > 10) {
5220 continue;
5221 }
5222 crc8 = drflac_crc8(crc8, channelAssignment, 4);
5223
5224 if (!drflac__read_uint8(bs, 3, &bitsPerSample)) {
5225 return DRFLAC_FALSE;
5226 }
5227 if (bitsPerSample == 3 || bitsPerSample == 7) {
5228 continue;
5229 }
5230 crc8 = drflac_crc8(crc8, bitsPerSample, 3);
5231
5232
5233 if (!drflac__read_uint8(bs, 1, &reserved)) {
5234 return DRFLAC_FALSE;
5235 }
5236 if (reserved == 1) {
5237 continue;
5238 }
5239 crc8 = drflac_crc8(crc8, reserved, 1);
5240
5241
5242 isVariableBlockSize = blockingStrategy == 1;
5243 if (isVariableBlockSize) {
5244 drflac_uint64 pcmFrameNumber;
5245 drflac_result result = drflac__read_utf8_coded_number(bs, &pcmFrameNumber, &crc8);
5246 if (result != DRFLAC_SUCCESS) {
5247 if (result == DRFLAC_AT_END) {
5248 return DRFLAC_FALSE;
5249 } else {
5250 continue;
5251 }
5252 }
5253 header->flacFrameNumber = 0;
5254 header->pcmFrameNumber = pcmFrameNumber;
5255 } else {
5256 drflac_uint64 flacFrameNumber = 0;
5257 drflac_result result = drflac__read_utf8_coded_number(bs, &flacFrameNumber, &crc8);
5258 if (result != DRFLAC_SUCCESS) {
5259 if (result == DRFLAC_AT_END) {
5260 return DRFLAC_FALSE;
5261 } else {
5262 continue;
5263 }
5264 }
5265 header->flacFrameNumber = (drflac_uint32)flacFrameNumber; /* <-- Safe cast. */
5266 header->pcmFrameNumber = 0;
5267 }
5268
5269
5270 DRFLAC_ASSERT(blockSize > 0);
5271 if (blockSize == 1) {
5272 header->blockSizeInPCMFrames = 192;
5273 } else if (blockSize <= 5) {
5274 DRFLAC_ASSERT(blockSize >= 2);
5275 header->blockSizeInPCMFrames = 576 * (1 << (blockSize - 2));
5276 } else if (blockSize == 6) {
5277 if (!drflac__read_uint16(bs, 8, &header->blockSizeInPCMFrames)) {
5278 return DRFLAC_FALSE;
5279 }
5280 crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 8);
5281 header->blockSizeInPCMFrames += 1;
5282 } else if (blockSize == 7) {
5283 if (!drflac__read_uint16(bs, 16, &header->blockSizeInPCMFrames)) {
5284 return DRFLAC_FALSE;
5285 }
5286 crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 16);
5287 if (header->blockSizeInPCMFrames == 0xFFFF) {
5288 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. */
5289 }
5290 header->blockSizeInPCMFrames += 1;
5291 } else {
5292 DRFLAC_ASSERT(blockSize >= 8);
5293 header->blockSizeInPCMFrames = 256 * (1 << (blockSize - 8));
5294 }
5295
5296
5297 if (sampleRate <= 11) {
5298 header->sampleRate = sampleRateTable[sampleRate];
5299 } else if (sampleRate == 12) {
5300 if (!drflac__read_uint32(bs, 8, &header->sampleRate)) {
5301 return DRFLAC_FALSE;
5302 }
5303 crc8 = drflac_crc8(crc8, header->sampleRate, 8);
5304 header->sampleRate *= 1000;
5305 } else if (sampleRate == 13) {
5306 if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
5307 return DRFLAC_FALSE;
5308 }
5309 crc8 = drflac_crc8(crc8, header->sampleRate, 16);
5310 } else if (sampleRate == 14) {
5311 if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
5312 return DRFLAC_FALSE;
5313 }
5314 crc8 = drflac_crc8(crc8, header->sampleRate, 16);
5315 header->sampleRate *= 10;
5316 } else {
5317 continue; /* Invalid. Assume an invalid block. */
5318 }
5319
5320
5321 header->channelAssignment = channelAssignment;
5322
5323 header->bitsPerSample = bitsPerSampleTable[bitsPerSample];
5324 if (header->bitsPerSample == 0) {
5325 header->bitsPerSample = streaminfoBitsPerSample;
5326 }
5327
5328 if (header->bitsPerSample != streaminfoBitsPerSample) {
5329 /* If this subframe has a different bitsPerSample then streaminfo or the first frame, reject it */
5330 return DRFLAC_FALSE;
5331 }
5332
5333 if (!drflac__read_uint8(bs, 8, &header->crc8)) {
5334 return DRFLAC_FALSE;
5335 }
5336
5337 #ifndef DR_FLAC_NO_CRC
5338 if (header->crc8 != crc8) {
5339 continue; /* CRC mismatch. Loop back to the top and find the next sync code. */
5340 }
5341 #endif
5342 return DRFLAC_TRUE;
5343 }
5344 }
5345
5346 static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe* pSubframe)
5347 {
5348 drflac_uint8 header;
5349 int type;
5350
5351 if (!drflac__read_uint8(bs, 8, &header)) {
5352 return DRFLAC_FALSE;
5353 }
5354
5355 /* First bit should always be 0. */
5356 if ((header & 0x80) != 0) {
5357 return DRFLAC_FALSE;
5358 }
5359
5360 type = (header & 0x7E) >> 1;
5361 if (type == 0) {
5362 pSubframe->subframeType = DRFLAC_SUBFRAME_CONSTANT;
5363 } else if (type == 1) {
5364 pSubframe->subframeType = DRFLAC_SUBFRAME_VERBATIM;
5365 } else {
5366 if ((type & 0x20) != 0) {
5367 pSubframe->subframeType = DRFLAC_SUBFRAME_LPC;
5368 pSubframe->lpcOrder = (drflac_uint8)(type & 0x1F) + 1;
5369 } else if ((type & 0x08) != 0) {
5370 pSubframe->subframeType = DRFLAC_SUBFRAME_FIXED;
5371 pSubframe->lpcOrder = (drflac_uint8)(type & 0x07);
5372 if (pSubframe->lpcOrder > 4) {
5373 pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
5374 pSubframe->lpcOrder = 0;
5375 }
5376 } else {
5377 pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
5378 }
5379 }
5380
5381 if (pSubframe->subframeType == DRFLAC_SUBFRAME_RESERVED) {
5382 return DRFLAC_FALSE;
5383 }
5384
5385 /* Wasted bits per sample. */
5386 pSubframe->wastedBitsPerSample = 0;
5387 if ((header & 0x01) == 1) {
5388 unsigned int wastedBitsPerSample;
5389 if (!drflac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) {
5390 return DRFLAC_FALSE;
5391 }
5392 pSubframe->wastedBitsPerSample = (drflac_uint8)wastedBitsPerSample + 1;
5393 }
5394
5395 return DRFLAC_TRUE;
5396 }
5397
5398 static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex, drflac_int32* pDecodedSamplesOut)
5399 {
5400 drflac_subframe* pSubframe;
5401 drflac_uint32 subframeBitsPerSample;
5402
5403 DRFLAC_ASSERT(bs != NULL);
5404 DRFLAC_ASSERT(frame != NULL);
5405
5406 pSubframe = frame->subframes + subframeIndex;
5407 if (!drflac__read_subframe_header(bs, pSubframe)) {
5408 return DRFLAC_FALSE;
5409 }
5410
5411 /* Side channels require an extra bit per sample. Took a while to figure that one out... */
5412 subframeBitsPerSample = frame->header.bitsPerSample;
5413 if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
5414 subframeBitsPerSample += 1;
5415 } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
5416 subframeBitsPerSample += 1;
5417 }
5418
5419 if (subframeBitsPerSample > 32) {
5420 /* libFLAC and ffmpeg reject 33-bit subframes as well */
5421 return DRFLAC_FALSE;
5422 }
5423
5424 /* Need to handle wasted bits per sample. */
5425 if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
5426 return DRFLAC_FALSE;
5427 }
5428 subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
5429
5430 pSubframe->pSamplesS32 = pDecodedSamplesOut;
5431
5432 switch (pSubframe->subframeType)
5433 {
5434 case DRFLAC_SUBFRAME_CONSTANT:
5435 {
5436 drflac__decode_samples__constant(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
5437 } break;
5438
5439 case DRFLAC_SUBFRAME_VERBATIM:
5440 {
5441 drflac__decode_samples__verbatim(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
5442 } break;
5443
5444 case DRFLAC_SUBFRAME_FIXED:
5445 {
5446 drflac__decode_samples__fixed(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
5447 } break;
5448
5449 case DRFLAC_SUBFRAME_LPC:
5450 {
5451 drflac__decode_samples__lpc(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
5452 } break;
5453
5454 default: return DRFLAC_FALSE;
5455 }
5456
5457 return DRFLAC_TRUE;
5458 }
5459
5460 static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex)
5461 {
5462 drflac_subframe* pSubframe;
5463 drflac_uint32 subframeBitsPerSample;
5464
5465 DRFLAC_ASSERT(bs != NULL);
5466 DRFLAC_ASSERT(frame != NULL);
5467
5468 pSubframe = frame->subframes + subframeIndex;
5469 if (!drflac__read_subframe_header(bs, pSubframe)) {
5470 return DRFLAC_FALSE;
5471 }
5472
5473 /* Side channels require an extra bit per sample. Took a while to figure that one out... */
5474 subframeBitsPerSample = frame->header.bitsPerSample;
5475 if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
5476 subframeBitsPerSample += 1;
5477 } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
5478 subframeBitsPerSample += 1;
5479 }
5480
5481 /* Need to handle wasted bits per sample. */
5482 if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
5483 return DRFLAC_FALSE;
5484 }
5485 subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
5486
5487 pSubframe->pSamplesS32 = NULL;
5488
5489 switch (pSubframe->subframeType)
5490 {
5491 case DRFLAC_SUBFRAME_CONSTANT:
5492 {
5493 if (!drflac__seek_bits(bs, subframeBitsPerSample)) {
5494 return DRFLAC_FALSE;
5495 }
5496 } break;
5497
5498 case DRFLAC_SUBFRAME_VERBATIM:
5499 {
5500 unsigned int bitsToSeek = frame->header.blockSizeInPCMFrames * subframeBitsPerSample;
5501 if (!drflac__seek_bits(bs, bitsToSeek)) {
5502 return DRFLAC_FALSE;
5503 }
5504 } break;
5505
5506 case DRFLAC_SUBFRAME_FIXED:
5507 {
5508 unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
5509 if (!drflac__seek_bits(bs, bitsToSeek)) {
5510 return DRFLAC_FALSE;
5511 }
5512
5513 if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
5514 return DRFLAC_FALSE;
5515 }
5516 } break;
5517
5518 case DRFLAC_SUBFRAME_LPC:
5519 {
5520 drflac_uint8 lpcPrecision;
5521
5522 unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
5523 if (!drflac__seek_bits(bs, bitsToSeek)) {
5524 return DRFLAC_FALSE;
5525 }
5526
5527 if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
5528 return DRFLAC_FALSE;
5529 }
5530 if (lpcPrecision == 15) {
5531 return DRFLAC_FALSE; /* Invalid. */
5532 }
5533 lpcPrecision += 1;
5534
5535
5536 bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5; /* +5 for shift. */
5537 if (!drflac__seek_bits(bs, bitsToSeek)) {
5538 return DRFLAC_FALSE;
5539 }
5540
5541 if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
5542 return DRFLAC_FALSE;
5543 }
5544 } break;
5545
5546 default: return DRFLAC_FALSE;
5547 }
5548
5549 return DRFLAC_TRUE;
5550 }
5551
5552
5553 static DRFLAC_INLINE drflac_uint8 drflac__get_channel_count_from_channel_assignment(drflac_int8 channelAssignment)
5554 {
5555 drflac_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2};
5556
5557 DRFLAC_ASSERT(channelAssignment <= 10);
5558 return lookup[channelAssignment];
5559 }
5560
5561 static drflac_result drflac__decode_flac_frame(drflac* pFlac)
5562 {
5563 int channelCount;
5564 int i;
5565 drflac_uint8 paddingSizeInBits;
5566 drflac_uint16 desiredCRC16;
5567 #ifndef DR_FLAC_NO_CRC
5568 drflac_uint16 actualCRC16;
5569 #endif
5570
5571 /* This function should be called while the stream is sitting on the first byte after the frame header. */
5572 DRFLAC_ZERO_MEMORY(pFlac->currentFLACFrame.subframes, sizeof(pFlac->currentFLACFrame.subframes));
5573
5574 /* The frame block size must never be larger than the maximum block size defined by the FLAC stream. */
5575 if (pFlac->currentFLACFrame.header.blockSizeInPCMFrames > pFlac->maxBlockSizeInPCMFrames) {
5576 return DRFLAC_ERROR;
5577 }
5578
5579 /* The number of channels in the frame must match the channel count from the STREAMINFO block. */
5580 channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
5581 if (channelCount != (int)pFlac->channels) {
5582 return DRFLAC_ERROR;
5583 }
5584
5585 for (i = 0; i < channelCount; ++i) {
5586 if (!drflac__decode_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i, pFlac->pDecodedSamples + (pFlac->currentFLACFrame.header.blockSizeInPCMFrames * i))) {
5587 return DRFLAC_ERROR;
5588 }
5589 }
5590
5591 paddingSizeInBits = (drflac_uint8)(DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7);
5592 if (paddingSizeInBits > 0) {
5593 drflac_uint8 padding = 0;
5594 if (!drflac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding)) {
5595 return DRFLAC_AT_END;
5596 }
5597 }
5598
5599 #ifndef DR_FLAC_NO_CRC
5600 actualCRC16 = drflac__flush_crc16(&pFlac->bs);
5601 #endif
5602 if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
5603 return DRFLAC_AT_END;
5604 }
5605
5606 #ifndef DR_FLAC_NO_CRC
5607 if (actualCRC16 != desiredCRC16) {
5608 return DRFLAC_CRC_MISMATCH; /* CRC mismatch. */
5609 }
5610 #endif
5611
5612 pFlac->currentFLACFrame.pcmFramesRemaining = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
5613
5614 return DRFLAC_SUCCESS;
5615 }
5616
5617 static drflac_result drflac__seek_flac_frame(drflac* pFlac)
5618 {
5619 int channelCount;
5620 int i;
5621 drflac_uint16 desiredCRC16;
5622 #ifndef DR_FLAC_NO_CRC
5623 drflac_uint16 actualCRC16;
5624 #endif
5625
5626 channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
5627 for (i = 0; i < channelCount; ++i) {
5628 if (!drflac__seek_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i)) {
5629 return DRFLAC_ERROR;
5630 }
5631 }
5632
5633 /* Padding. */
5634 if (!drflac__seek_bits(&pFlac->bs, DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7)) {
5635 return DRFLAC_ERROR;
5636 }
5637
5638 /* CRC. */
5639 #ifndef DR_FLAC_NO_CRC
5640 actualCRC16 = drflac__flush_crc16(&pFlac->bs);
5641 #endif
5642 if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
5643 return DRFLAC_AT_END;
5644 }
5645
5646 #ifndef DR_FLAC_NO_CRC
5647 if (actualCRC16 != desiredCRC16) {
5648 return DRFLAC_CRC_MISMATCH; /* CRC mismatch. */
5649 }
5650 #endif
5651
5652 return DRFLAC_SUCCESS;
5653 }
5654
5655 static drflac_bool32 drflac__read_and_decode_next_flac_frame(drflac* pFlac)
5656 {
5657 DRFLAC_ASSERT(pFlac != NULL);
5658
5659 for (;;) {
5660 drflac_result result;
5661
5662 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5663 return DRFLAC_FALSE;
5664 }
5665
5666 result = drflac__decode_flac_frame(pFlac);
5667 if (result != DRFLAC_SUCCESS) {
5668 if (result == DRFLAC_CRC_MISMATCH) {
5669 continue; /* CRC mismatch. Skip to the next frame. */
5670 } else {
5671 return DRFLAC_FALSE;
5672 }
5673 }
5674
5675 return DRFLAC_TRUE;
5676 }
5677 }
5678
5679 static void drflac__get_pcm_frame_range_of_current_flac_frame(drflac* pFlac, drflac_uint64* pFirstPCMFrame, drflac_uint64* pLastPCMFrame)
5680 {
5681 drflac_uint64 firstPCMFrame;
5682 drflac_uint64 lastPCMFrame;
5683
5684 DRFLAC_ASSERT(pFlac != NULL);
5685
5686 firstPCMFrame = pFlac->currentFLACFrame.header.pcmFrameNumber;
5687 if (firstPCMFrame == 0) {
5688 firstPCMFrame = ((drflac_uint64)pFlac->currentFLACFrame.header.flacFrameNumber) * pFlac->maxBlockSizeInPCMFrames;
5689 }
5690
5691 lastPCMFrame = firstPCMFrame + pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
5692 if (lastPCMFrame > 0) {
5693 lastPCMFrame -= 1; /* Needs to be zero based. */
5694 }
5695
5696 if (pFirstPCMFrame) {
5697 *pFirstPCMFrame = firstPCMFrame;
5698 }
5699 if (pLastPCMFrame) {
5700 *pLastPCMFrame = lastPCMFrame;
5701 }
5702 }
5703
5704 static drflac_bool32 drflac__seek_to_first_frame(drflac* pFlac)
5705 {
5706 drflac_bool32 result;
5707
5708 DRFLAC_ASSERT(pFlac != NULL);
5709
5710 result = drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes);
5711
5712 DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
5713 pFlac->currentPCMFrame = 0;
5714
5715 return result;
5716 }
5717
5718 static DRFLAC_INLINE drflac_result drflac__seek_to_next_flac_frame(drflac* pFlac)
5719 {
5720 /* This function should only ever be called while the decoder is sitting on the first byte past the FRAME_HEADER section. */
5721 DRFLAC_ASSERT(pFlac != NULL);
5722 return drflac__seek_flac_frame(pFlac);
5723 }
5724
5725
5726 static drflac_uint64 drflac__seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 pcmFramesToSeek)
5727 {
5728 drflac_uint64 pcmFramesRead = 0;
5729 while (pcmFramesToSeek > 0) {
5730 if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
5731 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
5732 break; /* Couldn't read the next frame, so just break from the loop and return. */
5733 }
5734 } else {
5735 if (pFlac->currentFLACFrame.pcmFramesRemaining > pcmFramesToSeek) {
5736 pcmFramesRead += pcmFramesToSeek;
5737 pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)pcmFramesToSeek; /* <-- Safe cast. Will always be < currentFrame.pcmFramesRemaining < 65536. */
5738 pcmFramesToSeek = 0;
5739 } else {
5740 pcmFramesRead += pFlac->currentFLACFrame.pcmFramesRemaining;
5741 pcmFramesToSeek -= pFlac->currentFLACFrame.pcmFramesRemaining;
5742 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
5743 }
5744 }
5745 }
5746
5747 pFlac->currentPCMFrame += pcmFramesRead;
5748 return pcmFramesRead;
5749 }
5750
5751
5752 static drflac_bool32 drflac__seek_to_pcm_frame__brute_force(drflac* pFlac, drflac_uint64 pcmFrameIndex)
5753 {
5754 drflac_bool32 isMidFrame = DRFLAC_FALSE;
5755 drflac_uint64 runningPCMFrameCount;
5756
5757 DRFLAC_ASSERT(pFlac != NULL);
5758
5759 /* 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. */
5760 if (pcmFrameIndex >= pFlac->currentPCMFrame) {
5761 /* Seeking forward. Need to seek from the current position. */
5762 runningPCMFrameCount = pFlac->currentPCMFrame;
5763
5764 /* The frame header for the first frame may not yet have been read. We need to do that if necessary. */
5765 if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
5766 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5767 return DRFLAC_FALSE;
5768 }
5769 } else {
5770 isMidFrame = DRFLAC_TRUE;
5771 }
5772 } else {
5773 /* Seeking backwards. Need to seek from the start of the file. */
5774 runningPCMFrameCount = 0;
5775
5776 /* Move back to the start. */
5777 if (!drflac__seek_to_first_frame(pFlac)) {
5778 return DRFLAC_FALSE;
5779 }
5780
5781 /* Decode the first frame in preparation for sample-exact seeking below. */
5782 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5783 return DRFLAC_FALSE;
5784 }
5785 }
5786
5787 /*
5788 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
5789 header. If based on the header we can determine that the frame contains the sample, we do a full decode of that frame.
5790 */
5791 for (;;) {
5792 drflac_uint64 pcmFrameCountInThisFLACFrame;
5793 drflac_uint64 firstPCMFrameInFLACFrame = 0;
5794 drflac_uint64 lastPCMFrameInFLACFrame = 0;
5795
5796 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
5797
5798 pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
5799 if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
5800 /*
5801 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
5802 it never existed and keep iterating.
5803 */
5804 drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
5805
5806 if (!isMidFrame) {
5807 drflac_result result = drflac__decode_flac_frame(pFlac);
5808 if (result == DRFLAC_SUCCESS) {
5809 /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
5810 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */
5811 } else {
5812 if (result == DRFLAC_CRC_MISMATCH) {
5813 goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */
5814 } else {
5815 return DRFLAC_FALSE;
5816 }
5817 }
5818 } else {
5819 /* We started seeking mid-frame which means we need to skip the frame decoding part. */
5820 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
5821 }
5822 } else {
5823 /*
5824 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
5825 frame never existed and leave the running sample count untouched.
5826 */
5827 if (!isMidFrame) {
5828 drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
5829 if (result == DRFLAC_SUCCESS) {
5830 runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
5831 } else {
5832 if (result == DRFLAC_CRC_MISMATCH) {
5833 goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */
5834 } else {
5835 return DRFLAC_FALSE;
5836 }
5837 }
5838 } else {
5839 /*
5840 We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with
5841 drflac__seek_to_next_flac_frame() which only works if the decoder is sitting on the byte just after the frame header.
5842 */
5843 runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
5844 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
5845 isMidFrame = DRFLAC_FALSE;
5846 }
5847
5848 /* If we are seeking to the end of the file and we've just hit it, we're done. */
5849 if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
5850 return DRFLAC_TRUE;
5851 }
5852 }
5853
5854 next_iteration:
5855 /* Grab the next frame in preparation for the next iteration. */
5856 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5857 return DRFLAC_FALSE;
5858 }
5859 }
5860 }
5861
5862
5863 #if !defined(DR_FLAC_NO_CRC)
5864 /*
5865 We use an average compression ratio to determine our approximate start location. FLAC files are generally about 50%-70% the size of their
5866 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
5867 location.
5868 */
5869 #define DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO 0.6f
5870
5871 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)
5872 {
5873 DRFLAC_ASSERT(pFlac != NULL);
5874 DRFLAC_ASSERT(pLastSuccessfulSeekOffset != NULL);
5875 DRFLAC_ASSERT(targetByte >= rangeLo);
5876 DRFLAC_ASSERT(targetByte <= rangeHi);
5877
5878 *pLastSuccessfulSeekOffset = pFlac->firstFLACFramePosInBytes;
5879
5880 for (;;) {
5881 /* After rangeLo == rangeHi == targetByte fails, we need to break out. */
5882 drflac_uint64 lastTargetByte = targetByte;
5883
5884 /* 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. */
5885 if (!drflac__seek_to_byte(&pFlac->bs, targetByte)) {
5886 /* If we couldn't even seek to the first byte in the stream we have a problem. Just abandon the whole thing. */
5887 if (targetByte == 0) {
5888 drflac__seek_to_first_frame(pFlac); /* Try to recover. */
5889 return DRFLAC_FALSE;
5890 }
5891
5892 /* Halve the byte location and continue. */
5893 targetByte = rangeLo + ((rangeHi - rangeLo)/2);
5894 rangeHi = targetByte;
5895 } else {
5896 /* Getting here should mean that we have seeked to an appropriate byte. */
5897
5898 /* Clear the details of the FLAC frame so we don't misreport data. */
5899 DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
5900
5901 /*
5902 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
5903 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
5904 so it needs to stay this way for now.
5905 */
5906 #if 1
5907 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
5908 /* Halve the byte location and continue. */
5909 targetByte = rangeLo + ((rangeHi - rangeLo)/2);
5910 rangeHi = targetByte;
5911 } else {
5912 break;
5913 }
5914 #else
5915 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
5916 /* Halve the byte location and continue. */
5917 targetByte = rangeLo + ((rangeHi - rangeLo)/2);
5918 rangeHi = targetByte;
5919 } else {
5920 break;
5921 }
5922 #endif
5923 }
5924
5925 /* We already tried this byte and there are no more to try, break out. */
5926 if(targetByte == lastTargetByte) {
5927 return DRFLAC_FALSE;
5928 }
5929 }
5930
5931 /* The current PCM frame needs to be updated based on the frame we just seeked to. */
5932 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
5933
5934 DRFLAC_ASSERT(targetByte <= rangeHi);
5935
5936 *pLastSuccessfulSeekOffset = targetByte;
5937 return DRFLAC_TRUE;
5938 }
5939
5940 static drflac_bool32 drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 offset)
5941 {
5942 /* 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(). */
5943 #if 0
5944 if (drflac__decode_flac_frame(pFlac) != DRFLAC_SUCCESS) {
5945 /* We failed to decode this frame which may be due to it being corrupt. We'll just use the next valid FLAC frame. */
5946 if (drflac__read_and_decode_next_flac_frame(pFlac) == DRFLAC_FALSE) {
5947 return DRFLAC_FALSE;
5948 }
5949 }
5950 #endif
5951
5952 return drflac__seek_forward_by_pcm_frames(pFlac, offset) == offset;
5953 }
5954
5955
5956 static drflac_bool32 drflac__seek_to_pcm_frame__binary_search_internal(drflac* pFlac, drflac_uint64 pcmFrameIndex, drflac_uint64 byteRangeLo, drflac_uint64 byteRangeHi)
5957 {
5958 /* This assumes pFlac->currentPCMFrame is sitting on byteRangeLo upon entry. */
5959
5960 drflac_uint64 targetByte;
5961 drflac_uint64 pcmRangeLo = pFlac->totalPCMFrameCount;
5962 drflac_uint64 pcmRangeHi = 0;
5963 drflac_uint64 lastSuccessfulSeekOffset = (drflac_uint64)-1;
5964 drflac_uint64 closestSeekOffsetBeforeTargetPCMFrame = byteRangeLo;
5965 drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
5966
5967 targetByte = byteRangeLo + (drflac_uint64)(((drflac_int64)((pcmFrameIndex - pFlac->currentPCMFrame) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO);
5968 if (targetByte > byteRangeHi) {
5969 targetByte = byteRangeHi;
5970 }
5971
5972 for (;;) {
5973 if (drflac__seek_to_approximate_flac_frame_to_byte(pFlac, targetByte, byteRangeLo, byteRangeHi, &lastSuccessfulSeekOffset)) {
5974 /* We found a FLAC frame. We need to check if it contains the sample we're looking for. */
5975 drflac_uint64 newPCMRangeLo;
5976 drflac_uint64 newPCMRangeHi;
5977 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &newPCMRangeLo, &newPCMRangeHi);
5978
5979 /* If we selected the same frame, it means we should be pretty close. Just decode the rest. */
5980 if (pcmRangeLo == newPCMRangeLo) {
5981 if (!drflac__seek_to_approximate_flac_frame_to_byte(pFlac, closestSeekOffsetBeforeTargetPCMFrame, closestSeekOffsetBeforeTargetPCMFrame, byteRangeHi, &lastSuccessfulSeekOffset)) {
5982 break; /* Failed to seek to closest frame. */
5983 }
5984
5985 if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
5986 return DRFLAC_TRUE;
5987 } else {
5988 break; /* Failed to seek forward. */
5989 }
5990 }
5991
5992 pcmRangeLo = newPCMRangeLo;
5993 pcmRangeHi = newPCMRangeHi;
5994
5995 if (pcmRangeLo <= pcmFrameIndex && pcmRangeHi >= pcmFrameIndex) {
5996 /* The target PCM frame is in this FLAC frame. */
5997 if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame) ) {
5998 return DRFLAC_TRUE;
5999 } else {
6000 break; /* Failed to seek to FLAC frame. */
6001 }
6002 } else {
6003 const float approxCompressionRatio = (drflac_int64)(lastSuccessfulSeekOffset - pFlac->firstFLACFramePosInBytes) / ((drflac_int64)(pcmRangeLo * pFlac->channels * pFlac->bitsPerSample)/8.0f);
6004
6005 if (pcmRangeLo > pcmFrameIndex) {
6006 /* We seeked too far forward. We need to move our target byte backward and try again. */
6007 byteRangeHi = lastSuccessfulSeekOffset;
6008 if (byteRangeLo > byteRangeHi) {
6009 byteRangeLo = byteRangeHi;
6010 }
6011
6012 targetByte = byteRangeLo + ((byteRangeHi - byteRangeLo) / 2);
6013 if (targetByte < byteRangeLo) {
6014 targetByte = byteRangeLo;
6015 }
6016 } else /*if (pcmRangeHi < pcmFrameIndex)*/ {
6017 /* We didn't seek far enough. We need to move our target byte forward and try again. */
6018
6019 /* If we're close enough we can just seek forward. */
6020 if ((pcmFrameIndex - pcmRangeLo) < seekForwardThreshold) {
6021 if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
6022 return DRFLAC_TRUE;
6023 } else {
6024 break; /* Failed to seek to FLAC frame. */
6025 }
6026 } else {
6027 byteRangeLo = lastSuccessfulSeekOffset;
6028 if (byteRangeHi < byteRangeLo) {
6029 byteRangeHi = byteRangeLo;
6030 }
6031
6032 targetByte = lastSuccessfulSeekOffset + (drflac_uint64)(((drflac_int64)((pcmFrameIndex-pcmRangeLo) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * approxCompressionRatio);
6033 if (targetByte > byteRangeHi) {
6034 targetByte = byteRangeHi;
6035 }
6036
6037 if (closestSeekOffsetBeforeTargetPCMFrame < lastSuccessfulSeekOffset) {
6038 closestSeekOffsetBeforeTargetPCMFrame = lastSuccessfulSeekOffset;
6039 }
6040 }
6041 }
6042 }
6043 } else {
6044 /* Getting here is really bad. We just recover as best we can, but moving to the first frame in the stream, and then abort. */
6045 break;
6046 }
6047 }
6048
6049 drflac__seek_to_first_frame(pFlac); /* <-- Try to recover. */
6050 return DRFLAC_FALSE;
6051 }
6052
6053 static drflac_bool32 drflac__seek_to_pcm_frame__binary_search(drflac* pFlac, drflac_uint64 pcmFrameIndex)
6054 {
6055 drflac_uint64 byteRangeLo;
6056 drflac_uint64 byteRangeHi;
6057 drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
6058
6059 /* Our algorithm currently assumes the FLAC stream is currently sitting at the start. */
6060 if (drflac__seek_to_first_frame(pFlac) == DRFLAC_FALSE) {
6061 return DRFLAC_FALSE;
6062 }
6063
6064 /* If we're close enough to the start, just move to the start and seek forward. */
6065 if (pcmFrameIndex < seekForwardThreshold) {
6066 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFrameIndex) == pcmFrameIndex;
6067 }
6068
6069 /*
6070 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
6071 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.
6072 */
6073 byteRangeLo = pFlac->firstFLACFramePosInBytes;
6074 byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
6075
6076 return drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi);
6077 }
6078 #endif /* !DR_FLAC_NO_CRC */
6079
6080 static drflac_bool32 drflac__seek_to_pcm_frame__seek_table(drflac* pFlac, drflac_uint64 pcmFrameIndex)
6081 {
6082 drflac_uint32 iClosestSeekpoint = 0;
6083 drflac_bool32 isMidFrame = DRFLAC_FALSE;
6084 drflac_uint64 runningPCMFrameCount;
6085 drflac_uint32 iSeekpoint;
6086
6087
6088 DRFLAC_ASSERT(pFlac != NULL);
6089
6090 if (pFlac->pSeekpoints == NULL || pFlac->seekpointCount == 0) {
6091 return DRFLAC_FALSE;
6092 }
6093
6094 /* Do not use the seektable if pcmFramIndex is not coverd by it. */
6095 if (pFlac->pSeekpoints[0].firstPCMFrame > pcmFrameIndex) {
6096 return DRFLAC_FALSE;
6097 }
6098
6099 for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
6100 if (pFlac->pSeekpoints[iSeekpoint].firstPCMFrame >= pcmFrameIndex) {
6101 break;
6102 }
6103
6104 iClosestSeekpoint = iSeekpoint;
6105 }
6106
6107 /* There's been cases where the seek table contains only zeros. We need to do some basic validation on the closest seekpoint. */
6108 if (pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount == 0 || pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount > pFlac->maxBlockSizeInPCMFrames) {
6109 return DRFLAC_FALSE;
6110 }
6111 if (pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame > pFlac->totalPCMFrameCount && pFlac->totalPCMFrameCount > 0) {
6112 return DRFLAC_FALSE;
6113 }
6114
6115 #if !defined(DR_FLAC_NO_CRC)
6116 /* 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. */
6117 if (pFlac->totalPCMFrameCount > 0) {
6118 drflac_uint64 byteRangeLo;
6119 drflac_uint64 byteRangeHi;
6120
6121 byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
6122 byteRangeLo = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset;
6123
6124 /*
6125 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
6126 value for byteRangeHi which will clamp it appropriately.
6127
6128 Note that the next seekpoint must have an offset greater than the closest seekpoint because otherwise our binary search algorithm will break down. There
6129 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.
6130 */
6131 if (iClosestSeekpoint < pFlac->seekpointCount-1) {
6132 drflac_uint32 iNextSeekpoint = iClosestSeekpoint + 1;
6133
6134 /* Basic validation on the seekpoints to ensure they're usable. */
6135 if (pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset >= pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset || pFlac->pSeekpoints[iNextSeekpoint].pcmFrameCount == 0) {
6136 return DRFLAC_FALSE; /* The next seekpoint doesn't look right. The seek table cannot be trusted from here. Abort. */
6137 }
6138
6139 if (pFlac->pSeekpoints[iNextSeekpoint].firstPCMFrame != (((drflac_uint64)0xFFFFFFFF << 32) | 0xFFFFFFFF)) { /* Make sure it's not a placeholder seekpoint. */
6140 byteRangeHi = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset - 1; /* byteRangeHi must be zero based. */
6141 }
6142 }
6143
6144 if (drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
6145 if (drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
6146 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
6147
6148 if (drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi)) {
6149 return DRFLAC_TRUE;
6150 }
6151 }
6152 }
6153 }
6154 #endif /* !DR_FLAC_NO_CRC */
6155
6156 /* Getting here means we need to use a slower algorithm because the binary search method failed or cannot be used. */
6157
6158 /*
6159 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
6160 from the seekpoint's first sample.
6161 */
6162 if (pcmFrameIndex >= pFlac->currentPCMFrame && pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame <= pFlac->currentPCMFrame) {
6163 /* Optimized case. Just seek forward from where we are. */
6164 runningPCMFrameCount = pFlac->currentPCMFrame;
6165
6166 /* The frame header for the first frame may not yet have been read. We need to do that if necessary. */
6167 if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
6168 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
6169 return DRFLAC_FALSE;
6170 }
6171 } else {
6172 isMidFrame = DRFLAC_TRUE;
6173 }
6174 } else {
6175 /* Slower case. Seek to the start of the seekpoint and then seek forward from there. */
6176 runningPCMFrameCount = pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame;
6177
6178 if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
6179 return DRFLAC_FALSE;
6180 }
6181
6182 /* Grab the frame the seekpoint is sitting on in preparation for the sample-exact seeking below. */
6183 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
6184 return DRFLAC_FALSE;
6185 }
6186 }
6187
6188 for (;;) {
6189 drflac_uint64 pcmFrameCountInThisFLACFrame;
6190 drflac_uint64 firstPCMFrameInFLACFrame = 0;
6191 drflac_uint64 lastPCMFrameInFLACFrame = 0;
6192
6193 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
6194
6195 pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
6196 if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
6197 /*
6198 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
6199 it never existed and keep iterating.
6200 */
6201 drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
6202
6203 if (!isMidFrame) {
6204 drflac_result result = drflac__decode_flac_frame(pFlac);
6205 if (result == DRFLAC_SUCCESS) {
6206 /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
6207 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */
6208 } else {
6209 if (result == DRFLAC_CRC_MISMATCH) {
6210 goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */
6211 } else {
6212 return DRFLAC_FALSE;
6213 }
6214 }
6215 } else {
6216 /* We started seeking mid-frame which means we need to skip the frame decoding part. */
6217 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
6218 }
6219 } else {
6220 /*
6221 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
6222 frame never existed and leave the running sample count untouched.
6223 */
6224 if (!isMidFrame) {
6225 drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
6226 if (result == DRFLAC_SUCCESS) {
6227 runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
6228 } else {
6229 if (result == DRFLAC_CRC_MISMATCH) {
6230 goto next_iteration; /* CRC mismatch. Pretend this frame never existed. */
6231 } else {
6232 return DRFLAC_FALSE;
6233 }
6234 }
6235 } else {
6236 /*
6237 We started seeking mid-frame which means we need to seek by reading to the end of the frame instead of with
6238 drflac__seek_to_next_flac_frame() which only works if the decoder is sitting on the byte just after the frame header.
6239 */
6240 runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
6241 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
6242 isMidFrame = DRFLAC_FALSE;
6243 }
6244
6245 /* If we are seeking to the end of the file and we've just hit it, we're done. */
6246 if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
6247 return DRFLAC_TRUE;
6248 }
6249 }
6250
6251 next_iteration:
6252 /* Grab the next frame in preparation for the next iteration. */
6253 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
6254 return DRFLAC_FALSE;
6255 }
6256 }
6257 }
6258
6259
6260 #ifndef DR_FLAC_NO_OGG
6261 typedef struct
6262 {
6263 drflac_uint8 capturePattern[4]; /* Should be "OggS" */
6264 drflac_uint8 structureVersion; /* Always 0. */
6265 drflac_uint8 headerType;
6266 drflac_uint64 granulePosition;
6267 drflac_uint32 serialNumber;
6268 drflac_uint32 sequenceNumber;
6269 drflac_uint32 checksum;
6270 drflac_uint8 segmentCount;
6271 drflac_uint8 segmentTable[255];
6272 } drflac_ogg_page_header;
6273 #endif
6274
6275 typedef struct
6276 {
6277 drflac_read_proc onRead;
6278 drflac_seek_proc onSeek;
6279 drflac_meta_proc onMeta;
6280 drflac_container container;
6281 void* pUserData;
6282 void* pUserDataMD;
6283 drflac_uint32 sampleRate;
6284 drflac_uint8 channels;
6285 drflac_uint8 bitsPerSample;
6286 drflac_uint64 totalPCMFrameCount;
6287 drflac_uint16 maxBlockSizeInPCMFrames;
6288 drflac_uint64 runningFilePos;
6289 drflac_bool32 hasStreamInfoBlock;
6290 drflac_bool32 hasMetadataBlocks;
6291 drflac_bs bs; /* <-- A bit streamer is required for loading data during initialization. */
6292 drflac_frame_header firstFrameHeader; /* <-- The header of the first frame that was read during relaxed initalization. Only set if there is no STREAMINFO block. */
6293
6294 #ifndef DR_FLAC_NO_OGG
6295 drflac_uint32 oggSerial;
6296 drflac_uint64 oggFirstBytePos;
6297 drflac_ogg_page_header oggBosHeader;
6298 #endif
6299 } drflac_init_info;
6300
6301 static DRFLAC_INLINE void drflac__decode_block_header(drflac_uint32 blockHeader, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
6302 {
6303 blockHeader = drflac__be2host_32(blockHeader);
6304 *isLastBlock = (drflac_uint8)((blockHeader & 0x80000000UL) >> 31);
6305 *blockType = (drflac_uint8)((blockHeader & 0x7F000000UL) >> 24);
6306 *blockSize = (blockHeader & 0x00FFFFFFUL);
6307 }
6308
6309 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)
6310 {
6311 drflac_uint32 blockHeader;
6312
6313 *blockSize = 0;
6314 if (onRead(pUserData, &blockHeader, 4) != 4) {
6315 return DRFLAC_FALSE;
6316 }
6317
6318 drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize);
6319 return DRFLAC_TRUE;
6320 }
6321
6322 static drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, drflac_streaminfo* pStreamInfo)
6323 {
6324 drflac_uint32 blockSizes;
6325 drflac_uint64 frameSizes = 0;
6326 drflac_uint64 importantProps;
6327 drflac_uint8 md5[16];
6328
6329 /* min/max block size. */
6330 if (onRead(pUserData, &blockSizes, 4) != 4) {
6331 return DRFLAC_FALSE;
6332 }
6333
6334 /* min/max frame size. */
6335 if (onRead(pUserData, &frameSizes, 6) != 6) {
6336 return DRFLAC_FALSE;
6337 }
6338
6339 /* Sample rate, channels, bits per sample and total sample count. */
6340 if (onRead(pUserData, &importantProps, 8) != 8) {
6341 return DRFLAC_FALSE;
6342 }
6343
6344 /* MD5 */
6345 if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5)) {
6346 return DRFLAC_FALSE;
6347 }
6348
6349 blockSizes = drflac__be2host_32(blockSizes);
6350 frameSizes = drflac__be2host_64(frameSizes);
6351 importantProps = drflac__be2host_64(importantProps);
6352
6353 pStreamInfo->minBlockSizeInPCMFrames = (drflac_uint16)((blockSizes & 0xFFFF0000) >> 16);
6354 pStreamInfo->maxBlockSizeInPCMFrames = (drflac_uint16) (blockSizes & 0x0000FFFF);
6355 pStreamInfo->minFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 24)) >> 40);
6356 pStreamInfo->maxFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 0)) >> 16);
6357 pStreamInfo->sampleRate = (drflac_uint32)((importantProps & (((drflac_uint64)0x000FFFFF << 16) << 28)) >> 44);
6358 pStreamInfo->channels = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000000E << 16) << 24)) >> 41) + 1;
6359 pStreamInfo->bitsPerSample = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000001F << 16) << 20)) >> 36) + 1;
6360 pStreamInfo->totalPCMFrameCount = ((importantProps & ((((drflac_uint64)0x0000000F << 16) << 16) | 0xFFFFFFFF)));
6361 DRFLAC_COPY_MEMORY(pStreamInfo->md5, md5, sizeof(md5));
6362
6363 return DRFLAC_TRUE;
6364 }
6365
6366
6367 static void* drflac__malloc_default(size_t sz, void* pUserData)
6368 {
6369 (void)pUserData;
6370 return DRFLAC_MALLOC(sz);
6371 }
6372
6373 static void* drflac__realloc_default(void* p, size_t sz, void* pUserData)
6374 {
6375 (void)pUserData;
6376 return DRFLAC_REALLOC(p, sz);
6377 }
6378
6379 static void drflac__free_default(void* p, void* pUserData)
6380 {
6381 (void)pUserData;
6382 DRFLAC_FREE(p);
6383 }
6384
6385
6386 static void* drflac__malloc_from_callbacks(size_t sz, const drflac_allocation_callbacks* pAllocationCallbacks)
6387 {
6388 if (pAllocationCallbacks == NULL) {
6389 return NULL;
6390 }
6391
6392 if (pAllocationCallbacks->onMalloc != NULL) {
6393 return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
6394 }
6395
6396 /* Try using realloc(). */
6397 if (pAllocationCallbacks->onRealloc != NULL) {
6398 return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
6399 }
6400
6401 return NULL;
6402 }
6403
6404 static void* drflac__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drflac_allocation_callbacks* pAllocationCallbacks)
6405 {
6406 if (pAllocationCallbacks == NULL) {
6407 return NULL;
6408 }
6409
6410 if (pAllocationCallbacks->onRealloc != NULL) {
6411 return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
6412 }
6413
6414 /* Try emulating realloc() in terms of malloc()/free(). */
6415 if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
6416 void* p2;
6417
6418 p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
6419 if (p2 == NULL) {
6420 return NULL;
6421 }
6422
6423 if (p != NULL) {
6424 DRFLAC_COPY_MEMORY(p2, p, szOld);
6425 pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
6426 }
6427
6428 return p2;
6429 }
6430
6431 return NULL;
6432 }
6433
6434 static void drflac__free_from_callbacks(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
6435 {
6436 if (p == NULL || pAllocationCallbacks == NULL) {
6437 return;
6438 }
6439
6440 if (pAllocationCallbacks->onFree != NULL) {
6441 pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
6442 }
6443 }
6444
6445
6446 static drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_uint64* pFirstFramePos, drflac_uint64* pSeektablePos, drflac_uint32* pSeektableSize, drflac_allocation_callbacks* pAllocationCallbacks)
6447 {
6448 /*
6449 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
6450 we'll be sitting on byte 42.
6451 */
6452 drflac_uint64 runningFilePos = 42;
6453 drflac_uint64 seektablePos = 0;
6454 drflac_uint32 seektableSize = 0;
6455
6456 for (;;) {
6457 drflac_metadata metadata;
6458 drflac_uint8 isLastBlock = 0;
6459 drflac_uint8 blockType;
6460 drflac_uint32 blockSize;
6461 if (drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize) == DRFLAC_FALSE) {
6462 return DRFLAC_FALSE;
6463 }
6464 runningFilePos += 4;
6465
6466 metadata.type = blockType;
6467 metadata.pRawData = NULL;
6468 metadata.rawDataSize = 0;
6469
6470 switch (blockType)
6471 {
6472 case DRFLAC_METADATA_BLOCK_TYPE_APPLICATION:
6473 {
6474 if (blockSize < 4) {
6475 return DRFLAC_FALSE;
6476 }
6477
6478 if (onMeta) {
6479 void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6480 if (pRawData == NULL) {
6481 return DRFLAC_FALSE;
6482 }
6483
6484 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6485 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6486 return DRFLAC_FALSE;
6487 }
6488
6489 metadata.pRawData = pRawData;
6490 metadata.rawDataSize = blockSize;
6491 metadata.data.application.id = drflac__be2host_32(*(drflac_uint32*)pRawData);
6492 metadata.data.application.pData = (const void*)((drflac_uint8*)pRawData + sizeof(drflac_uint32));
6493 metadata.data.application.dataSize = blockSize - sizeof(drflac_uint32);
6494 onMeta(pUserDataMD, &metadata);
6495
6496 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6497 }
6498 } break;
6499
6500 case DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE:
6501 {
6502 seektablePos = runningFilePos;
6503 seektableSize = blockSize;
6504
6505 if (onMeta) {
6506 drflac_uint32 iSeekpoint;
6507 void* pRawData;
6508
6509 pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6510 if (pRawData == NULL) {
6511 return DRFLAC_FALSE;
6512 }
6513
6514 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6515 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6516 return DRFLAC_FALSE;
6517 }
6518
6519 metadata.pRawData = pRawData;
6520 metadata.rawDataSize = blockSize;
6521 metadata.data.seektable.seekpointCount = blockSize/sizeof(drflac_seekpoint);
6522 metadata.data.seektable.pSeekpoints = (const drflac_seekpoint*)pRawData;
6523
6524 /* Endian swap. */
6525 for (iSeekpoint = 0; iSeekpoint < metadata.data.seektable.seekpointCount; ++iSeekpoint) {
6526 drflac_seekpoint* pSeekpoint = (drflac_seekpoint*)pRawData + iSeekpoint;
6527 pSeekpoint->firstPCMFrame = drflac__be2host_64(pSeekpoint->firstPCMFrame);
6528 pSeekpoint->flacFrameOffset = drflac__be2host_64(pSeekpoint->flacFrameOffset);
6529 pSeekpoint->pcmFrameCount = drflac__be2host_16(pSeekpoint->pcmFrameCount);
6530 }
6531
6532 onMeta(pUserDataMD, &metadata);
6533
6534 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6535 }
6536 } break;
6537
6538 case DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT:
6539 {
6540 if (blockSize < 8) {
6541 return DRFLAC_FALSE;
6542 }
6543
6544 if (onMeta) {
6545 void* pRawData;
6546 const char* pRunningData;
6547 const char* pRunningDataEnd;
6548 drflac_uint32 i;
6549
6550 pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6551 if (pRawData == NULL) {
6552 return DRFLAC_FALSE;
6553 }
6554
6555 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6556 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6557 return DRFLAC_FALSE;
6558 }
6559
6560 metadata.pRawData = pRawData;
6561 metadata.rawDataSize = blockSize;
6562
6563 pRunningData = (const char*)pRawData;
6564 pRunningDataEnd = (const char*)pRawData + blockSize;
6565
6566 metadata.data.vorbis_comment.vendorLength = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6567
6568 /* Need space for the rest of the block */
6569 if ((pRunningDataEnd - pRunningData) - 4 < (drflac_int64)metadata.data.vorbis_comment.vendorLength) { /* <-- Note the order of operations to avoid overflow to a valid value */
6570 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6571 return DRFLAC_FALSE;
6572 }
6573 metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength;
6574 metadata.data.vorbis_comment.commentCount = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6575
6576 /* Need space for 'commentCount' comments after the block, which at minimum is a drflac_uint32 per comment */
6577 if ((pRunningDataEnd - pRunningData) / sizeof(drflac_uint32) < metadata.data.vorbis_comment.commentCount) { /* <-- Note the order of operations to avoid overflow to a valid value */
6578 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6579 return DRFLAC_FALSE;
6580 }
6581 metadata.data.vorbis_comment.pComments = pRunningData;
6582
6583 /* Check that the comments section is valid before passing it to the callback */
6584 for (i = 0; i < metadata.data.vorbis_comment.commentCount; ++i) {
6585 drflac_uint32 commentLength;
6586
6587 if (pRunningDataEnd - pRunningData < 4) {
6588 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6589 return DRFLAC_FALSE;
6590 }
6591
6592 commentLength = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6593 if (pRunningDataEnd - pRunningData < (drflac_int64)commentLength) { /* <-- Note the order of operations to avoid overflow to a valid value */
6594 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6595 return DRFLAC_FALSE;
6596 }
6597 pRunningData += commentLength;
6598 }
6599
6600 onMeta(pUserDataMD, &metadata);
6601
6602 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6603 }
6604 } break;
6605
6606 case DRFLAC_METADATA_BLOCK_TYPE_CUESHEET:
6607 {
6608 if (blockSize < 396) {
6609 return DRFLAC_FALSE;
6610 }
6611
6612 if (onMeta) {
6613 void* pRawData;
6614 const char* pRunningData;
6615 const char* pRunningDataEnd;
6616 drflac_uint8 iTrack;
6617 drflac_uint8 iIndex;
6618
6619 pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6620 if (pRawData == NULL) {
6621 return DRFLAC_FALSE;
6622 }
6623
6624 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6625 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6626 return DRFLAC_FALSE;
6627 }
6628
6629 metadata.pRawData = pRawData;
6630 metadata.rawDataSize = blockSize;
6631
6632 pRunningData = (const char*)pRawData;
6633 pRunningDataEnd = (const char*)pRawData + blockSize;
6634
6635 DRFLAC_COPY_MEMORY(metadata.data.cuesheet.catalog, pRunningData, 128); pRunningData += 128;
6636 metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*(const drflac_uint64*)pRunningData); pRunningData += 8;
6637 metadata.data.cuesheet.isCD = (pRunningData[0] & 0x80) != 0; pRunningData += 259;
6638 metadata.data.cuesheet.trackCount = pRunningData[0]; pRunningData += 1;
6639 metadata.data.cuesheet.pTrackData = pRunningData;
6640
6641 /* Check that the cuesheet tracks are valid before passing it to the callback */
6642 for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) {
6643 drflac_uint8 indexCount;
6644 drflac_uint32 indexPointSize;
6645
6646 if (pRunningDataEnd - pRunningData < 36) {
6647 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6648 return DRFLAC_FALSE;
6649 }
6650
6651 /* Skip to the index point count */
6652 pRunningData += 35;
6653 indexCount = pRunningData[0]; pRunningData += 1;
6654 indexPointSize = indexCount * sizeof(drflac_cuesheet_track_index);
6655 if (pRunningDataEnd - pRunningData < (drflac_int64)indexPointSize) {
6656 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6657 return DRFLAC_FALSE;
6658 }
6659
6660 /* Endian swap. */
6661 for (iIndex = 0; iIndex < indexCount; ++iIndex) {
6662 drflac_cuesheet_track_index* pTrack = (drflac_cuesheet_track_index*)pRunningData;
6663 pRunningData += sizeof(drflac_cuesheet_track_index);
6664 pTrack->offset = drflac__be2host_64(pTrack->offset);
6665 }
6666 }
6667
6668 onMeta(pUserDataMD, &metadata);
6669
6670 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6671 }
6672 } break;
6673
6674 case DRFLAC_METADATA_BLOCK_TYPE_PICTURE:
6675 {
6676 if (blockSize < 32) {
6677 return DRFLAC_FALSE;
6678 }
6679
6680 if (onMeta) {
6681 void* pRawData;
6682 const char* pRunningData;
6683 const char* pRunningDataEnd;
6684
6685 pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6686 if (pRawData == NULL) {
6687 return DRFLAC_FALSE;
6688 }
6689
6690 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6691 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6692 return DRFLAC_FALSE;
6693 }
6694
6695 metadata.pRawData = pRawData;
6696 metadata.rawDataSize = blockSize;
6697
6698 pRunningData = (const char*)pRawData;
6699 pRunningDataEnd = (const char*)pRawData + blockSize;
6700
6701 metadata.data.picture.type = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6702 metadata.data.picture.mimeLength = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6703
6704 /* Need space for the rest of the block */
6705 if ((pRunningDataEnd - pRunningData) - 24 < (drflac_int64)metadata.data.picture.mimeLength) { /* <-- Note the order of operations to avoid overflow to a valid value */
6706 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6707 return DRFLAC_FALSE;
6708 }
6709 metadata.data.picture.mime = pRunningData; pRunningData += metadata.data.picture.mimeLength;
6710 metadata.data.picture.descriptionLength = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6711
6712 /* Need space for the rest of the block */
6713 if ((pRunningDataEnd - pRunningData) - 20 < (drflac_int64)metadata.data.picture.descriptionLength) { /* <-- Note the order of operations to avoid overflow to a valid value */
6714 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6715 return DRFLAC_FALSE;
6716 }
6717 metadata.data.picture.description = pRunningData; pRunningData += metadata.data.picture.descriptionLength;
6718 metadata.data.picture.width = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6719 metadata.data.picture.height = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6720 metadata.data.picture.colorDepth = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6721 metadata.data.picture.indexColorCount = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6722 metadata.data.picture.pictureDataSize = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
6723 metadata.data.picture.pPictureData = (const drflac_uint8*)pRunningData;
6724
6725 /* Need space for the picture after the block */
6726 if (pRunningDataEnd - pRunningData < (drflac_int64)metadata.data.picture.pictureDataSize) { /* <-- Note the order of operations to avoid overflow to a valid value */
6727 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6728 return DRFLAC_FALSE;
6729 }
6730
6731 onMeta(pUserDataMD, &metadata);
6732
6733 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6734 }
6735 } break;
6736
6737 case DRFLAC_METADATA_BLOCK_TYPE_PADDING:
6738 {
6739 if (onMeta) {
6740 metadata.data.padding.unused = 0;
6741
6742 /* 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. */
6743 if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
6744 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. */
6745 } else {
6746 onMeta(pUserDataMD, &metadata);
6747 }
6748 }
6749 } break;
6750
6751 case DRFLAC_METADATA_BLOCK_TYPE_INVALID:
6752 {
6753 /* Invalid chunk. Just skip over this one. */
6754 if (onMeta) {
6755 if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
6756 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. */
6757 }
6758 }
6759 } break;
6760
6761 default:
6762 {
6763 /*
6764 It's an unknown chunk, but not necessarily invalid. There's a chance more metadata blocks might be defined later on, so we
6765 can at the very least report the chunk to the application and let it look at the raw data.
6766 */
6767 if (onMeta) {
6768 void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
6769 if (pRawData == NULL) {
6770 return DRFLAC_FALSE;
6771 }
6772
6773 if (onRead(pUserData, pRawData, blockSize) != blockSize) {
6774 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6775 return DRFLAC_FALSE;
6776 }
6777
6778 metadata.pRawData = pRawData;
6779 metadata.rawDataSize = blockSize;
6780 onMeta(pUserDataMD, &metadata);
6781
6782 drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
6783 }
6784 } break;
6785 }
6786
6787 /* 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. */
6788 if (onMeta == NULL && blockSize > 0) {
6789 if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
6790 isLastBlock = DRFLAC_TRUE;
6791 }
6792 }
6793
6794 runningFilePos += blockSize;
6795 if (isLastBlock) {
6796 break;
6797 }
6798 }
6799
6800 *pSeektablePos = seektablePos;
6801 *pSeektableSize = seektableSize;
6802 *pFirstFramePos = runningFilePos;
6803
6804 return DRFLAC_TRUE;
6805 }
6806
6807 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)
6808 {
6809 /* Pre Condition: The bit stream should be sitting just past the 4-byte id header. */
6810
6811 drflac_uint8 isLastBlock;
6812 drflac_uint8 blockType;
6813 drflac_uint32 blockSize;
6814
6815 (void)onSeek;
6816
6817 pInit->container = drflac_container_native;
6818
6819 /* The first metadata block should be the STREAMINFO block. */
6820 if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
6821 return DRFLAC_FALSE;
6822 }
6823
6824 if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
6825 if (!relaxed) {
6826 /* We're opening in strict mode and the first block is not the STREAMINFO block. Error. */
6827 return DRFLAC_FALSE;
6828 } else {
6829 /*
6830 Relaxed mode. To open from here we need to just find the first frame and set the sample rate, etc. to whatever is defined
6831 for that frame.
6832 */
6833 pInit->hasStreamInfoBlock = DRFLAC_FALSE;
6834 pInit->hasMetadataBlocks = DRFLAC_FALSE;
6835
6836 if (!drflac__read_next_flac_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) {
6837 return DRFLAC_FALSE; /* Couldn't find a frame. */
6838 }
6839
6840 if (pInit->firstFrameHeader.bitsPerSample == 0) {
6841 return DRFLAC_FALSE; /* Failed to initialize because the first frame depends on the STREAMINFO block, which does not exist. */
6842 }
6843
6844 pInit->sampleRate = pInit->firstFrameHeader.sampleRate;
6845 pInit->channels = drflac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment);
6846 pInit->bitsPerSample = pInit->firstFrameHeader.bitsPerSample;
6847 pInit->maxBlockSizeInPCMFrames = 65535; /* <-- See notes here: https://xiph.org/flac/format.html#metadata_block_streaminfo */
6848 return DRFLAC_TRUE;
6849 }
6850 } else {
6851 drflac_streaminfo streaminfo;
6852 if (!drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
6853 return DRFLAC_FALSE;
6854 }
6855
6856 pInit->hasStreamInfoBlock = DRFLAC_TRUE;
6857 pInit->sampleRate = streaminfo.sampleRate;
6858 pInit->channels = streaminfo.channels;
6859 pInit->bitsPerSample = streaminfo.bitsPerSample;
6860 pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
6861 pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames; /* Don't care about the min block size - only the max (used for determining the size of the memory allocation). */
6862 pInit->hasMetadataBlocks = !isLastBlock;
6863
6864 if (onMeta) {
6865 drflac_metadata metadata;
6866 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
6867 metadata.pRawData = NULL;
6868 metadata.rawDataSize = 0;
6869 metadata.data.streaminfo = streaminfo;
6870 onMeta(pUserDataMD, &metadata);
6871 }
6872
6873 return DRFLAC_TRUE;
6874 }
6875 }
6876
6877 #ifndef DR_FLAC_NO_OGG
6878 #define DRFLAC_OGG_MAX_PAGE_SIZE 65307
6879 #define DRFLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199 /* CRC-32 of "OggS". */
6880
6881 typedef enum
6882 {
6883 drflac_ogg_recover_on_crc_mismatch,
6884 drflac_ogg_fail_on_crc_mismatch
6885 } drflac_ogg_crc_mismatch_recovery;
6886
6887 #ifndef DR_FLAC_NO_CRC
6888 static drflac_uint32 drflac__crc32_table[] = {
6889 0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L,
6890 0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L,
6891 0x2608EDB8L, 0x22C9F00FL, 0x2F8AD6D6L, 0x2B4BCB61L,
6892 0x350C9B64L, 0x31CD86D3L, 0x3C8EA00AL, 0x384FBDBDL,
6893 0x4C11DB70L, 0x48D0C6C7L, 0x4593E01EL, 0x4152FDA9L,
6894 0x5F15ADACL, 0x5BD4B01BL, 0x569796C2L, 0x52568B75L,
6895 0x6A1936C8L, 0x6ED82B7FL, 0x639B0DA6L, 0x675A1011L,
6896 0x791D4014L, 0x7DDC5DA3L, 0x709F7B7AL, 0x745E66CDL,
6897 0x9823B6E0L, 0x9CE2AB57L, 0x91A18D8EL, 0x95609039L,
6898 0x8B27C03CL, 0x8FE6DD8BL, 0x82A5FB52L, 0x8664E6E5L,
6899 0xBE2B5B58L, 0xBAEA46EFL, 0xB7A96036L, 0xB3687D81L,
6900 0xAD2F2D84L, 0xA9EE3033L, 0xA4AD16EAL, 0xA06C0B5DL,
6901 0xD4326D90L, 0xD0F37027L, 0xDDB056FEL, 0xD9714B49L,
6902 0xC7361B4CL, 0xC3F706FBL, 0xCEB42022L, 0xCA753D95L,
6903 0xF23A8028L, 0xF6FB9D9FL, 0xFBB8BB46L, 0xFF79A6F1L,
6904 0xE13EF6F4L, 0xE5FFEB43L, 0xE8BCCD9AL, 0xEC7DD02DL,
6905 0x34867077L, 0x30476DC0L, 0x3D044B19L, 0x39C556AEL,
6906 0x278206ABL, 0x23431B1CL, 0x2E003DC5L, 0x2AC12072L,
6907 0x128E9DCFL, 0x164F8078L, 0x1B0CA6A1L, 0x1FCDBB16L,
6908 0x018AEB13L, 0x054BF6A4L, 0x0808D07DL, 0x0CC9CDCAL,
6909 0x7897AB07L, 0x7C56B6B0L, 0x71159069L, 0x75D48DDEL,
6910 0x6B93DDDBL, 0x6F52C06CL, 0x6211E6B5L, 0x66D0FB02L,
6911 0x5E9F46BFL, 0x5A5E5B08L, 0x571D7DD1L, 0x53DC6066L,
6912 0x4D9B3063L, 0x495A2DD4L, 0x44190B0DL, 0x40D816BAL,
6913 0xACA5C697L, 0xA864DB20L, 0xA527FDF9L, 0xA1E6E04EL,
6914 0xBFA1B04BL, 0xBB60ADFCL, 0xB6238B25L, 0xB2E29692L,
6915 0x8AAD2B2FL, 0x8E6C3698L, 0x832F1041L, 0x87EE0DF6L,
6916 0x99A95DF3L, 0x9D684044L, 0x902B669DL, 0x94EA7B2AL,
6917 0xE0B41DE7L, 0xE4750050L, 0xE9362689L, 0xEDF73B3EL,
6918 0xF3B06B3BL, 0xF771768CL, 0xFA325055L, 0xFEF34DE2L,
6919 0xC6BCF05FL, 0xC27DEDE8L, 0xCF3ECB31L, 0xCBFFD686L,
6920 0xD5B88683L, 0xD1799B34L, 0xDC3ABDEDL, 0xD8FBA05AL,
6921 0x690CE0EEL, 0x6DCDFD59L, 0x608EDB80L, 0x644FC637L,
6922 0x7A089632L, 0x7EC98B85L, 0x738AAD5CL, 0x774BB0EBL,
6923 0x4F040D56L, 0x4BC510E1L, 0x46863638L, 0x42472B8FL,
6924 0x5C007B8AL, 0x58C1663DL, 0x558240E4L, 0x51435D53L,
6925 0x251D3B9EL, 0x21DC2629L, 0x2C9F00F0L, 0x285E1D47L,
6926 0x36194D42L, 0x32D850F5L, 0x3F9B762CL, 0x3B5A6B9BL,
6927 0x0315D626L, 0x07D4CB91L, 0x0A97ED48L, 0x0E56F0FFL,
6928 0x1011A0FAL, 0x14D0BD4DL, 0x19939B94L, 0x1D528623L,
6929 0xF12F560EL, 0xF5EE4BB9L, 0xF8AD6D60L, 0xFC6C70D7L,
6930 0xE22B20D2L, 0xE6EA3D65L, 0xEBA91BBCL, 0xEF68060BL,
6931 0xD727BBB6L, 0xD3E6A601L, 0xDEA580D8L, 0xDA649D6FL,
6932 0xC423CD6AL, 0xC0E2D0DDL, 0xCDA1F604L, 0xC960EBB3L,
6933 0xBD3E8D7EL, 0xB9FF90C9L, 0xB4BCB610L, 0xB07DABA7L,
6934 0xAE3AFBA2L, 0xAAFBE615L, 0xA7B8C0CCL, 0xA379DD7BL,
6935 0x9B3660C6L, 0x9FF77D71L, 0x92B45BA8L, 0x9675461FL,
6936 0x8832161AL, 0x8CF30BADL, 0x81B02D74L, 0x857130C3L,
6937 0x5D8A9099L, 0x594B8D2EL, 0x5408ABF7L, 0x50C9B640L,
6938 0x4E8EE645L, 0x4A4FFBF2L, 0x470CDD2BL, 0x43CDC09CL,
6939 0x7B827D21L, 0x7F436096L, 0x7200464FL, 0x76C15BF8L,
6940 0x68860BFDL, 0x6C47164AL, 0x61043093L, 0x65C52D24L,
6941 0x119B4BE9L, 0x155A565EL, 0x18197087L, 0x1CD86D30L,
6942 0x029F3D35L, 0x065E2082L, 0x0B1D065BL, 0x0FDC1BECL,
6943 0x3793A651L, 0x3352BBE6L, 0x3E119D3FL, 0x3AD08088L,
6944 0x2497D08DL, 0x2056CD3AL, 0x2D15EBE3L, 0x29D4F654L,
6945 0xC5A92679L, 0xC1683BCEL, 0xCC2B1D17L, 0xC8EA00A0L,
6946 0xD6AD50A5L, 0xD26C4D12L, 0xDF2F6BCBL, 0xDBEE767CL,
6947 0xE3A1CBC1L, 0xE760D676L, 0xEA23F0AFL, 0xEEE2ED18L,
6948 0xF0A5BD1DL, 0xF464A0AAL, 0xF9278673L, 0xFDE69BC4L,
6949 0x89B8FD09L, 0x8D79E0BEL, 0x803AC667L, 0x84FBDBD0L,
6950 0x9ABC8BD5L, 0x9E7D9662L, 0x933EB0BBL, 0x97FFAD0CL,
6951 0xAFB010B1L, 0xAB710D06L, 0xA6322BDFL, 0xA2F33668L,
6952 0xBCB4666DL, 0xB8757BDAL, 0xB5365D03L, 0xB1F740B4L
6953 };
6954 #endif
6955
6956 static DRFLAC_INLINE drflac_uint32 drflac_crc32_byte(drflac_uint32 crc32, drflac_uint8 data)
6957 {
6958 #ifndef DR_FLAC_NO_CRC
6959 return (crc32 << 8) ^ drflac__crc32_table[(drflac_uint8)((crc32 >> 24) & 0xFF) ^ data];
6960 #else
6961 (void)data;
6962 return crc32;
6963 #endif
6964 }
6965
6966 #if 0
6967 static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint32(drflac_uint32 crc32, drflac_uint32 data)
6968 {
6969 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 24) & 0xFF));
6970 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 16) & 0xFF));
6971 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 8) & 0xFF));
6972 crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 0) & 0xFF));
6973 return crc32;
6974 }
6975
6976 static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint64(drflac_uint32 crc32, drflac_uint64 data)
6977 {
6978 crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 32) & 0xFFFFFFFF));
6979 crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 0) & 0xFFFFFFFF));
6980 return crc32;
6981 }
6982 #endif
6983
6984 static DRFLAC_INLINE drflac_uint32 drflac_crc32_buffer(drflac_uint32 crc32, drflac_uint8* pData, drflac_uint32 dataSize)
6985 {
6986 /* This can be optimized. */
6987 drflac_uint32 i;
6988 for (i = 0; i < dataSize; ++i) {
6989 crc32 = drflac_crc32_byte(crc32, pData[i]);
6990 }
6991 return crc32;
6992 }
6993
6994
6995 static DRFLAC_INLINE drflac_bool32 drflac_ogg__is_capture_pattern(drflac_uint8 pattern[4])
6996 {
6997 return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S';
6998 }
6999
7000 static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_header_size(drflac_ogg_page_header* pHeader)
7001 {
7002 return 27 + pHeader->segmentCount;
7003 }
7004
7005 static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_body_size(drflac_ogg_page_header* pHeader)
7006 {
7007 drflac_uint32 pageBodySize = 0;
7008 int i;
7009
7010 for (i = 0; i < pHeader->segmentCount; ++i) {
7011 pageBodySize += pHeader->segmentTable[i];
7012 }
7013
7014 return pageBodySize;
7015 }
7016
7017 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)
7018 {
7019 drflac_uint8 data[23];
7020 drflac_uint32 i;
7021
7022 DRFLAC_ASSERT(*pCRC32 == DRFLAC_OGG_CAPTURE_PATTERN_CRC32);
7023
7024 if (onRead(pUserData, data, 23) != 23) {
7025 return DRFLAC_AT_END;
7026 }
7027 *pBytesRead += 23;
7028
7029 /*
7030 It's not actually used, but set the capture pattern to 'OggS' for completeness. Not doing this will cause static analysers to complain about
7031 us trying to access uninitialized data. We could alternatively just comment out this member of the drflac_ogg_page_header structure, but I
7032 like to have it map to the structure of the underlying data.
7033 */
7034 pHeader->capturePattern[0] = 'O';
7035 pHeader->capturePattern[1] = 'g';
7036 pHeader->capturePattern[2] = 'g';
7037 pHeader->capturePattern[3] = 'S';
7038
7039 pHeader->structureVersion = data[0];
7040 pHeader->headerType = data[1];
7041 DRFLAC_COPY_MEMORY(&pHeader->granulePosition, &data[ 2], 8);
7042 DRFLAC_COPY_MEMORY(&pHeader->serialNumber, &data[10], 4);
7043 DRFLAC_COPY_MEMORY(&pHeader->sequenceNumber, &data[14], 4);
7044 DRFLAC_COPY_MEMORY(&pHeader->checksum, &data[18], 4);
7045 pHeader->segmentCount = data[22];
7046
7047 /* Calculate the CRC. Note that for the calculation the checksum part of the page needs to be set to 0. */
7048 data[18] = 0;
7049 data[19] = 0;
7050 data[20] = 0;
7051 data[21] = 0;
7052
7053 for (i = 0; i < 23; ++i) {
7054 *pCRC32 = drflac_crc32_byte(*pCRC32, data[i]);
7055 }
7056
7057
7058 if (onRead(pUserData, pHeader->segmentTable, pHeader->segmentCount) != pHeader->segmentCount) {
7059 return DRFLAC_AT_END;
7060 }
7061 *pBytesRead += pHeader->segmentCount;
7062
7063 for (i = 0; i < pHeader->segmentCount; ++i) {
7064 *pCRC32 = drflac_crc32_byte(*pCRC32, pHeader->segmentTable[i]);
7065 }
7066
7067 return DRFLAC_SUCCESS;
7068 }
7069
7070 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)
7071 {
7072 drflac_uint8 id[4];
7073
7074 *pBytesRead = 0;
7075
7076 if (onRead(pUserData, id, 4) != 4) {
7077 return DRFLAC_AT_END;
7078 }
7079 *pBytesRead += 4;
7080
7081 /* We need to read byte-by-byte until we find the OggS capture pattern. */
7082 for (;;) {
7083 if (drflac_ogg__is_capture_pattern(id)) {
7084 drflac_result result;
7085
7086 *pCRC32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
7087
7088 result = drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32);
7089 if (result == DRFLAC_SUCCESS) {
7090 return DRFLAC_SUCCESS;
7091 } else {
7092 if (result == DRFLAC_CRC_MISMATCH) {
7093 continue;
7094 } else {
7095 return result;
7096 }
7097 }
7098 } else {
7099 /* The first 4 bytes did not equal the capture pattern. Read the next byte and try again. */
7100 id[0] = id[1];
7101 id[1] = id[2];
7102 id[2] = id[3];
7103 if (onRead(pUserData, &id[3], 1) != 1) {
7104 return DRFLAC_AT_END;
7105 }
7106 *pBytesRead += 1;
7107 }
7108 }
7109 }
7110
7111
7112 /*
7113 The main part of the Ogg encapsulation is the conversion from the physical Ogg bitstream to the native FLAC bitstream. It works
7114 in three general stages: Ogg Physical Bitstream -> Ogg/FLAC Logical Bitstream -> FLAC Native Bitstream. dr_flac is designed
7115 in such a way that the core sections assume everything is delivered in native format. Therefore, for each encapsulation type
7116 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
7117 the physical Ogg bitstream are converted and delivered in native FLAC format.
7118 */
7119 typedef struct
7120 {
7121 drflac_read_proc onRead; /* The original onRead callback from drflac_open() and family. */
7122 drflac_seek_proc onSeek; /* The original onSeek callback from drflac_open() and family. */
7123 void* pUserData; /* The user data passed on onRead and onSeek. This is the user data that was passed on drflac_open() and family. */
7124 drflac_uint64 currentBytePos; /* The position of the byte we are sitting on in the physical byte stream. Used for efficient seeking. */
7125 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. */
7126 drflac_uint32 serialNumber; /* The serial number of the FLAC audio pages. This is determined by the initial header page that was read during initialization. */
7127 drflac_ogg_page_header bosPageHeader; /* Used for seeking. */
7128 drflac_ogg_page_header currentPageHeader;
7129 drflac_uint32 bytesRemainingInPage;
7130 drflac_uint32 pageDataSize;
7131 drflac_uint8 pageData[DRFLAC_OGG_MAX_PAGE_SIZE];
7132 } drflac_oggbs; /* oggbs = Ogg Bitstream */
7133
7134 static size_t drflac_oggbs__read_physical(drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead)
7135 {
7136 size_t bytesActuallyRead = oggbs->onRead(oggbs->pUserData, bufferOut, bytesToRead);
7137 oggbs->currentBytePos += bytesActuallyRead;
7138
7139 return bytesActuallyRead;
7140 }
7141
7142 static drflac_bool32 drflac_oggbs__seek_physical(drflac_oggbs* oggbs, drflac_uint64 offset, drflac_seek_origin origin)
7143 {
7144 if (origin == drflac_seek_origin_start) {
7145 if (offset <= 0x7FFFFFFF) {
7146 if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_start)) {
7147 return DRFLAC_FALSE;
7148 }
7149 oggbs->currentBytePos = offset;
7150
7151 return DRFLAC_TRUE;
7152 } else {
7153 if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start)) {
7154 return DRFLAC_FALSE;
7155 }
7156 oggbs->currentBytePos = offset;
7157
7158 return drflac_oggbs__seek_physical(oggbs, offset - 0x7FFFFFFF, drflac_seek_origin_current);
7159 }
7160 } else {
7161 while (offset > 0x7FFFFFFF) {
7162 if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current)) {
7163 return DRFLAC_FALSE;
7164 }
7165 oggbs->currentBytePos += 0x7FFFFFFF;
7166 offset -= 0x7FFFFFFF;
7167 }
7168
7169 if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_current)) { /* <-- Safe cast thanks to the loop above. */
7170 return DRFLAC_FALSE;
7171 }
7172 oggbs->currentBytePos += offset;
7173
7174 return DRFLAC_TRUE;
7175 }
7176 }
7177
7178 static drflac_bool32 drflac_oggbs__goto_next_page(drflac_oggbs* oggbs, drflac_ogg_crc_mismatch_recovery recoveryMethod)
7179 {
7180 drflac_ogg_page_header header;
7181 for (;;) {
7182 drflac_uint32 crc32 = 0;
7183 drflac_uint32 bytesRead;
7184 drflac_uint32 pageBodySize;
7185 #ifndef DR_FLAC_NO_CRC
7186 drflac_uint32 actualCRC32;
7187 #endif
7188
7189 if (drflac_ogg__read_page_header(oggbs->onRead, oggbs->pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
7190 return DRFLAC_FALSE;
7191 }
7192 oggbs->currentBytePos += bytesRead;
7193
7194 pageBodySize = drflac_ogg__get_page_body_size(&header);
7195 if (pageBodySize > DRFLAC_OGG_MAX_PAGE_SIZE) {
7196 continue; /* Invalid page size. Assume it's corrupted and just move to the next page. */
7197 }
7198
7199 if (header.serialNumber != oggbs->serialNumber) {
7200 /* It's not a FLAC page. Skip it. */
7201 if (pageBodySize > 0 && !drflac_oggbs__seek_physical(oggbs, pageBodySize, drflac_seek_origin_current)) {
7202 return DRFLAC_FALSE;
7203 }
7204 continue;
7205 }
7206
7207
7208 /* 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. */
7209 if (drflac_oggbs__read_physical(oggbs, oggbs->pageData, pageBodySize) != pageBodySize) {
7210 return DRFLAC_FALSE;
7211 }
7212 oggbs->pageDataSize = pageBodySize;
7213
7214 #ifndef DR_FLAC_NO_CRC
7215 actualCRC32 = drflac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize);
7216 if (actualCRC32 != header.checksum) {
7217 if (recoveryMethod == drflac_ogg_recover_on_crc_mismatch) {
7218 continue; /* CRC mismatch. Skip this page. */
7219 } else {
7220 /*
7221 Even though we are failing on a CRC mismatch, we still want our stream to be in a good state. Therefore we
7222 go to the next valid page to ensure we're in a good state, but return false to let the caller know that the
7223 seek did not fully complete.
7224 */
7225 drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch);
7226 return DRFLAC_FALSE;
7227 }
7228 }
7229 #else
7230 (void)recoveryMethod; /* <-- Silence a warning. */
7231 #endif
7232
7233 oggbs->currentPageHeader = header;
7234 oggbs->bytesRemainingInPage = pageBodySize;
7235 return DRFLAC_TRUE;
7236 }
7237 }
7238
7239 /* Function below is unused at the moment, but I might be re-adding it later. */
7240 #if 0
7241 static drflac_uint8 drflac_oggbs__get_current_segment_index(drflac_oggbs* oggbs, drflac_uint8* pBytesRemainingInSeg)
7242 {
7243 drflac_uint32 bytesConsumedInPage = drflac_ogg__get_page_body_size(&oggbs->currentPageHeader) - oggbs->bytesRemainingInPage;
7244 drflac_uint8 iSeg = 0;
7245 drflac_uint32 iByte = 0;
7246 while (iByte < bytesConsumedInPage) {
7247 drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
7248 if (iByte + segmentSize > bytesConsumedInPage) {
7249 break;
7250 } else {
7251 iSeg += 1;
7252 iByte += segmentSize;
7253 }
7254 }
7255
7256 *pBytesRemainingInSeg = oggbs->currentPageHeader.segmentTable[iSeg] - (drflac_uint8)(bytesConsumedInPage - iByte);
7257 return iSeg;
7258 }
7259
7260 static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs)
7261 {
7262 /* 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. */
7263 for (;;) {
7264 drflac_bool32 atEndOfPage = DRFLAC_FALSE;
7265
7266 drflac_uint8 bytesRemainingInSeg;
7267 drflac_uint8 iFirstSeg = drflac_oggbs__get_current_segment_index(oggbs, &bytesRemainingInSeg);
7268
7269 drflac_uint32 bytesToEndOfPacketOrPage = bytesRemainingInSeg;
7270 for (drflac_uint8 iSeg = iFirstSeg; iSeg < oggbs->currentPageHeader.segmentCount; ++iSeg) {
7271 drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
7272 if (segmentSize < 255) {
7273 if (iSeg == oggbs->currentPageHeader.segmentCount-1) {
7274 atEndOfPage = DRFLAC_TRUE;
7275 }
7276
7277 break;
7278 }
7279
7280 bytesToEndOfPacketOrPage += segmentSize;
7281 }
7282
7283 /*
7284 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
7285 want to load the next page and keep searching for the end of the packet.
7286 */
7287 drflac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, drflac_seek_origin_current);
7288 oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage;
7289
7290 if (atEndOfPage) {
7291 /*
7292 We're potentially at the next packet, but we need to check the next page first to be sure because the packet may
7293 straddle pages.
7294 */
7295 if (!drflac_oggbs__goto_next_page(oggbs)) {
7296 return DRFLAC_FALSE;
7297 }
7298
7299 /* If it's a fresh packet it most likely means we're at the next packet. */
7300 if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
7301 return DRFLAC_TRUE;
7302 }
7303 } else {
7304 /* We're at the next packet. */
7305 return DRFLAC_TRUE;
7306 }
7307 }
7308 }
7309
7310 static drflac_bool32 drflac_oggbs__seek_to_next_frame(drflac_oggbs* oggbs)
7311 {
7312 /* The bitstream should be sitting on the first byte just after the header of the frame. */
7313
7314 /* What we're actually doing here is seeking to the start of the next packet. */
7315 return drflac_oggbs__seek_to_next_packet(oggbs);
7316 }
7317 #endif
7318
7319 static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead)
7320 {
7321 drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
7322 drflac_uint8* pRunningBufferOut = (drflac_uint8*)bufferOut;
7323 size_t bytesRead = 0;
7324
7325 DRFLAC_ASSERT(oggbs != NULL);
7326 DRFLAC_ASSERT(pRunningBufferOut != NULL);
7327
7328 /* Reading is done page-by-page. If we've run out of bytes in the page we need to move to the next one. */
7329 while (bytesRead < bytesToRead) {
7330 size_t bytesRemainingToRead = bytesToRead - bytesRead;
7331
7332 if (oggbs->bytesRemainingInPage >= bytesRemainingToRead) {
7333 DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), bytesRemainingToRead);
7334 bytesRead += bytesRemainingToRead;
7335 oggbs->bytesRemainingInPage -= (drflac_uint32)bytesRemainingToRead;
7336 break;
7337 }
7338
7339 /* If we get here it means some of the requested data is contained in the next pages. */
7340 if (oggbs->bytesRemainingInPage > 0) {
7341 DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage);
7342 bytesRead += oggbs->bytesRemainingInPage;
7343 pRunningBufferOut += oggbs->bytesRemainingInPage;
7344 oggbs->bytesRemainingInPage = 0;
7345 }
7346
7347 DRFLAC_ASSERT(bytesRemainingToRead > 0);
7348 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
7349 break; /* Failed to go to the next page. Might have simply hit the end of the stream. */
7350 }
7351 }
7352
7353 return bytesRead;
7354 }
7355
7356 static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_seek_origin origin)
7357 {
7358 drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
7359 int bytesSeeked = 0;
7360
7361 DRFLAC_ASSERT(oggbs != NULL);
7362 DRFLAC_ASSERT(offset >= 0); /* <-- Never seek backwards. */
7363
7364 /* Seeking is always forward which makes things a lot simpler. */
7365 if (origin == drflac_seek_origin_start) {
7366 if (!drflac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, drflac_seek_origin_start)) {
7367 return DRFLAC_FALSE;
7368 }
7369
7370 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
7371 return DRFLAC_FALSE;
7372 }
7373
7374 return drflac__on_seek_ogg(pUserData, offset, drflac_seek_origin_current);
7375 }
7376
7377 DRFLAC_ASSERT(origin == drflac_seek_origin_current);
7378
7379 while (bytesSeeked < offset) {
7380 int bytesRemainingToSeek = offset - bytesSeeked;
7381 DRFLAC_ASSERT(bytesRemainingToSeek >= 0);
7382
7383 if (oggbs->bytesRemainingInPage >= (size_t)bytesRemainingToSeek) {
7384 bytesSeeked += bytesRemainingToSeek;
7385 (void)bytesSeeked; /* <-- Silence a dead store warning emitted by Clang Static Analyzer. */
7386 oggbs->bytesRemainingInPage -= bytesRemainingToSeek;
7387 break;
7388 }
7389
7390 /* If we get here it means some of the requested data is contained in the next pages. */
7391 if (oggbs->bytesRemainingInPage > 0) {
7392 bytesSeeked += (int)oggbs->bytesRemainingInPage;
7393 oggbs->bytesRemainingInPage = 0;
7394 }
7395
7396 DRFLAC_ASSERT(bytesRemainingToSeek > 0);
7397 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
7398 /* Failed to go to the next page. We either hit the end of the stream or had a CRC mismatch. */
7399 return DRFLAC_FALSE;
7400 }
7401 }
7402
7403 return DRFLAC_TRUE;
7404 }
7405
7406
7407 static drflac_bool32 drflac_ogg__seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
7408 {
7409 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
7410 drflac_uint64 originalBytePos;
7411 drflac_uint64 runningGranulePosition;
7412 drflac_uint64 runningFrameBytePos;
7413 drflac_uint64 runningPCMFrameCount;
7414
7415 DRFLAC_ASSERT(oggbs != NULL);
7416
7417 originalBytePos = oggbs->currentBytePos; /* For recovery. Points to the OggS identifier. */
7418
7419 /* First seek to the first frame. */
7420 if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes)) {
7421 return DRFLAC_FALSE;
7422 }
7423 oggbs->bytesRemainingInPage = 0;
7424
7425 runningGranulePosition = 0;
7426 for (;;) {
7427 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
7428 drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
7429 return DRFLAC_FALSE; /* Never did find that sample... */
7430 }
7431
7432 runningFrameBytePos = oggbs->currentBytePos - drflac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize;
7433 if (oggbs->currentPageHeader.granulePosition >= pcmFrameIndex) {
7434 break; /* The sample is somewhere in the previous page. */
7435 }
7436
7437 /*
7438 At this point we know the sample is not in the previous page. It could possibly be in this page. For simplicity we
7439 disregard any pages that do not begin a fresh packet.
7440 */
7441 if ((oggbs->currentPageHeader.headerType & 0x01) == 0) { /* <-- Is it a fresh page? */
7442 if (oggbs->currentPageHeader.segmentTable[0] >= 2) {
7443 drflac_uint8 firstBytesInPage[2];
7444 firstBytesInPage[0] = oggbs->pageData[0];
7445 firstBytesInPage[1] = oggbs->pageData[1];
7446
7447 if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) { /* <-- Does the page begin with a frame's sync code? */
7448 runningGranulePosition = oggbs->currentPageHeader.granulePosition;
7449 }
7450
7451 continue;
7452 }
7453 }
7454 }
7455
7456 /*
7457 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
7458 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
7459 a new frame. This property means that after we've seeked to the page we can immediately start looping over frames until
7460 we find the one containing the target sample.
7461 */
7462 if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, drflac_seek_origin_start)) {
7463 return DRFLAC_FALSE;
7464 }
7465 if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
7466 return DRFLAC_FALSE;
7467 }
7468
7469 /*
7470 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
7471 looping over these frames until we find the one containing the sample we're after.
7472 */
7473 runningPCMFrameCount = runningGranulePosition;
7474 for (;;) {
7475 /*
7476 There are two ways to find the sample and seek past irrelevant frames:
7477 1) Use the native FLAC decoder.
7478 2) Use Ogg's framing system.
7479
7480 Both of these options have their own pros and cons. Using the native FLAC decoder is slower because it needs to
7481 do a full decode of the frame. Using Ogg's framing system is faster, but more complicated and involves some code
7482 duplication for the decoding of frame headers.
7483
7484 Another thing to consider is that using the Ogg framing system will perform direct seeking of the physical Ogg
7485 bitstream. This is important to consider because it means we cannot read data from the drflac_bs object using the
7486 standard drflac__*() APIs because that will read in extra data for its own internal caching which in turn breaks
7487 the positioning of the read pointer of the physical Ogg bitstream. Therefore, anything that would normally be read
7488 using the native FLAC decoding APIs, such as drflac__read_next_flac_frame_header(), need to be re-implemented so as to
7489 avoid the use of the drflac_bs object.
7490
7491 Considering these issues, I have decided to use the slower native FLAC decoding method for the following reasons:
7492 1) Seeking is already partially accelerated using Ogg's paging system in the code block above.
7493 2) Seeking in an Ogg encapsulated FLAC stream is probably quite uncommon.
7494 3) Simplicity.
7495 */
7496 drflac_uint64 firstPCMFrameInFLACFrame = 0;
7497 drflac_uint64 lastPCMFrameInFLACFrame = 0;
7498 drflac_uint64 pcmFrameCountInThisFrame;
7499
7500 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
7501 return DRFLAC_FALSE;
7502 }
7503
7504 drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
7505
7506 pcmFrameCountInThisFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
7507
7508 /* If we are seeking to the end of the file and we've just hit it, we're done. */
7509 if (pcmFrameIndex == pFlac->totalPCMFrameCount && (runningPCMFrameCount + pcmFrameCountInThisFrame) == pFlac->totalPCMFrameCount) {
7510 drflac_result result = drflac__decode_flac_frame(pFlac);
7511 if (result == DRFLAC_SUCCESS) {
7512 pFlac->currentPCMFrame = pcmFrameIndex;
7513 pFlac->currentFLACFrame.pcmFramesRemaining = 0;
7514 return DRFLAC_TRUE;
7515 } else {
7516 return DRFLAC_FALSE;
7517 }
7518 }
7519
7520 if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFrame)) {
7521 /*
7522 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
7523 it never existed and keep iterating.
7524 */
7525 drflac_result result = drflac__decode_flac_frame(pFlac);
7526 if (result == DRFLAC_SUCCESS) {
7527 /* The frame is valid. We just need to skip over some samples to ensure it's sample-exact. */
7528 drflac_uint64 pcmFramesToDecode = (size_t)(pcmFrameIndex - runningPCMFrameCount); /* <-- Safe cast because the maximum number of samples in a frame is 65535. */
7529 if (pcmFramesToDecode == 0) {
7530 return DRFLAC_TRUE;
7531 }
7532
7533 pFlac->currentPCMFrame = runningPCMFrameCount;
7534
7535 return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode; /* <-- If this fails, something bad has happened (it should never fail). */
7536 } else {
7537 if (result == DRFLAC_CRC_MISMATCH) {
7538 continue; /* CRC mismatch. Pretend this frame never existed. */
7539 } else {
7540 return DRFLAC_FALSE;
7541 }
7542 }
7543 } else {
7544 /*
7545 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
7546 frame never existed and leave the running sample count untouched.
7547 */
7548 drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
7549 if (result == DRFLAC_SUCCESS) {
7550 runningPCMFrameCount += pcmFrameCountInThisFrame;
7551 } else {
7552 if (result == DRFLAC_CRC_MISMATCH) {
7553 continue; /* CRC mismatch. Pretend this frame never existed. */
7554 } else {
7555 return DRFLAC_FALSE;
7556 }
7557 }
7558 }
7559 }
7560 }
7561
7562
7563
7564 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)
7565 {
7566 drflac_ogg_page_header header;
7567 drflac_uint32 crc32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
7568 drflac_uint32 bytesRead = 0;
7569
7570 /* Pre Condition: The bit stream should be sitting just past the 4-byte OggS capture pattern. */
7571 (void)relaxed;
7572
7573 pInit->container = drflac_container_ogg;
7574 pInit->oggFirstBytePos = 0;
7575
7576 /*
7577 We'll get here if the first 4 bytes of the stream were the OggS capture pattern, however it doesn't necessarily mean the
7578 stream includes FLAC encoded audio. To check for this we need to scan the beginning-of-stream page markers and check if
7579 any match the FLAC specification. Important to keep in mind that the stream may be multiplexed.
7580 */
7581 if (drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
7582 return DRFLAC_FALSE;
7583 }
7584 pInit->runningFilePos += bytesRead;
7585
7586 for (;;) {
7587 int pageBodySize;
7588
7589 /* Break if we're past the beginning of stream page. */
7590 if ((header.headerType & 0x02) == 0) {
7591 return DRFLAC_FALSE;
7592 }
7593
7594 /* Check if it's a FLAC header. */
7595 pageBodySize = drflac_ogg__get_page_body_size(&header);
7596 if (pageBodySize == 51) { /* 51 = the lacing value of the FLAC header packet. */
7597 /* It could be a FLAC page... */
7598 drflac_uint32 bytesRemainingInPage = pageBodySize;
7599 drflac_uint8 packetType;
7600
7601 if (onRead(pUserData, &packetType, 1) != 1) {
7602 return DRFLAC_FALSE;
7603 }
7604
7605 bytesRemainingInPage -= 1;
7606 if (packetType == 0x7F) {
7607 /* Increasingly more likely to be a FLAC page... */
7608 drflac_uint8 sig[4];
7609 if (onRead(pUserData, sig, 4) != 4) {
7610 return DRFLAC_FALSE;
7611 }
7612
7613 bytesRemainingInPage -= 4;
7614 if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') {
7615 /* Almost certainly a FLAC page... */
7616 drflac_uint8 mappingVersion[2];
7617 if (onRead(pUserData, mappingVersion, 2) != 2) {
7618 return DRFLAC_FALSE;
7619 }
7620
7621 if (mappingVersion[0] != 1) {
7622 return DRFLAC_FALSE; /* Only supporting version 1.x of the Ogg mapping. */
7623 }
7624
7625 /*
7626 The next 2 bytes are the non-audio packets, not including this one. We don't care about this because we're going to
7627 be handling it in a generic way based on the serial number and packet types.
7628 */
7629 if (!onSeek(pUserData, 2, drflac_seek_origin_current)) {
7630 return DRFLAC_FALSE;
7631 }
7632
7633 /* Expecting the native FLAC signature "fLaC". */
7634 if (onRead(pUserData, sig, 4) != 4) {
7635 return DRFLAC_FALSE;
7636 }
7637
7638 if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C') {
7639 /* The remaining data in the page should be the STREAMINFO block. */
7640 drflac_streaminfo streaminfo;
7641 drflac_uint8 isLastBlock;
7642 drflac_uint8 blockType;
7643 drflac_uint32 blockSize;
7644 if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
7645 return DRFLAC_FALSE;
7646 }
7647
7648 if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
7649 return DRFLAC_FALSE; /* Invalid block type. First block must be the STREAMINFO block. */
7650 }
7651
7652 if (drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
7653 /* Success! */
7654 pInit->hasStreamInfoBlock = DRFLAC_TRUE;
7655 pInit->sampleRate = streaminfo.sampleRate;
7656 pInit->channels = streaminfo.channels;
7657 pInit->bitsPerSample = streaminfo.bitsPerSample;
7658 pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
7659 pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames;
7660 pInit->hasMetadataBlocks = !isLastBlock;
7661
7662 if (onMeta) {
7663 drflac_metadata metadata;
7664 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
7665 metadata.pRawData = NULL;
7666 metadata.rawDataSize = 0;
7667 metadata.data.streaminfo = streaminfo;
7668 onMeta(pUserDataMD, &metadata);
7669 }
7670
7671 pInit->runningFilePos += pageBodySize;
7672 pInit->oggFirstBytePos = pInit->runningFilePos - 79; /* Subtracting 79 will place us right on top of the "OggS" identifier of the FLAC bos page. */
7673 pInit->oggSerial = header.serialNumber;
7674 pInit->oggBosHeader = header;
7675 break;
7676 } else {
7677 /* Failed to read STREAMINFO block. Aww, so close... */
7678 return DRFLAC_FALSE;
7679 }
7680 } else {
7681 /* Invalid file. */
7682 return DRFLAC_FALSE;
7683 }
7684 } else {
7685 /* Not a FLAC header. Skip it. */
7686 if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current)) {
7687 return DRFLAC_FALSE;
7688 }
7689 }
7690 } else {
7691 /* Not a FLAC header. Seek past the entire page and move on to the next. */
7692 if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current)) {
7693 return DRFLAC_FALSE;
7694 }
7695 }
7696 } else {
7697 if (!onSeek(pUserData, pageBodySize, drflac_seek_origin_current)) {
7698 return DRFLAC_FALSE;
7699 }
7700 }
7701
7702 pInit->runningFilePos += pageBodySize;
7703
7704
7705 /* Read the header of the next page. */
7706 if (drflac_ogg__read_page_header(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
7707 return DRFLAC_FALSE;
7708 }
7709 pInit->runningFilePos += bytesRead;
7710 }
7711
7712 /*
7713 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
7714 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
7715 Ogg bistream object.
7716 */
7717 pInit->hasMetadataBlocks = DRFLAC_TRUE; /* <-- Always have at least VORBIS_COMMENT metadata block. */
7718 return DRFLAC_TRUE;
7719 }
7720 #endif
7721
7722 static drflac_bool32 drflac__init_private(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD)
7723 {
7724 drflac_bool32 relaxed;
7725 drflac_uint8 id[4];
7726
7727 if (pInit == NULL || onRead == NULL || onSeek == NULL) {
7728 return DRFLAC_FALSE;
7729 }
7730
7731 DRFLAC_ZERO_MEMORY(pInit, sizeof(*pInit));
7732 pInit->onRead = onRead;
7733 pInit->onSeek = onSeek;
7734 pInit->onMeta = onMeta;
7735 pInit->container = container;
7736 pInit->pUserData = pUserData;
7737 pInit->pUserDataMD = pUserDataMD;
7738
7739 pInit->bs.onRead = onRead;
7740 pInit->bs.onSeek = onSeek;
7741 pInit->bs.pUserData = pUserData;
7742 drflac__reset_cache(&pInit->bs);
7743
7744
7745 /* If the container is explicitly defined then we can try opening in relaxed mode. */
7746 relaxed = container != drflac_container_unknown;
7747
7748 /* Skip over any ID3 tags. */
7749 for (;;) {
7750 if (onRead(pUserData, id, 4) != 4) {
7751 return DRFLAC_FALSE; /* Ran out of data. */
7752 }
7753 pInit->runningFilePos += 4;
7754
7755 if (id[0] == 'I' && id[1] == 'D' && id[2] == '3') {
7756 drflac_uint8 header[6];
7757 drflac_uint8 flags;
7758 drflac_uint32 headerSize;
7759
7760 if (onRead(pUserData, header, 6) != 6) {
7761 return DRFLAC_FALSE; /* Ran out of data. */
7762 }
7763 pInit->runningFilePos += 6;
7764
7765 flags = header[1];
7766
7767 DRFLAC_COPY_MEMORY(&headerSize, header+2, 4);
7768 headerSize = drflac__unsynchsafe_32(drflac__be2host_32(headerSize));
7769 if (flags & 0x10) {
7770 headerSize += 10;
7771 }
7772
7773 if (!onSeek(pUserData, headerSize, drflac_seek_origin_current)) {
7774 return DRFLAC_FALSE; /* Failed to seek past the tag. */
7775 }
7776 pInit->runningFilePos += headerSize;
7777 } else {
7778 break;
7779 }
7780 }
7781
7782 if (id[0] == 'f' && id[1] == 'L' && id[2] == 'a' && id[3] == 'C') {
7783 return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
7784 }
7785 #ifndef DR_FLAC_NO_OGG
7786 if (id[0] == 'O' && id[1] == 'g' && id[2] == 'g' && id[3] == 'S') {
7787 return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
7788 }
7789 #endif
7790
7791 /* If we get here it means we likely don't have a header. Try opening in relaxed mode, if applicable. */
7792 if (relaxed) {
7793 if (container == drflac_container_native) {
7794 return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
7795 }
7796 #ifndef DR_FLAC_NO_OGG
7797 if (container == drflac_container_ogg) {
7798 return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
7799 }
7800 #endif
7801 }
7802
7803 /* Unsupported container. */
7804 return DRFLAC_FALSE;
7805 }
7806
7807 static void drflac__init_from_info(drflac* pFlac, const drflac_init_info* pInit)
7808 {
7809 DRFLAC_ASSERT(pFlac != NULL);
7810 DRFLAC_ASSERT(pInit != NULL);
7811
7812 DRFLAC_ZERO_MEMORY(pFlac, sizeof(*pFlac));
7813 pFlac->bs = pInit->bs;
7814 pFlac->onMeta = pInit->onMeta;
7815 pFlac->pUserDataMD = pInit->pUserDataMD;
7816 pFlac->maxBlockSizeInPCMFrames = pInit->maxBlockSizeInPCMFrames;
7817 pFlac->sampleRate = pInit->sampleRate;
7818 pFlac->channels = (drflac_uint8)pInit->channels;
7819 pFlac->bitsPerSample = (drflac_uint8)pInit->bitsPerSample;
7820 pFlac->totalPCMFrameCount = pInit->totalPCMFrameCount;
7821 pFlac->container = pInit->container;
7822 }
7823
7824
7825 static drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD, const drflac_allocation_callbacks* pAllocationCallbacks)
7826 {
7827 drflac_init_info init;
7828 drflac_uint32 allocationSize;
7829 drflac_uint32 wholeSIMDVectorCountPerChannel;
7830 drflac_uint32 decodedSamplesAllocationSize;
7831 #ifndef DR_FLAC_NO_OGG
7832 drflac_oggbs oggbs;
7833 #endif
7834 drflac_uint64 firstFramePos;
7835 drflac_uint64 seektablePos;
7836 drflac_uint32 seektableSize;
7837 drflac_allocation_callbacks allocationCallbacks;
7838 drflac* pFlac;
7839
7840 /* CPU support first. */
7841 drflac__init_cpu_caps();
7842
7843 if (!drflac__init_private(&init, onRead, onSeek, onMeta, container, pUserData, pUserDataMD)) {
7844 return NULL;
7845 }
7846
7847 if (pAllocationCallbacks != NULL) {
7848 allocationCallbacks = *pAllocationCallbacks;
7849 if (allocationCallbacks.onFree == NULL || (allocationCallbacks.onMalloc == NULL && allocationCallbacks.onRealloc == NULL)) {
7850 return NULL; /* Invalid allocation callbacks. */
7851 }
7852 } else {
7853 allocationCallbacks.pUserData = NULL;
7854 allocationCallbacks.onMalloc = drflac__malloc_default;
7855 allocationCallbacks.onRealloc = drflac__realloc_default;
7856 allocationCallbacks.onFree = drflac__free_default;
7857 }
7858
7859
7860 /*
7861 The size of the allocation for the drflac object needs to be large enough to fit the following:
7862 1) The main members of the drflac structure
7863 2) A block of memory large enough to store the decoded samples of the largest frame in the stream
7864 3) If the container is Ogg, a drflac_oggbs object
7865
7866 The complicated part of the allocation is making sure there's enough room the decoded samples, taking into consideration
7867 the different SIMD instruction sets.
7868 */
7869 allocationSize = sizeof(drflac);
7870
7871 /*
7872 The allocation size for decoded frames depends on the number of 32-bit integers that fit inside the largest SIMD vector
7873 we are supporting.
7874 */
7875 if ((init.maxBlockSizeInPCMFrames % (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) == 0) {
7876 wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32)));
7877 } else {
7878 wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) + 1;
7879 }
7880
7881 decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * DRFLAC_MAX_SIMD_VECTOR_SIZE * init.channels;
7882
7883 allocationSize += decodedSamplesAllocationSize;
7884 allocationSize += DRFLAC_MAX_SIMD_VECTOR_SIZE; /* Allocate extra bytes to ensure we have enough for alignment. */
7885
7886 #ifndef DR_FLAC_NO_OGG
7887 /* There's additional data required for Ogg streams. */
7888 if (init.container == drflac_container_ogg) {
7889 allocationSize += sizeof(drflac_oggbs);
7890 }
7891
7892 DRFLAC_ZERO_MEMORY(&oggbs, sizeof(oggbs));
7893 if (init.container == drflac_container_ogg) {
7894 oggbs.onRead = onRead;
7895 oggbs.onSeek = onSeek;
7896 oggbs.pUserData = pUserData;
7897 oggbs.currentBytePos = init.oggFirstBytePos;
7898 oggbs.firstBytePos = init.oggFirstBytePos;
7899 oggbs.serialNumber = init.oggSerial;
7900 oggbs.bosPageHeader = init.oggBosHeader;
7901 oggbs.bytesRemainingInPage = 0;
7902 }
7903 #endif
7904
7905 /*
7906 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
7907 consist of only a single heap allocation. To this, the size of the seek table needs to be known, which we determine when reading
7908 and decoding the metadata.
7909 */
7910 firstFramePos = 42; /* <-- We know we are at byte 42 at this point. */
7911 seektablePos = 0;
7912 seektableSize = 0;
7913 if (init.hasMetadataBlocks) {
7914 drflac_read_proc onReadOverride = onRead;
7915 drflac_seek_proc onSeekOverride = onSeek;
7916 void* pUserDataOverride = pUserData;
7917
7918 #ifndef DR_FLAC_NO_OGG
7919 if (init.container == drflac_container_ogg) {
7920 onReadOverride = drflac__on_read_ogg;
7921 onSeekOverride = drflac__on_seek_ogg;
7922 pUserDataOverride = (void*)&oggbs;
7923 }
7924 #endif
7925
7926 if (!drflac__read_and_decode_metadata(onReadOverride, onSeekOverride, onMeta, pUserDataOverride, pUserDataMD, &firstFramePos, &seektablePos, &seektableSize, &allocationCallbacks)) {
7927 return NULL;
7928 }
7929
7930 allocationSize += seektableSize;
7931 }
7932
7933
7934 pFlac = (drflac*)drflac__malloc_from_callbacks(allocationSize, &allocationCallbacks);
7935 if (pFlac == NULL) {
7936 return NULL;
7937 }
7938
7939 drflac__init_from_info(pFlac, &init);
7940 pFlac->allocationCallbacks = allocationCallbacks;
7941 pFlac->pDecodedSamples = (drflac_int32*)drflac_align((size_t)pFlac->pExtraData, DRFLAC_MAX_SIMD_VECTOR_SIZE);
7942
7943 #ifndef DR_FLAC_NO_OGG
7944 if (init.container == drflac_container_ogg) {
7945 drflac_oggbs* pInternalOggbs = (drflac_oggbs*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize + seektableSize);
7946 DRFLAC_COPY_MEMORY(pInternalOggbs, &oggbs, sizeof(oggbs));
7947
7948 /* The Ogg bistream needs to be layered on top of the original bitstream. */
7949 pFlac->bs.onRead = drflac__on_read_ogg;
7950 pFlac->bs.onSeek = drflac__on_seek_ogg;
7951 pFlac->bs.pUserData = (void*)pInternalOggbs;
7952 pFlac->_oggbs = (void*)pInternalOggbs;
7953 }
7954 #endif
7955
7956 pFlac->firstFLACFramePosInBytes = firstFramePos;
7957
7958 /* 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. */
7959 #ifndef DR_FLAC_NO_OGG
7960 if (init.container == drflac_container_ogg)
7961 {
7962 pFlac->pSeekpoints = NULL;
7963 pFlac->seekpointCount = 0;
7964 }
7965 else
7966 #endif
7967 {
7968 /* If we have a seektable we need to load it now, making sure we move back to where we were previously. */
7969 if (seektablePos != 0) {
7970 pFlac->seekpointCount = seektableSize / sizeof(*pFlac->pSeekpoints);
7971 pFlac->pSeekpoints = (drflac_seekpoint*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize);
7972
7973 DRFLAC_ASSERT(pFlac->bs.onSeek != NULL);
7974 DRFLAC_ASSERT(pFlac->bs.onRead != NULL);
7975
7976 /* Seek to the seektable, then just read directly into our seektable buffer. */
7977 if (pFlac->bs.onSeek(pFlac->bs.pUserData, (int)seektablePos, drflac_seek_origin_start)) {
7978 if (pFlac->bs.onRead(pFlac->bs.pUserData, pFlac->pSeekpoints, seektableSize) == seektableSize) {
7979 /* Endian swap. */
7980 drflac_uint32 iSeekpoint;
7981 for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
7982 pFlac->pSeekpoints[iSeekpoint].firstPCMFrame = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].firstPCMFrame);
7983 pFlac->pSeekpoints[iSeekpoint].flacFrameOffset = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].flacFrameOffset);
7984 pFlac->pSeekpoints[iSeekpoint].pcmFrameCount = drflac__be2host_16(pFlac->pSeekpoints[iSeekpoint].pcmFrameCount);
7985 }
7986 } else {
7987 /* Failed to read the seektable. Pretend we don't have one. */
7988 pFlac->pSeekpoints = NULL;
7989 pFlac->seekpointCount = 0;
7990 }
7991
7992 /* We need to seek back to where we were. If this fails it's a critical error. */
7993 if (!pFlac->bs.onSeek(pFlac->bs.pUserData, (int)pFlac->firstFLACFramePosInBytes, drflac_seek_origin_start)) {
7994 drflac__free_from_callbacks(pFlac, &allocationCallbacks);
7995 return NULL;
7996 }
7997 } else {
7998 /* Failed to seek to the seektable. Ominous sign, but for now we can just pretend we don't have one. */
7999 pFlac->pSeekpoints = NULL;
8000 pFlac->seekpointCount = 0;
8001 }
8002 }
8003 }
8004
8005
8006 /*
8007 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
8008 the first frame.
8009 */
8010 if (!init.hasStreamInfoBlock) {
8011 pFlac->currentFLACFrame.header = init.firstFrameHeader;
8012 for (;;) {
8013 drflac_result result = drflac__decode_flac_frame(pFlac);
8014 if (result == DRFLAC_SUCCESS) {
8015 break;
8016 } else {
8017 if (result == DRFLAC_CRC_MISMATCH) {
8018 if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
8019 drflac__free_from_callbacks(pFlac, &allocationCallbacks);
8020 return NULL;
8021 }
8022 continue;
8023 } else {
8024 drflac__free_from_callbacks(pFlac, &allocationCallbacks);
8025 return NULL;
8026 }
8027 }
8028 }
8029 }
8030
8031 return pFlac;
8032 }
8033
8034
8035
8036 #ifndef DR_FLAC_NO_STDIO
8037 #include <stdio.h>
8038 #include <wchar.h> /* For wcslen(), wcsrtombs() */
8039
8040 /* 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. */
8041 #include <errno.h>
8042 static drflac_result drflac_result_from_errno(int e)
8043 {
8044 switch (e)
8045 {
8046 case 0: return DRFLAC_SUCCESS;
8047 #ifdef EPERM
8048 case EPERM: return DRFLAC_INVALID_OPERATION;
8049 #endif
8050 #ifdef ENOENT
8051 case ENOENT: return DRFLAC_DOES_NOT_EXIST;
8052 #endif
8053 #ifdef ESRCH
8054 case ESRCH: return DRFLAC_DOES_NOT_EXIST;
8055 #endif
8056 #ifdef EINTR
8057 case EINTR: return DRFLAC_INTERRUPT;
8058 #endif
8059 #ifdef EIO
8060 case EIO: return DRFLAC_IO_ERROR;
8061 #endif
8062 #ifdef ENXIO
8063 case ENXIO: return DRFLAC_DOES_NOT_EXIST;
8064 #endif
8065 #ifdef E2BIG
8066 case E2BIG: return DRFLAC_INVALID_ARGS;
8067 #endif
8068 #ifdef ENOEXEC
8069 case ENOEXEC: return DRFLAC_INVALID_FILE;
8070 #endif
8071 #ifdef EBADF
8072 case EBADF: return DRFLAC_INVALID_FILE;
8073 #endif
8074 #ifdef ECHILD
8075 case ECHILD: return DRFLAC_ERROR;
8076 #endif
8077 #ifdef EAGAIN
8078 case EAGAIN: return DRFLAC_UNAVAILABLE;
8079 #endif
8080 #ifdef ENOMEM
8081 case ENOMEM: return DRFLAC_OUT_OF_MEMORY;
8082 #endif
8083 #ifdef EACCES
8084 case EACCES: return DRFLAC_ACCESS_DENIED;
8085 #endif
8086 #ifdef EFAULT
8087 case EFAULT: return DRFLAC_BAD_ADDRESS;
8088 #endif
8089 #ifdef ENOTBLK
8090 case ENOTBLK: return DRFLAC_ERROR;
8091 #endif
8092 #ifdef EBUSY
8093 case EBUSY: return DRFLAC_BUSY;
8094 #endif
8095 #ifdef EEXIST
8096 case EEXIST: return DRFLAC_ALREADY_EXISTS;
8097 #endif
8098 #ifdef EXDEV
8099 case EXDEV: return DRFLAC_ERROR;
8100 #endif
8101 #ifdef ENODEV
8102 case ENODEV: return DRFLAC_DOES_NOT_EXIST;
8103 #endif
8104 #ifdef ENOTDIR
8105 case ENOTDIR: return DRFLAC_NOT_DIRECTORY;
8106 #endif
8107 #ifdef EISDIR
8108 case EISDIR: return DRFLAC_IS_DIRECTORY;
8109 #endif
8110 #ifdef EINVAL
8111 case EINVAL: return DRFLAC_INVALID_ARGS;
8112 #endif
8113 #ifdef ENFILE
8114 case ENFILE: return DRFLAC_TOO_MANY_OPEN_FILES;
8115 #endif
8116 #ifdef EMFILE
8117 case EMFILE: return DRFLAC_TOO_MANY_OPEN_FILES;
8118 #endif
8119 #ifdef ENOTTY
8120 case ENOTTY: return DRFLAC_INVALID_OPERATION;
8121 #endif
8122 #ifdef ETXTBSY
8123 case ETXTBSY: return DRFLAC_BUSY;
8124 #endif
8125 #ifdef EFBIG
8126 case EFBIG: return DRFLAC_TOO_BIG;
8127 #endif
8128 #ifdef ENOSPC
8129 case ENOSPC: return DRFLAC_NO_SPACE;
8130 #endif
8131 #ifdef ESPIPE
8132 case ESPIPE: return DRFLAC_BAD_SEEK;
8133 #endif
8134 #ifdef EROFS
8135 case EROFS: return DRFLAC_ACCESS_DENIED;
8136 #endif
8137 #ifdef EMLINK
8138 case EMLINK: return DRFLAC_TOO_MANY_LINKS;
8139 #endif
8140 #ifdef EPIPE
8141 case EPIPE: return DRFLAC_BAD_PIPE;
8142 #endif
8143 #ifdef EDOM
8144 case EDOM: return DRFLAC_OUT_OF_RANGE;
8145 #endif
8146 #ifdef ERANGE
8147 case ERANGE: return DRFLAC_OUT_OF_RANGE;
8148 #endif
8149 #ifdef EDEADLK
8150 case EDEADLK: return DRFLAC_DEADLOCK;
8151 #endif
8152 #ifdef ENAMETOOLONG
8153 case ENAMETOOLONG: return DRFLAC_PATH_TOO_LONG;
8154 #endif
8155 #ifdef ENOLCK
8156 case ENOLCK: return DRFLAC_ERROR;
8157 #endif
8158 #ifdef ENOSYS
8159 case ENOSYS: return DRFLAC_NOT_IMPLEMENTED;
8160 #endif
8161 #ifdef ENOTEMPTY
8162 case ENOTEMPTY: return DRFLAC_DIRECTORY_NOT_EMPTY;
8163 #endif
8164 #ifdef ELOOP
8165 case ELOOP: return DRFLAC_TOO_MANY_LINKS;
8166 #endif
8167 #ifdef ENOMSG
8168 case ENOMSG: return DRFLAC_NO_MESSAGE;
8169 #endif
8170 #ifdef EIDRM
8171 case EIDRM: return DRFLAC_ERROR;
8172 #endif
8173 #ifdef ECHRNG
8174 case ECHRNG: return DRFLAC_ERROR;
8175 #endif
8176 #ifdef EL2NSYNC
8177 case EL2NSYNC: return DRFLAC_ERROR;
8178 #endif
8179 #ifdef EL3HLT
8180 case EL3HLT: return DRFLAC_ERROR;
8181 #endif
8182 #ifdef EL3RST
8183 case EL3RST: return DRFLAC_ERROR;
8184 #endif
8185 #ifdef ELNRNG
8186 case ELNRNG: return DRFLAC_OUT_OF_RANGE;
8187 #endif
8188 #ifdef EUNATCH
8189 case EUNATCH: return DRFLAC_ERROR;
8190 #endif
8191 #ifdef ENOCSI
8192 case ENOCSI: return DRFLAC_ERROR;
8193 #endif
8194 #ifdef EL2HLT
8195 case EL2HLT: return DRFLAC_ERROR;
8196 #endif
8197 #ifdef EBADE
8198 case EBADE: return DRFLAC_ERROR;
8199 #endif
8200 #ifdef EBADR
8201 case EBADR: return DRFLAC_ERROR;
8202 #endif
8203 #ifdef EXFULL
8204 case EXFULL: return DRFLAC_ERROR;
8205 #endif
8206 #ifdef ENOANO
8207 case ENOANO: return DRFLAC_ERROR;
8208 #endif
8209 #ifdef EBADRQC
8210 case EBADRQC: return DRFLAC_ERROR;
8211 #endif
8212 #ifdef EBADSLT
8213 case EBADSLT: return DRFLAC_ERROR;
8214 #endif
8215 #ifdef EBFONT
8216 case EBFONT: return DRFLAC_INVALID_FILE;
8217 #endif
8218 #ifdef ENOSTR
8219 case ENOSTR: return DRFLAC_ERROR;
8220 #endif
8221 #ifdef ENODATA
8222 case ENODATA: return DRFLAC_NO_DATA_AVAILABLE;
8223 #endif
8224 #ifdef ETIME
8225 case ETIME: return DRFLAC_TIMEOUT;
8226 #endif
8227 #ifdef ENOSR
8228 case ENOSR: return DRFLAC_NO_DATA_AVAILABLE;
8229 #endif
8230 #ifdef ENONET
8231 case ENONET: return DRFLAC_NO_NETWORK;
8232 #endif
8233 #ifdef ENOPKG
8234 case ENOPKG: return DRFLAC_ERROR;
8235 #endif
8236 #ifdef EREMOTE
8237 case EREMOTE: return DRFLAC_ERROR;
8238 #endif
8239 #ifdef ENOLINK
8240 case ENOLINK: return DRFLAC_ERROR;
8241 #endif
8242 #ifdef EADV
8243 case EADV: return DRFLAC_ERROR;
8244 #endif
8245 #ifdef ESRMNT
8246 case ESRMNT: return DRFLAC_ERROR;
8247 #endif
8248 #ifdef ECOMM
8249 case ECOMM: return DRFLAC_ERROR;
8250 #endif
8251 #ifdef EPROTO
8252 case EPROTO: return DRFLAC_ERROR;
8253 #endif
8254 #ifdef EMULTIHOP
8255 case EMULTIHOP: return DRFLAC_ERROR;
8256 #endif
8257 #ifdef EDOTDOT
8258 case EDOTDOT: return DRFLAC_ERROR;
8259 #endif
8260 #ifdef EBADMSG
8261 case EBADMSG: return DRFLAC_BAD_MESSAGE;
8262 #endif
8263 #ifdef EOVERFLOW
8264 case EOVERFLOW: return DRFLAC_TOO_BIG;
8265 #endif
8266 #ifdef ENOTUNIQ
8267 case ENOTUNIQ: return DRFLAC_NOT_UNIQUE;
8268 #endif
8269 #ifdef EBADFD
8270 case EBADFD: return DRFLAC_ERROR;
8271 #endif
8272 #ifdef EREMCHG
8273 case EREMCHG: return DRFLAC_ERROR;
8274 #endif
8275 #ifdef ELIBACC
8276 case ELIBACC: return DRFLAC_ACCESS_DENIED;
8277 #endif
8278 #ifdef ELIBBAD
8279 case ELIBBAD: return DRFLAC_INVALID_FILE;
8280 #endif
8281 #ifdef ELIBSCN
8282 case ELIBSCN: return DRFLAC_INVALID_FILE;
8283 #endif
8284 #ifdef ELIBMAX
8285 case ELIBMAX: return DRFLAC_ERROR;
8286 #endif
8287 #ifdef ELIBEXEC
8288 case ELIBEXEC: return DRFLAC_ERROR;
8289 #endif
8290 #ifdef EILSEQ
8291 case EILSEQ: return DRFLAC_INVALID_DATA;
8292 #endif
8293 #ifdef ERESTART
8294 case ERESTART: return DRFLAC_ERROR;
8295 #endif
8296 #ifdef ESTRPIPE
8297 case ESTRPIPE: return DRFLAC_ERROR;
8298 #endif
8299 #ifdef EUSERS
8300 case EUSERS: return DRFLAC_ERROR;
8301 #endif
8302 #ifdef ENOTSOCK
8303 case ENOTSOCK: return DRFLAC_NOT_SOCKET;
8304 #endif
8305 #ifdef EDESTADDRREQ
8306 case EDESTADDRREQ: return DRFLAC_NO_ADDRESS;
8307 #endif
8308 #ifdef EMSGSIZE
8309 case EMSGSIZE: return DRFLAC_TOO_BIG;
8310 #endif
8311 #ifdef EPROTOTYPE
8312 case EPROTOTYPE: return DRFLAC_BAD_PROTOCOL;
8313 #endif
8314 #ifdef ENOPROTOOPT
8315 case ENOPROTOOPT: return DRFLAC_PROTOCOL_UNAVAILABLE;
8316 #endif
8317 #ifdef EPROTONOSUPPORT
8318 case EPROTONOSUPPORT: return DRFLAC_PROTOCOL_NOT_SUPPORTED;
8319 #endif
8320 #ifdef ESOCKTNOSUPPORT
8321 case ESOCKTNOSUPPORT: return DRFLAC_SOCKET_NOT_SUPPORTED;
8322 #endif
8323 #ifdef EOPNOTSUPP
8324 case EOPNOTSUPP: return DRFLAC_INVALID_OPERATION;
8325 #endif
8326 #ifdef EPFNOSUPPORT
8327 case EPFNOSUPPORT: return DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED;
8328 #endif
8329 #ifdef EAFNOSUPPORT
8330 case EAFNOSUPPORT: return DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED;
8331 #endif
8332 #ifdef EADDRINUSE
8333 case EADDRINUSE: return DRFLAC_ALREADY_IN_USE;
8334 #endif
8335 #ifdef EADDRNOTAVAIL
8336 case EADDRNOTAVAIL: return DRFLAC_ERROR;
8337 #endif
8338 #ifdef ENETDOWN
8339 case ENETDOWN: return DRFLAC_NO_NETWORK;
8340 #endif
8341 #ifdef ENETUNREACH
8342 case ENETUNREACH: return DRFLAC_NO_NETWORK;
8343 #endif
8344 #ifdef ENETRESET
8345 case ENETRESET: return DRFLAC_NO_NETWORK;
8346 #endif
8347 #ifdef ECONNABORTED
8348 case ECONNABORTED: return DRFLAC_NO_NETWORK;
8349 #endif
8350 #ifdef ECONNRESET
8351 case ECONNRESET: return DRFLAC_CONNECTION_RESET;
8352 #endif
8353 #ifdef ENOBUFS
8354 case ENOBUFS: return DRFLAC_NO_SPACE;
8355 #endif
8356 #ifdef EISCONN
8357 case EISCONN: return DRFLAC_ALREADY_CONNECTED;
8358 #endif
8359 #ifdef ENOTCONN
8360 case ENOTCONN: return DRFLAC_NOT_CONNECTED;
8361 #endif
8362 #ifdef ESHUTDOWN
8363 case ESHUTDOWN: return DRFLAC_ERROR;
8364 #endif
8365 #ifdef ETOOMANYREFS
8366 case ETOOMANYREFS: return DRFLAC_ERROR;
8367 #endif
8368 #ifdef ETIMEDOUT
8369 case ETIMEDOUT: return DRFLAC_TIMEOUT;
8370 #endif
8371 #ifdef ECONNREFUSED
8372 case ECONNREFUSED: return DRFLAC_CONNECTION_REFUSED;
8373 #endif
8374 #ifdef EHOSTDOWN
8375 case EHOSTDOWN: return DRFLAC_NO_HOST;
8376 #endif
8377 #ifdef EHOSTUNREACH
8378 case EHOSTUNREACH: return DRFLAC_NO_HOST;
8379 #endif
8380 #ifdef EALREADY
8381 case EALREADY: return DRFLAC_IN_PROGRESS;
8382 #endif
8383 #ifdef EINPROGRESS
8384 case EINPROGRESS: return DRFLAC_IN_PROGRESS;
8385 #endif
8386 #ifdef ESTALE
8387 case ESTALE: return DRFLAC_INVALID_FILE;
8388 #endif
8389 #ifdef EUCLEAN
8390 case EUCLEAN: return DRFLAC_ERROR;
8391 #endif
8392 #ifdef ENOTNAM
8393 case ENOTNAM: return DRFLAC_ERROR;
8394 #endif
8395 #ifdef ENAVAIL
8396 case ENAVAIL: return DRFLAC_ERROR;
8397 #endif
8398 #ifdef EISNAM
8399 case EISNAM: return DRFLAC_ERROR;
8400 #endif
8401 #ifdef EREMOTEIO
8402 case EREMOTEIO: return DRFLAC_IO_ERROR;
8403 #endif
8404 #ifdef EDQUOT
8405 case EDQUOT: return DRFLAC_NO_SPACE;
8406 #endif
8407 #ifdef ENOMEDIUM
8408 case ENOMEDIUM: return DRFLAC_DOES_NOT_EXIST;
8409 #endif
8410 #ifdef EMEDIUMTYPE
8411 case EMEDIUMTYPE: return DRFLAC_ERROR;
8412 #endif
8413 #ifdef ECANCELED
8414 case ECANCELED: return DRFLAC_CANCELLED;
8415 #endif
8416 #ifdef ENOKEY
8417 case ENOKEY: return DRFLAC_ERROR;
8418 #endif
8419 #ifdef EKEYEXPIRED
8420 case EKEYEXPIRED: return DRFLAC_ERROR;
8421 #endif
8422 #ifdef EKEYREVOKED
8423 case EKEYREVOKED: return DRFLAC_ERROR;
8424 #endif
8425 #ifdef EKEYREJECTED
8426 case EKEYREJECTED: return DRFLAC_ERROR;
8427 #endif
8428 #ifdef EOWNERDEAD
8429 case EOWNERDEAD: return DRFLAC_ERROR;
8430 #endif
8431 #ifdef ENOTRECOVERABLE
8432 case ENOTRECOVERABLE: return DRFLAC_ERROR;
8433 #endif
8434 #ifdef ERFKILL
8435 case ERFKILL: return DRFLAC_ERROR;
8436 #endif
8437 #ifdef EHWPOISON
8438 case EHWPOISON: return DRFLAC_ERROR;
8439 #endif
8440 default: return DRFLAC_ERROR;
8441 }
8442 }
8443
8444 static drflac_result drflac_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
8445 {
8446 #if defined(_MSC_VER) && _MSC_VER >= 1400
8447 errno_t err;
8448 #endif
8449
8450 if (ppFile != NULL) {
8451 *ppFile = NULL; /* Safety. */
8452 }
8453
8454 if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
8455 return DRFLAC_INVALID_ARGS;
8456 }
8457
8458 #if defined(_MSC_VER) && _MSC_VER >= 1400
8459 err = fopen_s(ppFile, pFilePath, pOpenMode);
8460 if (err != 0) {
8461 return drflac_result_from_errno(err);
8462 }
8463 #else
8464 #if defined(_WIN32) || defined(__APPLE__)
8465 *ppFile = fopen(pFilePath, pOpenMode);
8466 #else
8467 #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
8468 *ppFile = fopen64(pFilePath, pOpenMode);
8469 #else
8470 *ppFile = fopen(pFilePath, pOpenMode);
8471 #endif
8472 #endif
8473 if (*ppFile == NULL) {
8474 drflac_result result = drflac_result_from_errno(errno);
8475 if (result == DRFLAC_SUCCESS) {
8476 result = DRFLAC_ERROR; /* Just a safety check to make sure we never ever return success when pFile == NULL. */
8477 }
8478
8479 return result;
8480 }
8481 #endif
8482
8483 return DRFLAC_SUCCESS;
8484 }
8485
8486 /*
8487 _wfopen() isn't always available in all compilation environments.
8488
8489 * Windows only.
8490 * MSVC seems to support it universally as far back as VC6 from what I can tell (haven't checked further back).
8491 * MinGW-64 (both 32- and 64-bit) seems to support it.
8492 * MinGW wraps it in !defined(__STRICT_ANSI__).
8493 * OpenWatcom wraps it in !defined(_NO_EXT_KEYS).
8494
8495 This can be reviewed as compatibility issues arise. The preference is to use _wfopen_s() and _wfopen() as opposed to the wcsrtombs()
8496 fallback, so if you notice your compiler not detecting this properly I'm happy to look at adding support.
8497 */
8498 #if defined(_WIN32)
8499 #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
8500 #define DRFLAC_HAS_WFOPEN
8501 #endif
8502 #endif
8503
8504 static drflac_result drflac_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const drflac_allocation_callbacks* pAllocationCallbacks)
8505 {
8506 if (ppFile != NULL) {
8507 *ppFile = NULL; /* Safety. */
8508 }
8509
8510 if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
8511 return DRFLAC_INVALID_ARGS;
8512 }
8513
8514 #if defined(DRFLAC_HAS_WFOPEN)
8515 {
8516 /* Use _wfopen() on Windows. */
8517 #if defined(_MSC_VER) && _MSC_VER >= 1400
8518 errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
8519 if (err != 0) {
8520 return drflac_result_from_errno(err);
8521 }
8522 #else
8523 *ppFile = _wfopen(pFilePath, pOpenMode);
8524 if (*ppFile == NULL) {
8525 return drflac_result_from_errno(errno);
8526 }
8527 #endif
8528 (void)pAllocationCallbacks;
8529 }
8530 #else
8531 /*
8532 Use fopen() on anything other than Windows. Requires a conversion. This is annoying because fopen() is locale specific. The only real way I can
8533 think of to do this is with wcsrtombs(). Note that wcstombs() is apparently not thread-safe because it uses a static global mbstate_t object for
8534 maintaining state. I've checked this with -std=c89 and it works, but if somebody get's a compiler error I'll look into improving compatibility.
8535 */
8536 {
8537 mbstate_t mbs;
8538 size_t lenMB;
8539 const wchar_t* pFilePathTemp = pFilePath;
8540 char* pFilePathMB = NULL;
8541 char pOpenModeMB[32] = {0};
8542
8543 /* Get the length first. */
8544 DRFLAC_ZERO_OBJECT(&mbs);
8545 lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
8546 if (lenMB == (size_t)-1) {
8547 return drflac_result_from_errno(errno);
8548 }
8549
8550 pFilePathMB = (char*)drflac__malloc_from_callbacks(lenMB + 1, pAllocationCallbacks);
8551 if (pFilePathMB == NULL) {
8552 return DRFLAC_OUT_OF_MEMORY;
8553 }
8554
8555 pFilePathTemp = pFilePath;
8556 DRFLAC_ZERO_OBJECT(&mbs);
8557 wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
8558
8559 /* The open mode should always consist of ASCII characters so we should be able to do a trivial conversion. */
8560 {
8561 size_t i = 0;
8562 for (;;) {
8563 if (pOpenMode[i] == 0) {
8564 pOpenModeMB[i] = '\0';
8565 break;
8566 }
8567
8568 pOpenModeMB[i] = (char)pOpenMode[i];
8569 i += 1;
8570 }
8571 }
8572
8573 *ppFile = fopen(pFilePathMB, pOpenModeMB);
8574
8575 drflac__free_from_callbacks(pFilePathMB, pAllocationCallbacks);
8576 }
8577
8578 if (*ppFile == NULL) {
8579 return DRFLAC_ERROR;
8580 }
8581 #endif
8582
8583 return DRFLAC_SUCCESS;
8584 }
8585
8586 static size_t drflac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead)
8587 {
8588 return fread(bufferOut, 1, bytesToRead, (FILE*)pUserData);
8589 }
8590
8591 static drflac_bool32 drflac__on_seek_stdio(void* pUserData, int offset, drflac_seek_origin origin)
8592 {
8593 DRFLAC_ASSERT(offset >= 0); /* <-- Never seek backwards. */
8594
8595 return fseek((FILE*)pUserData, offset, (origin == drflac_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
8596 }
8597
8598
8599 DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks)
8600 {
8601 drflac* pFlac;
8602 FILE* pFile;
8603
8604 if (drflac_fopen(&pFile, pFileName, "rb") != DRFLAC_SUCCESS) {
8605 return NULL;
8606 }
8607
8608 pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
8609 if (pFlac == NULL) {
8610 fclose(pFile);
8611 return NULL;
8612 }
8613
8614 return pFlac;
8615 }
8616
8617 DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks)
8618 {
8619 drflac* pFlac;
8620 FILE* pFile;
8621
8622 if (drflac_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != DRFLAC_SUCCESS) {
8623 return NULL;
8624 }
8625
8626 pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
8627 if (pFlac == NULL) {
8628 fclose(pFile);
8629 return NULL;
8630 }
8631
8632 return pFlac;
8633 }
8634
8635 DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
8636 {
8637 drflac* pFlac;
8638 FILE* pFile;
8639
8640 if (drflac_fopen(&pFile, pFileName, "rb") != DRFLAC_SUCCESS) {
8641 return NULL;
8642 }
8643
8644 pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, onMeta, drflac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks);
8645 if (pFlac == NULL) {
8646 fclose(pFile);
8647 return pFlac;
8648 }
8649
8650 return pFlac;
8651 }
8652
8653 DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
8654 {
8655 drflac* pFlac;
8656 FILE* pFile;
8657
8658 if (drflac_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != DRFLAC_SUCCESS) {
8659 return NULL;
8660 }
8661
8662 pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, onMeta, drflac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks);
8663 if (pFlac == NULL) {
8664 fclose(pFile);
8665 return pFlac;
8666 }
8667
8668 return pFlac;
8669 }
8670 #endif /* DR_FLAC_NO_STDIO */
8671
8672 static size_t drflac__on_read_memory(void* pUserData, void* bufferOut, size_t bytesToRead)
8673 {
8674 drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
8675 size_t bytesRemaining;
8676
8677 DRFLAC_ASSERT(memoryStream != NULL);
8678 DRFLAC_ASSERT(memoryStream->dataSize >= memoryStream->currentReadPos);
8679
8680 bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos;
8681 if (bytesToRead > bytesRemaining) {
8682 bytesToRead = bytesRemaining;
8683 }
8684
8685 if (bytesToRead > 0) {
8686 DRFLAC_COPY_MEMORY(bufferOut, memoryStream->data + memoryStream->currentReadPos, bytesToRead);
8687 memoryStream->currentReadPos += bytesToRead;
8688 }
8689
8690 return bytesToRead;
8691 }
8692
8693 static drflac_bool32 drflac__on_seek_memory(void* pUserData, int offset, drflac_seek_origin origin)
8694 {
8695 drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
8696
8697 DRFLAC_ASSERT(memoryStream != NULL);
8698 DRFLAC_ASSERT(offset >= 0); /* <-- Never seek backwards. */
8699
8700 if (offset > (drflac_int64)memoryStream->dataSize) {
8701 return DRFLAC_FALSE;
8702 }
8703
8704 if (origin == drflac_seek_origin_current) {
8705 if (memoryStream->currentReadPos + offset <= memoryStream->dataSize) {
8706 memoryStream->currentReadPos += offset;
8707 } else {
8708 return DRFLAC_FALSE; /* Trying to seek too far forward. */
8709 }
8710 } else {
8711 if ((drflac_uint32)offset <= memoryStream->dataSize) {
8712 memoryStream->currentReadPos = offset;
8713 } else {
8714 return DRFLAC_FALSE; /* Trying to seek too far forward. */
8715 }
8716 }
8717
8718 return DRFLAC_TRUE;
8719 }
8720
8721 DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks)
8722 {
8723 drflac__memory_stream memoryStream;
8724 drflac* pFlac;
8725
8726 memoryStream.data = (const drflac_uint8*)pData;
8727 memoryStream.dataSize = dataSize;
8728 memoryStream.currentReadPos = 0;
8729 pFlac = drflac_open(drflac__on_read_memory, drflac__on_seek_memory, &memoryStream, pAllocationCallbacks);
8730 if (pFlac == NULL) {
8731 return NULL;
8732 }
8733
8734 pFlac->memoryStream = memoryStream;
8735
8736 /* This is an awful hack... */
8737 #ifndef DR_FLAC_NO_OGG
8738 if (pFlac->container == drflac_container_ogg)
8739 {
8740 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
8741 oggbs->pUserData = &pFlac->memoryStream;
8742 }
8743 else
8744 #endif
8745 {
8746 pFlac->bs.pUserData = &pFlac->memoryStream;
8747 }
8748
8749 return pFlac;
8750 }
8751
8752 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)
8753 {
8754 drflac__memory_stream memoryStream;
8755 drflac* pFlac;
8756
8757 memoryStream.data = (const drflac_uint8*)pData;
8758 memoryStream.dataSize = dataSize;
8759 memoryStream.currentReadPos = 0;
8760 pFlac = drflac_open_with_metadata_private(drflac__on_read_memory, drflac__on_seek_memory, onMeta, drflac_container_unknown, &memoryStream, pUserData, pAllocationCallbacks);
8761 if (pFlac == NULL) {
8762 return NULL;
8763 }
8764
8765 pFlac->memoryStream = memoryStream;
8766
8767 /* This is an awful hack... */
8768 #ifndef DR_FLAC_NO_OGG
8769 if (pFlac->container == drflac_container_ogg)
8770 {
8771 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
8772 oggbs->pUserData = &pFlac->memoryStream;
8773 }
8774 else
8775 #endif
8776 {
8777 pFlac->bs.pUserData = &pFlac->memoryStream;
8778 }
8779
8780 return pFlac;
8781 }
8782
8783
8784
8785 DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
8786 {
8787 return drflac_open_with_metadata_private(onRead, onSeek, NULL, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
8788 }
8789 DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
8790 {
8791 return drflac_open_with_metadata_private(onRead, onSeek, NULL, container, pUserData, pUserData, pAllocationCallbacks);
8792 }
8793
8794 DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
8795 {
8796 return drflac_open_with_metadata_private(onRead, onSeek, onMeta, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
8797 }
8798 DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
8799 {
8800 return drflac_open_with_metadata_private(onRead, onSeek, onMeta, container, pUserData, pUserData, pAllocationCallbacks);
8801 }
8802
8803 DRFLAC_API void drflac_close(drflac* pFlac)
8804 {
8805 if (pFlac == NULL) {
8806 return;
8807 }
8808
8809 #ifndef DR_FLAC_NO_STDIO
8810 /*
8811 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()
8812 was used by looking at the callbacks.
8813 */
8814 if (pFlac->bs.onRead == drflac__on_read_stdio) {
8815 fclose((FILE*)pFlac->bs.pUserData);
8816 }
8817
8818 #ifndef DR_FLAC_NO_OGG
8819 /* Need to clean up Ogg streams a bit differently due to the way the bit streaming is chained. */
8820 if (pFlac->container == drflac_container_ogg) {
8821 drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
8822 DRFLAC_ASSERT(pFlac->bs.onRead == drflac__on_read_ogg);
8823
8824 if (oggbs->onRead == drflac__on_read_stdio) {
8825 fclose((FILE*)oggbs->pUserData);
8826 }
8827 }
8828 #endif
8829 #endif
8830
8831 drflac__free_from_callbacks(pFlac, &pFlac->allocationCallbacks);
8832 }
8833
8834
8835 #if 0
8836 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)
8837 {
8838 drflac_uint64 i;
8839 for (i = 0; i < frameCount; ++i) {
8840 drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
8841 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
8842 drflac_uint32 right = left - side;
8843
8844 pOutputSamples[i*2+0] = (drflac_int32)left;
8845 pOutputSamples[i*2+1] = (drflac_int32)right;
8846 }
8847 }
8848 #endif
8849
8850 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)
8851 {
8852 drflac_uint64 i;
8853 drflac_uint64 frameCount4 = frameCount >> 2;
8854 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
8855 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
8856 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
8857 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
8858
8859 for (i = 0; i < frameCount4; ++i) {
8860 drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
8861 drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
8862 drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
8863 drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
8864
8865 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
8866 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
8867 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
8868 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
8869
8870 drflac_uint32 right0 = left0 - side0;
8871 drflac_uint32 right1 = left1 - side1;
8872 drflac_uint32 right2 = left2 - side2;
8873 drflac_uint32 right3 = left3 - side3;
8874
8875 pOutputSamples[i*8+0] = (drflac_int32)left0;
8876 pOutputSamples[i*8+1] = (drflac_int32)right0;
8877 pOutputSamples[i*8+2] = (drflac_int32)left1;
8878 pOutputSamples[i*8+3] = (drflac_int32)right1;
8879 pOutputSamples[i*8+4] = (drflac_int32)left2;
8880 pOutputSamples[i*8+5] = (drflac_int32)right2;
8881 pOutputSamples[i*8+6] = (drflac_int32)left3;
8882 pOutputSamples[i*8+7] = (drflac_int32)right3;
8883 }
8884
8885 for (i = (frameCount4 << 2); i < frameCount; ++i) {
8886 drflac_uint32 left = pInputSamples0U32[i] << shift0;
8887 drflac_uint32 side = pInputSamples1U32[i] << shift1;
8888 drflac_uint32 right = left - side;
8889
8890 pOutputSamples[i*2+0] = (drflac_int32)left;
8891 pOutputSamples[i*2+1] = (drflac_int32)right;
8892 }
8893 }
8894
8895 #if defined(DRFLAC_SUPPORT_SSE2)
8896 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)
8897 {
8898 drflac_uint64 i;
8899 drflac_uint64 frameCount4 = frameCount >> 2;
8900 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
8901 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
8902 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
8903 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
8904
8905 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
8906
8907 for (i = 0; i < frameCount4; ++i) {
8908 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
8909 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
8910 __m128i right = _mm_sub_epi32(left, side);
8911
8912 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
8913 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
8914 }
8915
8916 for (i = (frameCount4 << 2); i < frameCount; ++i) {
8917 drflac_uint32 left = pInputSamples0U32[i] << shift0;
8918 drflac_uint32 side = pInputSamples1U32[i] << shift1;
8919 drflac_uint32 right = left - side;
8920
8921 pOutputSamples[i*2+0] = (drflac_int32)left;
8922 pOutputSamples[i*2+1] = (drflac_int32)right;
8923 }
8924 }
8925 #endif
8926
8927 #if defined(DRFLAC_SUPPORT_NEON)
8928 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)
8929 {
8930 drflac_uint64 i;
8931 drflac_uint64 frameCount4 = frameCount >> 2;
8932 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
8933 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
8934 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
8935 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
8936 int32x4_t shift0_4;
8937 int32x4_t shift1_4;
8938
8939 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
8940
8941 shift0_4 = vdupq_n_s32(shift0);
8942 shift1_4 = vdupq_n_s32(shift1);
8943
8944 for (i = 0; i < frameCount4; ++i) {
8945 uint32x4_t left;
8946 uint32x4_t side;
8947 uint32x4_t right;
8948
8949 left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
8950 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
8951 right = vsubq_u32(left, side);
8952
8953 drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
8954 }
8955
8956 for (i = (frameCount4 << 2); i < frameCount; ++i) {
8957 drflac_uint32 left = pInputSamples0U32[i] << shift0;
8958 drflac_uint32 side = pInputSamples1U32[i] << shift1;
8959 drflac_uint32 right = left - side;
8960
8961 pOutputSamples[i*2+0] = (drflac_int32)left;
8962 pOutputSamples[i*2+1] = (drflac_int32)right;
8963 }
8964 }
8965 #endif
8966
8967 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)
8968 {
8969 #if defined(DRFLAC_SUPPORT_SSE2)
8970 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
8971 drflac_read_pcm_frames_s32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
8972 } else
8973 #elif defined(DRFLAC_SUPPORT_NEON)
8974 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
8975 drflac_read_pcm_frames_s32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
8976 } else
8977 #endif
8978 {
8979 /* Scalar fallback. */
8980 #if 0
8981 drflac_read_pcm_frames_s32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
8982 #else
8983 drflac_read_pcm_frames_s32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
8984 #endif
8985 }
8986 }
8987
8988
8989 #if 0
8990 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)
8991 {
8992 drflac_uint64 i;
8993 for (i = 0; i < frameCount; ++i) {
8994 drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
8995 drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
8996 drflac_uint32 left = right + side;
8997
8998 pOutputSamples[i*2+0] = (drflac_int32)left;
8999 pOutputSamples[i*2+1] = (drflac_int32)right;
9000 }
9001 }
9002 #endif
9003
9004 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)
9005 {
9006 drflac_uint64 i;
9007 drflac_uint64 frameCount4 = frameCount >> 2;
9008 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9009 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9010 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9011 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9012
9013 for (i = 0; i < frameCount4; ++i) {
9014 drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
9015 drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
9016 drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
9017 drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
9018
9019 drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
9020 drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
9021 drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
9022 drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
9023
9024 drflac_uint32 left0 = right0 + side0;
9025 drflac_uint32 left1 = right1 + side1;
9026 drflac_uint32 left2 = right2 + side2;
9027 drflac_uint32 left3 = right3 + side3;
9028
9029 pOutputSamples[i*8+0] = (drflac_int32)left0;
9030 pOutputSamples[i*8+1] = (drflac_int32)right0;
9031 pOutputSamples[i*8+2] = (drflac_int32)left1;
9032 pOutputSamples[i*8+3] = (drflac_int32)right1;
9033 pOutputSamples[i*8+4] = (drflac_int32)left2;
9034 pOutputSamples[i*8+5] = (drflac_int32)right2;
9035 pOutputSamples[i*8+6] = (drflac_int32)left3;
9036 pOutputSamples[i*8+7] = (drflac_int32)right3;
9037 }
9038
9039 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9040 drflac_uint32 side = pInputSamples0U32[i] << shift0;
9041 drflac_uint32 right = pInputSamples1U32[i] << shift1;
9042 drflac_uint32 left = right + side;
9043
9044 pOutputSamples[i*2+0] = (drflac_int32)left;
9045 pOutputSamples[i*2+1] = (drflac_int32)right;
9046 }
9047 }
9048
9049 #if defined(DRFLAC_SUPPORT_SSE2)
9050 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)
9051 {
9052 drflac_uint64 i;
9053 drflac_uint64 frameCount4 = frameCount >> 2;
9054 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9055 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9056 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9057 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9058
9059 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9060
9061 for (i = 0; i < frameCount4; ++i) {
9062 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
9063 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
9064 __m128i left = _mm_add_epi32(right, side);
9065
9066 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9067 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9068 }
9069
9070 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9071 drflac_uint32 side = pInputSamples0U32[i] << shift0;
9072 drflac_uint32 right = pInputSamples1U32[i] << shift1;
9073 drflac_uint32 left = right + side;
9074
9075 pOutputSamples[i*2+0] = (drflac_int32)left;
9076 pOutputSamples[i*2+1] = (drflac_int32)right;
9077 }
9078 }
9079 #endif
9080
9081 #if defined(DRFLAC_SUPPORT_NEON)
9082 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)
9083 {
9084 drflac_uint64 i;
9085 drflac_uint64 frameCount4 = frameCount >> 2;
9086 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9087 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9088 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9089 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9090 int32x4_t shift0_4;
9091 int32x4_t shift1_4;
9092
9093 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9094
9095 shift0_4 = vdupq_n_s32(shift0);
9096 shift1_4 = vdupq_n_s32(shift1);
9097
9098 for (i = 0; i < frameCount4; ++i) {
9099 uint32x4_t side;
9100 uint32x4_t right;
9101 uint32x4_t left;
9102
9103 side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
9104 right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
9105 left = vaddq_u32(right, side);
9106
9107 drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
9108 }
9109
9110 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9111 drflac_uint32 side = pInputSamples0U32[i] << shift0;
9112 drflac_uint32 right = pInputSamples1U32[i] << shift1;
9113 drflac_uint32 left = right + side;
9114
9115 pOutputSamples[i*2+0] = (drflac_int32)left;
9116 pOutputSamples[i*2+1] = (drflac_int32)right;
9117 }
9118 }
9119 #endif
9120
9121 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)
9122 {
9123 #if defined(DRFLAC_SUPPORT_SSE2)
9124 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9125 drflac_read_pcm_frames_s32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9126 } else
9127 #elif defined(DRFLAC_SUPPORT_NEON)
9128 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9129 drflac_read_pcm_frames_s32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9130 } else
9131 #endif
9132 {
9133 /* Scalar fallback. */
9134 #if 0
9135 drflac_read_pcm_frames_s32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9136 #else
9137 drflac_read_pcm_frames_s32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9138 #endif
9139 }
9140 }
9141
9142
9143 #if 0
9144 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)
9145 {
9146 for (drflac_uint64 i = 0; i < frameCount; ++i) {
9147 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9148 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9149
9150 mid = (mid << 1) | (side & 0x01);
9151
9152 pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
9153 pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
9154 }
9155 }
9156 #endif
9157
9158 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)
9159 {
9160 drflac_uint64 i;
9161 drflac_uint64 frameCount4 = frameCount >> 2;
9162 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9163 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9164 drflac_int32 shift = unusedBitsPerSample;
9165
9166 if (shift > 0) {
9167 shift -= 1;
9168 for (i = 0; i < frameCount4; ++i) {
9169 drflac_uint32 temp0L;
9170 drflac_uint32 temp1L;
9171 drflac_uint32 temp2L;
9172 drflac_uint32 temp3L;
9173 drflac_uint32 temp0R;
9174 drflac_uint32 temp1R;
9175 drflac_uint32 temp2R;
9176 drflac_uint32 temp3R;
9177
9178 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9179 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9180 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9181 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9182
9183 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9184 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9185 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9186 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9187
9188 mid0 = (mid0 << 1) | (side0 & 0x01);
9189 mid1 = (mid1 << 1) | (side1 & 0x01);
9190 mid2 = (mid2 << 1) | (side2 & 0x01);
9191 mid3 = (mid3 << 1) | (side3 & 0x01);
9192
9193 temp0L = (mid0 + side0) << shift;
9194 temp1L = (mid1 + side1) << shift;
9195 temp2L = (mid2 + side2) << shift;
9196 temp3L = (mid3 + side3) << shift;
9197
9198 temp0R = (mid0 - side0) << shift;
9199 temp1R = (mid1 - side1) << shift;
9200 temp2R = (mid2 - side2) << shift;
9201 temp3R = (mid3 - side3) << shift;
9202
9203 pOutputSamples[i*8+0] = (drflac_int32)temp0L;
9204 pOutputSamples[i*8+1] = (drflac_int32)temp0R;
9205 pOutputSamples[i*8+2] = (drflac_int32)temp1L;
9206 pOutputSamples[i*8+3] = (drflac_int32)temp1R;
9207 pOutputSamples[i*8+4] = (drflac_int32)temp2L;
9208 pOutputSamples[i*8+5] = (drflac_int32)temp2R;
9209 pOutputSamples[i*8+6] = (drflac_int32)temp3L;
9210 pOutputSamples[i*8+7] = (drflac_int32)temp3R;
9211 }
9212 } else {
9213 for (i = 0; i < frameCount4; ++i) {
9214 drflac_uint32 temp0L;
9215 drflac_uint32 temp1L;
9216 drflac_uint32 temp2L;
9217 drflac_uint32 temp3L;
9218 drflac_uint32 temp0R;
9219 drflac_uint32 temp1R;
9220 drflac_uint32 temp2R;
9221 drflac_uint32 temp3R;
9222
9223 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9224 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9225 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9226 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9227
9228 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9229 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9230 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9231 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9232
9233 mid0 = (mid0 << 1) | (side0 & 0x01);
9234 mid1 = (mid1 << 1) | (side1 & 0x01);
9235 mid2 = (mid2 << 1) | (side2 & 0x01);
9236 mid3 = (mid3 << 1) | (side3 & 0x01);
9237
9238 temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
9239 temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
9240 temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
9241 temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
9242
9243 temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
9244 temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
9245 temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
9246 temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
9247
9248 pOutputSamples[i*8+0] = (drflac_int32)temp0L;
9249 pOutputSamples[i*8+1] = (drflac_int32)temp0R;
9250 pOutputSamples[i*8+2] = (drflac_int32)temp1L;
9251 pOutputSamples[i*8+3] = (drflac_int32)temp1R;
9252 pOutputSamples[i*8+4] = (drflac_int32)temp2L;
9253 pOutputSamples[i*8+5] = (drflac_int32)temp2R;
9254 pOutputSamples[i*8+6] = (drflac_int32)temp3L;
9255 pOutputSamples[i*8+7] = (drflac_int32)temp3R;
9256 }
9257 }
9258
9259 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9260 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9261 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9262
9263 mid = (mid << 1) | (side & 0x01);
9264
9265 pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
9266 pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
9267 }
9268 }
9269
9270 #if defined(DRFLAC_SUPPORT_SSE2)
9271 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)
9272 {
9273 drflac_uint64 i;
9274 drflac_uint64 frameCount4 = frameCount >> 2;
9275 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9276 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9277 drflac_int32 shift = unusedBitsPerSample;
9278
9279 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9280
9281 if (shift == 0) {
9282 for (i = 0; i < frameCount4; ++i) {
9283 __m128i mid;
9284 __m128i side;
9285 __m128i left;
9286 __m128i right;
9287
9288 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9289 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9290
9291 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
9292
9293 left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
9294 right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
9295
9296 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9297 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9298 }
9299
9300 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9301 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9302 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9303
9304 mid = (mid << 1) | (side & 0x01);
9305
9306 pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
9307 pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
9308 }
9309 } else {
9310 shift -= 1;
9311 for (i = 0; i < frameCount4; ++i) {
9312 __m128i mid;
9313 __m128i side;
9314 __m128i left;
9315 __m128i right;
9316
9317 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9318 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9319
9320 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
9321
9322 left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
9323 right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
9324
9325 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9326 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9327 }
9328
9329 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9330 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9331 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9332
9333 mid = (mid << 1) | (side & 0x01);
9334
9335 pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
9336 pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
9337 }
9338 }
9339 }
9340 #endif
9341
9342 #if defined(DRFLAC_SUPPORT_NEON)
9343 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)
9344 {
9345 drflac_uint64 i;
9346 drflac_uint64 frameCount4 = frameCount >> 2;
9347 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9348 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9349 drflac_int32 shift = unusedBitsPerSample;
9350 int32x4_t wbpsShift0_4; /* wbps = Wasted Bits Per Sample */
9351 int32x4_t wbpsShift1_4; /* wbps = Wasted Bits Per Sample */
9352 uint32x4_t one4;
9353
9354 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9355
9356 wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9357 wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9358 one4 = vdupq_n_u32(1);
9359
9360 if (shift == 0) {
9361 for (i = 0; i < frameCount4; ++i) {
9362 uint32x4_t mid;
9363 uint32x4_t side;
9364 int32x4_t left;
9365 int32x4_t right;
9366
9367 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
9368 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
9369
9370 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
9371
9372 left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
9373 right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
9374
9375 drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
9376 }
9377
9378 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9379 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9380 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9381
9382 mid = (mid << 1) | (side & 0x01);
9383
9384 pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
9385 pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
9386 }
9387 } else {
9388 int32x4_t shift4;
9389
9390 shift -= 1;
9391 shift4 = vdupq_n_s32(shift);
9392
9393 for (i = 0; i < frameCount4; ++i) {
9394 uint32x4_t mid;
9395 uint32x4_t side;
9396 int32x4_t left;
9397 int32x4_t right;
9398
9399 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
9400 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
9401
9402 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
9403
9404 left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
9405 right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
9406
9407 drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
9408 }
9409
9410 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9411 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9412 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9413
9414 mid = (mid << 1) | (side & 0x01);
9415
9416 pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
9417 pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
9418 }
9419 }
9420 }
9421 #endif
9422
9423 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)
9424 {
9425 #if defined(DRFLAC_SUPPORT_SSE2)
9426 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9427 drflac_read_pcm_frames_s32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9428 } else
9429 #elif defined(DRFLAC_SUPPORT_NEON)
9430 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9431 drflac_read_pcm_frames_s32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9432 } else
9433 #endif
9434 {
9435 /* Scalar fallback. */
9436 #if 0
9437 drflac_read_pcm_frames_s32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9438 #else
9439 drflac_read_pcm_frames_s32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9440 #endif
9441 }
9442 }
9443
9444
9445 #if 0
9446 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)
9447 {
9448 for (drflac_uint64 i = 0; i < frameCount; ++i) {
9449 pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample));
9450 pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample));
9451 }
9452 }
9453 #endif
9454
9455 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)
9456 {
9457 drflac_uint64 i;
9458 drflac_uint64 frameCount4 = frameCount >> 2;
9459 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9460 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9461 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9462 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9463
9464 for (i = 0; i < frameCount4; ++i) {
9465 drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
9466 drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
9467 drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
9468 drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
9469
9470 drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
9471 drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
9472 drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
9473 drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
9474
9475 pOutputSamples[i*8+0] = (drflac_int32)tempL0;
9476 pOutputSamples[i*8+1] = (drflac_int32)tempR0;
9477 pOutputSamples[i*8+2] = (drflac_int32)tempL1;
9478 pOutputSamples[i*8+3] = (drflac_int32)tempR1;
9479 pOutputSamples[i*8+4] = (drflac_int32)tempL2;
9480 pOutputSamples[i*8+5] = (drflac_int32)tempR2;
9481 pOutputSamples[i*8+6] = (drflac_int32)tempL3;
9482 pOutputSamples[i*8+7] = (drflac_int32)tempR3;
9483 }
9484
9485 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9486 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
9487 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
9488 }
9489 }
9490
9491 #if defined(DRFLAC_SUPPORT_SSE2)
9492 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)
9493 {
9494 drflac_uint64 i;
9495 drflac_uint64 frameCount4 = frameCount >> 2;
9496 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9497 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9498 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9499 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9500
9501 for (i = 0; i < frameCount4; ++i) {
9502 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
9503 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
9504
9505 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
9506 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
9507 }
9508
9509 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9510 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
9511 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
9512 }
9513 }
9514 #endif
9515
9516 #if defined(DRFLAC_SUPPORT_NEON)
9517 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)
9518 {
9519 drflac_uint64 i;
9520 drflac_uint64 frameCount4 = frameCount >> 2;
9521 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9522 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9523 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9524 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9525
9526 int32x4_t shift4_0 = vdupq_n_s32(shift0);
9527 int32x4_t shift4_1 = vdupq_n_s32(shift1);
9528
9529 for (i = 0; i < frameCount4; ++i) {
9530 int32x4_t left;
9531 int32x4_t right;
9532
9533 left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift4_0));
9534 right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift4_1));
9535
9536 drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
9537 }
9538
9539 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9540 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
9541 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
9542 }
9543 }
9544 #endif
9545
9546 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)
9547 {
9548 #if defined(DRFLAC_SUPPORT_SSE2)
9549 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9550 drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9551 } else
9552 #elif defined(DRFLAC_SUPPORT_NEON)
9553 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9554 drflac_read_pcm_frames_s32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9555 } else
9556 #endif
9557 {
9558 /* Scalar fallback. */
9559 #if 0
9560 drflac_read_pcm_frames_s32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9561 #else
9562 drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9563 #endif
9564 }
9565 }
9566
9567
9568 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut)
9569 {
9570 drflac_uint64 framesRead;
9571 drflac_uint32 unusedBitsPerSample;
9572
9573 if (pFlac == NULL || framesToRead == 0) {
9574 return 0;
9575 }
9576
9577 if (pBufferOut == NULL) {
9578 return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
9579 }
9580
9581 DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
9582 unusedBitsPerSample = 32 - pFlac->bitsPerSample;
9583
9584 framesRead = 0;
9585 while (framesToRead > 0) {
9586 /* If we've run out of samples in this frame, go to the next. */
9587 if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
9588 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
9589 break; /* Couldn't read the next frame, so just break from the loop and return. */
9590 }
9591 } else {
9592 unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
9593 drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
9594 drflac_uint64 frameCountThisIteration = framesToRead;
9595
9596 if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
9597 frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
9598 }
9599
9600 if (channelCount == 2) {
9601 const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
9602 const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
9603
9604 switch (pFlac->currentFLACFrame.header.channelAssignment)
9605 {
9606 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
9607 {
9608 drflac_read_pcm_frames_s32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
9609 } break;
9610
9611 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
9612 {
9613 drflac_read_pcm_frames_s32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
9614 } break;
9615
9616 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
9617 {
9618 drflac_read_pcm_frames_s32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
9619 } break;
9620
9621 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
9622 default:
9623 {
9624 drflac_read_pcm_frames_s32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
9625 } break;
9626 }
9627 } else {
9628 /* Generic interleaving. */
9629 drflac_uint64 i;
9630 for (i = 0; i < frameCountThisIteration; ++i) {
9631 unsigned int j;
9632 for (j = 0; j < channelCount; ++j) {
9633 pBufferOut[(i*channelCount)+j] = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
9634 }
9635 }
9636 }
9637
9638 framesRead += frameCountThisIteration;
9639 pBufferOut += frameCountThisIteration * channelCount;
9640 framesToRead -= frameCountThisIteration;
9641 pFlac->currentPCMFrame += frameCountThisIteration;
9642 pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
9643 }
9644 }
9645
9646 return framesRead;
9647 }
9648
9649
9650 #if 0
9651 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)
9652 {
9653 drflac_uint64 i;
9654 for (i = 0; i < frameCount; ++i) {
9655 drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9656 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9657 drflac_uint32 right = left - side;
9658
9659 left >>= 16;
9660 right >>= 16;
9661
9662 pOutputSamples[i*2+0] = (drflac_int16)left;
9663 pOutputSamples[i*2+1] = (drflac_int16)right;
9664 }
9665 }
9666 #endif
9667
9668 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)
9669 {
9670 drflac_uint64 i;
9671 drflac_uint64 frameCount4 = frameCount >> 2;
9672 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9673 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9674 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9675 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9676
9677 for (i = 0; i < frameCount4; ++i) {
9678 drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
9679 drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
9680 drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
9681 drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
9682
9683 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
9684 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
9685 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
9686 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
9687
9688 drflac_uint32 right0 = left0 - side0;
9689 drflac_uint32 right1 = left1 - side1;
9690 drflac_uint32 right2 = left2 - side2;
9691 drflac_uint32 right3 = left3 - side3;
9692
9693 left0 >>= 16;
9694 left1 >>= 16;
9695 left2 >>= 16;
9696 left3 >>= 16;
9697
9698 right0 >>= 16;
9699 right1 >>= 16;
9700 right2 >>= 16;
9701 right3 >>= 16;
9702
9703 pOutputSamples[i*8+0] = (drflac_int16)left0;
9704 pOutputSamples[i*8+1] = (drflac_int16)right0;
9705 pOutputSamples[i*8+2] = (drflac_int16)left1;
9706 pOutputSamples[i*8+3] = (drflac_int16)right1;
9707 pOutputSamples[i*8+4] = (drflac_int16)left2;
9708 pOutputSamples[i*8+5] = (drflac_int16)right2;
9709 pOutputSamples[i*8+6] = (drflac_int16)left3;
9710 pOutputSamples[i*8+7] = (drflac_int16)right3;
9711 }
9712
9713 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9714 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9715 drflac_uint32 side = pInputSamples1U32[i] << shift1;
9716 drflac_uint32 right = left - side;
9717
9718 left >>= 16;
9719 right >>= 16;
9720
9721 pOutputSamples[i*2+0] = (drflac_int16)left;
9722 pOutputSamples[i*2+1] = (drflac_int16)right;
9723 }
9724 }
9725
9726 #if defined(DRFLAC_SUPPORT_SSE2)
9727 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)
9728 {
9729 drflac_uint64 i;
9730 drflac_uint64 frameCount4 = frameCount >> 2;
9731 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9732 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9733 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9734 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9735
9736 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9737
9738 for (i = 0; i < frameCount4; ++i) {
9739 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
9740 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
9741 __m128i right = _mm_sub_epi32(left, side);
9742
9743 left = _mm_srai_epi32(left, 16);
9744 right = _mm_srai_epi32(right, 16);
9745
9746 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
9747 }
9748
9749 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9750 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9751 drflac_uint32 side = pInputSamples1U32[i] << shift1;
9752 drflac_uint32 right = left - side;
9753
9754 left >>= 16;
9755 right >>= 16;
9756
9757 pOutputSamples[i*2+0] = (drflac_int16)left;
9758 pOutputSamples[i*2+1] = (drflac_int16)right;
9759 }
9760 }
9761 #endif
9762
9763 #if defined(DRFLAC_SUPPORT_NEON)
9764 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)
9765 {
9766 drflac_uint64 i;
9767 drflac_uint64 frameCount4 = frameCount >> 2;
9768 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9769 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9770 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9771 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9772 int32x4_t shift0_4;
9773 int32x4_t shift1_4;
9774
9775 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9776
9777 shift0_4 = vdupq_n_s32(shift0);
9778 shift1_4 = vdupq_n_s32(shift1);
9779
9780 for (i = 0; i < frameCount4; ++i) {
9781 uint32x4_t left;
9782 uint32x4_t side;
9783 uint32x4_t right;
9784
9785 left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
9786 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
9787 right = vsubq_u32(left, side);
9788
9789 left = vshrq_n_u32(left, 16);
9790 right = vshrq_n_u32(right, 16);
9791
9792 drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
9793 }
9794
9795 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9796 drflac_uint32 left = pInputSamples0U32[i] << shift0;
9797 drflac_uint32 side = pInputSamples1U32[i] << shift1;
9798 drflac_uint32 right = left - side;
9799
9800 left >>= 16;
9801 right >>= 16;
9802
9803 pOutputSamples[i*2+0] = (drflac_int16)left;
9804 pOutputSamples[i*2+1] = (drflac_int16)right;
9805 }
9806 }
9807 #endif
9808
9809 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)
9810 {
9811 #if defined(DRFLAC_SUPPORT_SSE2)
9812 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9813 drflac_read_pcm_frames_s16__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9814 } else
9815 #elif defined(DRFLAC_SUPPORT_NEON)
9816 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9817 drflac_read_pcm_frames_s16__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9818 } else
9819 #endif
9820 {
9821 /* Scalar fallback. */
9822 #if 0
9823 drflac_read_pcm_frames_s16__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9824 #else
9825 drflac_read_pcm_frames_s16__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9826 #endif
9827 }
9828 }
9829
9830
9831 #if 0
9832 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)
9833 {
9834 drflac_uint64 i;
9835 for (i = 0; i < frameCount; ++i) {
9836 drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
9837 drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
9838 drflac_uint32 left = right + side;
9839
9840 left >>= 16;
9841 right >>= 16;
9842
9843 pOutputSamples[i*2+0] = (drflac_int16)left;
9844 pOutputSamples[i*2+1] = (drflac_int16)right;
9845 }
9846 }
9847 #endif
9848
9849 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)
9850 {
9851 drflac_uint64 i;
9852 drflac_uint64 frameCount4 = frameCount >> 2;
9853 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9854 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9855 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9856 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9857
9858 for (i = 0; i < frameCount4; ++i) {
9859 drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
9860 drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
9861 drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
9862 drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
9863
9864 drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
9865 drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
9866 drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
9867 drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
9868
9869 drflac_uint32 left0 = right0 + side0;
9870 drflac_uint32 left1 = right1 + side1;
9871 drflac_uint32 left2 = right2 + side2;
9872 drflac_uint32 left3 = right3 + side3;
9873
9874 left0 >>= 16;
9875 left1 >>= 16;
9876 left2 >>= 16;
9877 left3 >>= 16;
9878
9879 right0 >>= 16;
9880 right1 >>= 16;
9881 right2 >>= 16;
9882 right3 >>= 16;
9883
9884 pOutputSamples[i*8+0] = (drflac_int16)left0;
9885 pOutputSamples[i*8+1] = (drflac_int16)right0;
9886 pOutputSamples[i*8+2] = (drflac_int16)left1;
9887 pOutputSamples[i*8+3] = (drflac_int16)right1;
9888 pOutputSamples[i*8+4] = (drflac_int16)left2;
9889 pOutputSamples[i*8+5] = (drflac_int16)right2;
9890 pOutputSamples[i*8+6] = (drflac_int16)left3;
9891 pOutputSamples[i*8+7] = (drflac_int16)right3;
9892 }
9893
9894 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9895 drflac_uint32 side = pInputSamples0U32[i] << shift0;
9896 drflac_uint32 right = pInputSamples1U32[i] << shift1;
9897 drflac_uint32 left = right + side;
9898
9899 left >>= 16;
9900 right >>= 16;
9901
9902 pOutputSamples[i*2+0] = (drflac_int16)left;
9903 pOutputSamples[i*2+1] = (drflac_int16)right;
9904 }
9905 }
9906
9907 #if defined(DRFLAC_SUPPORT_SSE2)
9908 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)
9909 {
9910 drflac_uint64 i;
9911 drflac_uint64 frameCount4 = frameCount >> 2;
9912 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9913 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9914 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9915 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9916
9917 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9918
9919 for (i = 0; i < frameCount4; ++i) {
9920 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
9921 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
9922 __m128i left = _mm_add_epi32(right, side);
9923
9924 left = _mm_srai_epi32(left, 16);
9925 right = _mm_srai_epi32(right, 16);
9926
9927 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
9928 }
9929
9930 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9931 drflac_uint32 side = pInputSamples0U32[i] << shift0;
9932 drflac_uint32 right = pInputSamples1U32[i] << shift1;
9933 drflac_uint32 left = right + side;
9934
9935 left >>= 16;
9936 right >>= 16;
9937
9938 pOutputSamples[i*2+0] = (drflac_int16)left;
9939 pOutputSamples[i*2+1] = (drflac_int16)right;
9940 }
9941 }
9942 #endif
9943
9944 #if defined(DRFLAC_SUPPORT_NEON)
9945 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)
9946 {
9947 drflac_uint64 i;
9948 drflac_uint64 frameCount4 = frameCount >> 2;
9949 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
9950 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
9951 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
9952 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
9953 int32x4_t shift0_4;
9954 int32x4_t shift1_4;
9955
9956 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
9957
9958 shift0_4 = vdupq_n_s32(shift0);
9959 shift1_4 = vdupq_n_s32(shift1);
9960
9961 for (i = 0; i < frameCount4; ++i) {
9962 uint32x4_t side;
9963 uint32x4_t right;
9964 uint32x4_t left;
9965
9966 side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
9967 right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
9968 left = vaddq_u32(right, side);
9969
9970 left = vshrq_n_u32(left, 16);
9971 right = vshrq_n_u32(right, 16);
9972
9973 drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
9974 }
9975
9976 for (i = (frameCount4 << 2); i < frameCount; ++i) {
9977 drflac_uint32 side = pInputSamples0U32[i] << shift0;
9978 drflac_uint32 right = pInputSamples1U32[i] << shift1;
9979 drflac_uint32 left = right + side;
9980
9981 left >>= 16;
9982 right >>= 16;
9983
9984 pOutputSamples[i*2+0] = (drflac_int16)left;
9985 pOutputSamples[i*2+1] = (drflac_int16)right;
9986 }
9987 }
9988 #endif
9989
9990 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)
9991 {
9992 #if defined(DRFLAC_SUPPORT_SSE2)
9993 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
9994 drflac_read_pcm_frames_s16__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9995 } else
9996 #elif defined(DRFLAC_SUPPORT_NEON)
9997 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
9998 drflac_read_pcm_frames_s16__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
9999 } else
10000 #endif
10001 {
10002 /* Scalar fallback. */
10003 #if 0
10004 drflac_read_pcm_frames_s16__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10005 #else
10006 drflac_read_pcm_frames_s16__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10007 #endif
10008 }
10009 }
10010
10011
10012 #if 0
10013 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)
10014 {
10015 for (drflac_uint64 i = 0; i < frameCount; ++i) {
10016 drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10017 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10018
10019 mid = (mid << 1) | (side & 0x01);
10020
10021 pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
10022 pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
10023 }
10024 }
10025 #endif
10026
10027 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)
10028 {
10029 drflac_uint64 i;
10030 drflac_uint64 frameCount4 = frameCount >> 2;
10031 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10032 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10033 drflac_uint32 shift = unusedBitsPerSample;
10034
10035 if (shift > 0) {
10036 shift -= 1;
10037 for (i = 0; i < frameCount4; ++i) {
10038 drflac_uint32 temp0L;
10039 drflac_uint32 temp1L;
10040 drflac_uint32 temp2L;
10041 drflac_uint32 temp3L;
10042 drflac_uint32 temp0R;
10043 drflac_uint32 temp1R;
10044 drflac_uint32 temp2R;
10045 drflac_uint32 temp3R;
10046
10047 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10048 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10049 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10050 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10051
10052 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10053 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10054 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10055 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10056
10057 mid0 = (mid0 << 1) | (side0 & 0x01);
10058 mid1 = (mid1 << 1) | (side1 & 0x01);
10059 mid2 = (mid2 << 1) | (side2 & 0x01);
10060 mid3 = (mid3 << 1) | (side3 & 0x01);
10061
10062 temp0L = (mid0 + side0) << shift;
10063 temp1L = (mid1 + side1) << shift;
10064 temp2L = (mid2 + side2) << shift;
10065 temp3L = (mid3 + side3) << shift;
10066
10067 temp0R = (mid0 - side0) << shift;
10068 temp1R = (mid1 - side1) << shift;
10069 temp2R = (mid2 - side2) << shift;
10070 temp3R = (mid3 - side3) << shift;
10071
10072 temp0L >>= 16;
10073 temp1L >>= 16;
10074 temp2L >>= 16;
10075 temp3L >>= 16;
10076
10077 temp0R >>= 16;
10078 temp1R >>= 16;
10079 temp2R >>= 16;
10080 temp3R >>= 16;
10081
10082 pOutputSamples[i*8+0] = (drflac_int16)temp0L;
10083 pOutputSamples[i*8+1] = (drflac_int16)temp0R;
10084 pOutputSamples[i*8+2] = (drflac_int16)temp1L;
10085 pOutputSamples[i*8+3] = (drflac_int16)temp1R;
10086 pOutputSamples[i*8+4] = (drflac_int16)temp2L;
10087 pOutputSamples[i*8+5] = (drflac_int16)temp2R;
10088 pOutputSamples[i*8+6] = (drflac_int16)temp3L;
10089 pOutputSamples[i*8+7] = (drflac_int16)temp3R;
10090 }
10091 } else {
10092 for (i = 0; i < frameCount4; ++i) {
10093 drflac_uint32 temp0L;
10094 drflac_uint32 temp1L;
10095 drflac_uint32 temp2L;
10096 drflac_uint32 temp3L;
10097 drflac_uint32 temp0R;
10098 drflac_uint32 temp1R;
10099 drflac_uint32 temp2R;
10100 drflac_uint32 temp3R;
10101
10102 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10103 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10104 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10105 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10106
10107 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10108 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10109 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10110 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10111
10112 mid0 = (mid0 << 1) | (side0 & 0x01);
10113 mid1 = (mid1 << 1) | (side1 & 0x01);
10114 mid2 = (mid2 << 1) | (side2 & 0x01);
10115 mid3 = (mid3 << 1) | (side3 & 0x01);
10116
10117 temp0L = ((drflac_int32)(mid0 + side0) >> 1);
10118 temp1L = ((drflac_int32)(mid1 + side1) >> 1);
10119 temp2L = ((drflac_int32)(mid2 + side2) >> 1);
10120 temp3L = ((drflac_int32)(mid3 + side3) >> 1);
10121
10122 temp0R = ((drflac_int32)(mid0 - side0) >> 1);
10123 temp1R = ((drflac_int32)(mid1 - side1) >> 1);
10124 temp2R = ((drflac_int32)(mid2 - side2) >> 1);
10125 temp3R = ((drflac_int32)(mid3 - side3) >> 1);
10126
10127 temp0L >>= 16;
10128 temp1L >>= 16;
10129 temp2L >>= 16;
10130 temp3L >>= 16;
10131
10132 temp0R >>= 16;
10133 temp1R >>= 16;
10134 temp2R >>= 16;
10135 temp3R >>= 16;
10136
10137 pOutputSamples[i*8+0] = (drflac_int16)temp0L;
10138 pOutputSamples[i*8+1] = (drflac_int16)temp0R;
10139 pOutputSamples[i*8+2] = (drflac_int16)temp1L;
10140 pOutputSamples[i*8+3] = (drflac_int16)temp1R;
10141 pOutputSamples[i*8+4] = (drflac_int16)temp2L;
10142 pOutputSamples[i*8+5] = (drflac_int16)temp2R;
10143 pOutputSamples[i*8+6] = (drflac_int16)temp3L;
10144 pOutputSamples[i*8+7] = (drflac_int16)temp3R;
10145 }
10146 }
10147
10148 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10149 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10150 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10151
10152 mid = (mid << 1) | (side & 0x01);
10153
10154 pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
10155 pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
10156 }
10157 }
10158
10159 #if defined(DRFLAC_SUPPORT_SSE2)
10160 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)
10161 {
10162 drflac_uint64 i;
10163 drflac_uint64 frameCount4 = frameCount >> 2;
10164 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10165 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10166 drflac_uint32 shift = unusedBitsPerSample;
10167
10168 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10169
10170 if (shift == 0) {
10171 for (i = 0; i < frameCount4; ++i) {
10172 __m128i mid;
10173 __m128i side;
10174 __m128i left;
10175 __m128i right;
10176
10177 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10178 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10179
10180 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
10181
10182 left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
10183 right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
10184
10185 left = _mm_srai_epi32(left, 16);
10186 right = _mm_srai_epi32(right, 16);
10187
10188 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
10189 }
10190
10191 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10192 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10193 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10194
10195 mid = (mid << 1) | (side & 0x01);
10196
10197 pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
10198 pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
10199 }
10200 } else {
10201 shift -= 1;
10202 for (i = 0; i < frameCount4; ++i) {
10203 __m128i mid;
10204 __m128i side;
10205 __m128i left;
10206 __m128i right;
10207
10208 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10209 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10210
10211 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
10212
10213 left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
10214 right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
10215
10216 left = _mm_srai_epi32(left, 16);
10217 right = _mm_srai_epi32(right, 16);
10218
10219 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
10220 }
10221
10222 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10223 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10224 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10225
10226 mid = (mid << 1) | (side & 0x01);
10227
10228 pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
10229 pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
10230 }
10231 }
10232 }
10233 #endif
10234
10235 #if defined(DRFLAC_SUPPORT_NEON)
10236 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)
10237 {
10238 drflac_uint64 i;
10239 drflac_uint64 frameCount4 = frameCount >> 2;
10240 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10241 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10242 drflac_uint32 shift = unusedBitsPerSample;
10243 int32x4_t wbpsShift0_4; /* wbps = Wasted Bits Per Sample */
10244 int32x4_t wbpsShift1_4; /* wbps = Wasted Bits Per Sample */
10245
10246 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10247
10248 wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10249 wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10250
10251 if (shift == 0) {
10252 for (i = 0; i < frameCount4; ++i) {
10253 uint32x4_t mid;
10254 uint32x4_t side;
10255 int32x4_t left;
10256 int32x4_t right;
10257
10258 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
10259 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
10260
10261 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
10262
10263 left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
10264 right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
10265
10266 left = vshrq_n_s32(left, 16);
10267 right = vshrq_n_s32(right, 16);
10268
10269 drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
10270 }
10271
10272 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10273 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10274 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10275
10276 mid = (mid << 1) | (side & 0x01);
10277
10278 pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
10279 pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
10280 }
10281 } else {
10282 int32x4_t shift4;
10283
10284 shift -= 1;
10285 shift4 = vdupq_n_s32(shift);
10286
10287 for (i = 0; i < frameCount4; ++i) {
10288 uint32x4_t mid;
10289 uint32x4_t side;
10290 int32x4_t left;
10291 int32x4_t right;
10292
10293 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
10294 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
10295
10296 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
10297
10298 left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
10299 right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
10300
10301 left = vshrq_n_s32(left, 16);
10302 right = vshrq_n_s32(right, 16);
10303
10304 drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
10305 }
10306
10307 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10308 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10309 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10310
10311 mid = (mid << 1) | (side & 0x01);
10312
10313 pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
10314 pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
10315 }
10316 }
10317 }
10318 #endif
10319
10320 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)
10321 {
10322 #if defined(DRFLAC_SUPPORT_SSE2)
10323 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10324 drflac_read_pcm_frames_s16__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10325 } else
10326 #elif defined(DRFLAC_SUPPORT_NEON)
10327 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10328 drflac_read_pcm_frames_s16__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10329 } else
10330 #endif
10331 {
10332 /* Scalar fallback. */
10333 #if 0
10334 drflac_read_pcm_frames_s16__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10335 #else
10336 drflac_read_pcm_frames_s16__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10337 #endif
10338 }
10339 }
10340
10341
10342 #if 0
10343 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)
10344 {
10345 for (drflac_uint64 i = 0; i < frameCount; ++i) {
10346 pOutputSamples[i*2+0] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) >> 16);
10347 pOutputSamples[i*2+1] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) >> 16);
10348 }
10349 }
10350 #endif
10351
10352 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)
10353 {
10354 drflac_uint64 i;
10355 drflac_uint64 frameCount4 = frameCount >> 2;
10356 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10357 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10358 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10359 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10360
10361 for (i = 0; i < frameCount4; ++i) {
10362 drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
10363 drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
10364 drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
10365 drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
10366
10367 drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
10368 drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
10369 drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
10370 drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
10371
10372 tempL0 >>= 16;
10373 tempL1 >>= 16;
10374 tempL2 >>= 16;
10375 tempL3 >>= 16;
10376
10377 tempR0 >>= 16;
10378 tempR1 >>= 16;
10379 tempR2 >>= 16;
10380 tempR3 >>= 16;
10381
10382 pOutputSamples[i*8+0] = (drflac_int16)tempL0;
10383 pOutputSamples[i*8+1] = (drflac_int16)tempR0;
10384 pOutputSamples[i*8+2] = (drflac_int16)tempL1;
10385 pOutputSamples[i*8+3] = (drflac_int16)tempR1;
10386 pOutputSamples[i*8+4] = (drflac_int16)tempL2;
10387 pOutputSamples[i*8+5] = (drflac_int16)tempR2;
10388 pOutputSamples[i*8+6] = (drflac_int16)tempL3;
10389 pOutputSamples[i*8+7] = (drflac_int16)tempR3;
10390 }
10391
10392 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10393 pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
10394 pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
10395 }
10396 }
10397
10398 #if defined(DRFLAC_SUPPORT_SSE2)
10399 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)
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 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10406 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10407
10408 for (i = 0; i < frameCount4; ++i) {
10409 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
10410 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
10411
10412 left = _mm_srai_epi32(left, 16);
10413 right = _mm_srai_epi32(right, 16);
10414
10415 /* 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. */
10416 _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
10417 }
10418
10419 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10420 pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
10421 pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
10422 }
10423 }
10424 #endif
10425
10426 #if defined(DRFLAC_SUPPORT_NEON)
10427 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)
10428 {
10429 drflac_uint64 i;
10430 drflac_uint64 frameCount4 = frameCount >> 2;
10431 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10432 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10433 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10434 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10435
10436 int32x4_t shift0_4 = vdupq_n_s32(shift0);
10437 int32x4_t shift1_4 = vdupq_n_s32(shift1);
10438
10439 for (i = 0; i < frameCount4; ++i) {
10440 int32x4_t left;
10441 int32x4_t right;
10442
10443 left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
10444 right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
10445
10446 left = vshrq_n_s32(left, 16);
10447 right = vshrq_n_s32(right, 16);
10448
10449 drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
10450 }
10451
10452 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10453 pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
10454 pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
10455 }
10456 }
10457 #endif
10458
10459 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)
10460 {
10461 #if defined(DRFLAC_SUPPORT_SSE2)
10462 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10463 drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10464 } else
10465 #elif defined(DRFLAC_SUPPORT_NEON)
10466 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10467 drflac_read_pcm_frames_s16__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10468 } else
10469 #endif
10470 {
10471 /* Scalar fallback. */
10472 #if 0
10473 drflac_read_pcm_frames_s16__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10474 #else
10475 drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10476 #endif
10477 }
10478 }
10479
10480 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut)
10481 {
10482 drflac_uint64 framesRead;
10483 drflac_uint32 unusedBitsPerSample;
10484
10485 if (pFlac == NULL || framesToRead == 0) {
10486 return 0;
10487 }
10488
10489 if (pBufferOut == NULL) {
10490 return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
10491 }
10492
10493 DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
10494 unusedBitsPerSample = 32 - pFlac->bitsPerSample;
10495
10496 framesRead = 0;
10497 while (framesToRead > 0) {
10498 /* If we've run out of samples in this frame, go to the next. */
10499 if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
10500 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
10501 break; /* Couldn't read the next frame, so just break from the loop and return. */
10502 }
10503 } else {
10504 unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
10505 drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
10506 drflac_uint64 frameCountThisIteration = framesToRead;
10507
10508 if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
10509 frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
10510 }
10511
10512 if (channelCount == 2) {
10513 const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
10514 const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
10515
10516 switch (pFlac->currentFLACFrame.header.channelAssignment)
10517 {
10518 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
10519 {
10520 drflac_read_pcm_frames_s16__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
10521 } break;
10522
10523 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
10524 {
10525 drflac_read_pcm_frames_s16__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
10526 } break;
10527
10528 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
10529 {
10530 drflac_read_pcm_frames_s16__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
10531 } break;
10532
10533 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
10534 default:
10535 {
10536 drflac_read_pcm_frames_s16__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
10537 } break;
10538 }
10539 } else {
10540 /* Generic interleaving. */
10541 drflac_uint64 i;
10542 for (i = 0; i < frameCountThisIteration; ++i) {
10543 unsigned int j;
10544 for (j = 0; j < channelCount; ++j) {
10545 drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
10546 pBufferOut[(i*channelCount)+j] = (drflac_int16)(sampleS32 >> 16);
10547 }
10548 }
10549 }
10550
10551 framesRead += frameCountThisIteration;
10552 pBufferOut += frameCountThisIteration * channelCount;
10553 framesToRead -= frameCountThisIteration;
10554 pFlac->currentPCMFrame += frameCountThisIteration;
10555 pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
10556 }
10557 }
10558
10559 return framesRead;
10560 }
10561
10562
10563 #if 0
10564 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)
10565 {
10566 drflac_uint64 i;
10567 for (i = 0; i < frameCount; ++i) {
10568 drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10569 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10570 drflac_uint32 right = left - side;
10571
10572 pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0);
10573 pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
10574 }
10575 }
10576 #endif
10577
10578 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)
10579 {
10580 drflac_uint64 i;
10581 drflac_uint64 frameCount4 = frameCount >> 2;
10582 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10583 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10584 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10585 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10586
10587 float factor = 1 / 2147483648.0;
10588
10589 for (i = 0; i < frameCount4; ++i) {
10590 drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
10591 drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
10592 drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
10593 drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
10594
10595 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
10596 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
10597 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
10598 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
10599
10600 drflac_uint32 right0 = left0 - side0;
10601 drflac_uint32 right1 = left1 - side1;
10602 drflac_uint32 right2 = left2 - side2;
10603 drflac_uint32 right3 = left3 - side3;
10604
10605 pOutputSamples[i*8+0] = (drflac_int32)left0 * factor;
10606 pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
10607 pOutputSamples[i*8+2] = (drflac_int32)left1 * factor;
10608 pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
10609 pOutputSamples[i*8+4] = (drflac_int32)left2 * factor;
10610 pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
10611 pOutputSamples[i*8+6] = (drflac_int32)left3 * factor;
10612 pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
10613 }
10614
10615 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10616 drflac_uint32 left = pInputSamples0U32[i] << shift0;
10617 drflac_uint32 side = pInputSamples1U32[i] << shift1;
10618 drflac_uint32 right = left - side;
10619
10620 pOutputSamples[i*2+0] = (drflac_int32)left * factor;
10621 pOutputSamples[i*2+1] = (drflac_int32)right * factor;
10622 }
10623 }
10624
10625 #if defined(DRFLAC_SUPPORT_SSE2)
10626 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)
10627 {
10628 drflac_uint64 i;
10629 drflac_uint64 frameCount4 = frameCount >> 2;
10630 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10631 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10632 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
10633 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
10634 __m128 factor;
10635
10636 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10637
10638 factor = _mm_set1_ps(1.0f / 8388608.0f);
10639
10640 for (i = 0; i < frameCount4; ++i) {
10641 __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
10642 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
10643 __m128i right = _mm_sub_epi32(left, side);
10644 __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
10645 __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
10646
10647 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
10648 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
10649 }
10650
10651 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10652 drflac_uint32 left = pInputSamples0U32[i] << shift0;
10653 drflac_uint32 side = pInputSamples1U32[i] << shift1;
10654 drflac_uint32 right = left - side;
10655
10656 pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
10657 pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
10658 }
10659 }
10660 #endif
10661
10662 #if defined(DRFLAC_SUPPORT_NEON)
10663 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)
10664 {
10665 drflac_uint64 i;
10666 drflac_uint64 frameCount4 = frameCount >> 2;
10667 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10668 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10669 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
10670 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
10671 float32x4_t factor4;
10672 int32x4_t shift0_4;
10673 int32x4_t shift1_4;
10674
10675 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10676
10677 factor4 = vdupq_n_f32(1.0f / 8388608.0f);
10678 shift0_4 = vdupq_n_s32(shift0);
10679 shift1_4 = vdupq_n_s32(shift1);
10680
10681 for (i = 0; i < frameCount4; ++i) {
10682 uint32x4_t left;
10683 uint32x4_t side;
10684 uint32x4_t right;
10685 float32x4_t leftf;
10686 float32x4_t rightf;
10687
10688 left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
10689 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
10690 right = vsubq_u32(left, side);
10691 leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
10692 rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
10693
10694 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
10695 }
10696
10697 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10698 drflac_uint32 left = pInputSamples0U32[i] << shift0;
10699 drflac_uint32 side = pInputSamples1U32[i] << shift1;
10700 drflac_uint32 right = left - side;
10701
10702 pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
10703 pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
10704 }
10705 }
10706 #endif
10707
10708 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)
10709 {
10710 #if defined(DRFLAC_SUPPORT_SSE2)
10711 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10712 drflac_read_pcm_frames_f32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10713 } else
10714 #elif defined(DRFLAC_SUPPORT_NEON)
10715 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10716 drflac_read_pcm_frames_f32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10717 } else
10718 #endif
10719 {
10720 /* Scalar fallback. */
10721 #if 0
10722 drflac_read_pcm_frames_f32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10723 #else
10724 drflac_read_pcm_frames_f32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10725 #endif
10726 }
10727 }
10728
10729
10730 #if 0
10731 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)
10732 {
10733 drflac_uint64 i;
10734 for (i = 0; i < frameCount; ++i) {
10735 drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
10736 drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
10737 drflac_uint32 left = right + side;
10738
10739 pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0);
10740 pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
10741 }
10742 }
10743 #endif
10744
10745 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)
10746 {
10747 drflac_uint64 i;
10748 drflac_uint64 frameCount4 = frameCount >> 2;
10749 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10750 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10751 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10752 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10753 float factor = 1 / 2147483648.0;
10754
10755 for (i = 0; i < frameCount4; ++i) {
10756 drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
10757 drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
10758 drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
10759 drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
10760
10761 drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
10762 drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
10763 drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
10764 drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
10765
10766 drflac_uint32 left0 = right0 + side0;
10767 drflac_uint32 left1 = right1 + side1;
10768 drflac_uint32 left2 = right2 + side2;
10769 drflac_uint32 left3 = right3 + side3;
10770
10771 pOutputSamples[i*8+0] = (drflac_int32)left0 * factor;
10772 pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
10773 pOutputSamples[i*8+2] = (drflac_int32)left1 * factor;
10774 pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
10775 pOutputSamples[i*8+4] = (drflac_int32)left2 * factor;
10776 pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
10777 pOutputSamples[i*8+6] = (drflac_int32)left3 * factor;
10778 pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
10779 }
10780
10781 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10782 drflac_uint32 side = pInputSamples0U32[i] << shift0;
10783 drflac_uint32 right = pInputSamples1U32[i] << shift1;
10784 drflac_uint32 left = right + side;
10785
10786 pOutputSamples[i*2+0] = (drflac_int32)left * factor;
10787 pOutputSamples[i*2+1] = (drflac_int32)right * factor;
10788 }
10789 }
10790
10791 #if defined(DRFLAC_SUPPORT_SSE2)
10792 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)
10793 {
10794 drflac_uint64 i;
10795 drflac_uint64 frameCount4 = frameCount >> 2;
10796 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10797 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10798 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
10799 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
10800 __m128 factor;
10801
10802 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10803
10804 factor = _mm_set1_ps(1.0f / 8388608.0f);
10805
10806 for (i = 0; i < frameCount4; ++i) {
10807 __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
10808 __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
10809 __m128i left = _mm_add_epi32(right, side);
10810 __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
10811 __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
10812
10813 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
10814 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
10815 }
10816
10817 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10818 drflac_uint32 side = pInputSamples0U32[i] << shift0;
10819 drflac_uint32 right = pInputSamples1U32[i] << shift1;
10820 drflac_uint32 left = right + side;
10821
10822 pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
10823 pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
10824 }
10825 }
10826 #endif
10827
10828 #if defined(DRFLAC_SUPPORT_NEON)
10829 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)
10830 {
10831 drflac_uint64 i;
10832 drflac_uint64 frameCount4 = frameCount >> 2;
10833 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10834 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10835 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
10836 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
10837 float32x4_t factor4;
10838 int32x4_t shift0_4;
10839 int32x4_t shift1_4;
10840
10841 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
10842
10843 factor4 = vdupq_n_f32(1.0f / 8388608.0f);
10844 shift0_4 = vdupq_n_s32(shift0);
10845 shift1_4 = vdupq_n_s32(shift1);
10846
10847 for (i = 0; i < frameCount4; ++i) {
10848 uint32x4_t side;
10849 uint32x4_t right;
10850 uint32x4_t left;
10851 float32x4_t leftf;
10852 float32x4_t rightf;
10853
10854 side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
10855 right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
10856 left = vaddq_u32(right, side);
10857 leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
10858 rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
10859
10860 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
10861 }
10862
10863 for (i = (frameCount4 << 2); i < frameCount; ++i) {
10864 drflac_uint32 side = pInputSamples0U32[i] << shift0;
10865 drflac_uint32 right = pInputSamples1U32[i] << shift1;
10866 drflac_uint32 left = right + side;
10867
10868 pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
10869 pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
10870 }
10871 }
10872 #endif
10873
10874 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)
10875 {
10876 #if defined(DRFLAC_SUPPORT_SSE2)
10877 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
10878 drflac_read_pcm_frames_f32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10879 } else
10880 #elif defined(DRFLAC_SUPPORT_NEON)
10881 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
10882 drflac_read_pcm_frames_f32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10883 } else
10884 #endif
10885 {
10886 /* Scalar fallback. */
10887 #if 0
10888 drflac_read_pcm_frames_f32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10889 #else
10890 drflac_read_pcm_frames_f32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
10891 #endif
10892 }
10893 }
10894
10895
10896 #if 0
10897 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)
10898 {
10899 for (drflac_uint64 i = 0; i < frameCount; ++i) {
10900 drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10901 drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10902
10903 mid = (mid << 1) | (side & 0x01);
10904
10905 pOutputSamples[i*2+0] = (float)((((drflac_int32)(mid + side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
10906 pOutputSamples[i*2+1] = (float)((((drflac_int32)(mid - side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
10907 }
10908 }
10909 #endif
10910
10911 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)
10912 {
10913 drflac_uint64 i;
10914 drflac_uint64 frameCount4 = frameCount >> 2;
10915 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
10916 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
10917 drflac_uint32 shift = unusedBitsPerSample;
10918 float factor = 1 / 2147483648.0;
10919
10920 if (shift > 0) {
10921 shift -= 1;
10922 for (i = 0; i < frameCount4; ++i) {
10923 drflac_uint32 temp0L;
10924 drflac_uint32 temp1L;
10925 drflac_uint32 temp2L;
10926 drflac_uint32 temp3L;
10927 drflac_uint32 temp0R;
10928 drflac_uint32 temp1R;
10929 drflac_uint32 temp2R;
10930 drflac_uint32 temp3R;
10931
10932 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10933 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10934 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10935 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10936
10937 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10938 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10939 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10940 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10941
10942 mid0 = (mid0 << 1) | (side0 & 0x01);
10943 mid1 = (mid1 << 1) | (side1 & 0x01);
10944 mid2 = (mid2 << 1) | (side2 & 0x01);
10945 mid3 = (mid3 << 1) | (side3 & 0x01);
10946
10947 temp0L = (mid0 + side0) << shift;
10948 temp1L = (mid1 + side1) << shift;
10949 temp2L = (mid2 + side2) << shift;
10950 temp3L = (mid3 + side3) << shift;
10951
10952 temp0R = (mid0 - side0) << shift;
10953 temp1R = (mid1 - side1) << shift;
10954 temp2R = (mid2 - side2) << shift;
10955 temp3R = (mid3 - side3) << shift;
10956
10957 pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
10958 pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
10959 pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
10960 pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
10961 pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
10962 pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
10963 pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
10964 pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
10965 }
10966 } else {
10967 for (i = 0; i < frameCount4; ++i) {
10968 drflac_uint32 temp0L;
10969 drflac_uint32 temp1L;
10970 drflac_uint32 temp2L;
10971 drflac_uint32 temp3L;
10972 drflac_uint32 temp0R;
10973 drflac_uint32 temp1R;
10974 drflac_uint32 temp2R;
10975 drflac_uint32 temp3R;
10976
10977 drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10978 drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10979 drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10980 drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
10981
10982 drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10983 drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10984 drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10985 drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
10986
10987 mid0 = (mid0 << 1) | (side0 & 0x01);
10988 mid1 = (mid1 << 1) | (side1 & 0x01);
10989 mid2 = (mid2 << 1) | (side2 & 0x01);
10990 mid3 = (mid3 << 1) | (side3 & 0x01);
10991
10992 temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
10993 temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
10994 temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
10995 temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
10996
10997 temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
10998 temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
10999 temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
11000 temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
11001
11002 pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
11003 pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
11004 pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
11005 pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
11006 pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
11007 pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
11008 pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
11009 pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
11010 }
11011 }
11012
11013 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11014 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11015 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11016
11017 mid = (mid << 1) | (side & 0x01);
11018
11019 pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) * factor;
11020 pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) * factor;
11021 }
11022 }
11023
11024 #if defined(DRFLAC_SUPPORT_SSE2)
11025 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)
11026 {
11027 drflac_uint64 i;
11028 drflac_uint64 frameCount4 = frameCount >> 2;
11029 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11030 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11031 drflac_uint32 shift = unusedBitsPerSample - 8;
11032 float factor;
11033 __m128 factor128;
11034
11035 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
11036
11037 factor = 1.0f / 8388608.0f;
11038 factor128 = _mm_set1_ps(factor);
11039
11040 if (shift == 0) {
11041 for (i = 0; i < frameCount4; ++i) {
11042 __m128i mid;
11043 __m128i side;
11044 __m128i tempL;
11045 __m128i tempR;
11046 __m128 leftf;
11047 __m128 rightf;
11048
11049 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
11050 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
11051
11052 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
11053
11054 tempL = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
11055 tempR = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
11056
11057 leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
11058 rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
11059
11060 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
11061 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
11062 }
11063
11064 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11065 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11066 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11067
11068 mid = (mid << 1) | (side & 0x01);
11069
11070 pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
11071 pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
11072 }
11073 } else {
11074 shift -= 1;
11075 for (i = 0; i < frameCount4; ++i) {
11076 __m128i mid;
11077 __m128i side;
11078 __m128i tempL;
11079 __m128i tempR;
11080 __m128 leftf;
11081 __m128 rightf;
11082
11083 mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
11084 side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
11085
11086 mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
11087
11088 tempL = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
11089 tempR = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
11090
11091 leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
11092 rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
11093
11094 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
11095 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
11096 }
11097
11098 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11099 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11100 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11101
11102 mid = (mid << 1) | (side & 0x01);
11103
11104 pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
11105 pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
11106 }
11107 }
11108 }
11109 #endif
11110
11111 #if defined(DRFLAC_SUPPORT_NEON)
11112 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)
11113 {
11114 drflac_uint64 i;
11115 drflac_uint64 frameCount4 = frameCount >> 2;
11116 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11117 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11118 drflac_uint32 shift = unusedBitsPerSample - 8;
11119 float factor;
11120 float32x4_t factor4;
11121 int32x4_t shift4;
11122 int32x4_t wbps0_4; /* Wasted Bits Per Sample */
11123 int32x4_t wbps1_4; /* Wasted Bits Per Sample */
11124
11125 DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
11126
11127 factor = 1.0f / 8388608.0f;
11128 factor4 = vdupq_n_f32(factor);
11129 wbps0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
11130 wbps1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
11131
11132 if (shift == 0) {
11133 for (i = 0; i < frameCount4; ++i) {
11134 int32x4_t lefti;
11135 int32x4_t righti;
11136 float32x4_t leftf;
11137 float32x4_t rightf;
11138
11139 uint32x4_t mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
11140 uint32x4_t side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
11141
11142 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
11143
11144 lefti = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
11145 righti = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
11146
11147 leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
11148 rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
11149
11150 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
11151 }
11152
11153 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11154 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11155 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11156
11157 mid = (mid << 1) | (side & 0x01);
11158
11159 pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
11160 pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
11161 }
11162 } else {
11163 shift -= 1;
11164 shift4 = vdupq_n_s32(shift);
11165 for (i = 0; i < frameCount4; ++i) {
11166 uint32x4_t mid;
11167 uint32x4_t side;
11168 int32x4_t lefti;
11169 int32x4_t righti;
11170 float32x4_t leftf;
11171 float32x4_t rightf;
11172
11173 mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
11174 side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
11175
11176 mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
11177
11178 lefti = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
11179 righti = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
11180
11181 leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
11182 rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
11183
11184 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
11185 }
11186
11187 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11188 drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11189 drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11190
11191 mid = (mid << 1) | (side & 0x01);
11192
11193 pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
11194 pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
11195 }
11196 }
11197 }
11198 #endif
11199
11200 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)
11201 {
11202 #if defined(DRFLAC_SUPPORT_SSE2)
11203 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
11204 drflac_read_pcm_frames_f32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11205 } else
11206 #elif defined(DRFLAC_SUPPORT_NEON)
11207 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
11208 drflac_read_pcm_frames_f32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11209 } else
11210 #endif
11211 {
11212 /* Scalar fallback. */
11213 #if 0
11214 drflac_read_pcm_frames_f32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11215 #else
11216 drflac_read_pcm_frames_f32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11217 #endif
11218 }
11219 }
11220
11221 #if 0
11222 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)
11223 {
11224 for (drflac_uint64 i = 0; i < frameCount; ++i) {
11225 pOutputSamples[i*2+0] = (float)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) / 2147483648.0);
11226 pOutputSamples[i*2+1] = (float)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) / 2147483648.0);
11227 }
11228 }
11229 #endif
11230
11231 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)
11232 {
11233 drflac_uint64 i;
11234 drflac_uint64 frameCount4 = frameCount >> 2;
11235 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11236 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11237 drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
11238 drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
11239 float factor = 1 / 2147483648.0;
11240
11241 for (i = 0; i < frameCount4; ++i) {
11242 drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
11243 drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
11244 drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
11245 drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
11246
11247 drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
11248 drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
11249 drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
11250 drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
11251
11252 pOutputSamples[i*8+0] = (drflac_int32)tempL0 * factor;
11253 pOutputSamples[i*8+1] = (drflac_int32)tempR0 * factor;
11254 pOutputSamples[i*8+2] = (drflac_int32)tempL1 * factor;
11255 pOutputSamples[i*8+3] = (drflac_int32)tempR1 * factor;
11256 pOutputSamples[i*8+4] = (drflac_int32)tempL2 * factor;
11257 pOutputSamples[i*8+5] = (drflac_int32)tempR2 * factor;
11258 pOutputSamples[i*8+6] = (drflac_int32)tempL3 * factor;
11259 pOutputSamples[i*8+7] = (drflac_int32)tempR3 * factor;
11260 }
11261
11262 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11263 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
11264 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
11265 }
11266 }
11267
11268 #if defined(DRFLAC_SUPPORT_SSE2)
11269 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)
11270 {
11271 drflac_uint64 i;
11272 drflac_uint64 frameCount4 = frameCount >> 2;
11273 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11274 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11275 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
11276 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
11277
11278 float factor = 1.0f / 8388608.0f;
11279 __m128 factor128 = _mm_set1_ps(factor);
11280
11281 for (i = 0; i < frameCount4; ++i) {
11282 __m128i lefti;
11283 __m128i righti;
11284 __m128 leftf;
11285 __m128 rightf;
11286
11287 lefti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
11288 righti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
11289
11290 leftf = _mm_mul_ps(_mm_cvtepi32_ps(lefti), factor128);
11291 rightf = _mm_mul_ps(_mm_cvtepi32_ps(righti), factor128);
11292
11293 _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
11294 _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
11295 }
11296
11297 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11298 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
11299 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
11300 }
11301 }
11302 #endif
11303
11304 #if defined(DRFLAC_SUPPORT_NEON)
11305 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)
11306 {
11307 drflac_uint64 i;
11308 drflac_uint64 frameCount4 = frameCount >> 2;
11309 const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
11310 const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
11311 drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
11312 drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
11313
11314 float factor = 1.0f / 8388608.0f;
11315 float32x4_t factor4 = vdupq_n_f32(factor);
11316 int32x4_t shift0_4 = vdupq_n_s32(shift0);
11317 int32x4_t shift1_4 = vdupq_n_s32(shift1);
11318
11319 for (i = 0; i < frameCount4; ++i) {
11320 int32x4_t lefti;
11321 int32x4_t righti;
11322 float32x4_t leftf;
11323 float32x4_t rightf;
11324
11325 lefti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
11326 righti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
11327
11328 leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
11329 rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
11330
11331 drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
11332 }
11333
11334 for (i = (frameCount4 << 2); i < frameCount; ++i) {
11335 pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
11336 pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
11337 }
11338 }
11339 #endif
11340
11341 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)
11342 {
11343 #if defined(DRFLAC_SUPPORT_SSE2)
11344 if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
11345 drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11346 } else
11347 #elif defined(DRFLAC_SUPPORT_NEON)
11348 if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
11349 drflac_read_pcm_frames_f32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11350 } else
11351 #endif
11352 {
11353 /* Scalar fallback. */
11354 #if 0
11355 drflac_read_pcm_frames_f32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11356 #else
11357 drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
11358 #endif
11359 }
11360 }
11361
11362 DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut)
11363 {
11364 drflac_uint64 framesRead;
11365 drflac_uint32 unusedBitsPerSample;
11366
11367 if (pFlac == NULL || framesToRead == 0) {
11368 return 0;
11369 }
11370
11371 if (pBufferOut == NULL) {
11372 return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
11373 }
11374
11375 DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
11376 unusedBitsPerSample = 32 - pFlac->bitsPerSample;
11377
11378 framesRead = 0;
11379 while (framesToRead > 0) {
11380 /* If we've run out of samples in this frame, go to the next. */
11381 if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
11382 if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
11383 break; /* Couldn't read the next frame, so just break from the loop and return. */
11384 }
11385 } else {
11386 unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
11387 drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
11388 drflac_uint64 frameCountThisIteration = framesToRead;
11389
11390 if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
11391 frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
11392 }
11393
11394 if (channelCount == 2) {
11395 const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
11396 const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
11397
11398 switch (pFlac->currentFLACFrame.header.channelAssignment)
11399 {
11400 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
11401 {
11402 drflac_read_pcm_frames_f32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
11403 } break;
11404
11405 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
11406 {
11407 drflac_read_pcm_frames_f32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
11408 } break;
11409
11410 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
11411 {
11412 drflac_read_pcm_frames_f32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
11413 } break;
11414
11415 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
11416 default:
11417 {
11418 drflac_read_pcm_frames_f32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
11419 } break;
11420 }
11421 } else {
11422 /* Generic interleaving. */
11423 drflac_uint64 i;
11424 for (i = 0; i < frameCountThisIteration; ++i) {
11425 unsigned int j;
11426 for (j = 0; j < channelCount; ++j) {
11427 drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
11428 pBufferOut[(i*channelCount)+j] = (float)(sampleS32 / 2147483648.0);
11429 }
11430 }
11431 }
11432
11433 framesRead += frameCountThisIteration;
11434 pBufferOut += frameCountThisIteration * channelCount;
11435 framesToRead -= frameCountThisIteration;
11436 pFlac->currentPCMFrame += frameCountThisIteration;
11437 pFlac->currentFLACFrame.pcmFramesRemaining -= (unsigned int)frameCountThisIteration;
11438 }
11439 }
11440
11441 return framesRead;
11442 }
11443
11444
11445 DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
11446 {
11447 if (pFlac == NULL) {
11448 return DRFLAC_FALSE;
11449 }
11450
11451 /* Don't do anything if we're already on the seek point. */
11452 if (pFlac->currentPCMFrame == pcmFrameIndex) {
11453 return DRFLAC_TRUE;
11454 }
11455
11456 /*
11457 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
11458 when the decoder was opened.
11459 */
11460 if (pFlac->firstFLACFramePosInBytes == 0) {
11461 return DRFLAC_FALSE;
11462 }
11463
11464 if (pcmFrameIndex == 0) {
11465 pFlac->currentPCMFrame = 0;
11466 return drflac__seek_to_first_frame(pFlac);
11467 } else {
11468 drflac_bool32 wasSuccessful = DRFLAC_FALSE;
11469 drflac_uint64 originalPCMFrame = pFlac->currentPCMFrame;
11470
11471 /* Clamp the sample to the end. */
11472 if (pcmFrameIndex > pFlac->totalPCMFrameCount) {
11473 pcmFrameIndex = pFlac->totalPCMFrameCount;
11474 }
11475
11476 /* If the target sample and the current sample are in the same frame we just move the position forward. */
11477 if (pcmFrameIndex > pFlac->currentPCMFrame) {
11478 /* Forward. */
11479 drflac_uint32 offset = (drflac_uint32)(pcmFrameIndex - pFlac->currentPCMFrame);
11480 if (pFlac->currentFLACFrame.pcmFramesRemaining > offset) {
11481 pFlac->currentFLACFrame.pcmFramesRemaining -= offset;
11482 pFlac->currentPCMFrame = pcmFrameIndex;
11483 return DRFLAC_TRUE;
11484 }
11485 } else {
11486 /* Backward. */
11487 drflac_uint32 offsetAbs = (drflac_uint32)(pFlac->currentPCMFrame - pcmFrameIndex);
11488 drflac_uint32 currentFLACFramePCMFrameCount = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
11489 drflac_uint32 currentFLACFramePCMFramesConsumed = currentFLACFramePCMFrameCount - pFlac->currentFLACFrame.pcmFramesRemaining;
11490 if (currentFLACFramePCMFramesConsumed > offsetAbs) {
11491 pFlac->currentFLACFrame.pcmFramesRemaining += offsetAbs;
11492 pFlac->currentPCMFrame = pcmFrameIndex;
11493 return DRFLAC_TRUE;
11494 }
11495 }
11496
11497 /*
11498 Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so
11499 we'll instead use Ogg's natural seeking facility.
11500 */
11501 #ifndef DR_FLAC_NO_OGG
11502 if (pFlac->container == drflac_container_ogg)
11503 {
11504 wasSuccessful = drflac_ogg__seek_to_pcm_frame(pFlac, pcmFrameIndex);
11505 }
11506 else
11507 #endif
11508 {
11509 /* First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower. */
11510 if (/*!wasSuccessful && */!pFlac->_noSeekTableSeek) {
11511 wasSuccessful = drflac__seek_to_pcm_frame__seek_table(pFlac, pcmFrameIndex);
11512 }
11513
11514 #if !defined(DR_FLAC_NO_CRC)
11515 /* Fall back to binary search if seek table seeking fails. This requires the length of the stream to be known. */
11516 if (!wasSuccessful && !pFlac->_noBinarySearchSeek && pFlac->totalPCMFrameCount > 0) {
11517 wasSuccessful = drflac__seek_to_pcm_frame__binary_search(pFlac, pcmFrameIndex);
11518 }
11519 #endif
11520
11521 /* Fall back to brute force if all else fails. */
11522 if (!wasSuccessful && !pFlac->_noBruteForceSeek) {
11523 wasSuccessful = drflac__seek_to_pcm_frame__brute_force(pFlac, pcmFrameIndex);
11524 }
11525 }
11526
11527 if (wasSuccessful) {
11528 pFlac->currentPCMFrame = pcmFrameIndex;
11529 } else {
11530 /* Seek failed. Try putting the decoder back to it's original state. */
11531 if (drflac_seek_to_pcm_frame(pFlac, originalPCMFrame) == DRFLAC_FALSE) {
11532 /* Failed to seek back to the original PCM frame. Fall back to 0. */
11533 drflac_seek_to_pcm_frame(pFlac, 0);
11534 }
11535 }
11536
11537 return wasSuccessful;
11538 }
11539 }
11540
11541
11542
11543 /* High Level APIs */
11544
11545 #if defined(SIZE_MAX)
11546 #define DRFLAC_SIZE_MAX SIZE_MAX
11547 #else
11548 #if defined(DRFLAC_64BIT)
11549 #define DRFLAC_SIZE_MAX ((drflac_uint64)0xFFFFFFFFFFFFFFFF)
11550 #else
11551 #define DRFLAC_SIZE_MAX 0xFFFFFFFF
11552 #endif
11553 #endif
11554
11555
11556 /* Using a macro as the definition of the drflac__full_decode_and_close_*() API family. Sue me. */
11557 #define DRFLAC_DEFINE_FULL_READ_AND_CLOSE(extension, type) \
11558 static type* drflac__full_read_and_close_ ## extension (drflac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut)\
11559 { \
11560 type* pSampleData = NULL; \
11561 drflac_uint64 totalPCMFrameCount; \
11562 \
11563 DRFLAC_ASSERT(pFlac != NULL); \
11564 \
11565 totalPCMFrameCount = pFlac->totalPCMFrameCount; \
11566 \
11567 if (totalPCMFrameCount == 0) { \
11568 type buffer[4096]; \
11569 drflac_uint64 pcmFramesRead; \
11570 size_t sampleDataBufferSize = sizeof(buffer); \
11571 \
11572 pSampleData = (type*)drflac__malloc_from_callbacks(sampleDataBufferSize, &pFlac->allocationCallbacks); \
11573 if (pSampleData == NULL) { \
11574 goto on_error; \
11575 } \
11576 \
11577 while ((pcmFramesRead = (drflac_uint64)drflac_read_pcm_frames_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0])/pFlac->channels, buffer)) > 0) { \
11578 if (((totalPCMFrameCount + pcmFramesRead) * pFlac->channels * sizeof(type)) > sampleDataBufferSize) { \
11579 type* pNewSampleData; \
11580 size_t newSampleDataBufferSize; \
11581 \
11582 newSampleDataBufferSize = sampleDataBufferSize * 2; \
11583 pNewSampleData = (type*)drflac__realloc_from_callbacks(pSampleData, newSampleDataBufferSize, sampleDataBufferSize, &pFlac->allocationCallbacks); \
11584 if (pNewSampleData == NULL) { \
11585 drflac__free_from_callbacks(pSampleData, &pFlac->allocationCallbacks); \
11586 goto on_error; \
11587 } \
11588 \
11589 sampleDataBufferSize = newSampleDataBufferSize; \
11590 pSampleData = pNewSampleData; \
11591 } \
11592 \
11593 DRFLAC_COPY_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), buffer, (size_t)(pcmFramesRead*pFlac->channels*sizeof(type))); \
11594 totalPCMFrameCount += pcmFramesRead; \
11595 } \
11596 \
11597 /* At this point everything should be decoded, but we just want to fill the unused part buffer with silence - need to \
11598 protect those ears from random noise! */ \
11599 DRFLAC_ZERO_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), (size_t)(sampleDataBufferSize - totalPCMFrameCount*pFlac->channels*sizeof(type))); \
11600 } else { \
11601 drflac_uint64 dataSize = totalPCMFrameCount*pFlac->channels*sizeof(type); \
11602 if (dataSize > (drflac_uint64)DRFLAC_SIZE_MAX) { \
11603 goto on_error; /* The decoded data is too big. */ \
11604 } \
11605 \
11606 pSampleData = (type*)drflac__malloc_from_callbacks((size_t)dataSize, &pFlac->allocationCallbacks); /* <-- Safe cast as per the check above. */ \
11607 if (pSampleData == NULL) { \
11608 goto on_error; \
11609 } \
11610 \
11611 totalPCMFrameCount = drflac_read_pcm_frames_##extension(pFlac, pFlac->totalPCMFrameCount, pSampleData); \
11612 } \
11613 \
11614 if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \
11615 if (channelsOut) *channelsOut = pFlac->channels; \
11616 if (totalPCMFrameCountOut) *totalPCMFrameCountOut = totalPCMFrameCount; \
11617 \
11618 drflac_close(pFlac); \
11619 return pSampleData; \
11620 \
11621 on_error: \
11622 drflac_close(pFlac); \
11623 return NULL; \
11624 }
11625
11626 DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s32, drflac_int32)
11627 DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s16, drflac_int16)
11628 DRFLAC_DEFINE_FULL_READ_AND_CLOSE(f32, float)
11629
11630 DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
11631 {
11632 drflac* pFlac;
11633
11634 if (channelsOut) {
11635 *channelsOut = 0;
11636 }
11637 if (sampleRateOut) {
11638 *sampleRateOut = 0;
11639 }
11640 if (totalPCMFrameCountOut) {
11641 *totalPCMFrameCountOut = 0;
11642 }
11643
11644 pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
11645 if (pFlac == NULL) {
11646 return NULL;
11647 }
11648
11649 return drflac__full_read_and_close_s32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
11650 }
11651
11652 DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
11653 {
11654 drflac* pFlac;
11655
11656 if (channelsOut) {
11657 *channelsOut = 0;
11658 }
11659 if (sampleRateOut) {
11660 *sampleRateOut = 0;
11661 }
11662 if (totalPCMFrameCountOut) {
11663 *totalPCMFrameCountOut = 0;
11664 }
11665
11666 pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
11667 if (pFlac == NULL) {
11668 return NULL;
11669 }
11670
11671 return drflac__full_read_and_close_s16(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
11672 }
11673
11674 DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
11675 {
11676 drflac* pFlac;
11677
11678 if (channelsOut) {
11679 *channelsOut = 0;
11680 }
11681 if (sampleRateOut) {
11682 *sampleRateOut = 0;
11683 }
11684 if (totalPCMFrameCountOut) {
11685 *totalPCMFrameCountOut = 0;
11686 }
11687
11688 pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
11689 if (pFlac == NULL) {
11690 return NULL;
11691 }
11692
11693 return drflac__full_read_and_close_f32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
11694 }
11695
11696 #ifndef DR_FLAC_NO_STDIO
11697 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)
11698 {
11699 drflac* pFlac;
11700
11701 if (sampleRate) {
11702 *sampleRate = 0;
11703 }
11704 if (channels) {
11705 *channels = 0;
11706 }
11707 if (totalPCMFrameCount) {
11708 *totalPCMFrameCount = 0;
11709 }
11710
11711 pFlac = drflac_open_file(filename, pAllocationCallbacks);
11712 if (pFlac == NULL) {
11713 return NULL;
11714 }
11715
11716 return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
11717 }
11718
11719 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)
11720 {
11721 drflac* pFlac;
11722
11723 if (sampleRate) {
11724 *sampleRate = 0;
11725 }
11726 if (channels) {
11727 *channels = 0;
11728 }
11729 if (totalPCMFrameCount) {
11730 *totalPCMFrameCount = 0;
11731 }
11732
11733 pFlac = drflac_open_file(filename, pAllocationCallbacks);
11734 if (pFlac == NULL) {
11735 return NULL;
11736 }
11737
11738 return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
11739 }
11740
11741 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)
11742 {
11743 drflac* pFlac;
11744
11745 if (sampleRate) {
11746 *sampleRate = 0;
11747 }
11748 if (channels) {
11749 *channels = 0;
11750 }
11751 if (totalPCMFrameCount) {
11752 *totalPCMFrameCount = 0;
11753 }
11754
11755 pFlac = drflac_open_file(filename, pAllocationCallbacks);
11756 if (pFlac == NULL) {
11757 return NULL;
11758 }
11759
11760 return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
11761 }
11762 #endif
11763
11764 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)
11765 {
11766 drflac* pFlac;
11767
11768 if (sampleRate) {
11769 *sampleRate = 0;
11770 }
11771 if (channels) {
11772 *channels = 0;
11773 }
11774 if (totalPCMFrameCount) {
11775 *totalPCMFrameCount = 0;
11776 }
11777
11778 pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
11779 if (pFlac == NULL) {
11780 return NULL;
11781 }
11782
11783 return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
11784 }
11785
11786 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)
11787 {
11788 drflac* pFlac;
11789
11790 if (sampleRate) {
11791 *sampleRate = 0;
11792 }
11793 if (channels) {
11794 *channels = 0;
11795 }
11796 if (totalPCMFrameCount) {
11797 *totalPCMFrameCount = 0;
11798 }
11799
11800 pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
11801 if (pFlac == NULL) {
11802 return NULL;
11803 }
11804
11805 return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
11806 }
11807
11808 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)
11809 {
11810 drflac* pFlac;
11811
11812 if (sampleRate) {
11813 *sampleRate = 0;
11814 }
11815 if (channels) {
11816 *channels = 0;
11817 }
11818 if (totalPCMFrameCount) {
11819 *totalPCMFrameCount = 0;
11820 }
11821
11822 pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
11823 if (pFlac == NULL) {
11824 return NULL;
11825 }
11826
11827 return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
11828 }
11829
11830
11831 DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
11832 {
11833 if (pAllocationCallbacks != NULL) {
11834 drflac__free_from_callbacks(p, pAllocationCallbacks);
11835 } else {
11836 drflac__free_default(p, NULL);
11837 }
11838 }
11839
11840
11841
11842
11843 DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments)
11844 {
11845 if (pIter == NULL) {
11846 return;
11847 }
11848
11849 pIter->countRemaining = commentCount;
11850 pIter->pRunningData = (const char*)pComments;
11851 }
11852
11853 DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut)
11854 {
11855 drflac_int32 length;
11856 const char* pComment;
11857
11858 /* Safety. */
11859 if (pCommentLengthOut) {
11860 *pCommentLengthOut = 0;
11861 }
11862
11863 if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
11864 return NULL;
11865 }
11866
11867 length = drflac__le2host_32_ptr_unaligned(pIter->pRunningData);
11868 pIter->pRunningData += 4;
11869
11870 pComment = pIter->pRunningData;
11871 pIter->pRunningData += length;
11872 pIter->countRemaining -= 1;
11873
11874 if (pCommentLengthOut) {
11875 *pCommentLengthOut = length;
11876 }
11877
11878 return pComment;
11879 }
11880
11881
11882
11883
11884 DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData)
11885 {
11886 if (pIter == NULL) {
11887 return;
11888 }
11889
11890 pIter->countRemaining = trackCount;
11891 pIter->pRunningData = (const char*)pTrackData;
11892 }
11893
11894 DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack)
11895 {
11896 drflac_cuesheet_track cuesheetTrack;
11897 const char* pRunningData;
11898 drflac_uint64 offsetHi;
11899 drflac_uint64 offsetLo;
11900
11901 if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
11902 return DRFLAC_FALSE;
11903 }
11904
11905 pRunningData = pIter->pRunningData;
11906
11907 offsetHi = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
11908 offsetLo = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
11909 cuesheetTrack.offset = offsetLo | (offsetHi << 32);
11910 cuesheetTrack.trackNumber = pRunningData[0]; pRunningData += 1;
11911 DRFLAC_COPY_MEMORY(cuesheetTrack.ISRC, pRunningData, sizeof(cuesheetTrack.ISRC)); pRunningData += 12;
11912 cuesheetTrack.isAudio = (pRunningData[0] & 0x80) != 0;
11913 cuesheetTrack.preEmphasis = (pRunningData[0] & 0x40) != 0; pRunningData += 14;
11914 cuesheetTrack.indexCount = pRunningData[0]; pRunningData += 1;
11915 cuesheetTrack.pIndexPoints = (const drflac_cuesheet_track_index*)pRunningData; pRunningData += cuesheetTrack.indexCount * sizeof(drflac_cuesheet_track_index);
11916
11917 pIter->pRunningData = pRunningData;
11918 pIter->countRemaining -= 1;
11919
11920 if (pCuesheetTrack) {
11921 *pCuesheetTrack = cuesheetTrack;
11922 }
11923
11924 return DRFLAC_TRUE;
11925 }
11926
11927 #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
11928 #pragma GCC diagnostic pop
11929 #endif
11930 #endif /* dr_flac_c */
11931 #endif /* DR_FLAC_IMPLEMENTATION */
11932
11933
11934 /*
11935 REVISION HISTORY
11936 ================
11937 v0.12.38 - 2022-04-10
11938 - Fix compilation error on older versions of GCC.
11939
11940 v0.12.37 - 2022-02-12
11941 - Improve ARM detection.
11942
11943 v0.12.36 - 2022-02-07
11944 - Fix a compilation error with the ARM build.
11945
11946 v0.12.35 - 2022-02-06
11947 - Fix a bug due to underestimating the amount of precision required for the prediction stage.
11948 - Fix some bugs found from fuzz testing.
11949
11950 v0.12.34 - 2022-01-07
11951 - Fix some misalignment bugs when reading metadata.
11952
11953 v0.12.33 - 2021-12-22
11954 - Fix a bug with seeking when the seek table does not start at PCM frame 0.
11955
11956 v0.12.32 - 2021-12-11
11957 - Fix a warning with Clang.
11958
11959 v0.12.31 - 2021-08-16
11960 - Silence some warnings.
11961
11962 v0.12.30 - 2021-07-31
11963 - Fix platform detection for ARM64.
11964
11965 v0.12.29 - 2021-04-02
11966 - Fix a bug where the running PCM frame index is set to an invalid value when over-seeking.
11967 - Fix a decoding error due to an incorrect validation check.
11968
11969 v0.12.28 - 2021-02-21
11970 - Fix a warning due to referencing _MSC_VER when it is undefined.
11971
11972 v0.12.27 - 2021-01-31
11973 - Fix a static analysis warning.
11974
11975 v0.12.26 - 2021-01-17
11976 - Fix a compilation warning due to _BSD_SOURCE being deprecated.
11977
11978 v0.12.25 - 2020-12-26
11979 - Update documentation.
11980
11981 v0.12.24 - 2020-11-29
11982 - Fix ARM64/NEON detection when compiling with MSVC.
11983
11984 v0.12.23 - 2020-11-21
11985 - Fix compilation with OpenWatcom.
11986
11987 v0.12.22 - 2020-11-01
11988 - Fix an error with the previous release.
11989
11990 v0.12.21 - 2020-11-01
11991 - Fix a possible deadlock when seeking.
11992 - Improve compiler support for older versions of GCC.
11993
11994 v0.12.20 - 2020-09-08
11995 - Fix a compilation error on older compilers.
11996
11997 v0.12.19 - 2020-08-30
11998 - Fix a bug due to an undefined 32-bit shift.
11999
12000 v0.12.18 - 2020-08-14
12001 - Fix a crash when compiling with clang-cl.
12002
12003 v0.12.17 - 2020-08-02
12004 - Simplify sized types.
12005
12006 v0.12.16 - 2020-07-25
12007 - Fix a compilation warning.
12008
12009 v0.12.15 - 2020-07-06
12010 - Check for negative LPC shifts and return an error.
12011
12012 v0.12.14 - 2020-06-23
12013 - Add include guard for the implementation section.
12014
12015 v0.12.13 - 2020-05-16
12016 - Add compile-time and run-time version querying.
12017 - DRFLAC_VERSION_MINOR
12018 - DRFLAC_VERSION_MAJOR
12019 - DRFLAC_VERSION_REVISION
12020 - DRFLAC_VERSION_STRING
12021 - drflac_version()
12022 - drflac_version_string()
12023
12024 v0.12.12 - 2020-04-30
12025 - Fix compilation errors with VC6.
12026
12027 v0.12.11 - 2020-04-19
12028 - Fix some pedantic warnings.
12029 - Fix some undefined behaviour warnings.
12030
12031 v0.12.10 - 2020-04-10
12032 - Fix some bugs when trying to seek with an invalid seek table.
12033
12034 v0.12.9 - 2020-04-05
12035 - Fix warnings.
12036
12037 v0.12.8 - 2020-04-04
12038 - Add drflac_open_file_w() and drflac_open_file_with_metadata_w().
12039 - Fix some static analysis warnings.
12040 - Minor documentation updates.
12041
12042 v0.12.7 - 2020-03-14
12043 - Fix compilation errors with VC6.
12044
12045 v0.12.6 - 2020-03-07
12046 - Fix compilation error with Visual Studio .NET 2003.
12047
12048 v0.12.5 - 2020-01-30
12049 - Silence some static analysis warnings.
12050
12051 v0.12.4 - 2020-01-29
12052 - Silence some static analysis warnings.
12053
12054 v0.12.3 - 2019-12-02
12055 - Fix some warnings when compiling with GCC and the -Og flag.
12056 - Fix a crash in out-of-memory situations.
12057 - Fix potential integer overflow bug.
12058 - Fix some static analysis warnings.
12059 - Fix a possible crash when using custom memory allocators without a custom realloc() implementation.
12060 - Fix a bug with binary search seeking where the bits per sample is not a multiple of 8.
12061
12062 v0.12.2 - 2019-10-07
12063 - Internal code clean up.
12064
12065 v0.12.1 - 2019-09-29
12066 - Fix some Clang Static Analyzer warnings.
12067 - Fix an unused variable warning.
12068
12069 v0.12.0 - 2019-09-23
12070 - API CHANGE: Add support for user defined memory allocation routines. This system allows the program to specify their own memory allocation
12071 routines with a user data pointer for client-specific contextual data. This adds an extra parameter to the end of the following APIs:
12072 - drflac_open()
12073 - drflac_open_relaxed()
12074 - drflac_open_with_metadata()
12075 - drflac_open_with_metadata_relaxed()
12076 - drflac_open_file()
12077 - drflac_open_file_with_metadata()
12078 - drflac_open_memory()
12079 - drflac_open_memory_with_metadata()
12080 - drflac_open_and_read_pcm_frames_s32()
12081 - drflac_open_and_read_pcm_frames_s16()
12082 - drflac_open_and_read_pcm_frames_f32()
12083 - drflac_open_file_and_read_pcm_frames_s32()
12084 - drflac_open_file_and_read_pcm_frames_s16()
12085 - drflac_open_file_and_read_pcm_frames_f32()
12086 - drflac_open_memory_and_read_pcm_frames_s32()
12087 - drflac_open_memory_and_read_pcm_frames_s16()
12088 - drflac_open_memory_and_read_pcm_frames_f32()
12089 Set this extra parameter to NULL to use defaults which is the same as the previous behaviour. Setting this NULL will use
12090 DRFLAC_MALLOC, DRFLAC_REALLOC and DRFLAC_FREE.
12091 - Remove deprecated APIs:
12092 - drflac_read_s32()
12093 - drflac_read_s16()
12094 - drflac_read_f32()
12095 - drflac_seek_to_sample()
12096 - drflac_open_and_decode_s32()
12097 - drflac_open_and_decode_s16()
12098 - drflac_open_and_decode_f32()
12099 - drflac_open_and_decode_file_s32()
12100 - drflac_open_and_decode_file_s16()
12101 - drflac_open_and_decode_file_f32()
12102 - drflac_open_and_decode_memory_s32()
12103 - drflac_open_and_decode_memory_s16()
12104 - drflac_open_and_decode_memory_f32()
12105 - Remove drflac.totalSampleCount which is now replaced with drflac.totalPCMFrameCount. You can emulate drflac.totalSampleCount
12106 by doing pFlac->totalPCMFrameCount*pFlac->channels.
12107 - Rename drflac.currentFrame to drflac.currentFLACFrame to remove ambiguity with PCM frames.
12108 - Fix errors when seeking to the end of a stream.
12109 - Optimizations to seeking.
12110 - SSE improvements and optimizations.
12111 - ARM NEON optimizations.
12112 - Optimizations to drflac_read_pcm_frames_s16().
12113 - Optimizations to drflac_read_pcm_frames_s32().
12114
12115 v0.11.10 - 2019-06-26
12116 - Fix a compiler error.
12117
12118 v0.11.9 - 2019-06-16
12119 - Silence some ThreadSanitizer warnings.
12120
12121 v0.11.8 - 2019-05-21
12122 - Fix warnings.
12123
12124 v0.11.7 - 2019-05-06
12125 - C89 fixes.
12126
12127 v0.11.6 - 2019-05-05
12128 - Add support for C89.
12129 - Fix a compiler warning when CRC is disabled.
12130 - Change license to choice of public domain or MIT-0.
12131
12132 v0.11.5 - 2019-04-19
12133 - Fix a compiler error with GCC.
12134
12135 v0.11.4 - 2019-04-17
12136 - Fix some warnings with GCC when compiling with -std=c99.
12137
12138 v0.11.3 - 2019-04-07
12139 - Silence warnings with GCC.
12140
12141 v0.11.2 - 2019-03-10
12142 - Fix a warning.
12143
12144 v0.11.1 - 2019-02-17
12145 - Fix a potential bug with seeking.
12146
12147 v0.11.0 - 2018-12-16
12148 - API CHANGE: Deprecated drflac_read_s32(), drflac_read_s16() and drflac_read_f32() and replaced them with
12149 drflac_read_pcm_frames_s32(), drflac_read_pcm_frames_s16() and drflac_read_pcm_frames_f32(). The new APIs take
12150 and return PCM frame counts instead of sample counts. To upgrade you will need to change the input count by
12151 dividing it by the channel count, and then do the same with the return value.
12152 - API_CHANGE: Deprecated drflac_seek_to_sample() and replaced with drflac_seek_to_pcm_frame(). Same rules as
12153 the changes to drflac_read_*() apply.
12154 - API CHANGE: Deprecated drflac_open_and_decode_*() and replaced with drflac_open_*_and_read_*(). Same rules as
12155 the changes to drflac_read_*() apply.
12156 - Optimizations.
12157
12158 v0.10.0 - 2018-09-11
12159 - Remove the DR_FLAC_NO_WIN32_IO option and the Win32 file IO functionality. If you need to use Win32 file IO you
12160 need to do it yourself via the callback API.
12161 - Fix the clang build.
12162 - Fix undefined behavior.
12163 - Fix errors with CUESHEET metdata blocks.
12164 - Add an API for iterating over each cuesheet track in the CUESHEET metadata block. This works the same way as the
12165 Vorbis comment API.
12166 - Other miscellaneous bug fixes, mostly relating to invalid FLAC streams.
12167 - Minor optimizations.
12168
12169 v0.9.11 - 2018-08-29
12170 - Fix a bug with sample reconstruction.
12171
12172 v0.9.10 - 2018-08-07
12173 - Improve 64-bit detection.
12174
12175 v0.9.9 - 2018-08-05
12176 - Fix C++ build on older versions of GCC.
12177
12178 v0.9.8 - 2018-07-24
12179 - Fix compilation errors.
12180
12181 v0.9.7 - 2018-07-05
12182 - Fix a warning.
12183
12184 v0.9.6 - 2018-06-29
12185 - Fix some typos.
12186
12187 v0.9.5 - 2018-06-23
12188 - Fix some warnings.
12189
12190 v0.9.4 - 2018-06-14
12191 - Optimizations to seeking.
12192 - Clean up.
12193
12194 v0.9.3 - 2018-05-22
12195 - Bug fix.
12196
12197 v0.9.2 - 2018-05-12
12198 - Fix a compilation error due to a missing break statement.
12199
12200 v0.9.1 - 2018-04-29
12201 - Fix compilation error with Clang.
12202
12203 v0.9 - 2018-04-24
12204 - Fix Clang build.
12205 - Start using major.minor.revision versioning.
12206
12207 v0.8g - 2018-04-19
12208 - Fix build on non-x86/x64 architectures.
12209
12210 v0.8f - 2018-02-02
12211 - Stop pretending to support changing rate/channels mid stream.
12212
12213 v0.8e - 2018-02-01
12214 - Fix a crash when the block size of a frame is larger than the maximum block size defined by the FLAC stream.
12215 - Fix a crash the the Rice partition order is invalid.
12216
12217 v0.8d - 2017-09-22
12218 - Add support for decoding streams with ID3 tags. ID3 tags are just skipped.
12219
12220 v0.8c - 2017-09-07
12221 - Fix warning on non-x86/x64 architectures.
12222
12223 v0.8b - 2017-08-19
12224 - Fix build on non-x86/x64 architectures.
12225
12226 v0.8a - 2017-08-13
12227 - A small optimization for the Clang build.
12228
12229 v0.8 - 2017-08-12
12230 - API CHANGE: Rename dr_* types to drflac_*.
12231 - Optimizations. This brings dr_flac back to about the same class of efficiency as the reference implementation.
12232 - Add support for custom implementations of malloc(), realloc(), etc.
12233 - Add CRC checking to Ogg encapsulated streams.
12234 - Fix VC++ 6 build. This is only for the C++ compiler. The C compiler is not currently supported.
12235 - Bug fixes.
12236
12237 v0.7 - 2017-07-23
12238 - Add support for opening a stream without a header block. To do this, use drflac_open_relaxed() / drflac_open_with_metadata_relaxed().
12239
12240 v0.6 - 2017-07-22
12241 - Add support for recovering from invalid frames. With this change, dr_flac will simply skip over invalid frames as if they
12242 never existed. Frames are checked against their sync code, the CRC-8 of the frame header and the CRC-16 of the whole frame.
12243
12244 v0.5 - 2017-07-16
12245 - Fix typos.
12246 - Change drflac_bool* types to unsigned.
12247 - Add CRC checking. This makes dr_flac slower, but can be disabled with #define DR_FLAC_NO_CRC.
12248
12249 v0.4f - 2017-03-10
12250 - Fix a couple of bugs with the bitstreaming code.
12251
12252 v0.4e - 2017-02-17
12253 - Fix some warnings.
12254
12255 v0.4d - 2016-12-26
12256 - Add support for 32-bit floating-point PCM decoding.
12257 - Use drflac_int* and drflac_uint* sized types to improve compiler support.
12258 - Minor improvements to documentation.
12259
12260 v0.4c - 2016-12-26
12261 - Add support for signed 16-bit integer PCM decoding.
12262
12263 v0.4b - 2016-10-23
12264 - A minor change to drflac_bool8 and drflac_bool32 types.
12265
12266 v0.4a - 2016-10-11
12267 - Rename drBool32 to drflac_bool32 for styling consistency.
12268
12269 v0.4 - 2016-09-29
12270 - API/ABI CHANGE: Use fixed size 32-bit booleans instead of the built-in bool type.
12271 - API CHANGE: Rename drflac_open_and_decode*() to drflac_open_and_decode*_s32().
12272 - API CHANGE: Swap the order of "channels" and "sampleRate" parameters in drflac_open_and_decode*(). Rationale for this is to
12273 keep it consistent with drflac_audio.
12274
12275 v0.3f - 2016-09-21
12276 - Fix a warning with GCC.
12277
12278 v0.3e - 2016-09-18
12279 - Fixed a bug where GCC 4.3+ was not getting properly identified.
12280 - Fixed a few typos.
12281 - Changed date formats to ISO 8601 (YYYY-MM-DD).
12282
12283 v0.3d - 2016-06-11
12284 - Minor clean up.
12285
12286 v0.3c - 2016-05-28
12287 - Fixed compilation error.
12288
12289 v0.3b - 2016-05-16
12290 - Fixed Linux/GCC build.
12291 - Updated documentation.
12292
12293 v0.3a - 2016-05-15
12294 - Minor fixes to documentation.
12295
12296 v0.3 - 2016-05-11
12297 - Optimizations. Now at about parity with the reference implementation on 32-bit builds.
12298 - Lots of clean up.
12299
12300 v0.2b - 2016-05-10
12301 - Bug fixes.
12302
12303 v0.2a - 2016-05-10
12304 - Made drflac_open_and_decode() more robust.
12305 - Removed an unused debugging variable
12306
12307 v0.2 - 2016-05-09
12308 - Added support for Ogg encapsulation.
12309 - API CHANGE. Have the onSeek callback take a third argument which specifies whether or not the seek
12310 should be relative to the start or the current position. Also changes the seeking rules such that
12311 seeking offsets will never be negative.
12312 - Have drflac_open_and_decode() fail gracefully if the stream has an unknown total sample count.
12313
12314 v0.1b - 2016-05-07
12315 - Properly close the file handle in drflac_open_file() and family when the decoder fails to initialize.
12316 - Removed a stale comment.
12317
12318 v0.1a - 2016-05-05
12319 - Minor formatting changes.
12320 - Fixed a warning on the GCC build.
12321
12322 v0.1 - 2016-05-03
12323 - Initial versioned release.
12324 */
12325
12326 /*
12327 This software is available as a choice of the following licenses. Choose
12328 whichever you prefer.
12329
12330 ===============================================================================
12331 ALTERNATIVE 1 - Public Domain (www.unlicense.org)
12332 ===============================================================================
12333 This is free and unencumbered software released into the public domain.
12334
12335 Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
12336 software, either in source code form or as a compiled binary, for any purpose,
12337 commercial or non-commercial, and by any means.
12338
12339 In jurisdictions that recognize copyright laws, the author or authors of this
12340 software dedicate any and all copyright interest in the software to the public
12341 domain. We make this dedication for the benefit of the public at large and to
12342 the detriment of our heirs and successors. We intend this dedication to be an
12343 overt act of relinquishment in perpetuity of all present and future rights to
12344 this software under copyright law.
12345
12346 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12347 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12348 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12349 AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
12350 ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
12351 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12352
12353 For more information, please refer to <http://unlicense.org/>
12354
12355 ===============================================================================
12356 ALTERNATIVE 2 - MIT No Attribution
12357 ===============================================================================
12358 Copyright 2020 David Reid
12359
12360 Permission is hereby granted, free of charge, to any person obtaining a copy of
12361 this software and associated documentation files (the "Software"), to deal in
12362 the Software without restriction, including without limitation the rights to
12363 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
12364 of the Software, and to permit persons to whom the Software is furnished to do
12365 so.
12366
12367 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12368 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
12369 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
12370 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
12371 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
12372 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
12373 SOFTWARE.
12374 */