1 // FLAC audio decoder. Public domain. See "unlicense" statement at the end of this file. 2 // dr_flac - v0.3d - 11/06/2016 3 // commit eebbf6ed17e9200a48c8f83a350a82722295558f 4 // 5 // David Reid - mackron@gmail.com 6 // 7 // some fixes from v0.4f - 2017-03-10 8 // - Fix a couple of bugs with the bitstreaming code. 9 // 10 // fix from 767c3fbda48f54ce1050afa75110ae69cccdf0dd 11 // 12 // some fixes from v0.8d - 2017-09-22 (actually, one) 13 // k8 SKIPPED: Add support for decoding streams with ID3 tags. ID3 tags are just skipped. 14 // k8: i am absolutely not interested in such fucked flac files, and won't support that idiocy. 15 // 16 // D translation by Ketmar // Invisible Vector 17 module audioformats.drflac; 18 19 nothrow @nogc: 20 version(decodeFLAC): 21 22 23 // USAGE 24 // 25 // dr_flac is a single-file library. 26 // 27 // To decode audio data, do something like the following: 28 // 29 // drflac* pFlac = drflac_open_file("MySong.flac"); 30 // if (pFlac is null) { 31 // // Failed to open FLAC file 32 // } 33 // 34 // int* pSamples = malloc(pFlac.totalSampleCount * (int)).sizeof; 35 // ulong numberOfInterleavedSamplesActuallyRead = drflac_read_s32(pFlac, pFlac.totalSampleCount, pSamples); 36 // 37 // The drflac object represents the decoder. It is a transparent type so all the information you need, such as the number of 38 // channels and the bits per sample, should be directly accessible - just make sure you don't change their values. Samples are 39 // always output as interleaved signed 32-bit PCM. In the example above a native FLAC stream was opened, however dr_flac has 40 // seamless support for Ogg encapsulated FLAC streams as well. 41 // 42 // 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 43 // the decoder will give you as many samples as it can, up to the amount requested. Later on when you need the next batch of 44 // samples, just call it again. Example: 45 // 46 // while (drflac_read_s32(pFlac, chunkSize, pChunkSamples) > 0) { 47 // do_something(); 48 // } 49 // 50 // You can seek to a specific sample with drflac_seek_to_sample(). The given sample is based on interleaving. So for example, 51 // if you were to seek to the sample at index 0 in a stereo stream, you'll be seeking to the first sample of the left channel. 52 // The sample at index 1 will be the first sample of the right channel. The sample at index 2 will be the second sample of the 53 // left channel, etc. 54 // 55 // 56 // If you just want to quickly decode an entire FLAC file in one go you can do something like this: 57 // 58 // uint sampleRate; 59 // uint channels; 60 // ulong totalSampleCount; 61 // int* pSampleData = drflac_open_and_decode_file("MySong.flac", &sampleRate, &channels, &totalSampleCount); 62 // if (pSampleData is null) { 63 // // Failed to open and decode FLAC file. 64 // } 65 // 66 // ... 67 // 68 // drflac_free(pSampleData); 69 // 70 // 71 // If you need access to metadata (album art, etc.), use drflac_open_with_metadata(), drflac_open_file_with_metdata() or 72 // drflac_open_memory_with_metadata(). The rationale for keeping these APIs separate is that they're slightly slower than the 73 // normal versions and also just a little bit harder to use. 74 // 75 // dr_flac reports metadata to the application through the use of a callback, and every metadata block is reported before 76 // drflac_open_with_metdata() returns. See https://github.com/mackron/dr_libs_tests/blob/master/dr_flac/dr_flac_test_2.c for 77 // an example on how to read metadata. 78 // 79 // 80 // 81 // OPTIONS 82 // #define these options before including this file. 83 // 84 // #define DR_FLAC_NO_STDIO 85 // Disable drflac_open_file(). 86 // 87 // #define DR_FLAC_NO_OGG 88 // Disables support for Ogg/FLAC streams. 89 // 90 // #define DR_FLAC_NO_WIN32_IO 91 // In the Win32 build, dr_flac uses the Win32 IO APIs for drflac_open_file() by default. This setting will make it use the 92 // standard FILE APIs instead. Ignored when DR_FLAC_NO_STDIO is #defined. (The rationale for this configuration is that 93 // there's a bug in one compiler's Win32 implementation of the FILE APIs which is not present in the Win32 IO APIs.) 94 // 95 // #define DR_FLAC_BUFFER_SIZE <number> 96 // Defines the size of the internal buffer to store data from onRead(). This buffer is used to reduce the number of calls 97 // back to the client for more data. Larger values means more memory, but better performance. My tests show diminishing 98 // returns after about 4KB (which is the default). Consider reducing this if you have a very efficient implementation of 99 // onRead(), or increase it if it's very inefficient. Must be a multiple of 8. 100 // 101 // 102 // 103 // QUICK NOTES 104 // - Based on my tests, the performance of the 32-bit build is at about parity with the reference implementation. The 64-bit build 105 // is slightly faster. 106 // - dr_flac does not currently do any CRC checks. 107 // - dr_flac should work fine with valid native FLAC files, but for broadcast streams it won't work if the header and STREAMINFO 108 // block is unavailable. 109 // - Audio data is output as signed 32-bit PCM, regardless of the bits per sample the FLAC stream is encoded as. 110 // - This has not been tested on big-endian architectures. 111 // - Rice codes in unencoded binary form (see https://xiph.org/flac/format.html#rice_partition) has not been tested. If anybody 112 // knows where I can find some test files for this, let me know. 113 // - Perverse and erroneous files have not been tested. Again, if you know where I can get some test files let me know. 114 // - dr_flac is not thread-safe, but it's APIs can be called from any thread so long as you do your own synchronization. 115 116 117 static if (is(typeof((){import iv.vfs;}()))) { 118 enum DrFlacHasVFS = true; 119 import iv.vfs; 120 } else { 121 enum DrFlacHasVFS = false; 122 } 123 124 125 // As data is read from the client it is placed into an internal buffer for fast access. This controls the 126 // size of that buffer. Larger values means more speed, but also more memory. In my testing there is diminishing 127 // returns after about 4KB, but you can fiddle with this to suit your own needs. Must be a multiple of 8. 128 static if (!is(typeof(DR_FLAC_BUFFER_SIZE))) enum DR_FLAC_BUFFER_SIZE = 4096; 129 130 // Check if we can enable 64-bit optimizations. 131 //version = DRFLAC_64BIT; 132 133 version(DRFLAC_64BIT) alias drflac_cache_t = ulong; else alias drflac_cache_t = uint; 134 135 // The various metadata block types. 136 enum DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO = 0; 137 enum DRFLAC_METADATA_BLOCK_TYPE_PADDING = 1; 138 enum DRFLAC_METADATA_BLOCK_TYPE_APPLICATION = 2; 139 enum DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE = 3; 140 enum DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT = 4; 141 enum DRFLAC_METADATA_BLOCK_TYPE_CUESHEET = 5; 142 enum DRFLAC_METADATA_BLOCK_TYPE_PICTURE = 6; 143 enum DRFLAC_METADATA_BLOCK_TYPE_INVALID = 127; 144 145 // The various picture types specified in the PICTURE block. 146 enum DRFLAC_PICTURE_TYPE_OTHER = 0; 147 enum DRFLAC_PICTURE_TYPE_FILE_ICON = 1; 148 enum DRFLAC_PICTURE_TYPE_OTHER_FILE_ICON = 2; 149 enum DRFLAC_PICTURE_TYPE_COVER_FRONT = 3; 150 enum DRFLAC_PICTURE_TYPE_COVER_BACK = 4; 151 enum DRFLAC_PICTURE_TYPE_LEAFLET_PAGE = 5; 152 enum DRFLAC_PICTURE_TYPE_MEDIA = 6; 153 enum DRFLAC_PICTURE_TYPE_LEAD_ARTIST = 7; 154 enum DRFLAC_PICTURE_TYPE_ARTIST = 8; 155 enum DRFLAC_PICTURE_TYPE_CONDUCTOR = 9; 156 enum DRFLAC_PICTURE_TYPE_BAND = 10; 157 enum DRFLAC_PICTURE_TYPE_COMPOSER = 11; 158 enum DRFLAC_PICTURE_TYPE_LYRICIST = 12; 159 enum DRFLAC_PICTURE_TYPE_RECORDING_LOCATION = 13; 160 enum DRFLAC_PICTURE_TYPE_DURING_RECORDING = 14; 161 enum DRFLAC_PICTURE_TYPE_DURING_PERFORMANCE = 15; 162 enum DRFLAC_PICTURE_TYPE_SCREEN_CAPTURE = 16; 163 enum DRFLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH = 17; 164 enum DRFLAC_PICTURE_TYPE_ILLUSTRATION = 18; 165 enum DRFLAC_PICTURE_TYPE_BAND_LOGOTYPE = 19; 166 enum DRFLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20; 167 168 alias drflac_container = int; 169 enum { 170 drflac_container_native, 171 drflac_container_ogg, 172 } 173 174 alias drflac_seek_origin = int; 175 enum { 176 drflac_seek_origin_start, 177 drflac_seek_origin_current, 178 } 179 180 // Packing is important on this structure because we map this directly to the raw data within the SEEKTABLE metadata block. 181 //#pragma pack(2) 182 align(2) struct drflac_seekpoint { 183 align(2): 184 ulong firstSample; 185 ulong frameOffset; // The offset from the first byte of the header of the first frame. 186 ushort sampleCount; 187 } 188 //#pragma pack() 189 190 struct drflac_streaminfo { 191 ushort minBlockSize; 192 ushort maxBlockSize; 193 uint minFrameSize; 194 uint maxFrameSize; 195 uint sampleRate; 196 ubyte channels; 197 ubyte bitsPerSample; 198 ulong totalSampleCount; 199 ubyte[16] md5; 200 } 201 202 struct drflac_metadata { 203 // The metadata type. Use this to know how to interpret the data below. 204 uint type; 205 206 // A pointer to the raw data. This points to a temporary buffer so don't hold on to it. It's best to 207 // not modify the contents of this buffer. Use the structures below for more meaningful and structured 208 // information about the metadata. It's possible for this to be null. 209 const(void)* pRawData; 210 211 // The size in bytes of the block and the buffer pointed to by pRawData if it's non-null. 212 uint rawDataSize; 213 214 static struct Padding { 215 int unused; 216 } 217 218 static struct Application { 219 uint id; 220 const(void)* pData; 221 uint dataSize; 222 } 223 224 static struct SeekTable { 225 uint seekpointCount; 226 const(drflac_seekpoint)* pSeekpoints; 227 } 228 229 static struct VorbisComment { 230 uint vendorLength; 231 const(char)* vendor; 232 uint commentCount; 233 const(char)* comments; 234 } 235 236 static struct CueSheet { 237 char[128] catalog; 238 ulong leadInSampleCount; 239 bool isCD; 240 ubyte trackCount; 241 const(ubyte)* pTrackData; 242 } 243 244 static struct Picture { 245 uint type; 246 uint mimeLength; 247 const(char)* mime; 248 uint descriptionLength; 249 const(char)* description; 250 uint width; 251 uint height; 252 uint colorDepth; 253 uint indexColorCount; 254 uint pictureDataSize; 255 const(ubyte)* pPictureData; 256 } 257 258 static union Data { 259 drflac_streaminfo streaminfo; 260 Padding padding; 261 Application application; 262 SeekTable seektable; 263 VorbisComment vorbis_comment; 264 CueSheet cuesheet; 265 Picture picture; 266 } 267 268 Data data; 269 } 270 271 272 // Callback for when data needs to be read from the client. 273 // 274 // pUserData [in] The user data that was passed to drflac_open() and family. 275 // pBufferOut [out] The output buffer. 276 // bytesToRead [in] The number of bytes to read. 277 // 278 // Returns the number of bytes actually read. 279 alias drflac_read_proc = size_t function (void* pUserData, void* pBufferOut, size_t bytesToRead); 280 281 // Callback for when data needs to be seeked. 282 // 283 // pUserData [in] The user data that was passed to drflac_open() and family. 284 // offset [in] The number of bytes to move, relative to the origin. Will never be negative. 285 // origin [in] The origin of the seek - the current position or the start of the stream. 286 // 287 // Returns whether or not the seek was successful. 288 // 289 // The offset will never be negative. Whether or not it is relative to the beginning or current position is determined 290 // by the "origin" parameter which will be either drflac_seek_origin_start or drflac_seek_origin_current. 291 alias drflac_seek_proc = bool function (void* pUserData, int offset, drflac_seek_origin origin); 292 293 // Callback for when a metadata block is read. 294 // 295 // pUserData [in] The user data that was passed to drflac_open() and family. 296 // pMetadata [in] A pointer to a structure containing the data of the metadata block. 297 // 298 // Use pMetadata.type to determine which metadata block is being handled and how to read the data. 299 alias drflac_meta_proc = void delegate (void* pUserData, drflac_metadata* pMetadata); 300 301 302 // Structure for internal use. Only used for decoders opened with drflac_open_memory. 303 struct drflac__memory_stream { 304 const(ubyte)* data; 305 size_t dataSize; 306 size_t currentReadPos; 307 } 308 309 // Structure for internal use. Used for bit streaming. 310 struct drflac_bs { 311 // The function to call when more data needs to be read. 312 //drflac_read_proc onRead; 313 314 // The function to call when the current read position needs to be moved. 315 //drflac_seek_proc onSeek; 316 317 // The user data to pass around to onRead and onSeek. 318 //void* pUserData; 319 320 ReadStruct rs; 321 322 bool stdio; //k8: it is drflac's stdio shit 323 324 // 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 325 // 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 326 // or not the bistreamer needs to run on a slower path to read those last bytes. This will never be more than (drflac_cache_t).sizeof. 327 size_t unalignedByteCount; 328 329 // The content of the unaligned bytes. 330 drflac_cache_t unalignedCache; 331 332 // The index of the next valid cache line in the "L2" cache. 333 size_t nextL2Line; 334 335 // The number of bits that have been consumed by the cache. This is used to determine how many valid bits are remaining. 336 size_t consumedBits; 337 338 // The cached data which was most recently read from the client. There are two levels of cache. Data flows as such: 339 // Client . L2 . L1. The L2 . L1 movement is aligned and runs on a fast path in just a few instructions. 340 drflac_cache_t[DR_FLAC_BUFFER_SIZE/(drflac_cache_t).sizeof] cacheL2; 341 drflac_cache_t cache; 342 } 343 344 struct drflac_subframe { 345 // The type of the subframe: SUBFRAME_CONSTANT, SUBFRAME_VERBATIM, SUBFRAME_FIXED or SUBFRAME_LPC. 346 ubyte subframeType; 347 348 // The number of wasted bits per sample as specified by the sub-frame header. 349 ubyte wastedBitsPerSample; 350 351 // The order to use for the prediction stage for SUBFRAME_FIXED and SUBFRAME_LPC. 352 ubyte lpcOrder; 353 354 // The number of bits per sample for this subframe. This is not always equal to the current frame's bit per sample because 355 // an extra bit is required for side channels when interchannel decorrelation is being used. 356 uint bitsPerSample; 357 358 // A pointer to the buffer containing the decoded samples in the subframe. This pointer is an offset from drflac::pExtraData, or 359 // null if the heap is not being used. Note that it's a signed 32-bit integer for each value. 360 int* pDecodedSamples; 361 } 362 363 struct drflac_frame_header { 364 // If the stream uses variable block sizes, this will be set to the index of the first sample. If fixed block sizes are used, this will 365 // always be set to 0. 366 ulong sampleNumber; 367 368 // 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. 369 uint frameNumber; 370 371 // The sample rate of this frame. 372 uint sampleRate; 373 374 // The number of samples in each sub-frame within this frame. 375 ushort blockSize; 376 377 // The channel assignment of this frame. This is not always set to the channel count. If interchannel decorrelation is being used this 378 // will be set to DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE, DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE or DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE. 379 ubyte channelAssignment; 380 381 // The number of bits per sample within this frame. 382 ubyte bitsPerSample; 383 384 // The frame's CRC. This is set, but unused at the moment. 385 ubyte crc8; 386 } 387 388 struct drflac_frame { 389 // The header. 390 drflac_frame_header header; 391 392 // The number of samples left to be read in this frame. This is initially set to the block size multiplied by the channel count. As samples 393 // are read, this will be decremented. When it reaches 0, the decoder will see this frame as fully consumed and load the next frame. 394 uint samplesRemaining; 395 396 // The list of sub-frames within the frame. There is one sub-frame for each channel, and there's a maximum of 8 channels. 397 drflac_subframe[8] subframes; 398 } 399 400 struct drflac { 401 // The function to call when a metadata block is read. 402 //drflac_meta_proc onMeta; 403 404 // The user data posted to the metadata callback function. 405 //void* pUserDataMD; 406 407 408 // The sample rate. Will be set to something like 44100. 409 uint sampleRate; 410 411 // 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 412 // value specified in the STREAMINFO block. 413 ubyte channels; 414 415 // The bits per sample. Will be set to somthing like 16, 24, etc. 416 ubyte bitsPerSample; 417 418 // The maximum block size, in samples. This number represents the number of samples in each channel (not combined). 419 ushort maxBlockSize; 420 421 // The total number of samples making up the stream. This includes every channel. For example, if the stream has 2 channels, 422 // with each channel having a total of 4096, this value will be set to 2*4096 = 8192. Can be 0 in which case it's still a 423 // valid stream, but just means the total sample count is unknown. Likely the case with streams like internet radio. 424 ulong totalSampleCount; 425 426 427 // The container type. This is set based on whether or not the decoder was opened from a native or Ogg stream. 428 drflac_container container; 429 430 431 // The position of the seektable in the file. 432 ulong seektablePos; 433 434 // The size of the seektable. 435 uint seektableSize; 436 437 438 // Information about the frame the decoder is currently sitting on. 439 drflac_frame currentFrame; 440 441 // The position of the first frame in the stream. This is only ever used for seeking. 442 ulong firstFramePos; 443 444 445 // A hack to avoid a malloc() when opening a decoder with drflac_open_memory(). 446 drflac__memory_stream memoryStream; 447 448 449 // A pointer to the decoded sample data. This is an offset of pExtraData. 450 int* pDecodedSamples; 451 452 453 // The bit streamer. The raw FLAC data is fed through this object. 454 drflac_bs bs; 455 456 // Variable length extra data. We attach this to the end of the object so we avoid unnecessary mallocs. 457 ubyte[1] pExtraData; 458 } 459 460 461 // Opens a FLAC decoder. 462 // 463 // onRead [in] The function to call when data needs to be read from the client. 464 // onSeek [in] The function to call when the read position of the client data needs to move. 465 // pUserData [in, optional] A pointer to application defined data that will be passed to onRead and onSeek. 466 // 467 // Returns a pointer to an object representing the decoder. 468 // 469 // Close the decoder with drflac_close(). 470 // 471 // This function will automatically detect whether or not you are attempting to open a native or Ogg encapsulated 472 // FLAC, both of which should work seamlessly without any manual intervention. Ogg encapsulation also works with 473 // multiplexed streams which basically means it can play FLAC encoded audio tracks in videos. 474 // 475 // This is the lowest level function for opening a FLAC stream. You can also use drflac_open_file() and drflac_open_memory() 476 // to open the stream from a file or from a block of memory respectively. 477 // 478 // The STREAMINFO block must be present for this to succeed. 479 // 480 // See also: drflac_open_file(), drflac_open_memory(), drflac_open_with_metadata(), drflac_close() 481 //drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData); 482 483 // Opens a FLAC decoder and notifies the caller of the metadata chunks (album art, etc.). 484 // 485 // onRead [in] The function to call when data needs to be read from the client. 486 // onSeek [in] The function to call when the read position of the client data needs to move. 487 // onMeta [in] The function to call for every metadata block. 488 // pUserData [in, optional] A pointer to application defined data that will be passed to onRead, onSeek and onMeta. 489 // 490 // Returns a pointer to an object representing the decoder. 491 // 492 // Close the decoder with drflac_close(). 493 // 494 // This is slower that drflac_open(), so avoid this one if you don't need metadata. Internally, this will do a malloc() 495 // and free() for every metadata block except for STREAMINFO and PADDING blocks. 496 // 497 // The caller is notified of the metadata via the onMeta callback. All metadata blocks withh be handled before the function 498 // returns. 499 // 500 // See also: drflac_open_file_with_metadata(), drflac_open_memory_with_metadata(), drflac_open(), drflac_close() 501 //drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData); 502 503 // Closes the given FLAC decoder. 504 // 505 // pFlac [in] The decoder to close. 506 // 507 // This will destroy the decoder object. 508 //void drflac_close(drflac* pFlac); 509 510 511 // Reads sample data from the given FLAC decoder, output as interleaved signed 32-bit PCM. 512 // 513 // pFlac [in] The decoder. 514 // samplesToRead [in] The number of samples to read. 515 // pBufferOut [out, optional] A pointer to the buffer that will receive the decoded samples. 516 // 517 // Returns the number of samples actually read. 518 // 519 // pBufferOut can be null, in which case the call will act as a seek, and the return value will be the number of samples 520 // seeked. 521 //ulong drflac_read_s32(drflac* pFlac, ulong samplesToRead, int* pBufferOut); 522 523 // Seeks to the sample at the given index. 524 // 525 // pFlac [in] The decoder. 526 // sampleIndex [in] The index of the sample to seek to. See notes below. 527 // 528 // Returns true if successful; false otherwise. 529 // 530 // The sample index is based on interleaving. In a stereo stream, for example, the sample at index 0 is the first sample 531 // in the left channel; the sample at index 1 is the first sample on the right channel, and so on. 532 // 533 // When seeking, you will likely want to ensure it's rounded to a multiple of the channel count. You can do this with 534 // something like drflac_seek_to_sample(pFlac, (mySampleIndex + (mySampleIndex % pFlac.channels))) 535 //bool drflac_seek_to_sample(drflac* pFlac, ulong sampleIndex); 536 537 538 // Opens a FLAC decoder from the file at the given path. 539 // 540 // filename [in] The path of the file to open, either absolute or relative to the current directory. 541 // 542 // Returns a pointer to an object representing the decoder. 543 // 544 // Close the decoder with drflac_close(). 545 // 546 // This will hold a handle to the file until the decoder is closed with drflac_close(). Some platforms will restrict the 547 // number of files a process can have open at any given time, so keep this mind if you have many decoders open at the 548 // same time. 549 // 550 // See also: drflac_open(), drflac_open_file_with_metadata(), drflac_close() 551 //drflac* drflac_open_file(const(char)[] filename); 552 553 // Opens a FLAC decoder from the file at the given path and notifies the caller of the metadata chunks (album art, etc.) 554 // 555 // Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled. 556 //drflac* drflac_open_file_with_metadata(const(char)[] filename, drflac_meta_proc onMeta, void* pUserData); 557 558 // Opens a FLAC decoder from a pre-allocated block of memory 559 // 560 // This does not create a copy of the data. It is up to the application to ensure the buffer remains valid for 561 // the lifetime of the decoder. 562 //drflac* drflac_open_memory(const void* data, size_t dataSize); 563 564 // Opens a FLAC decoder from a pre-allocated block of memory and notifies the caller of the metadata chunks (album art, etc.) 565 // 566 // Look at the documentation for drflac_open_with_metadata() for more information on how metadata is handled. 567 //drflac* drflac_open_memory_with_metadata(const void* data, size_t dataSize, drflac_meta_proc onMeta, void* pUserData); 568 569 570 571 //// High Level APIs //// 572 573 // Opens a FLAC stream from the given callbacks and fully decodes it in a single operation. The return value is a 574 // pointer to the sample data as interleaved signed 32-bit PCM. The returned data must be freed with drflac_free(). 575 // 576 // Sometimes a FLAC file won't keep track of the total sample count. In this situation the function will continuously 577 // read samples into a dynamically sized buffer on the heap until no samples are left. 578 // 579 // Do not call this function on a broadcast type of stream (like internet radio streams and whatnot). 580 //int* drflac_open_and_decode(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, uint* sampleRate, uint* channels, ulong* totalSampleCount); 581 582 //#ifndef DR_FLAC_NO_STDIO 583 // Same as drflac_open_and_decode() except opens the decoder from a file. 584 //int* drflac_open_and_decode_file(const(char)[] filename, uint* sampleRate, uint* channels, ulong* totalSampleCount); 585 //#endif 586 587 // Same as drflac_open_and_decode() except opens the decoder from a block of memory. 588 //int* drflac_open_and_decode_memory(const void* data, size_t dataSize, uint* sampleRate, uint* channels, ulong* totalSampleCount); 589 590 // Frees data returned by drflac_open_and_decode_*(). 591 //void drflac_free(void* pSampleDataReturnedByOpenAndDecode); 592 593 594 // Structure representing an iterator for vorbis comments in a VORBIS_COMMENT metadata block. 595 struct drflac_vorbis_comment_iterator { 596 uint countRemaining; 597 const(char)* pRunningData; 598 } 599 600 // Initializes a vorbis comment iterator. This can be used for iterating over the vorbis comments in a VORBIS_COMMENT 601 // metadata block. 602 //void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, uint commentCount, const(char)* pComments); 603 604 // Goes to the next vorbis comment in the given iterator. If null is returned it means there are no more comments. The 605 // returned string is NOT null terminated. 606 //const(char)* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, uint* pCommentLengthOut); 607 608 609 /////////////////////////////////////////////////////////////////////////////// 610 // 611 // IMPLEMENTATION 612 // 613 /////////////////////////////////////////////////////////////////////////////// 614 private: nothrow { 615 enum DRFLAC_SUBFRAME_CONSTANT = 0; 616 enum DRFLAC_SUBFRAME_VERBATIM = 1; 617 enum DRFLAC_SUBFRAME_FIXED = 8; 618 enum DRFLAC_SUBFRAME_LPC = 32; 619 enum DRFLAC_SUBFRAME_RESERVED = 255; 620 621 enum DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE = 0; 622 enum DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 = 1; 623 624 enum DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT = 0; 625 enum DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE = 8; 626 enum DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE = 9; 627 enum DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE = 10; 628 629 630 //// Endian Management //// 631 version(LittleEndian) enum drflac__is_little_endian = true; else enum drflac__is_little_endian = false; 632 633 ushort drflac__be2host_16 (ushort n) pure nothrow @safe @nogc { 634 static if (__VERSION__ > 2067) pragma(inline, true); 635 version(LittleEndian) { 636 return cast(ushort)((n>>8)|((n&0xff)<<8)); 637 } else { 638 return n; 639 } 640 } 641 642 uint drflac__be2host_32 (uint n) pure nothrow @safe @nogc { 643 static if (__VERSION__ > 2067) pragma(inline, true); 644 version(LittleEndian) { 645 import core.bitop : bswap; 646 return bswap(n); 647 } else { 648 return n; 649 } 650 } 651 652 ulong drflac__be2host_64 (ulong n) pure nothrow @safe @nogc { 653 static if (__VERSION__ > 2067) pragma(inline, true); 654 version(LittleEndian) { 655 import core.bitop : bswap; 656 version(GNU) { 657 auto n0 = cast(ulong)bswap(cast(uint)n); 658 auto n1 = cast(ulong)bswap(cast(uint)(n>>32)); 659 return (n0<<32)|n1; 660 } else { 661 return bswap(n); 662 } 663 } else { 664 return n; 665 } 666 } 667 668 669 uint drflac__le2host_32 (uint n) pure nothrow @safe @nogc { 670 static if (__VERSION__ > 2067) pragma(inline, true); 671 version(LittleEndian) { 672 return n; 673 } else { 674 import core.bitop : bswap; 675 return bswap(n); 676 } 677 } 678 679 680 version(DRFLAC_64BIT) { 681 alias drflac__be2host__cache_line = drflac__be2host_64; 682 } else { 683 alias drflac__be2host__cache_line = drflac__be2host_32; 684 } 685 686 // BIT READING ATTEMPT #2 687 // 688 // 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 689 // on the most significant bit. It uses the notion of an L1 and L2 cache (borrowed from CPU architecture), where the L1 cache 690 // 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 691 // 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 692 // from onRead() is read into. 693 enum DRFLAC_CACHE_L1_SIZE_BYTES(string bs) = "((("~bs~").cache).sizeof)"; 694 enum DRFLAC_CACHE_L1_SIZE_BITS(string bs) = "((("~bs~").cache).sizeof*8)"; 695 enum DRFLAC_CACHE_L1_BITS_REMAINING(string bs) = "("~DRFLAC_CACHE_L1_SIZE_BITS!(bs)~"-(("~bs~").consumedBits))"; 696 version(DRFLAC_64BIT) { 697 enum DRFLAC_CACHE_L1_SELECTION_MASK(string _bitCount) = "(~((cast(ulong)-1L)>>("~_bitCount~")))"; 698 } else { 699 enum DRFLAC_CACHE_L1_SELECTION_MASK(string _bitCount) = "(~((cast(uint)-1)>>("~_bitCount~")))"; 700 } 701 enum DRFLAC_CACHE_L1_SELECTION_SHIFT(string bs, string _bitCount) = "("~DRFLAC_CACHE_L1_SIZE_BITS!bs~"-("~_bitCount~"))"; 702 enum DRFLAC_CACHE_L1_SELECT(string bs, string _bitCount) = "((("~bs~").cache)&"~DRFLAC_CACHE_L1_SELECTION_MASK!_bitCount~")"; 703 enum DRFLAC_CACHE_L1_SELECT_AND_SHIFT(string bs, string _bitCount) = "("~DRFLAC_CACHE_L1_SELECT!(bs, _bitCount)~">>"~DRFLAC_CACHE_L1_SELECTION_SHIFT!(bs, _bitCount)~")"; 704 enum DRFLAC_CACHE_L2_SIZE_BYTES(string bs) = "((("~bs~").cacheL2).sizeof)"; 705 enum DRFLAC_CACHE_L2_LINE_COUNT(string bs) = "("~DRFLAC_CACHE_L2_SIZE_BYTES!bs~"/(("~bs~").cacheL2[0]).sizeof)"; 706 enum DRFLAC_CACHE_L2_LINES_REMAINING(string bs) = "("~DRFLAC_CACHE_L2_LINE_COUNT!bs~"-("~bs~").nextL2Line)"; 707 708 bool drflac__reload_l1_cache_from_l2 (drflac_bs* bs) { 709 // Fast path. Try loading straight from L2. 710 if (bs.nextL2Line < mixin(DRFLAC_CACHE_L2_LINE_COUNT!"bs")) { 711 bs.cache = bs.cacheL2.ptr[bs.nextL2Line++]; 712 return true; 713 } 714 715 // 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 any left. 716 if (bs.unalignedByteCount > 0) return false; // If we have any unaligned bytes it means there's no more aligned bytes left in the client. 717 718 size_t bytesRead = bs.rs.read(bs.cacheL2.ptr, mixin(DRFLAC_CACHE_L2_SIZE_BYTES!"bs")); 719 720 bs.nextL2Line = 0; 721 if (bytesRead == mixin(DRFLAC_CACHE_L2_SIZE_BYTES!"bs")) { 722 bs.cache = bs.cacheL2.ptr[bs.nextL2Line++]; 723 return true; 724 } 725 726 // If we get here it means we were unable to retrieve enough data to fill the entire L2 cache. It probably 727 // means we've just reached the end of the file. We need to move the valid data down to the end of the buffer 728 // and adjust the index of the next line accordingly. Also keep in mind that the L2 cache must be aligned to 729 // the size of the L1 so we'll need to seek backwards by any misaligned bytes. 730 size_t alignedL1LineCount = bytesRead/mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs"); 731 732 // We need to keep track of any unaligned bytes for later use. 733 bs.unalignedByteCount = bytesRead-(alignedL1LineCount*mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs")); 734 if (bs.unalignedByteCount > 0) { 735 bs.unalignedCache = bs.cacheL2.ptr[alignedL1LineCount]; 736 } 737 738 if (alignedL1LineCount > 0) { 739 size_t offset = mixin(DRFLAC_CACHE_L2_LINE_COUNT!"bs")-alignedL1LineCount; 740 for (size_t i = alignedL1LineCount; i > 0; --i) bs.cacheL2.ptr[i-1+offset] = bs.cacheL2.ptr[i-1]; 741 bs.nextL2Line = offset; 742 bs.cache = bs.cacheL2.ptr[bs.nextL2Line++]; 743 return true; 744 } else { 745 // If we get into this branch it means we weren't able to load any L1-aligned data. 746 bs.nextL2Line = mixin(DRFLAC_CACHE_L2_LINE_COUNT!"bs"); 747 return false; 748 } 749 } 750 751 bool drflac__reload_cache (drflac_bs* bs) { 752 // Fast path. Try just moving the next value in the L2 cache to the L1 cache. 753 if (drflac__reload_l1_cache_from_l2(bs)) { 754 bs.cache = drflac__be2host__cache_line(bs.cache); 755 bs.consumedBits = 0; 756 return true; 757 } 758 759 // Slow path. 760 761 // 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 762 // 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 763 // data from the unaligned cache. 764 size_t bytesRead = bs.unalignedByteCount; 765 if (bytesRead == 0) return false; 766 767 assert(bytesRead < mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs")); 768 bs.consumedBits = (mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs")-bytesRead)*8; 769 770 bs.cache = drflac__be2host__cache_line(bs.unalignedCache); 771 //bs.cache &= DRFLAC_CACHE_L1_SELECTION_MASK(DRFLAC_CACHE_L1_SIZE_BITS(bs)-bs.consumedBits); 772 bs.cache &= mixin(DRFLAC_CACHE_L1_SELECTION_MASK!(DRFLAC_CACHE_L1_SIZE_BITS!"bs"~"-bs.consumedBits")); 773 // <-- Make sure the consumed bits are always set to zero. Other parts of the library depend on this property. 774 bs.unalignedByteCount = 0; // <-- At this point the unaligned bytes have been moved into the cache and we thus have no more unaligned bytes. 775 return true; 776 } 777 778 void drflac__reset_cache (drflac_bs* bs) { 779 bs.nextL2Line = mixin(DRFLAC_CACHE_L2_LINE_COUNT!"bs"); // <-- This clears the L2 cache. 780 bs.consumedBits = mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs"); // <-- This clears the L1 cache. 781 bs.cache = 0; 782 bs.unalignedByteCount = 0; // <-- This clears the trailing unaligned bytes. 783 bs.unalignedCache = 0; 784 } 785 786 bool drflac__seek_bits (drflac_bs* bs, size_t bitsToSeek) { 787 if (bitsToSeek <= mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"bs")) { 788 bs.consumedBits += bitsToSeek; 789 bs.cache <<= bitsToSeek; 790 return true; 791 } else { 792 // It straddles the cached data. This function isn't called too frequently so I'm favouring simplicity here. 793 bitsToSeek -= mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"bs"); 794 bs.consumedBits += mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"bs"); 795 bs.cache = 0; 796 797 size_t wholeBytesRemainingToSeek = bitsToSeek/8; 798 if (wholeBytesRemainingToSeek > 0) { 799 // The next bytes to seek will be located in the L2 cache. The problem is that the L2 cache is not byte aligned, 800 // but rather DRFLAC_CACHE_L1_SIZE_BYTES aligned (usually 4 or 8). If, for example, the number of bytes to seek is 801 // 3, we'll need to handle it in a special way. 802 size_t wholeCacheLinesRemaining = wholeBytesRemainingToSeek/mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs"); 803 if (wholeCacheLinesRemaining < mixin(DRFLAC_CACHE_L2_LINES_REMAINING!"bs")) { 804 wholeBytesRemainingToSeek -= wholeCacheLinesRemaining*mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs"); 805 bitsToSeek -= wholeCacheLinesRemaining*mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs"); 806 bs.nextL2Line += wholeCacheLinesRemaining; 807 } else { 808 wholeBytesRemainingToSeek -= mixin(DRFLAC_CACHE_L2_LINES_REMAINING!"bs")*mixin(DRFLAC_CACHE_L1_SIZE_BYTES!"bs"); 809 bitsToSeek -= mixin(DRFLAC_CACHE_L2_LINES_REMAINING!"bs")*mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs"); 810 bs.nextL2Line += mixin(DRFLAC_CACHE_L2_LINES_REMAINING!"bs"); 811 // Note that we only seek on the client side if it's got any data left to seek. We can know this by checking 812 // if we have any unaligned data which can be determined with bs->unalignedByteCount. 813 if (wholeBytesRemainingToSeek > 0 && bs.unalignedByteCount == 0) { 814 if (!bs.rs.seek(cast(int)wholeBytesRemainingToSeek, drflac_seek_origin_current)) return false; 815 bitsToSeek -= wholeBytesRemainingToSeek*8; 816 } 817 } 818 } 819 if (bitsToSeek > 0) { 820 if (!drflac__reload_cache(bs)) return false; 821 return drflac__seek_bits(bs, bitsToSeek); 822 } 823 return true; 824 } 825 } 826 827 bool drflac__read_uint32 (drflac_bs* bs, uint bitCount, uint* pResultOut) { 828 assert(bs !is null); 829 assert(pResultOut !is null); 830 assert(bitCount > 0); 831 assert(bitCount <= 32); 832 833 if (bs.consumedBits == mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs")) { 834 if (!drflac__reload_cache(bs)) return false; 835 } 836 837 if (bitCount <= mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"bs")) { 838 if (bitCount < mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs")) { 839 *pResultOut = cast(uint)mixin(DRFLAC_CACHE_L1_SELECT_AND_SHIFT!("bs", "bitCount")); //k8 840 bs.consumedBits += bitCount; 841 bs.cache <<= bitCount; 842 } else { 843 *pResultOut = cast(uint)bs.cache; 844 bs.consumedBits = mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs"); 845 bs.cache = 0; 846 } 847 return true; 848 } else { 849 // 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. 850 size_t bitCountHi = mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"bs"); 851 size_t bitCountLo = bitCount-bitCountHi; 852 uint resultHi = cast(uint)mixin(DRFLAC_CACHE_L1_SELECT_AND_SHIFT!("bs", "bitCountHi")); //k8 853 if (!drflac__reload_cache(bs)) return false; 854 *pResultOut = cast(uint)((resultHi<<bitCountLo)|mixin(DRFLAC_CACHE_L1_SELECT_AND_SHIFT!("bs", "bitCountLo"))); //k8 855 bs.consumedBits += bitCountLo; 856 bs.cache <<= bitCountLo; 857 return true; 858 } 859 } 860 861 bool drflac__read_int32 (drflac_bs* bs, uint bitCount, int* pResult) { 862 assert(bs !is null); 863 assert(pResult !is null); 864 assert(bitCount > 0); 865 assert(bitCount <= 32); 866 867 uint result; 868 if (!drflac__read_uint32(bs, bitCount, &result)) return false; 869 870 uint signbit = ((result>>(bitCount-1))&0x01); 871 result |= (~signbit+1)<<bitCount; 872 873 *pResult = cast(int)result; 874 return true; 875 } 876 877 bool drflac__read_uint64 (drflac_bs* bs, uint bitCount, ulong* pResultOut) { 878 assert(bitCount <= 64); 879 assert(bitCount > 32); 880 881 uint resultHi; 882 if (!drflac__read_uint32(bs, bitCount-32, &resultHi)) return false; 883 884 uint resultLo; 885 if (!drflac__read_uint32(bs, 32, &resultLo)) return false; 886 887 *pResultOut = ((cast(ulong)resultHi)<<32)|(cast(ulong)resultLo); 888 return true; 889 } 890 891 bool drflac__read_uint16 (drflac_bs* bs, uint bitCount, ushort* pResult) { 892 assert(bs !is null); 893 assert(pResult !is null); 894 assert(bitCount > 0); 895 assert(bitCount <= 16); 896 897 uint result; 898 if (!drflac__read_uint32(bs, bitCount, &result)) return false; 899 900 *pResult = cast(ushort)result; 901 return true; 902 } 903 904 bool drflac__read_int16 (drflac_bs* bs, uint bitCount, short* pResult) { 905 assert(bs !is null); 906 assert(pResult !is null); 907 assert(bitCount > 0); 908 assert(bitCount <= 16); 909 910 int result; 911 if (!drflac__read_int32(bs, bitCount, &result)) return false; 912 913 *pResult = cast(short)result; 914 return true; 915 } 916 917 bool drflac__read_uint8 (drflac_bs* bs, uint bitCount, ubyte* pResult) { 918 assert(bs !is null); 919 assert(pResult !is null); 920 assert(bitCount > 0); 921 assert(bitCount <= 8); 922 923 uint result; 924 if (!drflac__read_uint32(bs, bitCount, &result)) return false; 925 926 *pResult = cast(ubyte)result; 927 return true; 928 } 929 930 bool drflac__read_int8 (drflac_bs* bs, uint bitCount, byte* pResult) { 931 assert(bs !is null); 932 assert(pResult !is null); 933 assert(bitCount > 0); 934 assert(bitCount <= 8); 935 936 int result; 937 if (!drflac__read_int32(bs, bitCount, &result)) return false; 938 939 *pResult = cast(byte)result; 940 return true; 941 } 942 943 944 bool drflac__seek_past_next_set_bit (drflac_bs* bs, uint* pOffsetOut) { 945 uint zeroCounter = 0; 946 while (bs.cache == 0) { 947 zeroCounter += cast(uint)mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"bs"); 948 if (!drflac__reload_cache(bs)) return false; 949 } 950 951 // At this point the cache should not be zero, in which case we know the first set bit should be somewhere in here. There is 952 // no need for us to perform any cache reloading logic here which should make things much faster. 953 assert(bs.cache != 0); 954 955 static immutable uint[16] bitOffsetTable = [ 956 0, 957 4, 958 3, 3, 959 2, 2, 2, 2, 960 1, 1, 1, 1, 1, 1, 1, 1 961 ]; 962 963 uint setBitOffsetPlus1 = bitOffsetTable.ptr[mixin(DRFLAC_CACHE_L1_SELECT_AND_SHIFT!("bs", "4"))]; 964 if (setBitOffsetPlus1 == 0) { 965 if (bs.cache == 1) { 966 setBitOffsetPlus1 = mixin(DRFLAC_CACHE_L1_SIZE_BITS!"bs"); 967 } else { 968 setBitOffsetPlus1 = 5; 969 for (;;) { 970 if ((bs.cache&mixin(DRFLAC_CACHE_L1_SELECT!("bs", "setBitOffsetPlus1")))) break; 971 setBitOffsetPlus1 += 1; 972 } 973 } 974 } 975 976 bs.consumedBits += setBitOffsetPlus1; 977 bs.cache <<= setBitOffsetPlus1; 978 979 *pOffsetOut = zeroCounter+setBitOffsetPlus1-1; 980 return true; 981 } 982 983 984 bool drflac__seek_to_byte (drflac_bs* bs, ulong offsetFromStart) { 985 assert(bs !is null); 986 assert(offsetFromStart > 0); 987 988 // Seeking from the start is not quite as trivial as it sounds because the onSeek callback takes a signed 32-bit integer (which 989 // is intentional because it simplifies the implementation of the onSeek callbacks), however offsetFromStart is unsigned 64-bit. 990 // 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. 991 if (offsetFromStart > 0x7FFFFFFF) { 992 ulong bytesRemaining = offsetFromStart; 993 if (!bs.rs.seek(0x7FFFFFFF, drflac_seek_origin_start)) return false; 994 bytesRemaining -= 0x7FFFFFFF; 995 while (bytesRemaining > 0x7FFFFFFF) { 996 if (!bs.rs.seek(0x7FFFFFFF, drflac_seek_origin_current)) return false; 997 bytesRemaining -= 0x7FFFFFFF; 998 } 999 if (bytesRemaining > 0) { 1000 if (!bs.rs.seek(cast(int)bytesRemaining, drflac_seek_origin_current)) return false; 1001 } 1002 } else { 1003 if (!bs.rs.seek(cast(int)offsetFromStart, drflac_seek_origin_start)) return false; 1004 } 1005 // The cache should be reset to force a reload of fresh data from the client. 1006 drflac__reset_cache(bs); 1007 return true; 1008 } 1009 1010 1011 bool drflac__read_utf8_coded_number (drflac_bs* bs, ulong* pNumberOut) { 1012 assert(bs !is null); 1013 assert(pNumberOut !is null); 1014 1015 ubyte[7] utf8 = 0; 1016 if (!drflac__read_uint8(bs, 8, utf8.ptr)) { 1017 *pNumberOut = 0; 1018 return false; 1019 } 1020 1021 if ((utf8.ptr[0]&0x80) == 0) { 1022 *pNumberOut = utf8.ptr[0]; 1023 return true; 1024 } 1025 1026 int byteCount = 1; 1027 if ((utf8.ptr[0]&0xE0) == 0xC0) byteCount = 2; 1028 else if ((utf8.ptr[0]&0xF0) == 0xE0) byteCount = 3; 1029 else if ((utf8.ptr[0]&0xF8) == 0xF0) byteCount = 4; 1030 else if ((utf8.ptr[0]&0xFC) == 0xF8) byteCount = 5; 1031 else if ((utf8.ptr[0]&0xFE) == 0xFC) byteCount = 6; 1032 else if ((utf8.ptr[0]&0xFF) == 0xFE) byteCount = 7; 1033 else { *pNumberOut = 0; return false; } // Bad UTF-8 encoding. 1034 1035 // Read extra bytes. 1036 assert(byteCount > 1); 1037 1038 ulong result = cast(ulong)(utf8.ptr[0]&(0xFF>>(byteCount+1))); 1039 for (int i = 1; i < byteCount; ++i) { 1040 if (!drflac__read_uint8(bs, 8, utf8.ptr+i)) { 1041 *pNumberOut = 0; 1042 return false; 1043 } 1044 result = (result<<6)|(utf8.ptr[i]&0x3F); 1045 } 1046 1047 *pNumberOut = result; 1048 return true; 1049 } 1050 1051 1052 bool drflac__read_and_seek_rice (drflac_bs* bs, ubyte m) { 1053 uint unused; 1054 if (!drflac__seek_past_next_set_bit(bs, &unused)) return false; 1055 if (m > 0) { 1056 if (!drflac__seek_bits(bs, m)) return false; 1057 } 1058 return true; 1059 } 1060 1061 1062 // The next two functions are responsible for calculating the prediction. 1063 // 1064 // 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 1065 // 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. 1066 int drflac__calculate_prediction_32 (uint order, int shift, const(short)* coefficients, int* pDecodedSamples) { 1067 assert(order <= 32); 1068 int prediction = 0; 1069 switch (order) { 1070 case 32: prediction += coefficients[31]*pDecodedSamples[-32]; goto case; 1071 case 31: prediction += coefficients[30]*pDecodedSamples[-31]; goto case; 1072 case 30: prediction += coefficients[29]*pDecodedSamples[-30]; goto case; 1073 case 29: prediction += coefficients[28]*pDecodedSamples[-29]; goto case; 1074 case 28: prediction += coefficients[27]*pDecodedSamples[-28]; goto case; 1075 case 27: prediction += coefficients[26]*pDecodedSamples[-27]; goto case; 1076 case 26: prediction += coefficients[25]*pDecodedSamples[-26]; goto case; 1077 case 25: prediction += coefficients[24]*pDecodedSamples[-25]; goto case; 1078 case 24: prediction += coefficients[23]*pDecodedSamples[-24]; goto case; 1079 case 23: prediction += coefficients[22]*pDecodedSamples[-23]; goto case; 1080 case 22: prediction += coefficients[21]*pDecodedSamples[-22]; goto case; 1081 case 21: prediction += coefficients[20]*pDecodedSamples[-21]; goto case; 1082 case 20: prediction += coefficients[19]*pDecodedSamples[-20]; goto case; 1083 case 19: prediction += coefficients[18]*pDecodedSamples[-19]; goto case; 1084 case 18: prediction += coefficients[17]*pDecodedSamples[-18]; goto case; 1085 case 17: prediction += coefficients[16]*pDecodedSamples[-17]; goto case; 1086 case 16: prediction += coefficients[15]*pDecodedSamples[-16]; goto case; 1087 case 15: prediction += coefficients[14]*pDecodedSamples[-15]; goto case; 1088 case 14: prediction += coefficients[13]*pDecodedSamples[-14]; goto case; 1089 case 13: prediction += coefficients[12]*pDecodedSamples[-13]; goto case; 1090 case 12: prediction += coefficients[11]*pDecodedSamples[-12]; goto case; 1091 case 11: prediction += coefficients[10]*pDecodedSamples[-11]; goto case; 1092 case 10: prediction += coefficients[ 9]*pDecodedSamples[-10]; goto case; 1093 case 9: prediction += coefficients[ 8]*pDecodedSamples[- 9]; goto case; 1094 case 8: prediction += coefficients[ 7]*pDecodedSamples[- 8]; goto case; 1095 case 7: prediction += coefficients[ 6]*pDecodedSamples[- 7]; goto case; 1096 case 6: prediction += coefficients[ 5]*pDecodedSamples[- 6]; goto case; 1097 case 5: prediction += coefficients[ 4]*pDecodedSamples[- 5]; goto case; 1098 case 4: prediction += coefficients[ 3]*pDecodedSamples[- 4]; goto case; 1099 case 3: prediction += coefficients[ 2]*pDecodedSamples[- 3]; goto case; 1100 case 2: prediction += coefficients[ 1]*pDecodedSamples[- 2]; goto case; 1101 case 1: prediction += coefficients[ 0]*pDecodedSamples[- 1]; goto default; 1102 default: 1103 } 1104 return cast(int)(prediction>>shift); 1105 } 1106 1107 int drflac__calculate_prediction_64 (uint order, int shift, const(short)* coefficients, int* pDecodedSamples) { 1108 assert(order <= 32); 1109 long prediction = 0; 1110 switch (order) { 1111 case 32: prediction += coefficients[31]*cast(long)pDecodedSamples[-32]; goto case; 1112 case 31: prediction += coefficients[30]*cast(long)pDecodedSamples[-31]; goto case; 1113 case 30: prediction += coefficients[29]*cast(long)pDecodedSamples[-30]; goto case; 1114 case 29: prediction += coefficients[28]*cast(long)pDecodedSamples[-29]; goto case; 1115 case 28: prediction += coefficients[27]*cast(long)pDecodedSamples[-28]; goto case; 1116 case 27: prediction += coefficients[26]*cast(long)pDecodedSamples[-27]; goto case; 1117 case 26: prediction += coefficients[25]*cast(long)pDecodedSamples[-26]; goto case; 1118 case 25: prediction += coefficients[24]*cast(long)pDecodedSamples[-25]; goto case; 1119 case 24: prediction += coefficients[23]*cast(long)pDecodedSamples[-24]; goto case; 1120 case 23: prediction += coefficients[22]*cast(long)pDecodedSamples[-23]; goto case; 1121 case 22: prediction += coefficients[21]*cast(long)pDecodedSamples[-22]; goto case; 1122 case 21: prediction += coefficients[20]*cast(long)pDecodedSamples[-21]; goto case; 1123 case 20: prediction += coefficients[19]*cast(long)pDecodedSamples[-20]; goto case; 1124 case 19: prediction += coefficients[18]*cast(long)pDecodedSamples[-19]; goto case; 1125 case 18: prediction += coefficients[17]*cast(long)pDecodedSamples[-18]; goto case; 1126 case 17: prediction += coefficients[16]*cast(long)pDecodedSamples[-17]; goto case; 1127 case 16: prediction += coefficients[15]*cast(long)pDecodedSamples[-16]; goto case; 1128 case 15: prediction += coefficients[14]*cast(long)pDecodedSamples[-15]; goto case; 1129 case 14: prediction += coefficients[13]*cast(long)pDecodedSamples[-14]; goto case; 1130 case 13: prediction += coefficients[12]*cast(long)pDecodedSamples[-13]; goto case; 1131 case 12: prediction += coefficients[11]*cast(long)pDecodedSamples[-12]; goto case; 1132 case 11: prediction += coefficients[10]*cast(long)pDecodedSamples[-11]; goto case; 1133 case 10: prediction += coefficients[ 9]*cast(long)pDecodedSamples[-10]; goto case; 1134 case 9: prediction += coefficients[ 8]*cast(long)pDecodedSamples[- 9]; goto case; 1135 case 8: prediction += coefficients[ 7]*cast(long)pDecodedSamples[- 8]; goto case; 1136 case 7: prediction += coefficients[ 6]*cast(long)pDecodedSamples[- 7]; goto case; 1137 case 6: prediction += coefficients[ 5]*cast(long)pDecodedSamples[- 6]; goto case; 1138 case 5: prediction += coefficients[ 4]*cast(long)pDecodedSamples[- 5]; goto case; 1139 case 4: prediction += coefficients[ 3]*cast(long)pDecodedSamples[- 4]; goto case; 1140 case 3: prediction += coefficients[ 2]*cast(long)pDecodedSamples[- 3]; goto case; 1141 case 2: prediction += coefficients[ 1]*cast(long)pDecodedSamples[- 2]; goto case; 1142 case 1: prediction += coefficients[ 0]*cast(long)pDecodedSamples[- 1]; goto default; 1143 default: 1144 } 1145 return cast(int)(prediction>>shift); 1146 } 1147 1148 1149 // Reads and decodes a string of residual values as Rice codes. The decoder should be sitting on the first bit of the Rice codes. 1150 // 1151 // This is the most frequently called function in the library. It does both the Rice decoding and the prediction in a single loop 1152 // iteration. The prediction is done at the end, and there's an annoying branch I'd like to avoid so the main function is defined 1153 // as a #define - sue me! 1154 //#define DRFLAC__DECODE_SAMPLES_WITH_RESIDULE__RICE__PROC(funcName, predictionFunc) 1155 enum DRFLAC__DECODE_SAMPLES_WITH_RESIDULE__RICE__PROC(string funcName, string predictionFunc) = 1156 "static bool "~funcName~" (drflac_bs* bs, uint count, ubyte riceParam, uint order, int shift, const(short)* coefficients, int* pSamplesOut) {\n"~ 1157 " assert(bs !is null);\n"~ 1158 " assert(count > 0);\n"~ 1159 " assert(pSamplesOut !is null);\n"~ 1160 "\n"~ 1161 " static immutable uint[16] bitOffsetTable = [\n"~ 1162 " 0,\n"~ 1163 " 4,\n"~ 1164 " 3, 3,\n"~ 1165 " 2, 2, 2, 2,\n"~ 1166 " 1, 1, 1, 1, 1, 1, 1, 1\n"~ 1167 " ];\n"~ 1168 "\n"~ 1169 " drflac_cache_t riceParamMask = cast(drflac_cache_t)("~DRFLAC_CACHE_L1_SELECTION_MASK!"riceParam"~");\n"~ 1170 " drflac_cache_t resultHiShift = cast(drflac_cache_t)("~DRFLAC_CACHE_L1_SIZE_BITS!"bs"~"-riceParam);\n"~ 1171 "\n"~ 1172 " for (int i = 0; i < cast(int)count; ++i) {\n"~ 1173 " uint zeroCounter = 0;\n"~ 1174 " while (bs.cache == 0) {\n"~ 1175 " zeroCounter += cast(uint)"~DRFLAC_CACHE_L1_BITS_REMAINING!"bs"~";\n"~ 1176 " if (!drflac__reload_cache(bs)) return false;\n"~ 1177 " }\n"~ 1178 "\n"~ 1179 " /* At this point the cache should not be zero, in which case we know the first set bit should be somewhere in here. There is\n"~ 1180 " no need for us to perform any cache reloading logic here which should make things much faster. */\n"~ 1181 " assert(bs.cache != 0);\n"~ 1182 " uint decodedRice;\n"~ 1183 "\n"~ 1184 " uint setBitOffsetPlus1 = bitOffsetTable.ptr["~DRFLAC_CACHE_L1_SELECT_AND_SHIFT!("bs", "4")~"];\n"~ 1185 " if (setBitOffsetPlus1 > 0) {\n"~ 1186 " decodedRice = (zeroCounter+(setBitOffsetPlus1-1))<<riceParam;\n"~ 1187 " } else {\n"~ 1188 " if (bs.cache == 1) {\n"~ 1189 " setBitOffsetPlus1 = cast(uint)("~DRFLAC_CACHE_L1_SIZE_BITS!"bs"~");\n"~ 1190 " decodedRice = cast(uint)((zeroCounter+("~DRFLAC_CACHE_L1_SIZE_BITS!"bs"~"-1))<<riceParam);\n"~ 1191 " } else {\n"~ 1192 " setBitOffsetPlus1 = 5;\n"~ 1193 " for (;;) {\n"~ 1194 " if ((bs.cache&"~DRFLAC_CACHE_L1_SELECT!("bs", "setBitOffsetPlus1")~")) {\n"~ 1195 " decodedRice = (zeroCounter+(setBitOffsetPlus1-1))<<riceParam;\n"~ 1196 " break;\n"~ 1197 " }\n"~ 1198 " setBitOffsetPlus1 += 1;\n"~ 1199 " }\n"~ 1200 " }\n"~ 1201 " }\n"~ 1202 "\n"~ 1203 " uint bitsLo = 0;\n"~ 1204 " uint riceLength = setBitOffsetPlus1+riceParam;\n"~ 1205 " if (riceLength < "~DRFLAC_CACHE_L1_BITS_REMAINING!"bs"~") {\n"~ 1206 " bitsLo = cast(uint)((bs.cache&(riceParamMask>>setBitOffsetPlus1))>>("~DRFLAC_CACHE_L1_SIZE_BITS!"bs"~"-riceLength));\n"~ 1207 " bs.consumedBits += riceLength;\n"~ 1208 " bs.cache <<= riceLength;\n"~ 1209 " } else {\n"~ 1210 " bs.consumedBits += riceLength;\n"~ 1211 " bs.cache <<= setBitOffsetPlus1;\n"~ 1212 "\n"~ 1213 " /* 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. */\n"~ 1214 " size_t bitCountLo = bs.consumedBits-"~DRFLAC_CACHE_L1_SIZE_BITS!"bs"~";\n"~ 1215 " drflac_cache_t resultHi = bs.cache&riceParamMask; /* <-- This mask is OK because all bits after the first bits are always zero. */\n"~ 1216 "\n"~ 1217 " if (bs.nextL2Line < "~DRFLAC_CACHE_L2_LINE_COUNT!"bs"~") {\n"~ 1218 " bs.cache = drflac__be2host__cache_line(bs.cacheL2.ptr[bs.nextL2Line++]);\n"~ 1219 " } else {\n"~ 1220 " /* Slow path. We need to fetch more data from the client. */\n"~ 1221 " if (!drflac__reload_cache(bs)) return false;\n"~ 1222 " }\n"~ 1223 "\n"~ 1224 " bitsLo = cast(uint)((resultHi>>resultHiShift)|"~DRFLAC_CACHE_L1_SELECT_AND_SHIFT!("bs", "bitCountLo")~");\n"~ 1225 " bs.consumedBits = bitCountLo;\n"~ 1226 " bs.cache <<= bitCountLo;\n"~ 1227 " }\n"~ 1228 "\n"~ 1229 " decodedRice |= bitsLo;\n"~ 1230 " decodedRice = (decodedRice>>1)^(~(decodedRice&0x01)+1); /* <-- Ah, much faster! :) */\n"~ 1231 " /*\n"~ 1232 " if ((decodedRice&0x01)) {\n"~ 1233 " decodedRice = ~(decodedRice>>1);\n"~ 1234 " } else {\n"~ 1235 " decodedRice = (decodedRice>>1);\n"~ 1236 " }\n"~ 1237 " */\n"~ 1238 "\n"~ 1239 " /* In order to properly calculate the prediction when the bits per sample is >16 we need to do it using 64-bit arithmetic. We can assume this\n"~ 1240 " is probably going to be slower on 32-bit systems so we'll do a more optimized 32-bit version when the bits per sample is low enough.*/\n"~ 1241 " pSamplesOut[i] = (cast(int)decodedRice+"~predictionFunc~"(order, shift, coefficients, pSamplesOut+i));\n"~ 1242 " }\n"~ 1243 "\n"~ 1244 " return true;\n"~ 1245 "}\n"; 1246 1247 mixin(DRFLAC__DECODE_SAMPLES_WITH_RESIDULE__RICE__PROC!("drflac__decode_samples_with_residual__rice_64", "drflac__calculate_prediction_64")); 1248 mixin(DRFLAC__DECODE_SAMPLES_WITH_RESIDULE__RICE__PROC!("drflac__decode_samples_with_residual__rice_32", "drflac__calculate_prediction_32")); 1249 1250 1251 // 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. 1252 bool drflac__read_and_seek_residual__rice (drflac_bs* bs, uint count, ubyte riceParam) { 1253 assert(bs !is null); 1254 assert(count > 0); 1255 1256 for (uint i = 0; i < count; ++i) { 1257 if (!drflac__read_and_seek_rice(bs, riceParam)) return false; 1258 } 1259 1260 return true; 1261 } 1262 1263 bool drflac__decode_samples_with_residual__unencoded (drflac_bs* bs, uint bitsPerSample, uint count, ubyte unencodedBitsPerSample, uint order, int shift, const short* coefficients, int* pSamplesOut) { 1264 assert(bs !is null); 1265 assert(count > 0); 1266 assert(unencodedBitsPerSample > 0 && unencodedBitsPerSample <= 32); 1267 assert(pSamplesOut !is null); 1268 1269 for (uint i = 0; i < count; ++i) { 1270 if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut+i)) return false; 1271 if (bitsPerSample > 16) { 1272 pSamplesOut[i] += drflac__calculate_prediction_64(order, shift, coefficients, pSamplesOut+i); 1273 } else { 1274 pSamplesOut[i] += drflac__calculate_prediction_32(order, shift, coefficients, pSamplesOut+i); 1275 } 1276 } 1277 1278 return true; 1279 } 1280 1281 1282 // Reads and decodes the residual for the sub-frame the decoder is currently sitting on. This function should be called 1283 // when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be ignored. The 1284 // <blockSize> and <order> parameters are used to determine how many residual values need to be decoded. 1285 bool drflac__decode_samples_with_residual (drflac_bs* bs, uint bitsPerSample, uint blockSize, uint order, int shift, const short* coefficients, int* pDecodedSamples) { 1286 assert(bs !is null); 1287 assert(blockSize != 0); 1288 assert(pDecodedSamples !is null); // <-- Should we allow null, in which case we just seek past the residual rather than do a full decode? 1289 1290 ubyte residualMethod; 1291 if (!drflac__read_uint8(bs, 2, &residualMethod)) return false; 1292 1293 if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) return false; // Unknown or unsupported residual coding method. 1294 1295 // Ignore the first <order> values. 1296 pDecodedSamples += order; 1297 1298 ubyte partitionOrder; 1299 if (!drflac__read_uint8(bs, 4, &partitionOrder)) return false; 1300 1301 uint samplesInPartition = (blockSize/(1<<partitionOrder))-order; 1302 uint partitionsRemaining = (1<<partitionOrder); 1303 for (;;) { 1304 ubyte riceParam = 0; 1305 if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) { 1306 if (!drflac__read_uint8(bs, 4, &riceParam)) return false; 1307 if (riceParam == 16) riceParam = 0xFF; 1308 } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { 1309 if (!drflac__read_uint8(bs, 5, &riceParam)) return false; 1310 if (riceParam == 32) riceParam = 0xFF; 1311 } 1312 1313 if (riceParam != 0xFF) { 1314 if (bitsPerSample > 16) { 1315 if (!drflac__decode_samples_with_residual__rice_64(bs, samplesInPartition, riceParam, order, shift, coefficients, pDecodedSamples)) return false; 1316 } else { 1317 if (!drflac__decode_samples_with_residual__rice_32(bs, samplesInPartition, riceParam, order, shift, coefficients, pDecodedSamples)) return false; 1318 } 1319 } else { 1320 ubyte unencodedBitsPerSample = 0; 1321 if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) return false; 1322 if (!drflac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, order, shift, coefficients, pDecodedSamples)) return false; 1323 } 1324 1325 pDecodedSamples += samplesInPartition; 1326 1327 if (partitionsRemaining == 1) break; 1328 1329 partitionsRemaining -= 1; 1330 samplesInPartition = blockSize/(1<<partitionOrder); 1331 } 1332 1333 return true; 1334 } 1335 1336 // Reads and seeks past the residual for the sub-frame the decoder is currently sitting on. This function should be called 1337 // when the decoder is sitting at the very start of the RESIDUAL block. The first <order> residuals will be set to 0. The 1338 // <blockSize> and <order> parameters are used to determine how many residual values need to be decoded. 1339 bool drflac__read_and_seek_residual (drflac_bs* bs, uint blockSize, uint order) { 1340 assert(bs !is null); 1341 assert(blockSize != 0); 1342 1343 ubyte residualMethod; 1344 if (!drflac__read_uint8(bs, 2, &residualMethod)) return false; 1345 1346 if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) return false; // Unknown or unsupported residual coding method. 1347 1348 ubyte partitionOrder; 1349 if (!drflac__read_uint8(bs, 4, &partitionOrder)) return false; 1350 1351 uint samplesInPartition = (blockSize/(1<<partitionOrder))-order; 1352 uint partitionsRemaining = (1<<partitionOrder); 1353 for (;;) { 1354 ubyte riceParam = 0; 1355 if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) { 1356 if (!drflac__read_uint8(bs, 4, &riceParam)) return false; 1357 if (riceParam == 16) riceParam = 0xFF; 1358 } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) { 1359 if (!drflac__read_uint8(bs, 5, &riceParam)) return false; 1360 if (riceParam == 32) riceParam = 0xFF; 1361 } 1362 1363 if (riceParam != 0xFF) { 1364 if (!drflac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) return false; 1365 } else { 1366 ubyte unencodedBitsPerSample = 0; 1367 if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) return false; 1368 if (!drflac__seek_bits(bs, unencodedBitsPerSample*samplesInPartition)) return false; 1369 } 1370 1371 if (partitionsRemaining == 1) break; 1372 1373 partitionsRemaining -= 1; 1374 samplesInPartition = blockSize/(1<<partitionOrder); 1375 } 1376 1377 return true; 1378 } 1379 1380 1381 bool drflac__decode_samples__constant (drflac_bs* bs, uint blockSize, uint bitsPerSample, int* pDecodedSamples) { 1382 // Only a single sample needs to be decoded here. 1383 int sample; 1384 if (!drflac__read_int32(bs, bitsPerSample, &sample)) return false; 1385 1386 // We don't really need to expand this, but it does simplify the process of reading samples. If this becomes a performance issue (unlikely) 1387 // we'll want to look at a more efficient way. 1388 for (uint i = 0; i < blockSize; ++i) pDecodedSamples[i] = sample; 1389 1390 return true; 1391 } 1392 1393 bool drflac__decode_samples__verbatim (drflac_bs* bs, uint blockSize, uint bitsPerSample, int* pDecodedSamples) { 1394 for (uint i = 0; i < blockSize; ++i) { 1395 int sample; 1396 if (!drflac__read_int32(bs, bitsPerSample, &sample)) return false; 1397 pDecodedSamples[i] = sample; 1398 } 1399 return true; 1400 } 1401 1402 bool drflac__decode_samples__fixed (drflac_bs* bs, uint blockSize, uint bitsPerSample, ubyte lpcOrder, int* pDecodedSamples) { 1403 static immutable short[4][5] lpcCoefficientsTable = [ 1404 [0, 0, 0, 0], 1405 [1, 0, 0, 0], 1406 [2, -1, 0, 0], 1407 [3, -3, 1, 0], 1408 [4, -6, 4, -1] 1409 ]; 1410 1411 // Warm up samples and coefficients. 1412 for (uint i = 0; i < lpcOrder; ++i) { 1413 int sample; 1414 if (!drflac__read_int32(bs, bitsPerSample, &sample)) return false; 1415 pDecodedSamples[i] = sample; 1416 } 1417 1418 if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, 0, lpcCoefficientsTable.ptr[lpcOrder].ptr, pDecodedSamples)) return false; 1419 1420 return true; 1421 } 1422 1423 bool drflac__decode_samples__lpc (drflac_bs* bs, uint blockSize, uint bitsPerSample, ubyte lpcOrder, int* pDecodedSamples) { 1424 // Warm up samples. 1425 for (ubyte i = 0; i < lpcOrder; ++i) { 1426 int sample; 1427 if (!drflac__read_int32(bs, bitsPerSample, &sample)) return false; 1428 pDecodedSamples[i] = sample; 1429 } 1430 1431 ubyte lpcPrecision; 1432 if (!drflac__read_uint8(bs, 4, &lpcPrecision)) return false; 1433 if (lpcPrecision == 15) return false; // Invalid. 1434 lpcPrecision += 1; 1435 1436 byte lpcShift; 1437 if (!drflac__read_int8(bs, 5, &lpcShift)) return false; 1438 1439 short[32] coefficients; 1440 for (ubyte i = 0; i < lpcOrder; ++i) { 1441 if (!drflac__read_int16(bs, lpcPrecision, coefficients.ptr+i)) return false; 1442 } 1443 1444 if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, coefficients.ptr, pDecodedSamples)) return false; 1445 1446 return true; 1447 } 1448 1449 1450 bool drflac__read_next_frame_header (drflac_bs* bs, ubyte streaminfoBitsPerSample, drflac_frame_header* header) { 1451 assert(bs !is null); 1452 assert(header !is null); 1453 1454 // At the moment the sync code is as a form of basic validation. The CRC is stored, but is unused at the moment. This 1455 // should probably be handled better in the future. 1456 1457 static immutable uint[12] sampleRateTable = [0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000]; 1458 static immutable ubyte[8] bitsPerSampleTable = [0, 8, 12, cast(ubyte)-1, 16, 20, 24, cast(ubyte)-1]; // -1 = reserved. 1459 1460 ushort syncCode = 0; 1461 if (!drflac__read_uint16(bs, 14, &syncCode)) return false; 1462 1463 if (syncCode != 0x3FFE) return false; // TODO: Try and recover by attempting to seek to and read the next frame? 1464 1465 ubyte reserved; 1466 if (!drflac__read_uint8(bs, 1, &reserved)) return false; 1467 1468 ubyte blockingStrategy = 0; 1469 if (!drflac__read_uint8(bs, 1, &blockingStrategy)) return false; 1470 1471 ubyte blockSize = 0; 1472 if (!drflac__read_uint8(bs, 4, &blockSize)) return false; 1473 1474 ubyte sampleRate = 0; 1475 if (!drflac__read_uint8(bs, 4, &sampleRate)) return false; 1476 1477 ubyte channelAssignment = 0; 1478 if (!drflac__read_uint8(bs, 4, &channelAssignment)) return false; 1479 1480 ubyte bitsPerSample = 0; 1481 if (!drflac__read_uint8(bs, 3, &bitsPerSample)) return false; 1482 1483 if (!drflac__read_uint8(bs, 1, &reserved)) return false; 1484 1485 bool isVariableBlockSize = blockingStrategy == 1; 1486 if (isVariableBlockSize) { 1487 ulong sampleNumber; 1488 if (!drflac__read_utf8_coded_number(bs, &sampleNumber)) return false; 1489 header.frameNumber = 0; 1490 header.sampleNumber = sampleNumber; 1491 } else { 1492 ulong frameNumber = 0; 1493 if (!drflac__read_utf8_coded_number(bs, &frameNumber)) return false; 1494 header.frameNumber = cast(uint)frameNumber; // <-- Safe cast. 1495 header.sampleNumber = 0; 1496 } 1497 1498 if (blockSize == 1) { 1499 header.blockSize = 192; 1500 } else if (blockSize >= 2 && blockSize <= 5) { 1501 header.blockSize = cast(ushort)(576*(1<<(blockSize-2))); //k8 1502 } else if (blockSize == 6) { 1503 if (!drflac__read_uint16(bs, 8, &header.blockSize)) return false; 1504 header.blockSize += 1; 1505 } else if (blockSize == 7) { 1506 if (!drflac__read_uint16(bs, 16, &header.blockSize)) return false; 1507 header.blockSize += 1; 1508 } else { 1509 header.blockSize = cast(ushort)(256*(1<<(blockSize-8))); //k8 1510 } 1511 1512 if (sampleRate <= 11) { 1513 header.sampleRate = sampleRateTable.ptr[sampleRate]; 1514 } else if (sampleRate == 12) { 1515 if (!drflac__read_uint32(bs, 8, &header.sampleRate)) return false; 1516 header.sampleRate *= 1000; 1517 } else if (sampleRate == 13) { 1518 if (!drflac__read_uint32(bs, 16, &header.sampleRate)) return false; 1519 } else if (sampleRate == 14) { 1520 if (!drflac__read_uint32(bs, 16, &header.sampleRate)) return false; 1521 header.sampleRate *= 10; 1522 } else { 1523 return false; // Invalid. 1524 } 1525 1526 header.channelAssignment = channelAssignment; 1527 1528 header.bitsPerSample = bitsPerSampleTable.ptr[bitsPerSample]; 1529 if (header.bitsPerSample == 0) header.bitsPerSample = streaminfoBitsPerSample; 1530 1531 if (drflac__read_uint8(bs, 8, &header.crc8) != 1) return false; 1532 1533 return true; 1534 } 1535 1536 bool drflac__read_subframe_header (drflac_bs* bs, drflac_subframe* pSubframe) { 1537 ubyte header; 1538 if (!drflac__read_uint8(bs, 8, &header)) return false; 1539 1540 // First bit should always be 0. 1541 if ((header&0x80) != 0) return false; 1542 1543 int type = (header&0x7E)>>1; 1544 if (type == 0) { 1545 pSubframe.subframeType = DRFLAC_SUBFRAME_CONSTANT; 1546 } else if (type == 1) { 1547 pSubframe.subframeType = DRFLAC_SUBFRAME_VERBATIM; 1548 } else { 1549 if ((type&0x20) != 0) { 1550 pSubframe.subframeType = DRFLAC_SUBFRAME_LPC; 1551 pSubframe.lpcOrder = (type&0x1F)+1; 1552 } else if ((type&0x08) != 0) { 1553 pSubframe.subframeType = DRFLAC_SUBFRAME_FIXED; 1554 pSubframe.lpcOrder = (type&0x07); 1555 if (pSubframe.lpcOrder > 4) { 1556 pSubframe.subframeType = DRFLAC_SUBFRAME_RESERVED; 1557 pSubframe.lpcOrder = 0; 1558 } 1559 } else { 1560 pSubframe.subframeType = DRFLAC_SUBFRAME_RESERVED; 1561 } 1562 } 1563 1564 if (pSubframe.subframeType == DRFLAC_SUBFRAME_RESERVED) return false; 1565 1566 // Wasted bits per sample. 1567 pSubframe.wastedBitsPerSample = 0; 1568 if ((header&0x01) == 1) { 1569 uint wastedBitsPerSample; 1570 if (!drflac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) return false; 1571 pSubframe.wastedBitsPerSample = cast(ubyte)(cast(ubyte)wastedBitsPerSample+1); // k8 1572 } 1573 1574 return true; 1575 } 1576 1577 bool drflac__decode_subframe (drflac_bs* bs, drflac_frame* frame, int subframeIndex, int* pDecodedSamplesOut) { 1578 assert(bs !is null); 1579 assert(frame !is null); 1580 1581 drflac_subframe* pSubframe = frame.subframes.ptr+subframeIndex; 1582 if (!drflac__read_subframe_header(bs, pSubframe)) return false; 1583 1584 // Side channels require an extra bit per sample. Took a while to figure that one out... 1585 pSubframe.bitsPerSample = frame.header.bitsPerSample; 1586 if ((frame.header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame.header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) { 1587 pSubframe.bitsPerSample += 1; 1588 } else if (frame.header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) { 1589 pSubframe.bitsPerSample += 1; 1590 } 1591 1592 // Need to handle wasted bits per sample. 1593 pSubframe.bitsPerSample -= pSubframe.wastedBitsPerSample; 1594 pSubframe.pDecodedSamples = pDecodedSamplesOut; 1595 1596 switch (pSubframe.subframeType) { 1597 case DRFLAC_SUBFRAME_CONSTANT: drflac__decode_samples__constant(bs, frame.header.blockSize, pSubframe.bitsPerSample, pSubframe.pDecodedSamples); break; 1598 case DRFLAC_SUBFRAME_VERBATIM: drflac__decode_samples__verbatim(bs, frame.header.blockSize, pSubframe.bitsPerSample, pSubframe.pDecodedSamples); break; 1599 case DRFLAC_SUBFRAME_FIXED: drflac__decode_samples__fixed(bs, frame.header.blockSize, pSubframe.bitsPerSample, pSubframe.lpcOrder, pSubframe.pDecodedSamples); break; 1600 case DRFLAC_SUBFRAME_LPC: drflac__decode_samples__lpc(bs, frame.header.blockSize, pSubframe.bitsPerSample, pSubframe.lpcOrder, pSubframe.pDecodedSamples); break; 1601 default: return false; 1602 } 1603 1604 return true; 1605 } 1606 1607 bool drflac__seek_subframe (drflac_bs* bs, drflac_frame* frame, int subframeIndex) { 1608 assert(bs !is null); 1609 assert(frame !is null); 1610 1611 drflac_subframe* pSubframe = frame.subframes.ptr+subframeIndex; 1612 if (!drflac__read_subframe_header(bs, pSubframe)) return false; 1613 1614 // Side channels require an extra bit per sample. Took a while to figure that one out... 1615 pSubframe.bitsPerSample = frame.header.bitsPerSample; 1616 if ((frame.header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame.header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) { 1617 pSubframe.bitsPerSample += 1; 1618 } else if (frame.header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) { 1619 pSubframe.bitsPerSample += 1; 1620 } 1621 1622 // Need to handle wasted bits per sample. 1623 pSubframe.bitsPerSample -= pSubframe.wastedBitsPerSample; 1624 pSubframe.pDecodedSamples = null; 1625 //pSubframe.pDecodedSamples = pFlac.pDecodedSamples+(pFlac.currentFrame.header.blockSize*subframeIndex); 1626 1627 switch (pSubframe.subframeType) { 1628 case DRFLAC_SUBFRAME_CONSTANT: 1629 if (!drflac__seek_bits(bs, pSubframe.bitsPerSample)) return false; 1630 break; 1631 1632 case DRFLAC_SUBFRAME_VERBATIM: 1633 uint bitsToSeek = frame.header.blockSize*pSubframe.bitsPerSample; 1634 if (!drflac__seek_bits(bs, bitsToSeek)) return false; 1635 break; 1636 1637 case DRFLAC_SUBFRAME_FIXED: 1638 uint bitsToSeek = pSubframe.lpcOrder*pSubframe.bitsPerSample; 1639 if (!drflac__seek_bits(bs, bitsToSeek)) return false; 1640 if (!drflac__read_and_seek_residual(bs, frame.header.blockSize, pSubframe.lpcOrder)) return false; 1641 break; 1642 1643 case DRFLAC_SUBFRAME_LPC: 1644 uint bitsToSeek = pSubframe.lpcOrder*pSubframe.bitsPerSample; 1645 if (!drflac__seek_bits(bs, bitsToSeek)) return false; 1646 ubyte lpcPrecision; 1647 if (!drflac__read_uint8(bs, 4, &lpcPrecision)) return false; 1648 if (lpcPrecision == 15) return false; // Invalid. 1649 lpcPrecision += 1; 1650 bitsToSeek = (pSubframe.lpcOrder*lpcPrecision)+5; // +5 for shift. 1651 if (!drflac__seek_bits(bs, bitsToSeek)) return false; 1652 if (!drflac__read_and_seek_residual(bs, frame.header.blockSize, pSubframe.lpcOrder)) return false; 1653 break; 1654 1655 default: return false; 1656 } 1657 1658 return true; 1659 } 1660 1661 1662 ubyte drflac__get_channel_count_from_channel_assignment (byte channelAssignment) { 1663 assert(channelAssignment <= 10); 1664 static immutable ubyte[11] lookup = [1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2]; 1665 return lookup.ptr[channelAssignment]; 1666 } 1667 1668 bool drflac__decode_frame (drflac* pFlac) { 1669 import core.stdc..string : memset; 1670 // This function should be called while the stream is sitting on the first byte after the frame header. 1671 memset(pFlac.currentFrame.subframes.ptr, 0, (pFlac.currentFrame.subframes).sizeof); 1672 1673 int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment); 1674 for (int i = 0; i < channelCount; ++i) { 1675 if (!drflac__decode_subframe(&pFlac.bs, &pFlac.currentFrame, i, pFlac.pDecodedSamples+(pFlac.currentFrame.header.blockSize*i))) return false; 1676 } 1677 1678 // At the end of the frame sits the padding and CRC. We don't use these so we can just seek past. 1679 if (!drflac__seek_bits(&pFlac.bs, (mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"(&pFlac.bs)")&7)+16)) return false; 1680 1681 pFlac.currentFrame.samplesRemaining = pFlac.currentFrame.header.blockSize*channelCount; 1682 1683 return true; 1684 } 1685 1686 bool drflac__seek_frame (drflac* pFlac) { 1687 int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment); 1688 for (int i = 0; i < channelCount; ++i) { 1689 if (!drflac__seek_subframe(&pFlac.bs, &pFlac.currentFrame, i)) return false; 1690 } 1691 // Padding and CRC. 1692 return drflac__seek_bits(&pFlac.bs, (mixin(DRFLAC_CACHE_L1_BITS_REMAINING!"(&pFlac.bs)")&7)+16); 1693 } 1694 1695 bool drflac__read_and_decode_next_frame (drflac* pFlac) { 1696 assert(pFlac !is null); 1697 1698 if (!drflac__read_next_frame_header(&pFlac.bs, pFlac.bitsPerSample, &pFlac.currentFrame.header)) return false; 1699 1700 return drflac__decode_frame(pFlac); 1701 } 1702 1703 1704 void drflac__get_current_frame_sample_range (drflac* pFlac, ulong* pFirstSampleInFrameOut, ulong* pLastSampleInFrameOut) { 1705 assert(pFlac !is null); 1706 1707 uint channelCount = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment); 1708 1709 ulong firstSampleInFrame = pFlac.currentFrame.header.sampleNumber; 1710 if (firstSampleInFrame == 0) firstSampleInFrame = pFlac.currentFrame.header.frameNumber*pFlac.maxBlockSize*channelCount; 1711 1712 ulong lastSampleInFrame = firstSampleInFrame+(pFlac.currentFrame.header.blockSize*channelCount); 1713 if (lastSampleInFrame > 0) lastSampleInFrame -= 1; // Needs to be zero based. 1714 1715 if (pFirstSampleInFrameOut) *pFirstSampleInFrameOut = firstSampleInFrame; 1716 if (pLastSampleInFrameOut) *pLastSampleInFrameOut = lastSampleInFrame; 1717 } 1718 1719 bool drflac__seek_to_first_frame (drflac* pFlac) { 1720 import core.stdc..string : memset; 1721 assert(pFlac !is null); 1722 1723 bool result = drflac__seek_to_byte(&pFlac.bs, pFlac.firstFramePos); 1724 1725 memset(&pFlac.currentFrame, 0, (pFlac.currentFrame).sizeof); 1726 return result; 1727 } 1728 1729 bool drflac__seek_to_next_frame (drflac* pFlac) { 1730 // This function should only ever be called while the decoder is sitting on the first byte past the FRAME_HEADER section. 1731 assert(pFlac !is null); 1732 return drflac__seek_frame(pFlac); 1733 } 1734 1735 bool drflac__seek_to_frame_containing_sample (drflac* pFlac, ulong sampleIndex) { 1736 assert(pFlac !is null); 1737 1738 if (!drflac__seek_to_first_frame(pFlac)) return false; 1739 1740 ulong firstSampleInFrame = 0; 1741 ulong lastSampleInFrame = 0; 1742 for (;;) { 1743 // We need to read the frame's header in order to determine the range of samples it contains. 1744 if (!drflac__read_next_frame_header(&pFlac.bs, pFlac.bitsPerSample, &pFlac.currentFrame.header)) return false; 1745 drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame); 1746 if (sampleIndex >= firstSampleInFrame && sampleIndex <= lastSampleInFrame) break; // The sample is in this frame. 1747 if (!drflac__seek_to_next_frame(pFlac)) return false; 1748 } 1749 1750 // If we get here we should be right at the start of the frame containing the sample. 1751 return true; 1752 } 1753 1754 bool drflac__seek_to_sample__brute_force (drflac* pFlac, ulong sampleIndex) { 1755 if (!drflac__seek_to_frame_containing_sample(pFlac, sampleIndex)) return false; 1756 1757 // At this point we should be sitting on the first byte of the frame containing the sample. We need to decode every sample up to (but 1758 // not including) the sample we're seeking to. 1759 ulong firstSampleInFrame = 0; 1760 drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, null); 1761 1762 assert(firstSampleInFrame <= sampleIndex); 1763 size_t samplesToDecode = cast(size_t)(sampleIndex-firstSampleInFrame); // <-- Safe cast because the maximum number of samples in a frame is 65535. 1764 if (samplesToDecode == 0) return true; 1765 1766 // At this point we are just sitting on the byte after the frame header. We need to decode the frame before reading anything from it. 1767 if (!drflac__decode_frame(pFlac)) return false; 1768 1769 return drflac_read_s32(pFlac, samplesToDecode, null) != 0; 1770 } 1771 1772 1773 bool drflac__seek_to_sample__seek_table (drflac* pFlac, ulong sampleIndex) { 1774 assert(pFlac !is null); 1775 1776 if (pFlac.seektablePos == 0) return false; 1777 1778 if (!drflac__seek_to_byte(&pFlac.bs, pFlac.seektablePos)) return false; 1779 1780 // The number of seek points is derived from the size of the SEEKTABLE block. 1781 uint seekpointCount = pFlac.seektableSize/18; // 18 = the size of each seek point. 1782 if (seekpointCount == 0) return false; // Would this ever happen? 1783 1784 drflac_seekpoint closestSeekpoint = {0}; 1785 1786 uint seekpointsRemaining = seekpointCount; 1787 while (seekpointsRemaining > 0) { 1788 drflac_seekpoint seekpoint; 1789 if (!drflac__read_uint64(&pFlac.bs, 64, &seekpoint.firstSample)) break; 1790 if (!drflac__read_uint64(&pFlac.bs, 64, &seekpoint.frameOffset)) break; 1791 if (!drflac__read_uint16(&pFlac.bs, 16, &seekpoint.sampleCount)) break; 1792 if (seekpoint.firstSample*pFlac.channels > sampleIndex) break; 1793 closestSeekpoint = seekpoint; 1794 seekpointsRemaining -= 1; 1795 } 1796 1797 // At this point we should have found the seekpoint closest to our sample. We need to seek to it using basically the same 1798 // technique as we use with the brute force method. 1799 if (!drflac__seek_to_byte(&pFlac.bs, pFlac.firstFramePos+closestSeekpoint.frameOffset)) return false; 1800 1801 ulong firstSampleInFrame = 0; 1802 ulong lastSampleInFrame = 0; 1803 for (;;) { 1804 // We need to read the frame's header in order to determine the range of samples it contains. 1805 if (!drflac__read_next_frame_header(&pFlac.bs, pFlac.bitsPerSample, &pFlac.currentFrame.header)) return false; 1806 drflac__get_current_frame_sample_range(pFlac, &firstSampleInFrame, &lastSampleInFrame); 1807 if (sampleIndex >= firstSampleInFrame && sampleIndex <= lastSampleInFrame) break; // The sample is in this frame. 1808 if (!drflac__seek_to_next_frame(pFlac)) return false; 1809 } 1810 1811 assert(firstSampleInFrame <= sampleIndex); 1812 1813 // At this point we are just sitting on the byte after the frame header. We need to decode the frame before reading anything from it. 1814 if (!drflac__decode_frame(pFlac)) return false; 1815 1816 size_t samplesToDecode = cast(size_t)(sampleIndex-firstSampleInFrame); // <-- Safe cast because the maximum number of samples in a frame is 65535. 1817 return drflac_read_s32(pFlac, samplesToDecode, null) == samplesToDecode; 1818 } 1819 1820 1821 //#ifndef DR_FLAC_NO_OGG 1822 struct drflac_ogg_page_header { 1823 ubyte[4] capturePattern; // Should be "OggS" 1824 ubyte structureVersion; // Always 0. 1825 ubyte headerType; 1826 ulong granulePosition; 1827 uint serialNumber; 1828 uint sequenceNumber; 1829 uint checksum; 1830 ubyte segmentCount; 1831 ubyte[255] segmentTable; 1832 } 1833 //#endif 1834 1835 struct drflac_init_info { 1836 //drflac_read_proc onRead; 1837 //drflac_seek_proc onSeek; 1838 //void* pUserData; 1839 ReadStruct rs; 1840 //drflac_meta_proc onMeta; 1841 //void* pUserDataMD; 1842 drflac_container container; 1843 uint sampleRate; 1844 ubyte channels; 1845 ubyte bitsPerSample; 1846 ulong totalSampleCount; 1847 ushort maxBlockSize; 1848 ulong runningFilePos; 1849 bool hasMetadataBlocks; 1850 1851 //#ifndef DR_FLAC_NO_OGG 1852 uint oggSerial; 1853 ulong oggFirstBytePos; 1854 drflac_ogg_page_header oggBosHeader; 1855 //#endif 1856 } 1857 1858 private struct ReadStruct { 1859 @nogc: 1860 static if (DrFlacHasVFS) VFile srcfile; 1861 drflac_read_proc onReadCB; 1862 drflac_seek_proc onSeekCB; 1863 void* pUserData; 1864 1865 size_t read (void* pBufferOut, size_t bytesToRead) nothrow { 1866 auto b = cast(ubyte*)pBufferOut; 1867 auto res = 0; 1868 try { 1869 while (bytesToRead > 0) { 1870 size_t rd = 0; 1871 if (onReadCB !is null) { 1872 rd = onReadCB(pUserData, b, bytesToRead); 1873 } else { 1874 static if (DrFlacHasVFS) { 1875 if (srcfile.isOpen) rd = srcfile.rawRead(b[0..bytesToRead]).length; 1876 } 1877 } 1878 if (rd == 0) break; 1879 b += rd; 1880 res += rd; 1881 bytesToRead -= rd; 1882 } 1883 return res; 1884 } catch (Exception e) { 1885 return 0; 1886 } 1887 } 1888 1889 bool seek (int offset, drflac_seek_origin origin) nothrow { 1890 try { 1891 if (onSeekCB !is null) { 1892 return onSeekCB(pUserData, offset, origin); 1893 } else { 1894 static if (DrFlacHasVFS) { 1895 if (srcfile.isOpen) { 1896 switch (origin) { 1897 case drflac_seek_origin_start: srcfile.seek(offset, Seek.Set); return true; 1898 case drflac_seek_origin_current: srcfile.seek(offset, Seek.Cur); return true; 1899 default: return false; 1900 } 1901 } 1902 } 1903 } 1904 return false; 1905 } catch (Exception e) { 1906 return 0; 1907 } 1908 } 1909 } 1910 1911 1912 void drflac__decode_block_header (uint blockHeader, ubyte* isLastBlock, ubyte* blockType, uint* blockSize) { 1913 blockHeader = drflac__be2host_32(blockHeader); 1914 *isLastBlock = (blockHeader&(0x01<<31))>>31; 1915 *blockType = (blockHeader&(0x7F<<24))>>24; 1916 *blockSize = (blockHeader&0xFFFFFF); 1917 } 1918 1919 bool drflac__read_and_decode_block_header (ref ReadStruct rs, ubyte* isLastBlock, ubyte* blockType, uint* blockSize) { 1920 uint blockHeader; 1921 if (rs.read(&blockHeader, 4) != 4) return false; 1922 drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize); 1923 return true; 1924 } 1925 1926 bool drflac__read_streaminfo (ref ReadStruct rs, drflac_streaminfo* pStreamInfo) { 1927 import core.stdc..string : memcpy; 1928 // min/max block size. 1929 uint blockSizes; 1930 if (rs.read(&blockSizes, 4) != 4) return false; 1931 // min/max frame size. 1932 ulong frameSizes = 0; 1933 if (rs.read(&frameSizes, 6) != 6) return false; 1934 // Sample rate, channels, bits per sample and total sample count. 1935 ulong importantProps; 1936 if (rs.read(&importantProps, 8) != 8) return false; 1937 // MD5 1938 ubyte[16] md5; 1939 if (rs.read(md5.ptr, md5.sizeof) != md5.sizeof) return false; 1940 1941 blockSizes = drflac__be2host_32(blockSizes); 1942 frameSizes = drflac__be2host_64(frameSizes); 1943 importantProps = drflac__be2host_64(importantProps); 1944 1945 pStreamInfo.minBlockSize = (blockSizes&0xFFFF0000)>>16; 1946 pStreamInfo.maxBlockSize = blockSizes&0x0000FFFF; 1947 pStreamInfo.minFrameSize = cast(uint)((frameSizes&0xFFFFFF0000000000UL)>>40); 1948 pStreamInfo.maxFrameSize = cast(uint)((frameSizes&0x000000FFFFFF0000UL)>>16); 1949 pStreamInfo.sampleRate = cast(uint)((importantProps&0xFFFFF00000000000UL)>>44); 1950 pStreamInfo.channels = cast(ubyte )((importantProps&0x00000E0000000000UL)>>41)+1; 1951 pStreamInfo.bitsPerSample = cast(ubyte )((importantProps&0x000001F000000000UL)>>36)+1; 1952 pStreamInfo.totalSampleCount = (importantProps&0x0000000FFFFFFFFFUL)*pStreamInfo.channels; 1953 memcpy(pStreamInfo.md5.ptr, md5.ptr, md5.sizeof); 1954 1955 return true; 1956 } 1957 1958 bool drflac__read_and_decode_metadata (drflac* pFlac, scope drflac_meta_proc onMeta, void* pUserDataMD) { 1959 import core.stdc.stdlib : malloc, free; 1960 assert(pFlac !is null); 1961 1962 // 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 1963 // we'll be sitting on byte 42. 1964 ulong runningFilePos = 42; 1965 ulong seektablePos = 0; 1966 uint seektableSize = 0; 1967 1968 for (;;) { 1969 ubyte isLastBlock = 0; 1970 ubyte blockType; 1971 uint blockSize; 1972 if (!drflac__read_and_decode_block_header(pFlac.bs.rs, &isLastBlock, &blockType, &blockSize)) return false; 1973 runningFilePos += 4; 1974 1975 drflac_metadata metadata; 1976 metadata.type = blockType; 1977 metadata.pRawData = null; 1978 metadata.rawDataSize = 0; 1979 1980 switch (blockType) { 1981 case DRFLAC_METADATA_BLOCK_TYPE_APPLICATION: 1982 if (onMeta) { 1983 void* pRawData = malloc(blockSize); 1984 if (pRawData is null) return false; 1985 scope(exit) free(pRawData); 1986 1987 if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false; 1988 1989 metadata.pRawData = pRawData; 1990 metadata.rawDataSize = blockSize; 1991 metadata.data.application.id = drflac__be2host_32(*cast(uint*)pRawData); 1992 metadata.data.application.pData = cast(const(void)*)(cast(ubyte*)pRawData+uint.sizeof); 1993 metadata.data.application.dataSize = blockSize-cast(uint)uint.sizeof; 1994 try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; } 1995 } 1996 break; 1997 1998 case DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE: 1999 seektablePos = runningFilePos; 2000 seektableSize = blockSize; 2001 2002 if (onMeta) { 2003 void* pRawData = malloc(blockSize); 2004 if (pRawData is null) return false; 2005 scope(exit) free(pRawData); 2006 2007 if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false; 2008 2009 metadata.pRawData = pRawData; 2010 metadata.rawDataSize = blockSize; 2011 metadata.data.seektable.seekpointCount = blockSize/(drflac_seekpoint).sizeof; 2012 metadata.data.seektable.pSeekpoints = cast(const(drflac_seekpoint)*)pRawData; 2013 2014 // Endian swap. 2015 for (uint iSeekpoint = 0; iSeekpoint < metadata.data.seektable.seekpointCount; ++iSeekpoint) { 2016 drflac_seekpoint* pSeekpoint = cast(drflac_seekpoint*)pRawData+iSeekpoint; 2017 pSeekpoint.firstSample = drflac__be2host_64(pSeekpoint.firstSample); 2018 pSeekpoint.frameOffset = drflac__be2host_64(pSeekpoint.frameOffset); 2019 pSeekpoint.sampleCount = drflac__be2host_16(pSeekpoint.sampleCount); 2020 } 2021 2022 try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; } 2023 } 2024 break; 2025 2026 case DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT: 2027 if (onMeta) { 2028 void* pRawData = malloc(blockSize); 2029 if (pRawData is null) return false; 2030 scope(exit) free(pRawData); 2031 2032 if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false; 2033 2034 metadata.pRawData = pRawData; 2035 metadata.rawDataSize = blockSize; 2036 2037 const(char)* pRunningData = cast(const(char)*)pRawData; 2038 metadata.data.vorbis_comment.vendorLength = drflac__le2host_32(*cast(uint*)pRunningData); pRunningData += 4; 2039 metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength; 2040 metadata.data.vorbis_comment.commentCount = drflac__le2host_32(*cast(uint*)pRunningData); pRunningData += 4; 2041 metadata.data.vorbis_comment.comments = pRunningData; 2042 try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; } 2043 } 2044 break; 2045 2046 case DRFLAC_METADATA_BLOCK_TYPE_CUESHEET: 2047 if (onMeta) { 2048 import core.stdc..string : memcpy; 2049 void* pRawData = malloc(blockSize); 2050 if (pRawData is null) return false; 2051 scope(exit) free(pRawData); 2052 2053 if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false; 2054 2055 metadata.pRawData = pRawData; 2056 metadata.rawDataSize = blockSize; 2057 2058 const(char)* pRunningData = cast(const(char)*)pRawData; 2059 memcpy(metadata.data.cuesheet.catalog.ptr, pRunningData, 128); pRunningData += 128; 2060 metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*cast(ulong*)pRunningData);pRunningData += 4; 2061 metadata.data.cuesheet.isCD = ((pRunningData[0]&0x80)>>7) != 0; pRunningData += 259; 2062 metadata.data.cuesheet.trackCount = pRunningData[0]; pRunningData += 1; 2063 metadata.data.cuesheet.pTrackData = cast(const(ubyte)*)pRunningData; 2064 try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; } 2065 } 2066 break; 2067 2068 case DRFLAC_METADATA_BLOCK_TYPE_PICTURE: 2069 if (onMeta) { 2070 void* pRawData = malloc(blockSize); 2071 if (pRawData is null) return false; 2072 scope(exit) free(pRawData); 2073 2074 if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false; 2075 2076 metadata.pRawData = pRawData; 2077 metadata.rawDataSize = blockSize; 2078 2079 const(char)* pRunningData = cast(const(char)*)pRawData; 2080 metadata.data.picture.type = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4; 2081 metadata.data.picture.mimeLength = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4; 2082 metadata.data.picture.mime = pRunningData; pRunningData += metadata.data.picture.mimeLength; 2083 metadata.data.picture.descriptionLength = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4; 2084 metadata.data.picture.description = pRunningData; 2085 metadata.data.picture.width = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4; 2086 metadata.data.picture.height = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4; 2087 metadata.data.picture.colorDepth = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4; 2088 metadata.data.picture.indexColorCount = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4; 2089 metadata.data.picture.pictureDataSize = drflac__be2host_32(*cast(uint*)pRunningData); pRunningData += 4; 2090 metadata.data.picture.pPictureData = cast(const(ubyte)*)pRunningData; 2091 try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; } 2092 } 2093 break; 2094 2095 case DRFLAC_METADATA_BLOCK_TYPE_PADDING: 2096 if (onMeta) { 2097 metadata.data.padding.unused = 0; 2098 // Padding doesn't have anything meaningful in it, so just skip over it. 2099 if (!pFlac.bs.rs.seek(blockSize, drflac_seek_origin_current)) return false; 2100 //onMeta(pUserDataMD, &metadata); 2101 } 2102 break; 2103 2104 case DRFLAC_METADATA_BLOCK_TYPE_INVALID: 2105 // Invalid chunk. Just skip over this one. 2106 if (onMeta) { 2107 if (!pFlac.bs.rs.seek(blockSize, drflac_seek_origin_current)) return false; 2108 } 2109 goto default; 2110 2111 default: 2112 // It's an unknown chunk, but not necessarily invalid. There's a chance more metadata blocks might be defined later on, so we 2113 // can at the very least report the chunk to the application and let it look at the raw data. 2114 if (onMeta) { 2115 void* pRawData = malloc(blockSize); 2116 if (pRawData is null) return false; 2117 scope(exit) free(pRawData); 2118 2119 if (pFlac.bs.rs.read(pRawData, blockSize) != blockSize) return false; 2120 2121 metadata.pRawData = pRawData; 2122 metadata.rawDataSize = blockSize; 2123 try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; } 2124 } 2125 break; 2126 } 2127 2128 // 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. 2129 if (onMeta is null) { 2130 if (!pFlac.bs.rs.seek(blockSize, drflac_seek_origin_current)) return false; 2131 } 2132 2133 runningFilePos += blockSize; 2134 if (isLastBlock) break; 2135 } 2136 2137 pFlac.seektablePos = seektablePos; 2138 pFlac.seektableSize = seektableSize; 2139 pFlac.firstFramePos = runningFilePos; 2140 2141 return true; 2142 } 2143 2144 bool drflac__init_private__native (drflac_init_info* pInit, ref ReadStruct rs, scope drflac_meta_proc onMeta, void* pUserDataMD) { 2145 // Pre: The bit stream should be sitting just past the 4-byte id header. 2146 2147 pInit.container = drflac_container_native; 2148 2149 // The first metadata block should be the STREAMINFO block. 2150 ubyte isLastBlock; 2151 ubyte blockType; 2152 uint blockSize; 2153 if (!drflac__read_and_decode_block_header(rs, &isLastBlock, &blockType, &blockSize)) return false; 2154 2155 if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) return false; // Invalid block type. First block must be the STREAMINFO block. 2156 2157 drflac_streaminfo streaminfo; 2158 if (!drflac__read_streaminfo(rs, &streaminfo)) return false; 2159 2160 pInit.sampleRate = streaminfo.sampleRate; 2161 pInit.channels = streaminfo.channels; 2162 pInit.bitsPerSample = streaminfo.bitsPerSample; 2163 pInit.totalSampleCount = streaminfo.totalSampleCount; 2164 pInit.maxBlockSize = streaminfo.maxBlockSize; // Don't care about the min block size - only the max (used for determining the size of the memory allocation). 2165 2166 if (onMeta !is null) { 2167 drflac_metadata metadata; 2168 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO; 2169 metadata.pRawData = null; 2170 metadata.rawDataSize = 0; 2171 metadata.data.streaminfo = streaminfo; 2172 try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; } 2173 } 2174 2175 pInit.hasMetadataBlocks = !isLastBlock; 2176 return true; 2177 } 2178 2179 //#ifndef DR_FLAC_NO_OGG 2180 bool drflac_ogg__is_capture_pattern (const(ubyte)* pattern/*[4]*/) { 2181 return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S'; 2182 } 2183 2184 uint drflac_ogg__get_page_header_size (drflac_ogg_page_header* pHeader) { 2185 return 27+pHeader.segmentCount; 2186 } 2187 2188 uint drflac_ogg__get_page_body_size (drflac_ogg_page_header* pHeader) { 2189 uint pageBodySize = 0; 2190 for (int i = 0; i < pHeader.segmentCount; ++i) pageBodySize += pHeader.segmentTable.ptr[i]; 2191 return pageBodySize; 2192 } 2193 2194 bool drflac_ogg__read_page_header_after_capture_pattern (ref ReadStruct rs, drflac_ogg_page_header* pHeader, uint* pHeaderSize) { 2195 if (rs.read(&pHeader.structureVersion, 1) != 1 || pHeader.structureVersion != 0) return false; // Unknown structure version. Possibly corrupt stream. 2196 if (rs.read(&pHeader.headerType, 1) != 1) return false; 2197 if (rs.read(&pHeader.granulePosition, 8) != 8) return false; 2198 if (rs.read(&pHeader.serialNumber, 4) != 4) return false; 2199 if (rs.read(&pHeader.sequenceNumber, 4) != 4) return false; 2200 if (rs.read(&pHeader.checksum, 4) != 4) return false; 2201 if (rs.read(&pHeader.segmentCount, 1) != 1 || pHeader.segmentCount == 0) return false; // Should not have a segment count of 0. 2202 if (rs.read(&pHeader.segmentTable, pHeader.segmentCount) != pHeader.segmentCount) return false; 2203 if (pHeaderSize) *pHeaderSize = (27+pHeader.segmentCount); 2204 return true; 2205 } 2206 2207 bool drflac_ogg__read_page_header (ref ReadStruct rs, drflac_ogg_page_header* pHeader, uint* pHeaderSize) { 2208 ubyte[4] id; 2209 if (rs.read(id.ptr, 4) != 4) return false; 2210 if (id.ptr[0] != 'O' || id.ptr[1] != 'g' || id.ptr[2] != 'g' || id.ptr[3] != 'S') return false; 2211 return drflac_ogg__read_page_header_after_capture_pattern(rs, pHeader, pHeaderSize); 2212 } 2213 2214 2215 // The main part of the Ogg encapsulation is the conversion from the physical Ogg bitstream to the native FLAC bitstream. It works 2216 // in three general stages: Ogg Physical Bitstream . Ogg/FLAC Logical Bitstream . FLAC Native Bitstream. dr_flac is architecured 2217 // in such a way that the core sections assume everything is delivered in native format. Therefore, for each encapsulation type 2218 // 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 2219 // the physical Ogg bitstream are converted and delivered in native FLAC format. 2220 struct drflac_oggbs { 2221 //drflac_read_proc onRead; // The original onRead callback from drflac_open() and family. 2222 //drflac_seek_proc onSeek; // The original onSeek callback from drflac_open() and family. 2223 //void* pUserData; // The user data passed on onRead and onSeek. This is the user data that was passed on drflac_open() and family. 2224 ReadStruct rs; 2225 ulong currentBytePos; // The position of the byte we are sitting on in the physical byte stream. Used for efficient seeking. 2226 ulong firstBytePos; // The position of the first byte in the physical bitstream. Points to the start of the "OggS" identifier of the FLAC bos page. 2227 uint serialNumber; // The serial number of the FLAC audio pages. This is determined by the initial header page that was read during initialization. 2228 drflac_ogg_page_header bosPageHeader; // Used for seeking. 2229 drflac_ogg_page_header currentPageHeader; 2230 uint bytesRemainingInPage; 2231 bool stdio; //k8: it is drflac's stdio shit 2232 } // oggbs = Ogg Bitstream 2233 2234 size_t drflac_oggbs__read_physical (drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead) { 2235 size_t bytesActuallyRead = oggbs.rs.read(bufferOut, bytesToRead); 2236 oggbs.currentBytePos += bytesActuallyRead; 2237 return bytesActuallyRead; 2238 } 2239 2240 bool drflac_oggbs__seek_physical (drflac_oggbs* oggbs, ulong offset, drflac_seek_origin origin) { 2241 if (origin == drflac_seek_origin_start) { 2242 if (offset <= 0x7FFFFFFF) { 2243 if (!oggbs.rs.seek(cast(int)offset, drflac_seek_origin_start)) return false; 2244 oggbs.currentBytePos = offset; 2245 return true; 2246 } else { 2247 if (!oggbs.rs.seek(0x7FFFFFFF, drflac_seek_origin_start)) return false; 2248 oggbs.currentBytePos = offset; 2249 return drflac_oggbs__seek_physical(oggbs, offset-0x7FFFFFFF, drflac_seek_origin_current); 2250 } 2251 } else { 2252 while (offset > 0x7FFFFFFF) { 2253 if (!oggbs.rs.seek(0x7FFFFFFF, drflac_seek_origin_current)) return false; 2254 oggbs.currentBytePos += 0x7FFFFFFF; 2255 offset -= 0x7FFFFFFF; 2256 } 2257 if (!oggbs.rs.seek(cast(int)offset, drflac_seek_origin_current)) return false; // <-- Safe cast thanks to the loop above. 2258 oggbs.currentBytePos += offset; 2259 return true; 2260 } 2261 } 2262 2263 bool drflac_oggbs__goto_next_page (drflac_oggbs* oggbs) { 2264 drflac_ogg_page_header header; 2265 for (;;) { 2266 uint headerSize; 2267 if (!drflac_ogg__read_page_header(oggbs.rs, &header, &headerSize)) return false; 2268 oggbs.currentBytePos += headerSize; 2269 uint pageBodySize = drflac_ogg__get_page_body_size(&header); 2270 if (header.serialNumber == oggbs.serialNumber) { 2271 oggbs.currentPageHeader = header; 2272 oggbs.bytesRemainingInPage = pageBodySize; 2273 return true; 2274 } 2275 // If we get here it means the page is not a FLAC page - skip it. 2276 if (pageBodySize > 0 && !drflac_oggbs__seek_physical(oggbs, pageBodySize, drflac_seek_origin_current)) return false; // <-- Safe cast - maximum size of a page is way below that of an int. 2277 } 2278 } 2279 2280 size_t drflac__on_read_ogg (void* pUserData, void* bufferOut, size_t bytesToRead) { 2281 drflac_oggbs* oggbs = cast(drflac_oggbs*)pUserData; 2282 assert(oggbs !is null); 2283 2284 ubyte* pRunningBufferOut = cast(ubyte*)bufferOut; 2285 2286 // Reading is done page-by-page. If we've run out of bytes in the page we need to move to the next one. 2287 size_t bytesRead = 0; 2288 while (bytesRead < bytesToRead) { 2289 size_t bytesRemainingToRead = bytesToRead-bytesRead; 2290 2291 if (oggbs.bytesRemainingInPage >= bytesRemainingToRead) { 2292 bytesRead += oggbs.rs.read(pRunningBufferOut, bytesRemainingToRead); 2293 oggbs.bytesRemainingInPage -= cast(uint)bytesRemainingToRead; 2294 break; 2295 } 2296 2297 // If we get here it means some of the requested data is contained in the next pages. 2298 if (oggbs.bytesRemainingInPage > 0) { 2299 size_t bytesJustRead = oggbs.rs.read(pRunningBufferOut, oggbs.bytesRemainingInPage); 2300 bytesRead += bytesJustRead; 2301 pRunningBufferOut += bytesJustRead; 2302 if (bytesJustRead != oggbs.bytesRemainingInPage) break; // Ran out of data. 2303 } 2304 2305 assert(bytesRemainingToRead > 0); 2306 if (!drflac_oggbs__goto_next_page(oggbs)) break; // Failed to go to the next chunk. Might have simply hit the end of the stream. 2307 } 2308 2309 oggbs.currentBytePos += bytesRead; 2310 return bytesRead; 2311 } 2312 2313 bool drflac__on_seek_ogg (void* pUserData, int offset, drflac_seek_origin origin) { 2314 drflac_oggbs* oggbs = cast(drflac_oggbs*)pUserData; 2315 assert(oggbs !is null); 2316 assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start)); 2317 2318 // Seeking is always forward which makes things a lot simpler. 2319 if (origin == drflac_seek_origin_start) { 2320 int startBytePos = cast(int)oggbs.firstBytePos+(79-42); // 79 = size of bos page; 42 = size of FLAC header data. Seek up to the first byte of the native FLAC data. 2321 if (!drflac_oggbs__seek_physical(oggbs, startBytePos, drflac_seek_origin_start)) return false; 2322 oggbs.currentPageHeader = oggbs.bosPageHeader; 2323 oggbs.bytesRemainingInPage = 42; // 42 = size of the native FLAC header data. That's our start point for seeking. 2324 return drflac__on_seek_ogg(pUserData, offset, drflac_seek_origin_current); 2325 } 2326 2327 assert(origin == drflac_seek_origin_current); 2328 2329 int bytesSeeked = 0; 2330 while (bytesSeeked < offset) { 2331 int bytesRemainingToSeek = offset-bytesSeeked; 2332 assert(bytesRemainingToSeek >= 0); 2333 2334 if (oggbs.bytesRemainingInPage >= cast(size_t)bytesRemainingToSeek) { 2335 if (!drflac_oggbs__seek_physical(oggbs, bytesRemainingToSeek, drflac_seek_origin_current)) return false; 2336 bytesSeeked += bytesRemainingToSeek; 2337 oggbs.bytesRemainingInPage -= bytesRemainingToSeek; 2338 break; 2339 } 2340 2341 // If we get here it means some of the requested data is contained in the next pages. 2342 if (oggbs.bytesRemainingInPage > 0) { 2343 if (!drflac_oggbs__seek_physical(oggbs, oggbs.bytesRemainingInPage, drflac_seek_origin_current)) return false; 2344 bytesSeeked += cast(int)oggbs.bytesRemainingInPage; 2345 } 2346 2347 assert(bytesRemainingToSeek > 0); 2348 if (!drflac_oggbs__goto_next_page(oggbs)) break; // Failed to go to the next chunk. Might have simply hit the end of the stream. 2349 } 2350 2351 return true; 2352 } 2353 2354 bool drflac_ogg__seek_to_sample (drflac* pFlac, ulong sample) { 2355 drflac_oggbs* oggbs = cast(drflac_oggbs*)((cast(int*)pFlac.pExtraData)+pFlac.maxBlockSize*pFlac.channels); 2356 2357 ulong originalBytePos = oggbs.currentBytePos; // For recovery. 2358 2359 // First seek to the first frame. 2360 if (!drflac__seek_to_byte(&pFlac.bs, pFlac.firstFramePos)) return false; 2361 oggbs.bytesRemainingInPage = 0; 2362 2363 ulong runningGranulePosition = 0; 2364 ulong runningFrameBytePos = oggbs.currentBytePos; // <-- Points to the OggS identifier. 2365 for (;;) { 2366 if (!drflac_oggbs__goto_next_page(oggbs)) { 2367 drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start); 2368 return false; // Never did find that sample... 2369 } 2370 2371 runningFrameBytePos = oggbs.currentBytePos-drflac_ogg__get_page_header_size(&oggbs.currentPageHeader); 2372 if (oggbs.currentPageHeader.granulePosition*pFlac.channels >= sample) break; // The sample is somewhere in the previous page. 2373 2374 // At this point we know the sample is not in the previous page. It could possibly be in this page. For simplicity we 2375 // disregard any pages that do not begin a fresh packet. 2376 if ((oggbs.currentPageHeader.headerType&0x01) == 0) { // <-- Is it a fresh page? 2377 if (oggbs.currentPageHeader.segmentTable.ptr[0] >= 2) { 2378 ubyte[2] firstBytesInPage; 2379 if (drflac_oggbs__read_physical(oggbs, firstBytesInPage.ptr, 2) != 2) { 2380 drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start); 2381 return false; 2382 } 2383 if ((firstBytesInPage.ptr[0] == 0xFF) && (firstBytesInPage.ptr[1]&0xFC) == 0xF8) { // <-- Does the page begin with a frame's sync code? 2384 runningGranulePosition = oggbs.currentPageHeader.granulePosition*pFlac.channels; 2385 } 2386 2387 if (!drflac_oggbs__seek_physical(oggbs, cast(int)oggbs.bytesRemainingInPage-2, drflac_seek_origin_current)) { 2388 drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start); 2389 return false; 2390 } 2391 2392 continue; 2393 } 2394 } 2395 2396 if (!drflac_oggbs__seek_physical(oggbs, cast(int)oggbs.bytesRemainingInPage, drflac_seek_origin_current)) { 2397 drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start); 2398 return false; 2399 } 2400 } 2401 2402 // 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 2403 // 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 2404 // a new frame. This property means that after we've seeked to the page we can immediately start looping over frames until 2405 // we find the one containing the target sample. 2406 if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, drflac_seek_origin_start)) return false; 2407 if (!drflac_oggbs__goto_next_page(oggbs)) return false; 2408 2409 // 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 2410 // looping over these frames until we find the one containing the sample we're after. 2411 ulong firstSampleInFrame = runningGranulePosition; 2412 for (;;) { 2413 // NOTE for later: When using Ogg's page/segment based seeking later on we can't use this function (or any drflac__* 2414 // reading functions) because otherwise it will pull extra data for use in it's own internal caches which will then 2415 // break the positioning of the read pointer for the Ogg bitstream. 2416 if (!drflac__read_next_frame_header(&pFlac.bs, pFlac.bitsPerSample, &pFlac.currentFrame.header)) return false; 2417 2418 int channels = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment); 2419 ulong lastSampleInFrame = firstSampleInFrame+(pFlac.currentFrame.header.blockSize*channels); 2420 lastSampleInFrame -= 1; // <-- Zero based. 2421 2422 if (sample >= firstSampleInFrame && sample <= lastSampleInFrame) break; // The sample is in this frame. 2423 2424 // If we get here it means the sample is not in this frame so we need to move to the next one. Now the cool thing 2425 // with Ogg is that we can efficiently seek past the frame by looking at the lacing values of each segment in 2426 // the page. 2427 firstSampleInFrame = lastSampleInFrame+1; 2428 2429 version(all) { 2430 // Slow way. This uses the native FLAC decoder to seek past the frame. This is slow because it needs to do a partial 2431 // decode of the frame. Although this is how the native version works, we can use Ogg's framing system to make it 2432 // more efficient. Leaving this here for reference and to use as a basis for debugging purposes. 2433 if (!drflac__seek_to_next_frame(pFlac)) return false; 2434 } else { 2435 // TODO: This is not yet complete. See note at the top of this loop body. 2436 2437 // Fast(er) way. This uses Ogg's framing system to seek past the frame. This should be much more efficient than the 2438 // native FLAC seeking. 2439 if (!drflac_oggbs__seek_to_next_frame(oggbs)) return false; 2440 } 2441 } 2442 2443 assert(firstSampleInFrame <= sample); 2444 2445 if (!drflac__decode_frame(pFlac)) return false; 2446 2447 size_t samplesToDecode = cast(size_t)(sample-firstSampleInFrame); // <-- Safe cast because the maximum number of samples in a frame is 65535. 2448 return drflac_read_s32(pFlac, samplesToDecode, null) == samplesToDecode; 2449 } 2450 2451 2452 bool drflac__init_private__ogg (drflac_init_info* pInit, ref ReadStruct rs, scope drflac_meta_proc onMeta, void* pUserDataMD) { 2453 // Pre: The bit stream should be sitting just past the 4-byte OggS capture pattern. 2454 2455 pInit.container = drflac_container_ogg; 2456 pInit.oggFirstBytePos = 0; 2457 2458 // We'll get here if the first 4 bytes of the stream were the OggS capture pattern, however it doesn't necessarily mean the 2459 // stream includes FLAC encoded audio. To check for this we need to scan the beginning-of-stream page markers and check if 2460 // any match the FLAC specification. Important to keep in mind that the stream may be multiplexed. 2461 drflac_ogg_page_header header; 2462 2463 uint headerSize = 0; 2464 if (!drflac_ogg__read_page_header_after_capture_pattern(rs, &header, &headerSize)) return false; 2465 pInit.runningFilePos += headerSize; 2466 2467 for (;;) { 2468 // Break if we're past the beginning of stream page. 2469 if ((header.headerType&0x02) == 0) return false; 2470 2471 // Check if it's a FLAC header. 2472 int pageBodySize = drflac_ogg__get_page_body_size(&header); 2473 if (pageBodySize == 51) { // 51 = the lacing value of the FLAC header packet. 2474 // It could be a FLAC page... 2475 uint bytesRemainingInPage = pageBodySize; 2476 2477 ubyte packetType; 2478 if (rs.read(&packetType, 1) != 1) return false; 2479 2480 bytesRemainingInPage -= 1; 2481 if (packetType == 0x7F) { 2482 // Increasingly more likely to be a FLAC page... 2483 ubyte[4] sig; 2484 if (rs.read(sig.ptr, 4) != 4) return false; 2485 2486 bytesRemainingInPage -= 4; 2487 if (sig.ptr[0] == 'F' && sig.ptr[1] == 'L' && sig.ptr[2] == 'A' && sig.ptr[3] == 'C') { 2488 // Almost certainly a FLAC page... 2489 ubyte[2] mappingVersion; 2490 if (rs.read(mappingVersion.ptr, 2) != 2) return false; 2491 2492 if (mappingVersion.ptr[0] != 1) return false; // Only supporting version 1.x of the Ogg mapping. 2493 2494 // The next 2 bytes are the non-audio packets, not including this one. We don't care about this because we're going to 2495 // be handling it in a generic way based on the serial number and packet types. 2496 if (!rs.seek(2, drflac_seek_origin_current)) return false; 2497 2498 // Expecting the native FLAC signature "fLaC". 2499 if (rs.read(sig.ptr, 4) != 4) return false; 2500 2501 if (sig.ptr[0] == 'f' && sig.ptr[1] == 'L' && sig.ptr[2] == 'a' && sig.ptr[3] == 'C') { 2502 // The remaining data in the page should be the STREAMINFO block. 2503 ubyte isLastBlock; 2504 ubyte blockType; 2505 uint blockSize; 2506 if (!drflac__read_and_decode_block_header(rs, &isLastBlock, &blockType, &blockSize)) return false; 2507 2508 if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) return false; // Invalid block type. First block must be the STREAMINFO block. 2509 2510 drflac_streaminfo streaminfo; 2511 if (drflac__read_streaminfo(rs, &streaminfo)) { 2512 // Success! 2513 pInit.sampleRate = streaminfo.sampleRate; 2514 pInit.channels = streaminfo.channels; 2515 pInit.bitsPerSample = streaminfo.bitsPerSample; 2516 pInit.totalSampleCount = streaminfo.totalSampleCount; 2517 pInit.maxBlockSize = streaminfo.maxBlockSize; 2518 2519 if (onMeta !is null) { 2520 drflac_metadata metadata; 2521 metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO; 2522 metadata.pRawData = null; 2523 metadata.rawDataSize = 0; 2524 metadata.data.streaminfo = streaminfo; 2525 try { onMeta(pUserDataMD, &metadata); } catch (Exception e) { return false; } 2526 } 2527 2528 pInit.runningFilePos += pageBodySize; 2529 pInit.oggFirstBytePos = pInit.runningFilePos-79; // Subtracting 79 will place us right on top of the "OggS" identifier of the FLAC bos page. 2530 pInit.oggSerial = header.serialNumber; 2531 pInit.oggBosHeader = header; 2532 break; 2533 } else { 2534 // Failed to read STREAMINFO block. Aww, so close... 2535 return false; 2536 } 2537 } else { 2538 // Invalid file. 2539 return false; 2540 } 2541 } else { 2542 // Not a FLAC header. Skip it. 2543 if (!rs.seek(bytesRemainingInPage, drflac_seek_origin_current)) return false; 2544 } 2545 } else { 2546 // Not a FLAC header. Seek past the entire page and move on to the next. 2547 if (!rs.seek(bytesRemainingInPage, drflac_seek_origin_current)) return false; 2548 } 2549 } else { 2550 if (!rs.seek(pageBodySize, drflac_seek_origin_current)) return false; 2551 } 2552 2553 pInit.runningFilePos += pageBodySize; 2554 2555 // Read the header of the next page. 2556 if (!drflac_ogg__read_page_header(rs, &header, &headerSize)) return false; 2557 pInit.runningFilePos += headerSize; 2558 } 2559 2560 2561 // 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 2562 // packets in the FLAC logical stream contain the metadata. The only thing left to do in the initialiation phase for Ogg is to create the 2563 // Ogg bistream object. 2564 pInit.hasMetadataBlocks = true; // <-- Always have at least VORBIS_COMMENT metadata block. 2565 return true; 2566 } 2567 //#endif 2568 2569 bool drflac__check_init_private (drflac_init_info* pInit, scope drflac_meta_proc onMeta, void* pUserDataMD) { 2570 ubyte[4] id; 2571 if (pInit.rs.read(id.ptr, 4) != 4) return false; 2572 if (id.ptr[0] == 'f' && id.ptr[1] == 'L' && id.ptr[2] == 'a' && id.ptr[3] == 'C') return drflac__init_private__native(pInit, pInit.rs, onMeta, pUserDataMD); 2573 //#ifndef DR_FLAC_NO_OGG 2574 if (id.ptr[0] == 'O' && id.ptr[1] == 'g' && id.ptr[2] == 'g' && id.ptr[3] == 'S') return drflac__init_private__ogg(pInit, pInit.rs, onMeta, pUserDataMD); 2575 //#endif 2576 // unsupported container 2577 return false; 2578 } 2579 2580 bool drflac__init_private (drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, scope drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD) { 2581 if (pInit is null || onRead is null || onSeek is null) return false; 2582 2583 pInit.rs.onReadCB = onRead; 2584 pInit.rs.onSeekCB = onSeek; 2585 pInit.rs.pUserData = pUserData; 2586 //pInit.onMeta = onMeta; 2587 //pInit.pUserDataMD = pUserDataMD; 2588 2589 return drflac__check_init_private(pInit, onMeta, pUserDataMD); 2590 } 2591 2592 } //nothrow 2593 2594 static if (DrFlacHasVFS) 2595 bool drflac__init_private (drflac_init_info* pInit, VFile fl, scope drflac_meta_proc onMeta, void* pUserDataMD) { 2596 //import core.stdc.string : memset; 2597 //memset(&pInit.rs.srcfile, 0, pInit.rs.srcfile.sizeof); // just in case 2598 2599 pInit.rs.srcfile = fl; 2600 pInit.rs.onReadCB = null; 2601 pInit.rs.onSeekCB = null; 2602 pInit.rs.pUserData = null; 2603 //pInit.onMeta = onMeta; 2604 //pInit.pUserDataMD = pUserDataMD; 2605 2606 return drflac__check_init_private(pInit, onMeta, pUserDataMD); 2607 } 2608 2609 nothrow { 2610 void drflac__init_from_info (drflac* pFlac, drflac_init_info* pInit) { 2611 import core.stdc..string : memcpy, memset; 2612 assert(pFlac !is null); 2613 assert(pInit !is null); 2614 2615 memset(pFlac, 0, (*pFlac).sizeof); 2616 pFlac.bs.rs = pInit.rs; 2617 pFlac.bs.nextL2Line = (pFlac.bs.cacheL2).sizeof/(pFlac.bs.cacheL2.ptr[0]).sizeof; // <-- Initialize to this to force a client-side data retrieval right from the start. 2618 pFlac.bs.consumedBits = (pFlac.bs.cache).sizeof*8; 2619 2620 //pFlac.onMeta = pInit.onMeta; 2621 //pFlac.pUserDataMD = pInit.pUserDataMD; 2622 pFlac.maxBlockSize = pInit.maxBlockSize; 2623 pFlac.sampleRate = pInit.sampleRate; 2624 pFlac.channels = cast(ubyte)pInit.channels; 2625 pFlac.bitsPerSample = cast(ubyte)pInit.bitsPerSample; 2626 pFlac.totalSampleCount = pInit.totalSampleCount; 2627 pFlac.container = pInit.container; 2628 } 2629 2630 drflac* drflac_open_with_metadata_private_xx (drflac_init_info* init, scope drflac_meta_proc onMeta, void* pUserDataMD, bool stdio) { 2631 import core.stdc.stdlib : malloc, free; 2632 import core.stdc..string : memset; 2633 2634 size_t allocationSize = (drflac).sizeof; 2635 allocationSize += init.maxBlockSize*init.channels*(int).sizeof; 2636 //allocationSize += init.seektableSize; 2637 2638 //#ifndef DR_FLAC_NO_OGG 2639 // There's additional data required for Ogg streams. 2640 if (init.container == drflac_container_ogg) allocationSize += (drflac_oggbs).sizeof; 2641 //#endif 2642 2643 drflac* pFlac = cast(drflac*)malloc(allocationSize); 2644 memset(pFlac, 0, (*pFlac).sizeof); 2645 drflac__init_from_info(pFlac, init); 2646 pFlac.pDecodedSamples = cast(int*)pFlac.pExtraData; 2647 2648 //#ifndef DR_FLAC_NO_OGG 2649 if (init.container == drflac_container_ogg) { 2650 drflac_oggbs* oggbs = cast(drflac_oggbs*)((cast(int*)pFlac.pExtraData)+init.maxBlockSize*init.channels); 2651 oggbs.stdio = stdio; 2652 oggbs.rs = init.rs; 2653 oggbs.currentBytePos = init.oggFirstBytePos; 2654 oggbs.firstBytePos = init.oggFirstBytePos; 2655 oggbs.serialNumber = init.oggSerial; 2656 oggbs.bosPageHeader = init.oggBosHeader; 2657 oggbs.bytesRemainingInPage = 0; 2658 2659 // The Ogg bistream needs to be layered on top of the original bitstream. 2660 pFlac.bs.rs.onReadCB = &drflac__on_read_ogg; 2661 pFlac.bs.rs.onSeekCB = &drflac__on_seek_ogg; 2662 pFlac.bs.rs.pUserData = cast(void*)oggbs; 2663 } 2664 //#endif 2665 2666 // Decode metadata before returning. 2667 if (init.hasMetadataBlocks) { 2668 if (!drflac__read_and_decode_metadata(pFlac, onMeta, pUserDataMD)) { 2669 free(pFlac); 2670 return null; 2671 } 2672 } 2673 2674 return pFlac; 2675 } 2676 2677 2678 drflac* drflac_open_with_metadata_private (drflac_read_proc onRead, drflac_seek_proc onSeek, scope drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, bool stdio) { 2679 drflac_init_info init; 2680 if (!drflac__init_private(&init, onRead, onSeek, onMeta, pUserData, pUserDataMD)) return null; 2681 return drflac_open_with_metadata_private_xx(&init, onMeta, pUserDataMD, stdio); 2682 } 2683 2684 } //nothrow 2685 2686 static if (DrFlacHasVFS) 2687 drflac* drflac_open_with_metadata_private (VFile fl, scope drflac_meta_proc onMeta, void* pUserDataMD, bool stdio) { 2688 drflac_init_info init; 2689 if (!drflac__init_private(&init, fl, onMeta, pUserDataMD)) return null; 2690 return drflac_open_with_metadata_private_xx(&init, onMeta, pUserDataMD, stdio); 2691 } 2692 2693 2694 nothrow { 2695 alias drflac_file = void*; 2696 2697 size_t drflac__on_read_stdio (void* pUserData, void* bufferOut, size_t bytesToRead) { 2698 import core.stdc.stdio; 2699 return fread(bufferOut, 1, bytesToRead, cast(FILE*)pUserData); 2700 } 2701 2702 bool drflac__on_seek_stdio (void* pUserData, int offset, drflac_seek_origin origin) { 2703 import core.stdc.stdio; 2704 assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start)); 2705 return fseek(cast(FILE*)pUserData, offset, (origin == drflac_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0; 2706 } 2707 2708 drflac_file drflac__open_file_handle (const(char)[] filename) { 2709 import std.internal.cstring : tempCString; 2710 import core.stdc.stdio; 2711 FILE* pFile = fopen(filename.tempCString, "rb"); 2712 if (pFile is null) return null; 2713 return cast(drflac_file)pFile; 2714 } 2715 2716 void drflac__close_file_handle (drflac_file file) { 2717 import core.stdc.stdio; 2718 fclose(cast(FILE*)file); 2719 } 2720 2721 public drflac* drflac_open_file (const(char)[] filename) { 2722 2723 2724 drflac_file file = drflac__open_file_handle(filename); 2725 if (file is null) return null; 2726 2727 drflac* pFlac = drflac_open(&drflac__on_read_stdio, &drflac__on_seek_stdio, cast(void*)file); 2728 if (pFlac is null) { 2729 drflac__close_file_handle(file); 2730 return null; 2731 } 2732 pFlac.bs.stdio = true; 2733 2734 return pFlac; 2735 } 2736 2737 public drflac* drflac_open_file_with_metadata (const(char)[] filename, scope drflac_meta_proc onMeta, void* pUserData=null) { 2738 2739 drflac_file file = drflac__open_file_handle(filename); 2740 if (file is null) return null; 2741 2742 drflac* pFlac = drflac_open_with_metadata_private(&drflac__on_read_stdio, &drflac__on_seek_stdio, onMeta, cast(void*)file, pUserData, true); 2743 if (pFlac is null) { 2744 drflac__close_file_handle(file); 2745 return pFlac; 2746 } 2747 pFlac.bs.stdio = true; 2748 2749 return pFlac; 2750 } 2751 2752 } //nothrow 2753 2754 static if (DrFlacHasVFS) { 2755 public drflac* drflac_open_file (VFile fl, scope drflac_meta_proc onMeta=null) { 2756 2757 drflac* pFlac; 2758 if (onMeta !is null) { 2759 pFlac = drflac_open_with_metadata_private(fl, onMeta, null, true); 2760 } else { 2761 pFlac = drflac_open(fl); 2762 } 2763 if (pFlac is null) return null; 2764 pFlac.bs.stdio = false; 2765 2766 return pFlac; 2767 } 2768 } 2769 2770 nothrow { 2771 2772 size_t drflac__on_read_memory (void* pUserData, void* bufferOut, size_t bytesToRead) { 2773 drflac__memory_stream* memoryStream = cast(drflac__memory_stream*)pUserData; 2774 assert(memoryStream !is null); 2775 assert(memoryStream.dataSize >= memoryStream.currentReadPos); 2776 2777 size_t bytesRemaining = memoryStream.dataSize-memoryStream.currentReadPos; 2778 if (bytesToRead > bytesRemaining) bytesToRead = bytesRemaining; 2779 2780 if (bytesToRead > 0) { 2781 import core.stdc..string : memcpy; 2782 memcpy(bufferOut, memoryStream.data+memoryStream.currentReadPos, bytesToRead); 2783 memoryStream.currentReadPos += bytesToRead; 2784 } 2785 2786 return bytesToRead; 2787 } 2788 2789 bool drflac__on_seek_memory (void* pUserData, int offset, drflac_seek_origin origin) { 2790 drflac__memory_stream* memoryStream = cast(drflac__memory_stream*)pUserData; 2791 assert(memoryStream !is null); 2792 assert(offset > 0 || (offset == 0 && origin == drflac_seek_origin_start)); 2793 2794 if (origin == drflac_seek_origin_current) { 2795 if (memoryStream.currentReadPos+offset <= memoryStream.dataSize) { 2796 memoryStream.currentReadPos += offset; 2797 } else { 2798 memoryStream.currentReadPos = memoryStream.dataSize; // Trying to seek too far forward. 2799 } 2800 } else { 2801 if (cast(uint)offset <= memoryStream.dataSize) { 2802 memoryStream.currentReadPos = offset; 2803 } else { 2804 memoryStream.currentReadPos = memoryStream.dataSize; // Trying to seek too far forward. 2805 } 2806 } 2807 2808 return true; 2809 } 2810 2811 public drflac* drflac_open_memory (const(void)* data, size_t dataSize) { 2812 2813 drflac__memory_stream memoryStream; 2814 memoryStream.data = cast(const(ubyte)*)data; 2815 memoryStream.dataSize = dataSize; 2816 memoryStream.currentReadPos = 0; 2817 2818 drflac* pFlac = drflac_open(&drflac__on_read_memory, &drflac__on_seek_memory, &memoryStream); 2819 if (pFlac is null) return null; 2820 2821 pFlac.memoryStream = memoryStream; 2822 2823 // This is an awful hack... 2824 //#ifndef DR_FLAC_NO_OGG 2825 if (pFlac.container == drflac_container_ogg) { 2826 drflac_oggbs* oggbs = cast(drflac_oggbs*)((cast(int*)pFlac.pExtraData)+pFlac.maxBlockSize*pFlac.channels); 2827 oggbs.rs.pUserData = &pFlac.memoryStream; 2828 } 2829 else 2830 //#endif 2831 { 2832 pFlac.bs.rs.pUserData = &pFlac.memoryStream; 2833 } 2834 2835 return pFlac; 2836 } 2837 2838 public drflac* drflac_open_memory_with_metadata (const(void)* data, size_t dataSize, scope drflac_meta_proc onMeta, void* pUserData) { 2839 2840 drflac__memory_stream memoryStream; 2841 memoryStream.data = cast(const(ubyte)*)data; 2842 memoryStream.dataSize = dataSize; 2843 memoryStream.currentReadPos = 0; 2844 2845 drflac* pFlac = drflac_open_with_metadata_private(&drflac__on_read_memory, &drflac__on_seek_memory, onMeta, &memoryStream, pUserData, false); 2846 if (pFlac is null) return null; 2847 2848 pFlac.memoryStream = memoryStream; 2849 2850 // This is an awful hack... 2851 //#ifndef DR_FLAC_NO_OGG 2852 if (pFlac.container == drflac_container_ogg) { 2853 drflac_oggbs* oggbs = cast(drflac_oggbs*)((cast(int*)pFlac.pExtraData)+pFlac.maxBlockSize*pFlac.channels); 2854 oggbs.rs.pUserData = &pFlac.memoryStream; 2855 } else 2856 //#endif 2857 { 2858 pFlac.bs.rs.pUserData = &pFlac.memoryStream; 2859 } 2860 2861 return pFlac; 2862 } 2863 2864 public drflac* drflac_open (drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData) { 2865 return drflac_open_with_metadata_private(onRead, onSeek, null, pUserData, pUserData, false); 2866 } 2867 2868 } //nothrow 2869 2870 static if (DrFlacHasVFS) 2871 public drflac* drflac_open (VFile fl) { 2872 return drflac_open_with_metadata_private(fl, null, null, false); 2873 } 2874 2875 nothrow { 2876 2877 public drflac* drflac_open_with_metadata (drflac_read_proc onRead, drflac_seek_proc onSeek, scope drflac_meta_proc onMeta, void* pUserData) { 2878 return drflac_open_with_metadata_private(onRead, onSeek, onMeta, pUserData, pUserData, false); 2879 } 2880 2881 public void drflac_close (drflac* pFlac) { 2882 import core.stdc.stdlib : free; 2883 if (pFlac is null) return; 2884 2885 // 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() 2886 // was used by looking at the callbacks. 2887 //if (pFlac.bs.onRead == drflac__on_read_stdio) drflac__close_file_handle(cast(drflac_file)pFlac.bs.pUserData); 2888 if (pFlac.bs.stdio) drflac__close_file_handle(cast(drflac_file)pFlac.bs.rs.pUserData); 2889 2890 //#ifndef DR_FLAC_NO_OGG 2891 // Need to clean up Ogg streams a bit differently due to the way the bit streaming is chained. 2892 if (pFlac.container == drflac_container_ogg) { 2893 //assert(pFlac.bs.onRead == drflac__on_read_ogg); 2894 drflac_oggbs* oggbs = cast(drflac_oggbs*)(cast(int*)pFlac.pExtraData+pFlac.maxBlockSize*pFlac.channels); 2895 //if (oggbs.onRead == drflac__on_read_stdio) drflac__close_file_handle(cast(drflac_file)oggbs.pUserData); 2896 if (oggbs.stdio) drflac__close_file_handle(cast(drflac_file)oggbs.rs.pUserData); 2897 } 2898 //#endif 2899 free(pFlac); 2900 } 2901 2902 2903 ulong drflac__read_s32__misaligned (drflac* pFlac, ulong samplesToRead, int* bufferOut) { 2904 uint channelCount = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment); 2905 2906 // We should never be calling this when the number of samples to read is >= the sample count. 2907 assert(samplesToRead < channelCount); 2908 assert(pFlac.currentFrame.samplesRemaining > 0 && samplesToRead <= pFlac.currentFrame.samplesRemaining); 2909 2910 ulong samplesRead = 0; 2911 while (samplesToRead > 0) { 2912 ulong totalSamplesInFrame = pFlac.currentFrame.header.blockSize*channelCount; 2913 ulong samplesReadFromFrameSoFar = totalSamplesInFrame-pFlac.currentFrame.samplesRemaining; 2914 uint channelIndex = samplesReadFromFrameSoFar%channelCount; 2915 2916 ulong nextSampleInFrame = samplesReadFromFrameSoFar/channelCount; 2917 2918 int decodedSample = 0; 2919 switch (pFlac.currentFrame.header.channelAssignment) { 2920 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE: 2921 if (channelIndex == 0) { 2922 decodedSample = pFlac.currentFrame.subframes.ptr[channelIndex].pDecodedSamples[cast(uint)nextSampleInFrame]; 2923 } else { 2924 int side = pFlac.currentFrame.subframes.ptr[channelIndex+0].pDecodedSamples[cast(uint)nextSampleInFrame]; 2925 int left = pFlac.currentFrame.subframes.ptr[channelIndex-1].pDecodedSamples[cast(uint)nextSampleInFrame]; 2926 decodedSample = left-side; 2927 } 2928 break; 2929 2930 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE: 2931 if (channelIndex == 0) { 2932 int side = pFlac.currentFrame.subframes.ptr[channelIndex+0].pDecodedSamples[cast(uint)nextSampleInFrame]; 2933 int right = pFlac.currentFrame.subframes.ptr[channelIndex+1].pDecodedSamples[cast(uint)nextSampleInFrame]; 2934 decodedSample = side+right; 2935 } else { 2936 decodedSample = pFlac.currentFrame.subframes.ptr[channelIndex].pDecodedSamples[cast(uint)nextSampleInFrame]; 2937 } 2938 break; 2939 2940 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE: 2941 int mid; 2942 int side; 2943 if (channelIndex == 0) { 2944 mid = pFlac.currentFrame.subframes.ptr[channelIndex+0].pDecodedSamples[cast(uint)nextSampleInFrame]; 2945 side = pFlac.currentFrame.subframes.ptr[channelIndex+1].pDecodedSamples[cast(uint)nextSampleInFrame]; 2946 mid = ((cast(uint)mid)<<1)|(side&0x01); 2947 decodedSample = (mid+side)>>1; 2948 } else { 2949 mid = pFlac.currentFrame.subframes.ptr[channelIndex-1].pDecodedSamples[cast(uint)nextSampleInFrame]; 2950 side = pFlac.currentFrame.subframes.ptr[channelIndex+0].pDecodedSamples[cast(uint)nextSampleInFrame]; 2951 mid = ((cast(uint)mid)<<1)|(side&0x01); 2952 decodedSample = (mid-side)>>1; 2953 } 2954 break; 2955 2956 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: goto default; 2957 default: 2958 decodedSample = pFlac.currentFrame.subframes.ptr[channelIndex].pDecodedSamples[cast(uint)nextSampleInFrame]; 2959 break; 2960 } 2961 2962 decodedSample <<= ((32-pFlac.bitsPerSample)+pFlac.currentFrame.subframes.ptr[channelIndex].wastedBitsPerSample); 2963 2964 if (bufferOut) *bufferOut++ = decodedSample; 2965 2966 samplesRead += 1; 2967 pFlac.currentFrame.samplesRemaining -= 1; 2968 samplesToRead -= 1; 2969 } 2970 2971 return samplesRead; 2972 } 2973 2974 ulong drflac__seek_forward_by_samples (drflac* pFlac, ulong samplesToRead) { 2975 ulong samplesRead = 0; 2976 while (samplesToRead > 0) { 2977 if (pFlac.currentFrame.samplesRemaining == 0) { 2978 if (!drflac__read_and_decode_next_frame(pFlac)) break; // Couldn't read the next frame, so just break from the loop and return. 2979 } else { 2980 samplesRead += 1; 2981 pFlac.currentFrame.samplesRemaining -= 1; 2982 samplesToRead -= 1; 2983 } 2984 } 2985 return samplesRead; 2986 } 2987 2988 public ulong drflac_read_s32 (drflac* pFlac, ulong samplesToRead, int* bufferOut) { 2989 // Note that <bufferOut> is allowed to be null, in which case this will be treated as something like a seek. 2990 if (pFlac is null || samplesToRead == 0) return 0; 2991 2992 if (bufferOut is null) return drflac__seek_forward_by_samples(pFlac, samplesToRead); 2993 2994 ulong samplesRead = 0; 2995 while (samplesToRead > 0) { 2996 // If we've run out of samples in this frame, go to the next. 2997 if (pFlac.currentFrame.samplesRemaining == 0) { 2998 if (!drflac__read_and_decode_next_frame(pFlac)) break; // Couldn't read the next frame, so just break from the loop and return. 2999 } else { 3000 // Here is where we grab the samples and interleave them. 3001 3002 uint channelCount = drflac__get_channel_count_from_channel_assignment(pFlac.currentFrame.header.channelAssignment); 3003 ulong totalSamplesInFrame = pFlac.currentFrame.header.blockSize*channelCount; 3004 ulong samplesReadFromFrameSoFar = totalSamplesInFrame-pFlac.currentFrame.samplesRemaining; 3005 3006 int misalignedSampleCount = cast(int)(samplesReadFromFrameSoFar%channelCount); 3007 if (misalignedSampleCount > 0) { 3008 ulong misalignedSamplesRead = drflac__read_s32__misaligned(pFlac, misalignedSampleCount, bufferOut); 3009 samplesRead += misalignedSamplesRead; 3010 samplesReadFromFrameSoFar += misalignedSamplesRead; 3011 bufferOut += misalignedSamplesRead; 3012 samplesToRead -= misalignedSamplesRead; 3013 } 3014 3015 ulong alignedSampleCountPerChannel = samplesToRead/channelCount; 3016 if (alignedSampleCountPerChannel > pFlac.currentFrame.samplesRemaining/channelCount) { 3017 alignedSampleCountPerChannel = pFlac.currentFrame.samplesRemaining/channelCount; 3018 } 3019 3020 ulong firstAlignedSampleInFrame = samplesReadFromFrameSoFar/channelCount; 3021 uint unusedBitsPerSample = 32-pFlac.bitsPerSample; 3022 3023 switch (pFlac.currentFrame.header.channelAssignment) { 3024 case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE: 3025 const int* pDecodedSamples0 = pFlac.currentFrame.subframes.ptr[0].pDecodedSamples+firstAlignedSampleInFrame; 3026 const int* pDecodedSamples1 = pFlac.currentFrame.subframes.ptr[1].pDecodedSamples+firstAlignedSampleInFrame; 3027 3028 for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) { 3029 int left = pDecodedSamples0[i]; 3030 int side = pDecodedSamples1[i]; 3031 int right = left-side; 3032 bufferOut[i*2+0] = left<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[0].wastedBitsPerSample); 3033 bufferOut[i*2+1] = right<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[1].wastedBitsPerSample); 3034 } 3035 break; 3036 3037 case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE: 3038 const int* pDecodedSamples0 = pFlac.currentFrame.subframes.ptr[0].pDecodedSamples+firstAlignedSampleInFrame; 3039 const int* pDecodedSamples1 = pFlac.currentFrame.subframes.ptr[1].pDecodedSamples+firstAlignedSampleInFrame; 3040 for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) { 3041 int side = pDecodedSamples0[i]; 3042 int right = pDecodedSamples1[i]; 3043 int left = right+side; 3044 bufferOut[i*2+0] = left<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[0].wastedBitsPerSample); 3045 bufferOut[i*2+1] = right<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[1].wastedBitsPerSample); 3046 } 3047 break; 3048 3049 case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE: 3050 const int* pDecodedSamples0 = pFlac.currentFrame.subframes.ptr[0].pDecodedSamples+firstAlignedSampleInFrame; 3051 const int* pDecodedSamples1 = pFlac.currentFrame.subframes.ptr[1].pDecodedSamples+firstAlignedSampleInFrame; 3052 for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) { 3053 int side = pDecodedSamples1[i]; 3054 int mid = ((cast(uint)pDecodedSamples0[i])<<1)|(side&0x01); 3055 bufferOut[i*2+0] = ((mid+side)>>1)<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[0].wastedBitsPerSample); 3056 bufferOut[i*2+1] = ((mid-side)>>1)<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[1].wastedBitsPerSample); 3057 } 3058 break; 3059 3060 case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT: goto default; 3061 default: 3062 if (pFlac.currentFrame.header.channelAssignment == 1) { // 1 = Stereo 3063 // Stereo optimized inner loop unroll. 3064 const int* pDecodedSamples0 = pFlac.currentFrame.subframes.ptr[0].pDecodedSamples+firstAlignedSampleInFrame; 3065 const int* pDecodedSamples1 = pFlac.currentFrame.subframes.ptr[1].pDecodedSamples+firstAlignedSampleInFrame; 3066 for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) { 3067 bufferOut[i*2+0] = pDecodedSamples0[i]<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[0].wastedBitsPerSample); 3068 bufferOut[i*2+1] = pDecodedSamples1[i]<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[1].wastedBitsPerSample); 3069 } 3070 } else { 3071 // Generic interleaving. 3072 for (/*ulong*/uint i = 0; i < alignedSampleCountPerChannel; ++i) { 3073 for (uint j = 0; j < channelCount; ++j) { 3074 bufferOut[(i*channelCount)+j] = (pFlac.currentFrame.subframes.ptr[j].pDecodedSamples[cast(uint)firstAlignedSampleInFrame+i])<<(unusedBitsPerSample+pFlac.currentFrame.subframes.ptr[j].wastedBitsPerSample); 3075 } 3076 } 3077 } 3078 break; 3079 } 3080 3081 ulong alignedSamplesRead = alignedSampleCountPerChannel*channelCount; 3082 samplesRead += alignedSamplesRead; 3083 samplesReadFromFrameSoFar += alignedSamplesRead; 3084 bufferOut += alignedSamplesRead; 3085 samplesToRead -= alignedSamplesRead; 3086 pFlac.currentFrame.samplesRemaining -= cast(uint)alignedSamplesRead; 3087 3088 // At this point we may still have some excess samples left to read. 3089 if (samplesToRead > 0 && pFlac.currentFrame.samplesRemaining > 0) { 3090 ulong excessSamplesRead = 0; 3091 if (samplesToRead < pFlac.currentFrame.samplesRemaining) { 3092 excessSamplesRead = drflac__read_s32__misaligned(pFlac, samplesToRead, bufferOut); 3093 } else { 3094 excessSamplesRead = drflac__read_s32__misaligned(pFlac, pFlac.currentFrame.samplesRemaining, bufferOut); 3095 } 3096 3097 samplesRead += excessSamplesRead; 3098 samplesReadFromFrameSoFar += excessSamplesRead; 3099 bufferOut += excessSamplesRead; 3100 samplesToRead -= excessSamplesRead; 3101 } 3102 } 3103 } 3104 3105 return samplesRead; 3106 } 3107 3108 public bool drflac_seek_to_sample (drflac* pFlac, ulong sampleIndex) { 3109 if (pFlac is null) return false; 3110 3111 // 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 3112 // when the decoder was opened. 3113 if (pFlac.firstFramePos == 0) return false; 3114 3115 if (sampleIndex == 0) return drflac__seek_to_first_frame(pFlac); 3116 3117 // Clamp the sample to the end. 3118 if (sampleIndex >= pFlac.totalSampleCount) sampleIndex = pFlac.totalSampleCount-1; 3119 3120 // Different techniques depending on encapsulation. Using the native FLAC seektable with Ogg encapsulation is a bit awkward so 3121 // we'll instead use Ogg's natural seeking facility. 3122 //#ifndef DR_FLAC_NO_OGG 3123 if (pFlac.container == drflac_container_ogg) { 3124 return drflac_ogg__seek_to_sample(pFlac, sampleIndex); 3125 } 3126 else 3127 //#endif 3128 { 3129 // First try seeking via the seek table. If this fails, fall back to a brute force seek which is much slower. 3130 if (!drflac__seek_to_sample__seek_table(pFlac, sampleIndex)) return drflac__seek_to_sample__brute_force(pFlac, sampleIndex); 3131 } 3132 3133 return true; 3134 } 3135 3136 3137 3138 //// High Level APIs //// 3139 int* drflac__full_decode_and_close (drflac* pFlac, uint* sampleRateOut, uint* channelsOut, ulong* totalSampleCountOut) { 3140 import core.stdc.stdlib : malloc, realloc, free; 3141 import core.stdc..string : memset, memcpy; 3142 assert(pFlac !is null); 3143 3144 int* pSampleData = null; 3145 ulong totalSampleCount = pFlac.totalSampleCount; 3146 3147 if (totalSampleCount == 0) { 3148 int[4096] buffer; 3149 3150 size_t sampleDataBufferSize = (buffer).sizeof; 3151 pSampleData = cast(int*)malloc(sampleDataBufferSize); 3152 if (pSampleData is null) goto on_error; 3153 3154 ulong samplesRead; 3155 while ((samplesRead = cast(ulong)drflac_read_s32(pFlac, (buffer).sizeof/(buffer[0]).sizeof, buffer.ptr)) > 0) { 3156 if (((totalSampleCount+samplesRead)*(int).sizeof) > sampleDataBufferSize) { 3157 sampleDataBufferSize *= 2; 3158 int* pNewSampleData = cast(int*)realloc(pSampleData, sampleDataBufferSize); 3159 if (pNewSampleData is null) { 3160 free(pSampleData); 3161 goto on_error; 3162 } 3163 pSampleData = pNewSampleData; 3164 } 3165 memcpy(pSampleData+totalSampleCount, buffer.ptr, cast(size_t)(samplesRead*(int).sizeof)); 3166 totalSampleCount += samplesRead; 3167 } 3168 // At this point everything should be decoded, but we just want to fill the unused part buffer with silence - need to 3169 // protect those ears from random noise! 3170 memset(pSampleData+totalSampleCount, 0, cast(size_t)(sampleDataBufferSize-totalSampleCount*(int).sizeof)); 3171 } else { 3172 ulong dataSize = totalSampleCount*(int).sizeof; 3173 if (dataSize > uint.max) goto on_error; // The decoded data is too big. 3174 3175 pSampleData = cast(int*)malloc(cast(size_t)dataSize); // <-- Safe cast as per the check above. 3176 if (pSampleData is null) goto on_error; 3177 3178 ulong samplesDecoded = drflac_read_s32(pFlac, pFlac.totalSampleCount, pSampleData); 3179 if (samplesDecoded != pFlac.totalSampleCount) { 3180 free(pSampleData); 3181 goto on_error; // Something went wrong when decoding the FLAC stream. 3182 } 3183 } 3184 3185 if (sampleRateOut) *sampleRateOut = pFlac.sampleRate; 3186 if (channelsOut) *channelsOut = pFlac.channels; 3187 if (totalSampleCountOut) *totalSampleCountOut = totalSampleCount; 3188 3189 drflac_close(pFlac); 3190 return pSampleData; 3191 3192 on_error: 3193 drflac_close(pFlac); 3194 return null; 3195 } 3196 3197 public int* drflac_open_and_decode (drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, uint* sampleRate, uint* channels, ulong* totalSampleCount) { 3198 // Safety. 3199 if (sampleRate) *sampleRate = 0; 3200 if (channels) *channels = 0; 3201 if (totalSampleCount) *totalSampleCount = 0; 3202 3203 drflac* pFlac = drflac_open(onRead, onSeek, pUserData); 3204 if (pFlac is null) return null; 3205 3206 return drflac__full_decode_and_close(pFlac, sampleRate, channels, totalSampleCount); 3207 } 3208 3209 public int* drflac_open_and_decode_file (const(char)[] filename, uint* sampleRate, uint* channels, ulong* totalSampleCount) { 3210 if (sampleRate) *sampleRate = 0; 3211 if (channels) *channels = 0; 3212 if (totalSampleCount) *totalSampleCount = 0; 3213 3214 drflac* pFlac = drflac_open_file(filename); 3215 if (pFlac is null) return null; 3216 3217 return drflac__full_decode_and_close(pFlac, sampleRate, channels, totalSampleCount); 3218 } 3219 3220 public int* drflac_open_and_decode_memory (const void* data, size_t dataSize, uint* sampleRate, uint* channels, ulong* totalSampleCount) { 3221 if (sampleRate) *sampleRate = 0; 3222 if (channels) *channels = 0; 3223 if (totalSampleCount) *totalSampleCount = 0; 3224 3225 drflac* pFlac = drflac_open_memory(data, dataSize); 3226 if (pFlac is null) return null; 3227 3228 return drflac__full_decode_and_close(pFlac, sampleRate, channels, totalSampleCount); 3229 } 3230 3231 public void drflac_free (void* pSampleDataReturnedByOpenAndDecode) { 3232 import core.stdc.stdlib : free; 3233 free(pSampleDataReturnedByOpenAndDecode); 3234 } 3235 3236 3237 public void drflac_init_vorbis_comment_iterator (drflac_vorbis_comment_iterator* pIter, uint commentCount, const(char)* pComments) { 3238 if (pIter is null) return; 3239 pIter.countRemaining = commentCount; 3240 pIter.pRunningData = pComments; 3241 } 3242 3243 public const(char)* drflac_next_vorbis_comment (drflac_vorbis_comment_iterator* pIter, uint* pCommentLengthOut) { 3244 // Safety. 3245 if (pCommentLengthOut) *pCommentLengthOut = 0; 3246 3247 if (pIter is null || pIter.countRemaining == 0 || pIter.pRunningData is null) return null; 3248 3249 uint length = drflac__le2host_32(*cast(uint*)pIter.pRunningData); 3250 pIter.pRunningData += 4; 3251 3252 const(char)* pComment = pIter.pRunningData; 3253 pIter.pRunningData += length; 3254 pIter.countRemaining -= 1; 3255 3256 if (pCommentLengthOut) *pCommentLengthOut = length; 3257 return pComment; 3258 } 3259 3260 3261 public long drflac_vorbis_comment_size (uint commentCount, const(char)* pComments) { 3262 uint res = 0; 3263 while (commentCount-- > 0) { 3264 uint length = drflac__le2host_32(*cast(uint*)pComments); 3265 pComments += 4; 3266 pComments += length; 3267 res += length+4; 3268 } 3269 return res; 3270 } 3271 3272 } 3273 3274 // REVISION HISTORY 3275 // 3276 // v0.3d - 11/06/2016 3277 // - Minor clean up. 3278 // 3279 // v0.3c - 28/05/2016 3280 // - Fixed compilation error. 3281 // 3282 // v0.3b - 16/05/2016 3283 // - Fixed Linux/GCC build. 3284 // - Updated documentation. 3285 // 3286 // v0.3a - 15/05/2016 3287 // - Minor fixes to documentation. 3288 // 3289 // v0.3 - 11/05/2016 3290 // - Optimizations. Now at about parity with the reference implementation on 32-bit builds. 3291 // - Lots of clean up. 3292 // 3293 // v0.2b - 10/05/2016 3294 // - Bug fixes. 3295 // 3296 // v0.2a - 10/05/2016 3297 // - Made drflac_open_and_decode() more robust. 3298 // - Removed an unused debugging variable 3299 // 3300 // v0.2 - 09/05/2016 3301 // - Added support for Ogg encapsulation. 3302 // - API CHANGE. Have the onSeek callback take a third argument which specifies whether or not the seek 3303 // should be relative to the start or the current position. Also changes the seeking rules such that 3304 // seeking offsets will never be negative. 3305 // - Have drflac_open_and_decode() fail gracefully if the stream has an unknown total sample count. 3306 // 3307 // v0.1b - 07/05/2016 3308 // - Properly close the file handle in drflac_open_file() and family when the decoder fails to initialize. 3309 // - Removed a stale comment. 3310 // 3311 // v0.1a - 05/05/2016 3312 // - Minor formatting changes. 3313 // - Fixed a warning on the GCC build. 3314 // 3315 // v0.1 - 03/05/2016 3316 // - Initial versioned release. 3317 3318 // TODO 3319 // - Add support for initializing the decoder without a header STREAMINFO block. 3320 // - Test CUESHEET metadata blocks. 3321 3322 3323 /* 3324 This is free and unencumbered software released into the public domain. 3325 3326 Anyone is free to copy, modify, publish, use, compile, sell, or 3327 distribute this software, either in source code form or as a compiled 3328 binary, for any purpose, commercial or non-commercial, and by any 3329 means. 3330 3331 In jurisdictions that recognize copyright laws, the author or authors 3332 of this software dedicate any and all copyright interest in the 3333 software to the public domain. We make this dedication for the benefit 3334 of the public at large and to the detriment of our heirs and 3335 successors. We intend this dedication to be an overt act of 3336 relinquishment in perpetuity of all present and future rights to this 3337 software under copyright law. 3338 3339 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 3340 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 3341 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 3342 IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR 3343 OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, 3344 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 3345 OTHER DEALINGS IN THE SOFTWARE. 3346 3347 For more information, please refer to <http://unlicense.org/> 3348 */