1 /*
2  * ALAC (Apple Lossless Audio Codec) decoder
3  * Copyright (c) 2005 David Hammerton
4  * All rights reserved.
5  *
6  * This is the actual decoder.
7  *
8  * http://crazney.net/programs/itunes/alac.html
9  *
10  * Permission is hereby granted, free of charge, to any person
11  * obtaining a copy of this software and associated documentation
12  * files (the "Software"), to deal in the Software without
13  * restriction, including without limitation the rights to use,
14  * copy, modify, merge, publish, distribute, sublicense, and/or
15  * sell copies of the Software, and to permit persons to whom the
16  * Software is furnished to do so, subject to the following conditions:
17  *
18  * The above copyright notice and this permission notice shall be
19  * included in all copies or substantial portions of the Software.
20  *
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
23  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
25  * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
26  * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
28  * OTHER DEALINGS IN THE SOFTWARE.
29  *
30  */
31 
32 static const int host_bigendian = 0;
33 
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #ifdef _WIN32
38     #include "stdint_win.h"
39 #else
40     #include <stdint.h>
41 #endif
42 
43 #include "alac.h"
44 
45 #define _Swap32(v) do { \
46                    v = (((v) & 0x000000FF) << 0x18) | \
47                        (((v) & 0x0000FF00) << 0x08) | \
48                        (((v) & 0x00FF0000) >> 0x08) | \
49                        (((v) & 0xFF000000) >> 0x18); } while(0)
50 
51 #define _Swap16(v) do { \
52                    v = (((v) & 0x00FF) << 0x08) | \
53                        (((v) & 0xFF00) >> 0x08); } while (0)
54 
55 struct {signed int x:24;} se_struct_24;
56 #define SignExtend24(val) (se_struct_24.x = val)
57 
allocate_buffers(alac_file * alac)58 void allocate_buffers(alac_file *alac)
59 {
60     alac->predicterror_buffer_a = malloc(alac->setinfo_max_samples_per_frame * 4);
61     alac->predicterror_buffer_b = malloc(alac->setinfo_max_samples_per_frame * 4);
62 
63     alac->outputsamples_buffer_a = malloc(alac->setinfo_max_samples_per_frame * 4);
64     alac->outputsamples_buffer_b = malloc(alac->setinfo_max_samples_per_frame * 4);
65 
66     alac->uncompressed_bytes_buffer_a = malloc(alac->setinfo_max_samples_per_frame * 4);
67     alac->uncompressed_bytes_buffer_b = malloc(alac->setinfo_max_samples_per_frame * 4);
68 }
69 
deallocate_buffers(alac_file * alac)70 void deallocate_buffers(alac_file *alac)
71 {
72     free(alac->predicterror_buffer_a);
73     free(alac->predicterror_buffer_b);
74 
75     free(alac->outputsamples_buffer_a);
76     free(alac->outputsamples_buffer_b);
77 
78     free(alac->uncompressed_bytes_buffer_a);
79     free(alac->uncompressed_bytes_buffer_b);
80 }
81 
alac_set_info(alac_file * alac,char * inputbuffer)82 void alac_set_info(alac_file *alac, char *inputbuffer)
83 {
84   char *ptr = inputbuffer;
85   ptr += 4; /* size */
86   ptr += 4; /* frma */
87   ptr += 4; /* alac */
88   ptr += 4; /* size */
89   ptr += 4; /* alac */
90 
91   ptr += 4; /* 0 ? */
92 
93   alac->setinfo_max_samples_per_frame = *(uint32_t*)ptr; /* buffer size / 2 ? */
94   if (!host_bigendian)
95       _Swap32(alac->setinfo_max_samples_per_frame);
96   ptr += 4;
97   alac->setinfo_7a = *(uint8_t*)ptr;
98   ptr += 1;
99   alac->setinfo_sample_size = *(uint8_t*)ptr;
100   ptr += 1;
101   alac->setinfo_rice_historymult = *(uint8_t*)ptr;
102   ptr += 1;
103   alac->setinfo_rice_initialhistory = *(uint8_t*)ptr;
104   ptr += 1;
105   alac->setinfo_rice_kmodifier = *(uint8_t*)ptr;
106   ptr += 1;
107   alac->setinfo_7f = *(uint8_t*)ptr;
108   ptr += 1;
109   alac->setinfo_80 = *(uint16_t*)ptr;
110   if (!host_bigendian)
111       _Swap16(alac->setinfo_80);
112   ptr += 2;
113   alac->setinfo_82 = *(uint32_t*)ptr;
114   if (!host_bigendian)
115       _Swap32(alac->setinfo_82);
116   ptr += 4;
117   alac->setinfo_86 = *(uint32_t*)ptr;
118   if (!host_bigendian)
119       _Swap32(alac->setinfo_86);
120   ptr += 4;
121   alac->setinfo_8a_rate = *(uint32_t*)ptr;
122   if (!host_bigendian)
123       _Swap32(alac->setinfo_8a_rate);
124   ptr += 4;
125 
126   allocate_buffers(alac);
127 
128 }
129 
130 /* stream reading */
131 
132 /* supports reading 1 to 16 bits, in big endian format */
readbits_16(alac_file * alac,int bits)133 static uint32_t readbits_16(alac_file *alac, int bits)
134 {
135     uint32_t result;
136     int new_accumulator;
137 
138     result = (alac->input_buffer[0] << 16) |
139              (alac->input_buffer[1] << 8) |
140              (alac->input_buffer[2]);
141 
142     /* shift left by the number of bits we've already read,
143      * so that the top 'n' bits of the 24 bits we read will
144      * be the return bits */
145     result = result << alac->input_buffer_bitaccumulator;
146 
147     result = result & 0x00ffffff;
148 
149     /* and then only want the top 'n' bits from that, where
150      * n is 'bits' */
151     result = result >> (24 - bits);
152 
153     new_accumulator = (alac->input_buffer_bitaccumulator + bits);
154 
155     /* increase the buffer pointer if we've read over n bytes. */
156     alac->input_buffer += (new_accumulator >> 3);
157 
158     /* and the remainder goes back into the bit accumulator */
159     alac->input_buffer_bitaccumulator = (new_accumulator & 7);
160 
161     return result;
162 }
163 
164 /* supports reading 1 to 32 bits, in big endian format */
readbits(alac_file * alac,int bits)165 static uint32_t readbits(alac_file *alac, int bits)
166 {
167     int32_t result = 0;
168 
169     if (bits > 16)
170     {
171         bits -= 16;
172         result = readbits_16(alac, 16) << bits;
173     }
174 
175     result |= readbits_16(alac, bits);
176 
177     return result;
178 }
179 
180 /* reads a single bit */
readbit(alac_file * alac)181 static int readbit(alac_file *alac)
182 {
183     int result;
184     int new_accumulator;
185 
186     result = alac->input_buffer[0];
187 
188     result = result << alac->input_buffer_bitaccumulator;
189 
190     result = result >> 7 & 1;
191 
192     new_accumulator = (alac->input_buffer_bitaccumulator + 1);
193 
194     alac->input_buffer += (new_accumulator / 8);
195 
196     alac->input_buffer_bitaccumulator = (new_accumulator % 8);
197 
198     return result;
199 }
200 
unreadbits(alac_file * alac,int bits)201 static void unreadbits(alac_file *alac, int bits)
202 {
203     int new_accumulator = (alac->input_buffer_bitaccumulator - bits);
204 
205     alac->input_buffer += (new_accumulator >> 3);
206 
207     alac->input_buffer_bitaccumulator = (new_accumulator & 7);
208     if (alac->input_buffer_bitaccumulator < 0)
209         alac->input_buffer_bitaccumulator *= -1;
210 }
211 
212 /* various implementations of count_leading_zero:
213  * the first one is the original one, the simplest and most
214  * obvious for what it's doing. never use this.
215  * then there are the asm ones. fill in as necessary
216  * and finally an unrolled and optimised c version
217  * to fall back to
218  */
219 #if 0
220 /* hideously inefficient. could use a bitmask search,
221  * alternatively bsr on x86,
222  */
223 static int count_leading_zeros(int32_t input)
224 {
225     int i = 0;
226     while (!(0x80000000 & input) && i < 32)
227     {
228         i++;
229         input = input << 1;
230     }
231     return i;
232 }
233 #elif defined(__GNUC__)
234 /* for some reason the unrolled version (below) is
235  * actually faster than this. yay intel!
236  */
count_leading_zeros(int input)237 static int count_leading_zeros(int input)
238 {
239     return __builtin_clz(input);
240 }
241 #elif defined(_MSC_VER) && defined(_M_IX86)
count_leading_zeros(int input)242 static int count_leading_zeros(int input)
243 {
244     int output = 0;
245     if (!input) return 32;
246     __asm
247     {
248         mov eax, input;
249         mov edx, 0x1f;
250         bsr ecx, eax;
251         sub edx, ecx;
252         mov output, edx;
253     }
254     return output;
255 }
256 #else
257 #warning using generic count leading zeroes. You may wish to write one for your CPU / compiler
count_leading_zeros(int input)258 static int count_leading_zeros(int input)
259 {
260     int output = 0;
261     int curbyte = 0;
262 
263     curbyte = input >> 24;
264     if (curbyte) goto found;
265     output += 8;
266 
267     curbyte = input >> 16;
268     if (curbyte & 0xff) goto found;
269     output += 8;
270 
271     curbyte = input >> 8;
272     if (curbyte & 0xff) goto found;
273     output += 8;
274 
275     curbyte = input;
276     if (curbyte & 0xff) goto found;
277     output += 8;
278 
279     return output;
280 
281 found:
282     if (!(curbyte & 0xf0))
283     {
284         output += 4;
285     }
286     else
287         curbyte >>= 4;
288 
289     if (curbyte & 0x8)
290         return output;
291     if (curbyte & 0x4)
292         return output + 1;
293     if (curbyte & 0x2)
294         return output + 2;
295     if (curbyte & 0x1)
296         return output + 3;
297 
298     /* shouldn't get here: */
299     return output + 4;
300 }
301 #endif
302 
303 #define RICE_THRESHOLD 8 // maximum number of bits for a rice prefix.
304 
entropy_decode_value(alac_file * alac,int readSampleSize,int k,int rice_kmodifier_mask)305 int32_t entropy_decode_value(alac_file* alac,
306                              int readSampleSize,
307                              int k,
308                              int rice_kmodifier_mask)
309 {
310     int32_t x = 0; // decoded value
311 
312     // read x, number of 1s before 0 represent the rice value.
313     while (x <= RICE_THRESHOLD && readbit(alac))
314     {
315         x++;
316     }
317 
318     if (x > RICE_THRESHOLD)
319     {
320         // read the number from the bit stream (raw value)
321         int32_t value;
322 
323         value = readbits(alac, readSampleSize);
324 
325         // mask value
326         value &= (((uint32_t)0xffffffff) >> (32 - readSampleSize));
327 
328         x = value;
329     }
330     else
331     {
332         if (k != 1)
333         {
334             int extraBits = readbits(alac, k);
335 
336             // x = x * (2^k - 1)
337             x *= (((1 << k) - 1) & rice_kmodifier_mask);
338 
339             if (extraBits > 1)
340                 x += extraBits - 1;
341             else
342                 unreadbits(alac, 1);
343         }
344     }
345 
346     return x;
347 }
348 
entropy_rice_decode(alac_file * alac,int32_t * outputBuffer,int outputSize,int readSampleSize,int rice_initialhistory,int rice_kmodifier,int rice_historymult,int rice_kmodifier_mask)349 void entropy_rice_decode(alac_file* alac,
350                          int32_t* outputBuffer,
351                          int outputSize,
352                          int readSampleSize,
353                          int rice_initialhistory,
354                          int rice_kmodifier,
355                          int rice_historymult,
356                          int rice_kmodifier_mask)
357 {
358     int             outputCount;
359     int             history = rice_initialhistory;
360     int             signModifier = 0;
361 
362     for (outputCount = 0; outputCount < outputSize; outputCount++)
363     {
364         int32_t     decodedValue;
365         int32_t     finalValue;
366         int32_t     k;
367 
368         k = 31 - rice_kmodifier - count_leading_zeros((history >> 9) + 3);
369 
370         if (k < 0) k += rice_kmodifier;
371         else k = rice_kmodifier;
372 
373         // note: don't use rice_kmodifier_mask here (set mask to 0xFFFFFFFF)
374         decodedValue = entropy_decode_value(alac, readSampleSize, k, 0xFFFFFFFF);
375 
376         decodedValue += signModifier;
377         finalValue = (decodedValue + 1) / 2; // inc by 1 and shift out sign bit
378         if (decodedValue & 1) // the sign is stored in the low bit
379             finalValue *= -1;
380 
381         outputBuffer[outputCount] = finalValue;
382 
383         signModifier = 0;
384 
385         // update history
386         history += (decodedValue * rice_historymult)
387                 - ((history * rice_historymult) >> 9);
388 
389         if (decodedValue > 0xFFFF)
390             history = 0xFFFF;
391 
392         // special case, for compressed blocks of 0
393         if ((history < 128) && (outputCount + 1 < outputSize))
394         {
395             int32_t     blockSize;
396 
397             signModifier = 1;
398 
399             k = count_leading_zeros(history) + ((history + 16) / 64) - 24;
400 
401             // note: blockSize is always 16bit
402             blockSize = entropy_decode_value(alac, 16, k, rice_kmodifier_mask);
403 
404             // got blockSize 0s
405             if (blockSize > 0)
406             {
407                 memset(&outputBuffer[outputCount + 1], 0, blockSize * sizeof(*outputBuffer));
408                 outputCount += blockSize;
409             }
410 
411             if (blockSize > 0xFFFF)
412                 signModifier = 0;
413 
414             history = 0;
415         }
416     }
417 }
418 
419 #define SIGN_EXTENDED32(val, bits) ((val << (32 - bits)) >> (32 - bits))
420 
421 #define SIGN_ONLY(v) \
422                      ((v < 0) ? (-1) : \
423                                 ((v > 0) ? (1) : \
424                                            (0)))
425 
predictor_decompress_fir_adapt(int32_t * error_buffer,int32_t * buffer_out,int output_size,int readsamplesize,int16_t * predictor_coef_table,int predictor_coef_num,int predictor_quantitization)426 static void predictor_decompress_fir_adapt(int32_t *error_buffer,
427                                            int32_t *buffer_out,
428                                            int output_size,
429                                            int readsamplesize,
430                                            int16_t *predictor_coef_table,
431                                            int predictor_coef_num,
432                                            int predictor_quantitization)
433 {
434     int i;
435 
436     /* first sample always copies */
437     *buffer_out = *error_buffer;
438 
439     if (!predictor_coef_num)
440     {
441         if (output_size <= 1) return;
442         memcpy(buffer_out+1, error_buffer+1, (output_size-1) * 4);
443         return;
444     }
445 
446     if (predictor_coef_num == 0x1f) /* 11111 - max value of predictor_coef_num */
447     { /* second-best case scenario for fir decompression,
448        * error describes a small difference from the previous sample only
449        */
450         if (output_size <= 1) return;
451         for (i = 0; i < output_size - 1; i++)
452         {
453             int32_t prev_value;
454             int32_t error_value;
455 
456             prev_value = buffer_out[i];
457             error_value = error_buffer[i+1];
458             buffer_out[i+1] = SIGN_EXTENDED32((prev_value + error_value), readsamplesize);
459         }
460         return;
461     }
462 
463     /* read warm-up samples */
464     if (predictor_coef_num > 0)
465     {
466         int i;
467         for (i = 0; i < predictor_coef_num; i++)
468         {
469             int32_t val;
470 
471             val = buffer_out[i] + error_buffer[i+1];
472 
473             val = SIGN_EXTENDED32(val, readsamplesize);
474 
475             buffer_out[i+1] = val;
476         }
477     }
478 
479 #if 0
480     /* 4 and 8 are very common cases (the only ones i've seen). these
481      * should be unrolled and optimised
482      */
483     if (predictor_coef_num == 4)
484     {
485         /* FIXME: optimised general case */
486         return;
487     }
488 
489     if (predictor_coef_table == 8)
490     {
491         /* FIXME: optimised general case */
492         return;
493     }
494 #endif
495 
496 
497     /* general case */
498     if (predictor_coef_num > 0)
499     {
500         for (i = predictor_coef_num + 1;
501              i < output_size;
502              i++)
503         {
504             int j;
505             int sum = 0;
506             int outval;
507             int error_val = error_buffer[i];
508 
509             for (j = 0; j < predictor_coef_num; j++)
510             {
511                 sum += (buffer_out[predictor_coef_num-j] - buffer_out[0]) *
512                        predictor_coef_table[j];
513             }
514 
515             outval = (1 << (predictor_quantitization-1)) + sum;
516             outval = outval >> predictor_quantitization;
517             outval = outval + buffer_out[0] + error_val;
518             outval = SIGN_EXTENDED32(outval, readsamplesize);
519 
520             buffer_out[predictor_coef_num+1] = outval;
521 
522             if (error_val > 0)
523             {
524                 int predictor_num = predictor_coef_num - 1;
525 
526                 while (predictor_num >= 0 && error_val > 0)
527                 {
528                     int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
529                     int sign = SIGN_ONLY(val);
530 
531                     predictor_coef_table[predictor_num] -= sign;
532 
533                     val *= sign; /* absolute value */
534 
535                     error_val -= ((val >> predictor_quantitization) *
536                                   (predictor_coef_num - predictor_num));
537 
538                     predictor_num--;
539                 }
540             }
541             else if (error_val < 0)
542             {
543                 int predictor_num = predictor_coef_num - 1;
544 
545                 while (predictor_num >= 0 && error_val < 0)
546                 {
547                     int val = buffer_out[0] - buffer_out[predictor_coef_num - predictor_num];
548                     int sign = - SIGN_ONLY(val);
549 
550                     predictor_coef_table[predictor_num] -= sign;
551 
552                     val *= sign; /* neg value */
553 
554                     error_val -= ((val >> predictor_quantitization) *
555                                   (predictor_coef_num - predictor_num));
556 
557                     predictor_num--;
558                 }
559             }
560 
561             buffer_out++;
562         }
563     }
564 }
565 
deinterlace_16(int32_t * buffer_a,int32_t * buffer_b,int16_t * buffer_out,int numchannels,int numsamples,uint8_t interlacing_shift,uint8_t interlacing_leftweight)566 void deinterlace_16(int32_t *buffer_a, int32_t *buffer_b,
567                     int16_t *buffer_out,
568                     int numchannels, int numsamples,
569                     uint8_t interlacing_shift,
570                     uint8_t interlacing_leftweight)
571 {
572     int i;
573     if (numsamples <= 0) return;
574 
575     /* weighted interlacing */
576     if (interlacing_leftweight)
577     {
578         for (i = 0; i < numsamples; i++)
579         {
580             int32_t difference, midright;
581             int16_t left;
582             int16_t right;
583 
584             midright = buffer_a[i];
585             difference = buffer_b[i];
586 
587 
588             right = midright - ((difference * interlacing_leftweight) >> interlacing_shift);
589             left = right + difference;
590 
591             /* output is always little endian */
592             if (host_bigendian)
593             {
594                 _Swap16(left);
595                 _Swap16(right);
596             }
597 
598             buffer_out[i*numchannels] = left;
599             buffer_out[i*numchannels + 1] = right;
600         }
601 
602         return;
603     }
604 
605     /* otherwise basic interlacing took place */
606     for (i = 0; i < numsamples; i++)
607     {
608         int16_t left, right;
609 
610         left = buffer_a[i];
611         right = buffer_b[i];
612 
613         /* output is always little endian */
614         if (host_bigendian)
615         {
616             _Swap16(left);
617             _Swap16(right);
618         }
619 
620         buffer_out[i*numchannels] = left;
621         buffer_out[i*numchannels + 1] = right;
622     }
623 }
624 
deinterlace_24(int32_t * buffer_a,int32_t * buffer_b,int uncompressed_bytes,int32_t * uncompressed_bytes_buffer_a,int32_t * uncompressed_bytes_buffer_b,void * buffer_out,int numchannels,int numsamples,uint8_t interlacing_shift,uint8_t interlacing_leftweight)625 void deinterlace_24(int32_t *buffer_a, int32_t *buffer_b,
626                     int uncompressed_bytes,
627                     int32_t *uncompressed_bytes_buffer_a, int32_t *uncompressed_bytes_buffer_b,
628                     void *buffer_out,
629                     int numchannels, int numsamples,
630                     uint8_t interlacing_shift,
631                     uint8_t interlacing_leftweight)
632 {
633     int i;
634     if (numsamples <= 0) return;
635 
636     /* weighted interlacing */
637     if (interlacing_leftweight)
638     {
639         for (i = 0; i < numsamples; i++)
640         {
641             int32_t difference, midright;
642             int32_t left;
643             int32_t right;
644 
645             midright = buffer_a[i];
646             difference = buffer_b[i];
647 
648             right = midright - ((difference * interlacing_leftweight) >> interlacing_shift);
649             left = right + difference;
650 
651             if (uncompressed_bytes)
652             {
653                 uint32_t mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8));
654                 left <<= (uncompressed_bytes * 8);
655                 right <<= (uncompressed_bytes * 8);
656 
657                 left |= uncompressed_bytes_buffer_a[i] & mask;
658                 right |= uncompressed_bytes_buffer_b[i] & mask;
659             }
660 
661             ((uint8_t*)buffer_out)[i * numchannels * 3] = (left) & 0xFF;
662             ((uint8_t*)buffer_out)[i * numchannels * 3 + 1] = (left >> 8) & 0xFF;
663             ((uint8_t*)buffer_out)[i * numchannels * 3 + 2] = (left >> 16) & 0xFF;
664 
665             ((uint8_t*)buffer_out)[i * numchannels * 3 + 3] = (right) & 0xFF;
666             ((uint8_t*)buffer_out)[i * numchannels * 3 + 4] = (right >> 8) & 0xFF;
667             ((uint8_t*)buffer_out)[i * numchannels * 3 + 5] = (right >> 16) & 0xFF;
668         }
669 
670         return;
671     }
672 
673     /* otherwise basic interlacing took place */
674     for (i = 0; i < numsamples; i++)
675     {
676         int32_t left, right;
677 
678         left = buffer_a[i];
679         right = buffer_b[i];
680 
681         if (uncompressed_bytes)
682         {
683             uint32_t mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8));
684             left <<= (uncompressed_bytes * 8);
685             right <<= (uncompressed_bytes * 8);
686 
687             left |= uncompressed_bytes_buffer_a[i] & mask;
688             right |= uncompressed_bytes_buffer_b[i] & mask;
689         }
690 
691         ((uint8_t*)buffer_out)[i * numchannels * 3] = (left) & 0xFF;
692         ((uint8_t*)buffer_out)[i * numchannels * 3 + 1] = (left >> 8) & 0xFF;
693         ((uint8_t*)buffer_out)[i * numchannels * 3 + 2] = (left >> 16) & 0xFF;
694 
695         ((uint8_t*)buffer_out)[i * numchannels * 3 + 3] = (right) & 0xFF;
696         ((uint8_t*)buffer_out)[i * numchannels * 3 + 4] = (right >> 8) & 0xFF;
697         ((uint8_t*)buffer_out)[i * numchannels * 3 + 5] = (right >> 16) & 0xFF;
698 
699     }
700 
701 }
702 
decode_frame(alac_file * alac,unsigned char * inbuffer,void * outbuffer,int * outputsize)703 void decode_frame(alac_file *alac,
704                   unsigned char *inbuffer,
705                   void *outbuffer, int *outputsize)
706 {
707     int channels;
708     int32_t outputsamples = alac->setinfo_max_samples_per_frame;
709 
710     /* setup the stream */
711     alac->input_buffer = inbuffer;
712     alac->input_buffer_bitaccumulator = 0;
713 
714     channels = readbits(alac, 3);
715 
716     *outputsize = outputsamples * alac->bytespersample;
717 
718     switch(channels)
719     {
720     case 0: /* 1 channel */
721     {
722         int hassize;
723         int isnotcompressed;
724         int readsamplesize;
725 
726         int uncompressed_bytes;
727         int ricemodifier;
728 
729         /* 2^result = something to do with output waiting.
730          * perhaps matters if we read > 1 frame in a pass?
731          */
732         readbits(alac, 4);
733 
734         readbits(alac, 12); /* unknown, skip 12 bits */
735 
736         hassize = readbits(alac, 1); /* the output sample size is stored soon */
737 
738         uncompressed_bytes = readbits(alac, 2); /* number of bytes in the (compressed) stream that are not compressed */
739 
740         isnotcompressed = readbits(alac, 1); /* whether the frame is compressed */
741 
742         if (hassize)
743         {
744             /* now read the number of samples,
745              * as a 32bit integer */
746             outputsamples = readbits(alac, 32);
747             *outputsize = outputsamples * alac->bytespersample;
748         }
749 
750         readsamplesize = alac->setinfo_sample_size - (uncompressed_bytes * 8);
751 
752         if (!isnotcompressed)
753         { /* so it is compressed */
754             int16_t predictor_coef_table[32];
755             int predictor_coef_num;
756             int prediction_type;
757             int prediction_quantitization;
758             int i;
759 
760             /* skip 16 bits, not sure what they are. seem to be used in
761              * two channel case */
762             readbits(alac, 8);
763             readbits(alac, 8);
764 
765             prediction_type = readbits(alac, 4);
766             prediction_quantitization = readbits(alac, 4);
767 
768             ricemodifier = readbits(alac, 3);
769             predictor_coef_num = readbits(alac, 5);
770 
771             /* read the predictor table */
772             for (i = 0; i < predictor_coef_num; i++)
773             {
774                 predictor_coef_table[i] = (int16_t)readbits(alac, 16);
775             }
776 
777             if (uncompressed_bytes)
778             {
779                 int i;
780                 for (i = 0; i < outputsamples; i++)
781                 {
782                     alac->uncompressed_bytes_buffer_a[i] = readbits(alac, uncompressed_bytes * 8);
783                 }
784             }
785 
786             entropy_rice_decode(alac,
787                                 alac->predicterror_buffer_a,
788                                 outputsamples,
789                                 readsamplesize,
790                                 alac->setinfo_rice_initialhistory,
791                                 alac->setinfo_rice_kmodifier,
792                                 ricemodifier * alac->setinfo_rice_historymult / 4,
793                                 (1 << alac->setinfo_rice_kmodifier) - 1);
794 
795             if (prediction_type == 0)
796             { /* adaptive fir */
797                 predictor_decompress_fir_adapt(alac->predicterror_buffer_a,
798                                                alac->outputsamples_buffer_a,
799                                                outputsamples,
800                                                readsamplesize,
801                                                predictor_coef_table,
802                                                predictor_coef_num,
803                                                prediction_quantitization);
804             }
805             else
806             {
807                 xprintf("FIXME: unhandled predicition type: %i\n", prediction_type);
808                 /* i think the only other prediction type (or perhaps this is just a
809                  * boolean?) runs adaptive fir twice.. like:
810                  * predictor_decompress_fir_adapt(predictor_error, tempout, ...)
811                  * predictor_decompress_fir_adapt(predictor_error, outputsamples ...)
812                  * little strange..
813                  */
814             }
815 
816         }
817         else
818         { /* not compressed, easy case */
819             if (alac->setinfo_sample_size <= 16)
820             {
821                 int i;
822                 for (i = 0; i < outputsamples; i++)
823                 {
824                     int32_t audiobits = readbits(alac, alac->setinfo_sample_size);
825 
826                     audiobits = SIGN_EXTENDED32(audiobits, alac->setinfo_sample_size);
827 
828                     alac->outputsamples_buffer_a[i] = audiobits;
829                 }
830             }
831             else
832             {
833                 int i;
834                 for (i = 0; i < outputsamples; i++)
835                 {
836                     int32_t audiobits;
837 
838                     audiobits = readbits(alac, 16);
839                     /* special case of sign extension..
840                      * as we'll be ORing the low 16bits into this */
841                     audiobits = audiobits << (alac->setinfo_sample_size - 16);
842                     audiobits |= readbits(alac, alac->setinfo_sample_size - 16);
843                     audiobits = SignExtend24(audiobits);
844 
845                     alac->outputsamples_buffer_a[i] = audiobits;
846                 }
847             }
848             uncompressed_bytes = 0; // always 0 for uncompressed
849         }
850 
851         switch(alac->setinfo_sample_size)
852         {
853         case 16:
854         {
855             int i;
856             for (i = 0; i < outputsamples; i++)
857             {
858                 int16_t sample = alac->outputsamples_buffer_a[i];
859                 if (host_bigendian)
860                     _Swap16(sample);
861                 ((int16_t*)outbuffer)[i * alac->numchannels] = sample;
862             }
863             break;
864         }
865         case 24:
866         {
867             int i;
868             for (i = 0; i < outputsamples; i++)
869             {
870                 int32_t sample = alac->outputsamples_buffer_a[i];
871 
872                 if (uncompressed_bytes)
873                 {
874                     uint32_t mask;
875                     sample = sample << (uncompressed_bytes * 8);
876                     mask = ~(0xFFFFFFFF << (uncompressed_bytes * 8));
877                     sample |= alac->uncompressed_bytes_buffer_a[i] & mask;
878                 }
879 
880                 ((uint8_t*)outbuffer)[i * alac->numchannels * 3] = (sample) & 0xFF;
881                 ((uint8_t*)outbuffer)[i * alac->numchannels * 3 + 1] = (sample >> 8) & 0xFF;
882                 ((uint8_t*)outbuffer)[i * alac->numchannels * 3 + 2] = (sample >> 16) & 0xFF;
883             }
884             break;
885         }
886         case 20:
887         case 32:
888             xprintf("FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
889             break;
890         default:
891             break;
892         }
893         break;
894     }
895     case 1: /* 2 channels */
896     {
897         int hassize;
898         int isnotcompressed;
899         int readsamplesize;
900 
901         int uncompressed_bytes;
902 
903         uint8_t interlacing_shift;
904         uint8_t interlacing_leftweight;
905 
906         /* 2^result = something to do with output waiting.
907          * perhaps matters if we read > 1 frame in a pass?
908          */
909         readbits(alac, 4);
910 
911         readbits(alac, 12); /* unknown, skip 12 bits */
912 
913         hassize = readbits(alac, 1); /* the output sample size is stored soon */
914 
915         uncompressed_bytes = readbits(alac, 2); /* the number of bytes in the (compressed) stream that are not compressed */
916 
917         isnotcompressed = readbits(alac, 1); /* whether the frame is compressed */
918 
919         if (hassize)
920         {
921             /* now read the number of samples,
922              * as a 32bit integer */
923             outputsamples = readbits(alac, 32);
924             *outputsize = outputsamples * alac->bytespersample;
925         }
926 
927         readsamplesize = alac->setinfo_sample_size - (uncompressed_bytes * 8) + 1;
928 
929         if (!isnotcompressed)
930         { /* compressed */
931             int16_t predictor_coef_table_a[32];
932             int predictor_coef_num_a;
933             int prediction_type_a;
934             int prediction_quantitization_a;
935             int ricemodifier_a;
936 
937             int16_t predictor_coef_table_b[32];
938             int predictor_coef_num_b;
939             int prediction_type_b;
940             int prediction_quantitization_b;
941             int ricemodifier_b;
942 
943             int i;
944 
945             interlacing_shift = readbits(alac, 8);
946             interlacing_leftweight = readbits(alac, 8);
947 
948             /******** channel 1 ***********/
949             prediction_type_a = readbits(alac, 4);
950             prediction_quantitization_a = readbits(alac, 4);
951 
952             ricemodifier_a = readbits(alac, 3);
953             predictor_coef_num_a = readbits(alac, 5);
954 
955             /* read the predictor table */
956             for (i = 0; i < predictor_coef_num_a; i++)
957             {
958                 predictor_coef_table_a[i] = (int16_t)readbits(alac, 16);
959             }
960 
961             /******** channel 2 *********/
962             prediction_type_b = readbits(alac, 4);
963             prediction_quantitization_b = readbits(alac, 4);
964 
965             ricemodifier_b = readbits(alac, 3);
966             predictor_coef_num_b = readbits(alac, 5);
967 
968             /* read the predictor table */
969             for (i = 0; i < predictor_coef_num_b; i++)
970             {
971                 predictor_coef_table_b[i] = (int16_t)readbits(alac, 16);
972             }
973 
974             /*********************/
975             if (uncompressed_bytes)
976             { /* see mono case */
977                 int i;
978                 for (i = 0; i < outputsamples; i++)
979                 {
980                     alac->uncompressed_bytes_buffer_a[i] = readbits(alac, uncompressed_bytes * 8);
981                     alac->uncompressed_bytes_buffer_b[i] = readbits(alac, uncompressed_bytes * 8);
982                 }
983             }
984 
985             /* channel 1 */
986             entropy_rice_decode(alac,
987                                 alac->predicterror_buffer_a,
988                                 outputsamples,
989                                 readsamplesize,
990                                 alac->setinfo_rice_initialhistory,
991                                 alac->setinfo_rice_kmodifier,
992                                 ricemodifier_a * alac->setinfo_rice_historymult / 4,
993                                 (1 << alac->setinfo_rice_kmodifier) - 1);
994 
995             if (prediction_type_a == 0)
996             { /* adaptive fir */
997                 predictor_decompress_fir_adapt(alac->predicterror_buffer_a,
998                                                alac->outputsamples_buffer_a,
999                                                outputsamples,
1000                                                readsamplesize,
1001                                                predictor_coef_table_a,
1002                                                predictor_coef_num_a,
1003                                                prediction_quantitization_a);
1004             }
1005             else
1006             { /* see mono case */
1007                 xprintf("FIXME: unhandled predicition type: %i\n", prediction_type_a);
1008             }
1009 
1010             /* channel 2 */
1011             entropy_rice_decode(alac,
1012                                 alac->predicterror_buffer_b,
1013                                 outputsamples,
1014                                 readsamplesize,
1015                                 alac->setinfo_rice_initialhistory,
1016                                 alac->setinfo_rice_kmodifier,
1017                                 ricemodifier_b * alac->setinfo_rice_historymult / 4,
1018                                 (1 << alac->setinfo_rice_kmodifier) - 1);
1019 
1020             if (prediction_type_b == 0)
1021             { /* adaptive fir */
1022                 predictor_decompress_fir_adapt(alac->predicterror_buffer_b,
1023                                                alac->outputsamples_buffer_b,
1024                                                outputsamples,
1025                                                readsamplesize,
1026                                                predictor_coef_table_b,
1027                                                predictor_coef_num_b,
1028                                                prediction_quantitization_b);
1029             }
1030             else
1031             {
1032                 xprintf("FIXME: unhandled predicition type: %i\n", prediction_type_b);
1033             }
1034         }
1035         else
1036         { /* not compressed, easy case */
1037             if (alac->setinfo_sample_size <= 16)
1038             {
1039                 int i;
1040                 for (i = 0; i < outputsamples; i++)
1041                 {
1042                     int32_t audiobits_a, audiobits_b;
1043 
1044                     audiobits_a = readbits(alac, alac->setinfo_sample_size);
1045                     audiobits_b = readbits(alac, alac->setinfo_sample_size);
1046 
1047                     audiobits_a = SIGN_EXTENDED32(audiobits_a, alac->setinfo_sample_size);
1048                     audiobits_b = SIGN_EXTENDED32(audiobits_b, alac->setinfo_sample_size);
1049 
1050                     alac->outputsamples_buffer_a[i] = audiobits_a;
1051                     alac->outputsamples_buffer_b[i] = audiobits_b;
1052                 }
1053             }
1054             else
1055             {
1056                 int i;
1057                 for (i = 0; i < outputsamples; i++)
1058                 {
1059                     int32_t audiobits_a, audiobits_b;
1060 
1061                     audiobits_a = readbits(alac, 16);
1062                     audiobits_a = audiobits_a << (alac->setinfo_sample_size - 16);
1063                     audiobits_a |= readbits(alac, alac->setinfo_sample_size - 16);
1064                     audiobits_a = SignExtend24(audiobits_a);
1065 
1066                     audiobits_b = readbits(alac, 16);
1067                     audiobits_b = audiobits_b << (alac->setinfo_sample_size - 16);
1068                     audiobits_b |= readbits(alac, alac->setinfo_sample_size - 16);
1069                     audiobits_b = SignExtend24(audiobits_b);
1070 
1071                     alac->outputsamples_buffer_a[i] = audiobits_a;
1072                     alac->outputsamples_buffer_b[i] = audiobits_b;
1073                 }
1074             }
1075             uncompressed_bytes = 0; // always 0 for uncompressed
1076             interlacing_shift = 0;
1077             interlacing_leftweight = 0;
1078         }
1079 
1080         switch(alac->setinfo_sample_size)
1081         {
1082         case 16:
1083         {
1084             deinterlace_16(alac->outputsamples_buffer_a,
1085                            alac->outputsamples_buffer_b,
1086                            (int16_t*)outbuffer,
1087                            alac->numchannels,
1088                            outputsamples,
1089                            interlacing_shift,
1090                            interlacing_leftweight);
1091             break;
1092         }
1093         case 24:
1094         {
1095             deinterlace_24(alac->outputsamples_buffer_a,
1096                            alac->outputsamples_buffer_b,
1097                            uncompressed_bytes,
1098                            alac->uncompressed_bytes_buffer_a,
1099                            alac->uncompressed_bytes_buffer_b,
1100                            (int16_t*)outbuffer,
1101                            alac->numchannels,
1102                            outputsamples,
1103                            interlacing_shift,
1104                            interlacing_leftweight);
1105             break;
1106         }
1107         case 20:
1108         case 32:
1109             xprintf("FIXME: unimplemented sample size %i\n", alac->setinfo_sample_size);
1110             break;
1111         default:
1112             break;
1113         }
1114 
1115         break;
1116     }
1117     }
1118 }
1119 
create_alac(int samplesize,int numchannels)1120 alac_file *create_alac(int samplesize, int numchannels)
1121 {
1122     alac_file *newfile = malloc(sizeof(alac_file));
1123 
1124     newfile->samplesize = samplesize;
1125     newfile->numchannels = numchannels;
1126     newfile->bytespersample = (samplesize / 8) * numchannels;
1127 
1128     return newfile;
1129 }
1130 
delete_alac(alac_file * f)1131 void delete_alac(alac_file* f)
1132 {
1133     free(f);
1134 }
1135