1 ////////////////////////////////////////////////////////////////////////////
2 //                           **** WAVPACK ****                            //
3 //                  Hybrid Lossless Wavefile Compressor                   //
4 //                Copyright (c) 1998 - 2019 David Bryant.                 //
5 //                          All Rights Reserved.                          //
6 //      Distributed under the BSD Software License (see license.txt)      //
7 ////////////////////////////////////////////////////////////////////////////
8 
9 // wavpack_local.h
10 
11 #ifndef WAVPACK_LOCAL_H
12 #define WAVPACK_LOCAL_H
13 
14 #include "wavpack.h"
15 
16 #if defined(_WIN32)
17 #define strdup(x) _strdup(x)
18 #define FASTCALL __fastcall
19 #else
20 #define FASTCALL
21 #endif
22 
23 #if defined(_WIN32) || \
24     (defined(BYTE_ORDER) && defined(LITTLE_ENDIAN) && (BYTE_ORDER == LITTLE_ENDIAN)) || \
25     (defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__))
26 #define BITSTREAM_SHORTS    // use 16-bit "shorts" for reading/writing bitstreams (instead of chars)
27                             //  (only works on little-endian machines)
28 #endif
29 
30 #include <sys/types.h>
31 
32 // This header file contains all the definitions required by WavPack.
33 
34 #if defined(_MSC_VER) && _MSC_VER < 1600
35 #include <stdlib.h>
36 typedef unsigned __int64 uint64_t;
37 typedef unsigned __int32 uint32_t;
38 typedef unsigned __int16 uint16_t;
39 typedef unsigned __int8 uint8_t;
40 typedef __int64 int64_t;
41 typedef __int32 int32_t;
42 typedef __int16 int16_t;
43 typedef __int8  int8_t;
44 #else
45 #include <stdint.h>
46 #endif
47 
48 // Because the C99 specification states that "The order of allocation of
49 // bit-fields within a unit (high-order to low-order or low-order to
50 // high-order) is implementation-defined" (6.7.2.1), I decided to change
51 // the representation of floating-point values from a structure of
52 // bit-fields to a 32-bit integer with access macros. Note that the WavPack
53 // library doesn't use any floating-point math to implement compression of
54 // floating-point data (although a little floating-point math is used in
55 // high-level functions unrelated to the codec).
56 
57 typedef int32_t f32;
58 
59 #define get_mantissa(f)     ((f) & 0x7fffff)
60 #define get_magnitude(f)    ((f) & 0x7fffffff)
61 #define get_exponent(f)     (((f) >> 23) & 0xff)
62 #define get_sign(f)         (((f) >> 31) & 0x1)
63 
64 #define set_mantissa(f,v)   (f) ^= (((f) ^ (v)) & 0x7fffff)
65 #define set_exponent(f,v)   (f) ^= (((f) ^ ((uint32_t)(v) << 23)) & 0x7f800000)
66 #define set_sign(f,v)       (f) ^= (((f) ^ ((uint32_t)(v) << 31)) & 0x80000000)
67 
68 #include <stdio.h>
69 
70 #define FALSE 0
71 #define TRUE 1
72 
73 // ID3v1 and APEv2 TAG formats (may occur at the end of WavPack files)
74 
75 typedef struct {
76     char tag_id [3], title [30], artist [30], album [30];
77     char year [4], comment [30], genre;
78 } ID3_Tag;
79 
80 typedef struct {
81     char ID [8];
82     int32_t version, length, item_count, flags;
83     char res [8];
84 } APE_Tag_Hdr;
85 
86 #define APE_Tag_Hdr_Format "8LLLL"
87 
88 #define APE_TAG_TYPE_TEXT       0x0
89 #define APE_TAG_TYPE_BINARY     0x1
90 #define APE_TAG_THIS_IS_HEADER  0x20000000
91 #define APE_TAG_CONTAINS_HEADER 0x80000000
92 #define APE_TAG_MAX_LENGTH      (1024 * 1024 * 16)
93 
94 typedef struct {
95     int64_t tag_file_pos;
96     int tag_begins_file;
97     ID3_Tag id3_tag;
98     APE_Tag_Hdr ape_tag_hdr;
99     unsigned char *ape_tag_data;
100 } M_Tag;
101 
102 // or-values for "flags"
103 
104 #define CUR_STREAM_VERS     0x407       // universally compatible stream version
105 
106 
107 //////////////////////////// WavPack Metadata /////////////////////////////////
108 
109 // This is an internal representation of metadata.
110 
111 typedef struct {
112     int32_t byte_length;
113     void *data;
114     unsigned char id;
115 } WavpackMetadata;
116 
117 
118 ///////////////////////// WavPack Configuration ///////////////////////////////
119 
120 /*
121  * These config flags are not actually used for external configuration, which is
122  * why they're not in the external wavpack.h file, but they are used internally
123  * in the flags field of the WavpackConfig struct.
124  */
125 
126 #define CONFIG_MONO_FLAG        4       // not stereo
127 #define CONFIG_FLOAT_DATA       0x80    // ieee 32-bit floating point data
128 
129 #define CONFIG_AUTO_SHAPING     0x4000  // automatic noise shaping
130 #define CONFIG_LOSSY_MODE       0x1000000 // obsolete (for information)
131 
132 /*
133  * These config flags were never actually used, or are no longer used, or are
134  * used for something else now. They may be used in the future for what they
135  * say, or for something else. WavPack files in the wild *may* have some of
136  * these bit set in their config flags (with these older meanings), but only
137  * if the stream version is 0x410 or less than 0x407. Of course, this is not
138  * very important because once the file has been encoded, the config bits are
139  * just for information purposes (i.e., they do not affect decoding),
140  *
141 #define CONFIG_ADOBE_MODE       0x100   // "adobe" mode for 32-bit floats
142 #define CONFIG_VERY_FAST_FLAG   0x400   // double fast
143 #define CONFIG_COPY_TIME        0x20000 // copy file-time from source
144 #define CONFIG_QUALITY_MODE     0x200000 // psychoacoustic quality mode
145 #define CONFIG_RAW_FLAG         0x400000 // raw mode (not implemented yet)
146 #define CONFIG_QUIET_MODE       0x10000000 // don't report progress %
147 #define CONFIG_IGNORE_LENGTH    0x20000000 // ignore length in wav header
148 #define CONFIG_NEW_RIFF_HEADER  0x40000000 // generate new RIFF wav header
149  *
150  */
151 
152 #define EXTRA_SCAN_ONLY         1
153 #define EXTRA_STEREO_MODES      2
154 #define EXTRA_TRY_DELTAS        8
155 #define EXTRA_ADJUST_DELTAS     16
156 #define EXTRA_SORT_FIRST        32
157 #define EXTRA_BRANCHES          0x1c0
158 #define EXTRA_SKIP_8TO16        512
159 #define EXTRA_TERMS             0x3c00
160 #define EXTRA_DUMP_TERMS        16384
161 #define EXTRA_SORT_LAST         32768
162 
163 //////////////////////////////// WavPack Stream ///////////////////////////////
164 
165 // This internal structure contains everything required to handle a WavPack
166 // "stream", which is defined as a stereo or mono stream of audio samples. For
167 // multichannel audio several of these would be required. Each stream contains
168 // pointers to hold a complete allocated block of WavPack data, although it's
169 // possible to decode WavPack blocks without buffering an entire block.
170 
171 typedef struct bs {
172 #ifdef BITSTREAM_SHORTS
173     uint16_t *buf, *end, *ptr;
174 #else
175     unsigned char *buf, *end, *ptr;
176 #endif
177     void (*wrap)(struct bs *bs);
178     int error, bc;
179     uint32_t sr;
180 } Bitstream;
181 
182 #define MAX_WRAPPER_BYTES 16777216
183 #define NEW_MAX_STREAMS 4096
184 #define OLD_MAX_STREAMS 8
185 #define MAX_NTERMS 16
186 #define MAX_TERM 8
187 
188 // DSD-specific definitions
189 
190 #define MAX_HISTORY_BITS    5       // maximum number of history bits in DSD "fast" mode
191                                     // note that 5 history bits requires 32 history bins
192 #define MAX_BYTES_PER_BIN   1280    // maximum bytes for the value lookup array (per bin)
193                                     //  such that the total storage per bin = 2K (also
194                                     //  counting probabilities and summed_probabilities)
195 
196 // Note that this structure is directly accessed in assembly files, so modify with care
197 
198 struct decorr_pass {
199     int32_t term, delta, weight_A, weight_B;
200     int32_t samples_A [MAX_TERM], samples_B [MAX_TERM];
201     int32_t aweight_A, aweight_B;
202     int32_t sum_A, sum_B;
203 };
204 
205 typedef struct {
206     signed char joint_stereo, delta, terms [MAX_NTERMS+1];
207 } WavpackDecorrSpec;
208 
209 struct entropy_data {
210     uint32_t median [3], slow_level, error_limit;
211 };
212 
213 struct words_data {
214     uint32_t bitrate_delta [2], bitrate_acc [2];
215     uint32_t pend_data, holding_one, zeros_acc;
216     int holding_zero, pend_count;
217     struct entropy_data c [2];
218 };
219 
220 typedef struct {
221     int32_t value, filter0, filter1, filter2, filter3, filter4, filter5, filter6, factor;
222     unsigned int byte;
223 } DSDfilters;
224 
225 typedef struct {
226     WavpackHeader wphdr;
227     struct words_data w;
228 
229     unsigned char *blockbuff, *blockend;
230     unsigned char *block2buff, *block2end;
231     int32_t *sample_buffer;
232 
233     int64_t sample_index;
234     int bits, num_terms, mute_error, joint_stereo, false_stereo, shift;
235     int num_decorrs, num_passes, best_decorr, mask_decorr;
236     uint32_t crc, crc_x, crc_wvx;
237     Bitstream wvbits, wvcbits, wvxbits;
238     int init_done, wvc_skip;
239     float delta_decay;
240 
241     unsigned char int32_sent_bits, int32_zeros, int32_ones, int32_dups;
242     unsigned char float_flags, float_shift, float_max_exp, float_norm_exp;
243 
244     struct {
245         int32_t shaping_acc [2], shaping_delta [2], error [2];
246         double noise_sum, noise_ave, noise_max;
247         int16_t *shaping_data, *shaping_array;
248         int32_t shaping_samples;
249     } dc;
250 
251     struct decorr_pass decorr_passes [MAX_NTERMS], analysis_pass;
252     const WavpackDecorrSpec *decorr_specs;
253 
254     struct {
255         unsigned char *byteptr, *endptr, (*probabilities) [256], *lookup_buffer, **value_lookup, mode, ready;
256         int history_bins, p0, p1;
257         uint16_t (*summed_probabilities) [256];
258         uint32_t low, high, value;
259         DSDfilters filters [2];
260         int32_t *ptable;
261     } dsd;
262 
263 } WavpackStream;
264 
265 // flags for float_flags:
266 
267 #define FLOAT_SHIFT_ONES 1      // bits left-shifted into float = '1'
268 #define FLOAT_SHIFT_SAME 2      // bits left-shifted into float are the same
269 #define FLOAT_SHIFT_SENT 4      // bits shifted into float are sent literally
270 #define FLOAT_ZEROS_SENT 8      // "zeros" are not all real zeros
271 #define FLOAT_NEG_ZEROS  0x10   // contains negative zeros
272 #define FLOAT_EXCEPTIONS 0x20   // contains exceptions (inf, nan, etc.)
273 
274 /////////////////////////////// WavPack Context ///////////////////////////////
275 
276 // This internal structure holds everything required to encode or decode WavPack
277 // files. It is recommended that direct access to this structure be minimized
278 // and the provided utilities used instead.
279 
280 struct WavpackContext {
281     WavpackConfig config;
282 
283     WavpackMetadata *metadata;
284     uint32_t metabytes;
285     int metacount;
286 
287     unsigned char *wrapper_data;
288     uint32_t wrapper_bytes;
289 
290     WavpackBlockOutput blockout;
291     void *wv_out, *wvc_out;
292 
293     WavpackStreamReader64 *reader;
294     void *wv_in, *wvc_in;
295 
296     int64_t filelen, file2len, filepos, file2pos, total_samples, initial_index;
297     uint32_t crc_errors, first_flags;
298     int wvc_flag, open_flags, norm_offset, reduced_channels, lossy_blocks, version_five;
299     uint32_t block_samples, ave_block_samples, block_boundary, max_samples, acc_samples, riff_trailer_bytes;
300     int riff_header_added, riff_header_created;
301     M_Tag m_tag;
302 
303     int current_stream, num_streams, max_streams, stream_version;
304     WavpackStream **streams;
305     void *stream3;
306 
307     // these items were added in 5.0 to support alternate file types (especially CAF & DSD)
308     unsigned char file_format, *channel_reordering, *channel_identities;
309     uint32_t channel_layout, dsd_multiplier;
310     void *decimation_context;
311     char file_extension [8];
312 
313     void (*close_callback)(void *wpc);
314     char error_message [80];
315 };
316 
317 //////////////////////// function prototypes and macros //////////////////////
318 
319 #define CLEAR(destin) memset (&destin, 0, sizeof (destin));
320 
321 //////////////////////////////// decorrelation //////////////////////////////
322 // modules: pack.c, unpack.c, unpack_floats.c, extra1.c, extra2.c
323 
324 // #define SKIP_DECORRELATION   // experimental switch to disable all decorrelation on encode
325 
326 // These macros implement the weight application and update operations
327 // that are at the heart of the decorrelation loops. Note that there are
328 // sometimes two and even three versions of each macro. Theses should be
329 // equivalent and produce identical results, but some may perform better
330 // or worse on a given architecture.
331 
332 #if 1   // PERFCOND - apply decorrelation weight when no 32-bit overflow possible
333 #define apply_weight_i(weight, sample) ((weight * sample + 512) >> 10)
334 #else
335 #define apply_weight_i(weight, sample) ((((weight * sample) >> 8) + 2) >> 2)
336 #endif
337 
338 #if 1   // PERFCOND - apply decorrelation weight when 32-bit overflow is possible
339 #define apply_weight_f(weight, sample) (((((sample & 0xffff) * weight) >> 9) + \
340     (((sample & ~0xffff) >> 9) * weight) + 1) >> 1)
341 #elif 1
342 #define apply_weight_f(weight, sample) ((int32_t)((weight * (int64_t) sample + 512) >> 10))
343 #else
344 #define apply_weight_f(weight, sample) ((int32_t)floor(((double) weight * sample + 512.0) / 1024.0))
345 #endif
346 
347 #if 1   // PERFCOND - universal version that checks input magnitude or always uses long version
348 #define apply_weight(weight, sample) (sample != (int16_t) sample ? \
349     apply_weight_f (weight, sample) : apply_weight_i (weight, sample))
350 #else
351 #define apply_weight(weight, sample) (apply_weight_f (weight, sample))
352 #endif
353 
354 #if 1   // PERFCOND
355 #define update_weight(weight, delta, source, result) \
356     if (source && result) { int32_t s = (int32_t) (source ^ result) >> 31; weight = (delta ^ s) + (weight - s); }
357 #elif 1
358 #define update_weight(weight, delta, source, result) \
359     if (source && result) weight += (((source ^ result) >> 30) | 1) * delta;
360 #else
361 #define update_weight(weight, delta, source, result) \
362     if (source && result) (source ^ result) < 0 ? (weight -= delta) : (weight += delta);
363 #endif
364 
365 #define update_weight_clip(weight, delta, source, result) \
366     if (source && result) { \
367         const int32_t s = (source ^ result) >> 31; \
368         if ((weight = (weight ^ s) + (delta - s)) > 1024) weight = 1024; \
369         weight = (weight ^ s) - s; \
370     }
371 
372 void pack_init (WavpackContext *wpc);
373 int pack_block (WavpackContext *wpc, int32_t *buffer);
374 void send_general_metadata (WavpackContext *wpc);
375 void free_metadata (WavpackMetadata *wpmd);
376 int copy_metadata (WavpackMetadata *wpmd, unsigned char *buffer_start, unsigned char *buffer_end);
377 double WavpackGetEncodedNoise (WavpackContext *wpc, double *peak);
378 int unpack_init (WavpackContext *wpc);
379 int read_decorr_terms (WavpackStream *wps, WavpackMetadata *wpmd);
380 int read_decorr_weights (WavpackStream *wps, WavpackMetadata *wpmd);
381 int read_decorr_samples (WavpackStream *wps, WavpackMetadata *wpmd);
382 int read_shaping_info (WavpackStream *wps, WavpackMetadata *wpmd);
383 int32_t unpack_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count);
384 int check_crc_error (WavpackContext *wpc);
385 int scan_float_data (WavpackStream *wps, f32 *values, int32_t num_values);
386 void send_float_data (WavpackStream *wps, f32 *values, int32_t num_values);
387 void float_values (WavpackStream *wps, int32_t *values, int32_t num_values);
388 void dynamic_noise_shaping (WavpackContext *wpc, int32_t *buffer, int shortening_allowed);
389 void execute_stereo (WavpackContext *wpc, int32_t *samples, int no_history, int do_samples);
390 void execute_mono (WavpackContext *wpc, int32_t *samples, int no_history, int do_samples);
391 
392 ////////////////////////// DSD related (including decimation) //////////////////////////
393 // modules: pack_dsd.c unpack_dsd.c
394 
395 void pack_dsd_init (WavpackContext *wpc);
396 int pack_dsd_block (WavpackContext *wpc, int32_t *buffer);
397 int init_dsd_block (WavpackContext *wpc, WavpackMetadata *wpmd);
398 int32_t unpack_dsd_samples (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count);
399 
400 void *decimate_dsd_init (int num_channels);
401 void decimate_dsd_reset (void *decimate_context);
402 void decimate_dsd_run (void *decimate_context, int32_t *samples, int num_samples);
403 void decimate_dsd_destroy (void *decimate_context);
404 
405 ///////////////////////////////// CPU feature detection ////////////////////////////////
406 
407 int unpack_cpu_has_feature_x86 (int findex), pack_cpu_has_feature_x86 (int findex);
408 
409 #define CPU_FEATURE_MMX     23
410 
411 ///////////////////////////// pre-4.0 version decoding ////////////////////////////
412 // modules: unpack3.c, unpack3_open.c, unpack3_seek.c
413 
414 WavpackContext *open_file3 (WavpackContext *wpc, char *error);
415 int32_t unpack_samples3 (WavpackContext *wpc, int32_t *buffer, uint32_t sample_count);
416 int seek_sample3 (WavpackContext *wpc, uint32_t desired_index);
417 uint32_t get_sample_index3 (WavpackContext *wpc);
418 void free_stream3 (WavpackContext *wpc);
419 int get_version3 (WavpackContext *wpc);
420 
421 ////////////////////////////// bitstream macros & functions /////////////////////////////
422 
423 #define bs_is_open(bs) ((bs)->ptr != NULL)
424 uint32_t bs_close_read (Bitstream *bs);
425 
426 #define getbit(bs) ( \
427     (((bs)->bc) ? \
428         ((bs)->bc--, (bs)->sr & 1) : \
429             (((++((bs)->ptr) != (bs)->end) ? (void) 0 : (bs)->wrap (bs)), (bs)->bc = sizeof (*((bs)->ptr)) * 8 - 1, ((bs)->sr = *((bs)->ptr)) & 1) \
430     ) ? \
431         ((bs)->sr >>= 1, 1) : \
432         ((bs)->sr >>= 1, 0) \
433 )
434 
435 #define getbits(value, nbits, bs) do { \
436     while ((nbits) > (bs)->bc) { \
437         if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \
438         (bs)->sr |= (uint32_t)*((bs)->ptr) << (bs)->bc; \
439         (bs)->bc += sizeof (*((bs)->ptr)) * 8; \
440     } \
441     *(value) = (bs)->sr; \
442     if ((bs)->bc > 32) { \
443         (bs)->bc -= (nbits); \
444         (bs)->sr = *((bs)->ptr) >> (sizeof (*((bs)->ptr)) * 8 - (bs)->bc); \
445     } \
446     else { \
447         (bs)->bc -= (nbits); \
448         (bs)->sr >>= (nbits); \
449     } \
450 } while (0)
451 
452 #define putbit(bit, bs) do { if (bit) (bs)->sr |= (1U << (bs)->bc); \
453     if (++((bs)->bc) == sizeof (*((bs)->ptr)) * 8) { \
454         *((bs)->ptr) = (bs)->sr; \
455         (bs)->sr = (bs)->bc = 0; \
456         if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \
457     }} while (0)
458 
459 #define putbit_0(bs) do { \
460     if (++((bs)->bc) == sizeof (*((bs)->ptr)) * 8) { \
461         *((bs)->ptr) = (bs)->sr; \
462         (bs)->sr = (bs)->bc = 0; \
463         if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \
464     }} while (0)
465 
466 #define putbit_1(bs) do { (bs)->sr |= (1U << (bs)->bc); \
467     if (++((bs)->bc) == sizeof (*((bs)->ptr)) * 8) { \
468         *((bs)->ptr) = (bs)->sr; \
469         (bs)->sr = (bs)->bc = 0; \
470         if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \
471     }} while (0)
472 
473 #define putbits(value, nbits, bs) do { \
474     (bs)->sr |= (uint32_t)(value) << (bs)->bc; \
475     if (((bs)->bc += (nbits)) >= sizeof (*((bs)->ptr)) * 8) \
476         do { \
477             *((bs)->ptr) = (bs)->sr; \
478             (bs)->sr >>= sizeof (*((bs)->ptr)) * 8; \
479             if (((bs)->bc -= sizeof (*((bs)->ptr)) * 8) > 32 - sizeof (*((bs)->ptr)) * 8) \
480                 (bs)->sr |= ((value) >> ((nbits) - (bs)->bc)); \
481             if (++((bs)->ptr) == (bs)->end) (bs)->wrap (bs); \
482         } while ((bs)->bc >= sizeof (*((bs)->ptr)) * 8); \
483 } while (0)
484 
485 ///////////////////////////// entropy encoder / decoder ////////////////////////////
486 // modules: entropy_utils.c, read_words.c, write_words.c
487 
488 // these control the time constant "slow_level" which is used for hybrid mode
489 // that controls bitrate as a function of residual level (HYBRID_BITRATE).
490 #define SLS 8
491 #define SLO ((1 << (SLS - 1)))
492 
493 #define LIMIT_ONES 16   // maximum consecutive 1s sent for "div" data
494 
495 // these control the time constant of the 3 median level breakpoints
496 #define DIV0 128        // 5/7 of samples
497 #define DIV1 64         // 10/49 of samples
498 #define DIV2 32         // 20/343 of samples
499 
500 // this macro retrieves the specified median breakpoint (without frac; min = 1)
501 #define GET_MED(med) (((c->median [med]) >> 4) + 1)
502 
503 // These macros update the specified median breakpoints. Note that the median
504 // is incremented when the sample is higher than the median, else decremented.
505 // They are designed so that the median will never drop below 1 and the value
506 // is essentially stationary if there are 2 increments for every 5 decrements.
507 
508 #define INC_MED0() (c->median [0] += ((c->median [0] + DIV0) / DIV0) * 5)
509 #define DEC_MED0() (c->median [0] -= ((c->median [0] + (DIV0-2)) / DIV0) * 2)
510 #define INC_MED1() (c->median [1] += ((c->median [1] + DIV1) / DIV1) * 5)
511 #define DEC_MED1() (c->median [1] -= ((c->median [1] + (DIV1-2)) / DIV1) * 2)
512 #define INC_MED2() (c->median [2] += ((c->median [2] + DIV2) / DIV2) * 5)
513 #define DEC_MED2() (c->median [2] -= ((c->median [2] + (DIV2-2)) / DIV2) * 2)
514 
515 #ifdef HAVE___BUILTIN_CLZ
516 #define count_bits(av) ((av) ? 32 - __builtin_clz (av) : 0)
517 #elif defined (_WIN64)
count_bits(uint32_t av)518 static __inline int count_bits (uint32_t av) { unsigned long res; return _BitScanReverse (&res, av) ? (int)(res + 1) : 0; }
519 #else
520 #define count_bits(av) ( \
521  (av) < (1 << 8) ? nbits_table [av] : \
522   ( \
523    (av) < (1L << 16) ? nbits_table [(av) >> 8] + 8 : \
524    ((av) < (1L << 24) ? nbits_table [(av) >> 16] + 16 : nbits_table [(av) >> 24] + 24) \
525   ) \
526 )
527 #endif
528 
529 void init_words (WavpackStream *wps);
530 void write_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd);
531 void write_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd);
532 int read_entropy_vars (WavpackStream *wps, WavpackMetadata *wpmd);
533 int read_hybrid_profile (WavpackStream *wps, WavpackMetadata *wpmd);
534 int32_t FASTCALL send_word (WavpackStream *wps, int32_t value, int chan);
535 void send_words_lossless (WavpackStream *wps, int32_t *buffer, int32_t nsamples);
536 int32_t FASTCALL get_word (WavpackStream *wps, int chan, int32_t *correction);
537 int32_t get_words_lossless (WavpackStream *wps, int32_t *buffer, int32_t nsamples);
538 void flush_word (WavpackStream *wps);
539 int32_t nosend_word (WavpackStream *wps, int32_t value, int chan);
540 void scan_word (WavpackStream *wps, int32_t *samples, uint32_t num_samples, int dir);
541 void update_error_limit (WavpackStream *wps);
542 
543 extern const uint32_t bitset [32];
544 extern const uint32_t bitmask [32];
545 extern const char nbits_table [256];
546 
547 int wp_log2s (int32_t value);
548 int32_t wp_exp2s (int log);
549 int FASTCALL wp_log2 (uint32_t avalue);
550 
551 #ifdef OPT_ASM_X86
552 #define LOG2BUFFER log2buffer_x86
553 #elif defined(OPT_ASM_X64) && (defined (_WIN64) || defined(__CYGWIN__) || defined(__MINGW64__) || defined(__midipix__))
554 #define LOG2BUFFER log2buffer_x64win
555 #elif defined(OPT_ASM_X64)
556 #define LOG2BUFFER log2buffer_x64
557 #else
558 #define LOG2BUFFER log2buffer
559 #endif
560 
561 uint32_t LOG2BUFFER (int32_t *samples, uint32_t num_samples, int limit);
562 
563 signed char store_weight (int weight);
564 int restore_weight (signed char weight);
565 
566 #define WORD_EOF ((int32_t)(1U << 31))
567 
568 void WavpackFloatNormalize (int32_t *values, int32_t num_values, int delta_exp);
569 
570 /////////////////////////// high-level unpacking API and support ////////////////////////////
571 // modules: open_utils.c, unpack_utils.c, unpack_seek.c, unpack_floats.c
572 
573 WavpackContext *WavpackOpenFileInputEx64 (WavpackStreamReader64 *reader, void *wv_id, void *wvc_id, char *error, int flags, int norm_offset);
574 WavpackContext *WavpackOpenFileInputEx (WavpackStreamReader *reader, void *wv_id, void *wvc_id, char *error, int flags, int norm_offset);
575 WavpackContext *WavpackOpenFileInput (const char *infilename, char *error, int flags, int norm_offset);
576 
577 #define OPEN_WVC        0x1     // open/read "correction" file
578 #define OPEN_TAGS       0x2     // read ID3v1 / APEv2 tags (seekable file)
579 #define OPEN_WRAPPER    0x4     // make audio wrapper available (i.e. RIFF)
580 #define OPEN_2CH_MAX    0x8     // open multichannel as stereo (no downmix)
581 #define OPEN_NORMALIZE  0x10    // normalize floating point data to +/- 1.0
582 #define OPEN_STREAMING  0x20    // "streaming" mode blindly unpacks blocks
583                                 // w/o regard to header file position info
584 #define OPEN_EDIT_TAGS  0x40    // allow editing of tags
585 #define OPEN_FILE_UTF8  0x80    // assume filenames are UTF-8 encoded, not ANSI (Windows only)
586 
587 // new for version 5
588 
589 #define OPEN_DSD_NATIVE 0x100   // open DSD files as bitstreams
590                                 // (returned as 8-bit "samples" stored in 32-bit words)
591 #define OPEN_DSD_AS_PCM 0x200   // open DSD files as 24-bit PCM (decimated 8x)
592 #define OPEN_ALT_TYPES  0x400   // application is aware of alternate file types & qmode
593                                 // (just affects retrieving wrappers & MD5 checksums)
594 #define OPEN_NO_CHECKSUM 0x800  // don't verify block checksums before decoding
595 
596 int WavpackGetMode (WavpackContext *wpc);
597 
598 int WavpackGetQualifyMode (WavpackContext *wpc);
599 int WavpackGetVersion (WavpackContext *wpc);
600 uint32_t WavpackUnpackSamples (WavpackContext *wpc, int32_t *buffer, uint32_t samples);
601 int WavpackSeekSample (WavpackContext *wpc, uint32_t sample);
602 int WavpackSeekSample64 (WavpackContext *wpc, int64_t sample);
603 int WavpackGetMD5Sum (WavpackContext *wpc, unsigned char data [16]);
604 
605 int WavpackVerifySingleBlock (unsigned char *buffer, int verify_checksum);
606 uint32_t read_next_header (WavpackStreamReader64 *reader, void *id, WavpackHeader *wphdr);
607 int read_wvc_block (WavpackContext *wpc);
608 
609 /////////////////////////// high-level packing API and support ////////////////////////////
610 // modules: pack_utils.c, pack_floats.c
611 
612 WavpackContext *WavpackOpenFileOutput (WavpackBlockOutput blockout, void *wv_id, void *wvc_id);
613 int WavpackSetConfiguration (WavpackContext *wpc, WavpackConfig *config, uint32_t total_samples);
614 int WavpackSetConfiguration64 (WavpackContext *wpc, WavpackConfig *config, int64_t total_samples, const unsigned char *chan_ids);
615 int WavpackPackInit (WavpackContext *wpc);
616 int WavpackAddWrapper (WavpackContext *wpc, void *data, uint32_t bcount);
617 int WavpackPackSamples (WavpackContext *wpc, int32_t *sample_buffer, uint32_t sample_count);
618 int WavpackFlushSamples (WavpackContext *wpc);
619 int WavpackStoreMD5Sum (WavpackContext *wpc, unsigned char data [16]);
620 void WavpackSeekTrailingWrapper (WavpackContext *wpc);
621 void WavpackUpdateNumSamples (WavpackContext *wpc, void *first_block);
622 void *WavpackGetWrapperLocation (void *first_block, uint32_t *size);
623 
624 /////////////////////////////////// common utilities ////////////////////////////////////
625 // module: common_utils.c
626 
627 extern const uint32_t sample_rates [16];
628 uint32_t WavpackGetLibraryVersion (void);
629 const char *WavpackGetLibraryVersionString (void);
630 uint32_t WavpackGetSampleRate (WavpackContext *wpc);
631 int WavpackGetBitsPerSample (WavpackContext *wpc);
632 int WavpackGetBytesPerSample (WavpackContext *wpc);
633 int WavpackGetNumChannels (WavpackContext *wpc);
634 int WavpackGetChannelMask (WavpackContext *wpc);
635 int WavpackGetReducedChannels (WavpackContext *wpc);
636 int WavpackGetFloatNormExp (WavpackContext *wpc);
637 uint32_t WavpackGetNumSamples (WavpackContext *wpc);
638 int64_t WavpackGetNumSamples64 (WavpackContext *wpc);
639 uint32_t WavpackGetSampleIndex (WavpackContext *wpc);
640 int64_t WavpackGetSampleIndex64 (WavpackContext *wpc);
641 char *WavpackGetErrorMessage (WavpackContext *wpc);
642 int WavpackGetNumErrors (WavpackContext *wpc);
643 int WavpackLossyBlocks (WavpackContext *wpc);
644 uint32_t WavpackGetWrapperBytes (WavpackContext *wpc);
645 unsigned char *WavpackGetWrapperData (WavpackContext *wpc);
646 void WavpackFreeWrapper (WavpackContext *wpc);
647 double WavpackGetProgress (WavpackContext *wpc);
648 uint32_t WavpackGetFileSize (WavpackContext *wpc);
649 int64_t WavpackGetFileSize64 (WavpackContext *wpc);
650 double WavpackGetRatio (WavpackContext *wpc);
651 double WavpackGetAverageBitrate (WavpackContext *wpc, int count_wvc);
652 double WavpackGetInstantBitrate (WavpackContext *wpc);
653 WavpackContext *WavpackCloseFile (WavpackContext *wpc);
654 void WavpackLittleEndianToNative (void *data, char *format);
655 void WavpackNativeToLittleEndian (void *data, char *format);
656 void WavpackBigEndianToNative (void *data, char *format);
657 void WavpackNativeToBigEndian (void *data, char *format);
658 
659 void install_close_callback (WavpackContext *wpc, void cb_func (void *wpc));
660 void free_dsd_tables (WavpackStream *wps);
661 void free_streams (WavpackContext *wpc);
662 
663 /////////////////////////////////// tag utilities ////////////////////////////////////
664 // modules: tags.c, tag_utils.c
665 
666 int WavpackGetNumTagItems (WavpackContext *wpc);
667 int WavpackGetTagItem (WavpackContext *wpc, const char *item, char *value, int size);
668 int WavpackGetTagItemIndexed (WavpackContext *wpc, int index, char *item, int size);
669 int WavpackGetNumBinaryTagItems (WavpackContext *wpc);
670 int WavpackGetBinaryTagItem (WavpackContext *wpc, const char *item, char *value, int size);
671 int WavpackGetBinaryTagItemIndexed (WavpackContext *wpc, int index, char *item, int size);
672 int WavpackAppendTagItem (WavpackContext *wpc, const char *item, const char *value, int vsize);
673 int WavpackAppendBinaryTagItem (WavpackContext *wpc, const char *item, const char *value, int vsize);
674 int WavpackDeleteTagItem (WavpackContext *wpc, const char *item);
675 int WavpackWriteTag (WavpackContext *wpc);
676 int load_tag (WavpackContext *wpc);
677 void free_tag (M_Tag *m_tag);
678 int valid_tag (M_Tag *m_tag);
679 int editable_tag (M_Tag *m_tag);
680 
681 #endif
682 
683