Git init
[external/libsndfile.git] / src / ms_adpcm.c
1 /*
2 ** Copyright (C) 1999-2009 Erik de Castro Lopo <erikd@mega-nerd.com>
3 **
4 ** This program is free software; you can redistribute it and/or modify
5 ** it under the terms of the GNU Lesser General Public License as published by
6 ** the Free Software Foundation; either version 2.1 of the License, or
7 ** (at your option) any later version.
8 **
9 ** This program is distributed in the hope that it will be useful,
10 ** but WITHOUT ANY WARRANTY; without even the implied warranty of
11 ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 ** GNU Lesser General Public License for more details.
13 **
14 ** You should have received a copy of the GNU Lesser General Public License
15 ** along with this program; if not, write to the Free Software
16 ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
17 */
18
19 #include        "sfconfig.h"
20
21 #include        <stdio.h>
22 #include        <stdlib.h>
23 #include        <string.h>
24 #include        <math.h>
25
26 #include        "sndfile.h"
27 #include        "sfendian.h"
28 #include        "common.h"
29 #include        "wav_w64.h"
30
31 /* These required here because we write the header in this file. */
32
33 #define RIFF_MARKER     (MAKE_MARKER ('R', 'I', 'F', 'F'))
34 #define WAVE_MARKER     (MAKE_MARKER ('W', 'A', 'V', 'E'))
35 #define fmt_MARKER      (MAKE_MARKER ('f', 'm', 't', ' '))
36 #define fact_MARKER     (MAKE_MARKER ('f', 'a', 'c', 't'))
37 #define data_MARKER     (MAKE_MARKER ('d', 'a', 't', 'a'))
38
39 #define WAVE_FORMAT_MS_ADPCM    0x0002
40
41 typedef struct
42 {       int                             channels, blocksize, samplesperblock, blocks, dataremaining ;
43         int                             blockcount ;
44         sf_count_t              samplecount ;
45         short                   *samples ;
46         unsigned char   *block ;
47 #if HAVE_FLEXIBLE_ARRAY
48         short                   dummydata [] ; /* ISO C99 struct flexible array. */
49 #else
50         short                   dummydata [0] ; /* This is a hack an might not work. */
51 #endif
52 } MSADPCM_PRIVATE ;
53
54 /*============================================================================================
55 ** MS ADPCM static data and functions.
56 */
57
58 static int AdaptationTable [] =
59 {       230, 230, 230, 230, 307, 409, 512, 614,
60         768, 614, 512, 409, 307, 230, 230, 230
61 } ;
62
63 /* TODO : The first 7 coef's are are always hardcode and must
64    appear in the actual WAVE file.  They should be read in
65    in case a sound program added extras to the list. */
66
67 static int AdaptCoeff1 [MSADPCM_ADAPT_COEFF_COUNT] =
68 {       256, 512, 0, 192, 240, 460, 392
69 } ;
70
71 static int AdaptCoeff2 [MSADPCM_ADAPT_COEFF_COUNT] =
72 {       0, -256, 0, 64, 0, -208, -232
73 } ;
74
75 /*============================================================================================
76 **      MS ADPCM Block Layout.
77 **      ======================
78 **      Block is usually 256, 512 or 1024 bytes depending on sample rate.
79 **      For a mono file, the block is laid out as follows:
80 **              byte    purpose
81 **              0               block predictor [0..6]
82 **              1,2             initial idelta (positive)
83 **              3,4             sample 1
84 **              5,6             sample 0
85 **              7..n    packed bytecodes
86 **
87 **      For a stereo file, the block is laid out as follows:
88 **              byte    purpose
89 **              0               block predictor [0..6] for left channel
90 **              1               block predictor [0..6] for right channel
91 **              2,3             initial idelta (positive) for left channel
92 **              4,5             initial idelta (positive) for right channel
93 **              6,7             sample 1 for left channel
94 **              8,9             sample 1 for right channel
95 **              10,11   sample 0 for left channel
96 **              12,13   sample 0 for right channel
97 **              14..n   packed bytecodes
98 */
99
100 /*============================================================================================
101 ** Static functions.
102 */
103
104 static  int     msadpcm_decode_block    (SF_PRIVATE *psf, MSADPCM_PRIVATE *pms) ;
105 static sf_count_t msadpcm_read_block    (SF_PRIVATE *psf, MSADPCM_PRIVATE *pms, short *ptr, int len) ;
106
107 static  int     msadpcm_encode_block    (SF_PRIVATE *psf, MSADPCM_PRIVATE *pms) ;
108 static sf_count_t msadpcm_write_block   (SF_PRIVATE *psf, MSADPCM_PRIVATE *pms, const short *ptr, int len) ;
109
110 static sf_count_t       msadpcm_read_s  (SF_PRIVATE *psf, short *ptr, sf_count_t len) ;
111 static sf_count_t       msadpcm_read_i  (SF_PRIVATE *psf, int *ptr, sf_count_t len) ;
112 static sf_count_t       msadpcm_read_f  (SF_PRIVATE *psf, float *ptr, sf_count_t len) ;
113 static sf_count_t       msadpcm_read_d  (SF_PRIVATE *psf, double *ptr, sf_count_t len) ;
114
115 static sf_count_t       msadpcm_write_s (SF_PRIVATE *psf, const short *ptr, sf_count_t len) ;
116 static sf_count_t       msadpcm_write_i (SF_PRIVATE *psf, const int *ptr, sf_count_t len) ;
117 static sf_count_t       msadpcm_write_f (SF_PRIVATE *psf, const float *ptr, sf_count_t len) ;
118 static sf_count_t       msadpcm_write_d (SF_PRIVATE *psf, const double *ptr, sf_count_t len) ;
119
120 static sf_count_t msadpcm_seek  (SF_PRIVATE *psf, int mode, sf_count_t offset) ;
121 static  int     msadpcm_close   (SF_PRIVATE *psf) ;
122
123 static  void    choose_predictor (unsigned int channels, short *data, int *bpred, int *idelta) ;
124
125 /*============================================================================================
126 ** MS ADPCM Read Functions.
127 */
128
129 int
130 wav_w64_msadpcm_init    (SF_PRIVATE *psf, int blockalign, int samplesperblock)
131 {       MSADPCM_PRIVATE *pms ;
132         unsigned int    pmssize ;
133         int                             count ;
134
135         if (psf->codec_data != NULL)
136         {       psf_log_printf (psf, "*** psf->codec_data is not NULL.\n") ;
137                 return SFE_INTERNAL ;
138                 } ;
139
140         if (psf->file.mode == SFM_WRITE)
141                 samplesperblock = 2 + 2 * (blockalign - 7 * psf->sf.channels) / psf->sf.channels ;
142
143         pmssize = sizeof (MSADPCM_PRIVATE) + blockalign + 3 * psf->sf.channels * samplesperblock ;
144
145         if (! (psf->codec_data = malloc (pmssize)))
146                 return SFE_MALLOC_FAILED ;
147         pms = (MSADPCM_PRIVATE*) psf->codec_data ;
148         memset (pms, 0, pmssize) ;
149
150         pms->samples    = pms->dummydata ;
151         pms->block              = (unsigned char*) (pms->dummydata + psf->sf.channels * samplesperblock) ;
152
153         pms->channels   = psf->sf.channels ;
154         pms->blocksize  = blockalign ;
155         pms->samplesperblock = samplesperblock ;
156
157         if (pms->blocksize == 0)
158         {       psf_log_printf (psf, "*** Error : pms->blocksize should not be zero.\n") ;
159                 return SFE_INTERNAL ;
160                 } ;
161
162         if (psf->file.mode == SFM_READ)
163         {       pms->dataremaining       = psf->datalength ;
164
165                 if (psf->datalength % pms->blocksize)
166                         pms->blocks = psf->datalength / pms->blocksize + 1 ;
167                 else
168                         pms->blocks = psf->datalength / pms->blocksize ;
169
170                 count = 2 * (pms->blocksize - 6 * pms->channels) / pms->channels ;
171                 if (pms->samplesperblock != count)
172                 {       psf_log_printf (psf, "*** Error : samplesperblock should be %d.\n", count) ;
173                         return SFE_INTERNAL ;
174                         } ;
175
176                 psf->sf.frames = (psf->datalength / pms->blocksize) * pms->samplesperblock ;
177
178                 psf_log_printf (psf, " bpred   idelta\n") ;
179
180                 msadpcm_decode_block (psf, pms) ;
181
182                 psf->read_short         = msadpcm_read_s ;
183                 psf->read_int           = msadpcm_read_i ;
184                 psf->read_float         = msadpcm_read_f ;
185                 psf->read_double        = msadpcm_read_d ;
186                 } ;
187
188         if (psf->file.mode == SFM_WRITE)
189         {       pms->samples = pms->dummydata ;
190
191                 pms->samplecount = 0 ;
192
193                 psf->write_short        = msadpcm_write_s ;
194                 psf->write_int          = msadpcm_write_i ;
195                 psf->write_float        = msadpcm_write_f ;
196                 psf->write_double       = msadpcm_write_d ;
197                 } ;
198
199         psf->codec_close = msadpcm_close ;
200         psf->seek = msadpcm_seek ;
201
202         return 0 ;
203 } /* wav_w64_msadpcm_init */
204
205 static int
206 msadpcm_decode_block    (SF_PRIVATE *psf, MSADPCM_PRIVATE *pms)
207 {       int             chan, k, blockindx, sampleindx ;
208         short   bytecode, bpred [2], chan_idelta [2] ;
209
210     int predict ;
211     int current ;
212     int idelta ;
213
214         pms->blockcount ++ ;
215         pms->samplecount = 0 ;
216
217         if (pms->blockcount > pms->blocks)
218         {       memset (pms->samples, 0, pms->samplesperblock * pms->channels) ;
219                 return 1 ;
220                 } ;
221
222         if ((k = psf_fread (pms->block, 1, pms->blocksize, psf)) != pms->blocksize)
223                 psf_log_printf (psf, "*** Warning : short read (%d != %d).\n", k, pms->blocksize) ;
224
225         /* Read and check the block header. */
226
227         if (pms->channels == 1)
228         {       bpred [0] = pms->block [0] ;
229
230                 if (bpred [0] >= 7)
231                         psf_log_printf (psf, "MS ADPCM synchronisation error (%d).\n", bpred [0]) ;
232
233                 chan_idelta [0] = pms->block [1] | (pms->block [2] << 8) ;
234                 chan_idelta [1] = 0 ;
235
236                 psf_log_printf (psf, "(%d) (%d)\n", bpred [0], chan_idelta [0]) ;
237
238                 pms->samples [1] = pms->block [3] | (pms->block [4] << 8) ;
239                 pms->samples [0] = pms->block [5] | (pms->block [6] << 8) ;
240                 blockindx = 7 ;
241                 }
242         else
243         {       bpred [0] = pms->block [0] ;
244                 bpred [1] = pms->block [1] ;
245
246                 if (bpred [0] >= 7 || bpred [1] >= 7)
247                         psf_log_printf (psf, "MS ADPCM synchronisation error (%d %d).\n", bpred [0], bpred [1]) ;
248
249                 chan_idelta [0] = pms->block [2] | (pms->block [3] << 8) ;
250                 chan_idelta [1] = pms->block [4] | (pms->block [5] << 8) ;
251
252                 psf_log_printf (psf, "(%d, %d) (%d, %d)\n", bpred [0], bpred [1], chan_idelta [0], chan_idelta [1]) ;
253
254                 pms->samples [2] = pms->block [6] | (pms->block [7] << 8) ;
255                 pms->samples [3] = pms->block [8] | (pms->block [9] << 8) ;
256
257                 pms->samples [0] = pms->block [10] | (pms->block [11] << 8) ;
258                 pms->samples [1] = pms->block [12] | (pms->block [13] << 8) ;
259
260                 blockindx = 14 ;
261                 } ;
262
263         /*--------------------------------------------------------
264         This was left over from a time when calculations were done
265         as ints rather than shorts. Keep this around as a reminder
266         in case I ever find a file which decodes incorrectly.
267
268     if (chan_idelta [0] & 0x8000)
269                 chan_idelta [0] -= 0x10000 ;
270     if (chan_idelta [1] & 0x8000)
271                 chan_idelta [1] -= 0x10000 ;
272         --------------------------------------------------------*/
273
274         /* Pull apart the packed 4 bit samples and store them in their
275         ** correct sample positions.
276         */
277
278         sampleindx = 2 * pms->channels ;
279         while (blockindx < pms->blocksize)
280         {       bytecode = pms->block [blockindx++] ;
281                 pms->samples [sampleindx++] = (bytecode >> 4) & 0x0F ;
282                 pms->samples [sampleindx++] = bytecode & 0x0F ;
283                 } ;
284
285         /* Decode the encoded 4 bit samples. */
286
287         for (k = 2 * pms->channels ; k < (pms->samplesperblock * pms->channels) ; k ++)
288         {       chan = (pms->channels > 1) ? (k % 2) : 0 ;
289
290                 bytecode = pms->samples [k] & 0xF ;
291
292                 /* Compute next Adaptive Scale Factor (ASF) */
293                 idelta = chan_idelta [chan] ;
294                 chan_idelta [chan] = (AdaptationTable [bytecode] * idelta) >> 8 ;       /* => / 256 => FIXED_POINT_ADAPTATION_BASE == 256 */
295                 if (chan_idelta [chan] < 16)
296                         chan_idelta [chan] = 16 ;
297                 if (bytecode & 0x8)
298                         bytecode -= 0x10 ;
299
300         predict = ((pms->samples [k - pms->channels] * AdaptCoeff1 [bpred [chan]])
301                                         + (pms->samples [k - 2 * pms->channels] * AdaptCoeff2 [bpred [chan]])) >> 8 ; /* => / 256 => FIXED_POINT_COEFF_BASE == 256 */
302                 current = (bytecode * idelta) + predict ;
303
304                 if (current > 32767)
305                         current = 32767 ;
306                 else if (current < -32768)
307                         current = -32768 ;
308
309                 pms->samples [k] = current ;
310                 } ;
311
312         return 1 ;
313 } /* msadpcm_decode_block */
314
315 static sf_count_t
316 msadpcm_read_block      (SF_PRIVATE *psf, MSADPCM_PRIVATE *pms, short *ptr, int len)
317 {       int     count, total = 0, indx = 0 ;
318
319         while (indx < len)
320         {       if (pms->blockcount >= pms->blocks && pms->samplecount >= pms->samplesperblock)
321                 {       memset (&(ptr [indx]), 0, (size_t) ((len - indx) * sizeof (short))) ;
322                         return total ;
323                         } ;
324
325                 if (pms->samplecount >= pms->samplesperblock)
326                         msadpcm_decode_block (psf, pms) ;
327
328                 count = (pms->samplesperblock - pms->samplecount) * pms->channels ;
329                 count = (len - indx > count) ? count : len - indx ;
330
331                 memcpy (&(ptr [indx]), &(pms->samples [pms->samplecount * pms->channels]), count * sizeof (short)) ;
332                 indx += count ;
333                 pms->samplecount += count / pms->channels ;
334                 total = indx ;
335                 } ;
336
337         return total ;
338 } /* msadpcm_read_block */
339
340 static sf_count_t
341 msadpcm_read_s  (SF_PRIVATE *psf, short *ptr, sf_count_t len)
342 {       MSADPCM_PRIVATE         *pms ;
343         int                     readcount, count ;
344         sf_count_t      total = 0 ;
345
346         if (! psf->codec_data)
347                 return 0 ;
348         pms = (MSADPCM_PRIVATE*) psf->codec_data ;
349
350         while (len > 0)
351         {       readcount = (len > 0x10000000) ? 0x10000000 : (int) len ;
352
353                 count = msadpcm_read_block (psf, pms, ptr, readcount) ;
354
355                 total += count ;
356                 len -= count ;
357                 if (count != readcount)
358                         break ;
359                 } ;
360
361         return total ;
362 } /* msadpcm_read_s */
363
364 static sf_count_t
365 msadpcm_read_i  (SF_PRIVATE *psf, int *ptr, sf_count_t len)
366 {       MSADPCM_PRIVATE *pms ;
367         short           *sptr ;
368         int                     k, bufferlen, readcount = 0, count ;
369         sf_count_t      total = 0 ;
370
371         if (! psf->codec_data)
372                 return 0 ;
373         pms = (MSADPCM_PRIVATE*) psf->codec_data ;
374
375         sptr = psf->u.sbuf ;
376         bufferlen = ARRAY_LEN (psf->u.sbuf) ;
377         while (len > 0)
378         {       readcount = (len >= bufferlen) ? bufferlen : len ;
379                 count = msadpcm_read_block (psf, pms, sptr, readcount) ;
380                 for (k = 0 ; k < readcount ; k++)
381                         ptr [total + k] = sptr [k] << 16 ;
382                 total += count ;
383                 len -= readcount ;
384                 if (count != readcount)
385                         break ;
386                 } ;
387         return total ;
388 } /* msadpcm_read_i */
389
390 static sf_count_t
391 msadpcm_read_f  (SF_PRIVATE *psf, float *ptr, sf_count_t len)
392 {       MSADPCM_PRIVATE *pms ;
393         short           *sptr ;
394         int                     k, bufferlen, readcount = 0, count ;
395         sf_count_t      total = 0 ;
396         float           normfact ;
397
398         if (! psf->codec_data)
399                 return 0 ;
400         pms = (MSADPCM_PRIVATE*) psf->codec_data ;
401
402         normfact = (psf->norm_float == SF_TRUE) ? 1.0 / ((float) 0x8000) : 1.0 ;
403         sptr = psf->u.sbuf ;
404         bufferlen = ARRAY_LEN (psf->u.sbuf) ;
405         while (len > 0)
406         {       readcount = (len >= bufferlen) ? bufferlen : len ;
407                 count = msadpcm_read_block (psf, pms, sptr, readcount) ;
408                 for (k = 0 ; k < readcount ; k++)
409                         ptr [total + k] = normfact * (float) (sptr [k]) ;
410                 total += count ;
411                 len -= readcount ;
412                 if (count != readcount)
413                         break ;
414                 } ;
415         return total ;
416 } /* msadpcm_read_f */
417
418 static sf_count_t
419 msadpcm_read_d  (SF_PRIVATE *psf, double *ptr, sf_count_t len)
420 {       MSADPCM_PRIVATE *pms ;
421         short           *sptr ;
422         int                     k, bufferlen, readcount = 0, count ;
423         sf_count_t      total = 0 ;
424         double          normfact ;
425
426         normfact = (psf->norm_double == SF_TRUE) ? 1.0 / ((double) 0x8000) : 1.0 ;
427
428         if (! psf->codec_data)
429                 return 0 ;
430         pms = (MSADPCM_PRIVATE*) psf->codec_data ;
431
432         sptr = psf->u.sbuf ;
433         bufferlen = ARRAY_LEN (psf->u.sbuf) ;
434         while (len > 0)
435         {       readcount = (len >= bufferlen) ? bufferlen : len ;
436                 count = msadpcm_read_block (psf, pms, sptr, readcount) ;
437                 for (k = 0 ; k < readcount ; k++)
438                         ptr [total + k] = normfact * (double) (sptr [k]) ;
439                 total += count ;
440                 len -= readcount ;
441                 if (count != readcount)
442                         break ;
443                 } ;
444         return total ;
445 } /* msadpcm_read_d */
446
447 static sf_count_t
448 msadpcm_seek    (SF_PRIVATE *psf, int mode, sf_count_t offset)
449 {       MSADPCM_PRIVATE *pms ;
450         int                     newblock, newsample ;
451
452         if (! psf->codec_data)
453                 return 0 ;
454         pms = (MSADPCM_PRIVATE*) psf->codec_data ;
455
456         if (psf->datalength < 0 || psf->dataoffset < 0)
457         {       psf->error = SFE_BAD_SEEK ;
458                 return  PSF_SEEK_ERROR ;
459                 } ;
460
461         if (offset == 0)
462         {       psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
463                 pms->blockcount = 0 ;
464                 msadpcm_decode_block (psf, pms) ;
465                 pms->samplecount = 0 ;
466                 return 0 ;
467                 } ;
468
469         if (offset < 0 || offset > pms->blocks * pms->samplesperblock)
470         {       psf->error = SFE_BAD_SEEK ;
471                 return  PSF_SEEK_ERROR ;
472                 } ;
473
474         newblock        = offset / pms->samplesperblock ;
475         newsample       = offset % pms->samplesperblock ;
476
477         if (mode == SFM_READ)
478         {       psf_fseek (psf, psf->dataoffset + newblock * pms->blocksize, SEEK_SET) ;
479                 pms->blockcount = newblock ;
480                 msadpcm_decode_block (psf, pms) ;
481                 pms->samplecount = newsample ;
482                 }
483         else
484         {       /* What to do about write??? */
485                 psf->error = SFE_BAD_SEEK ;
486                 return  PSF_SEEK_ERROR ;
487                 } ;
488
489         return newblock * pms->samplesperblock + newsample ;
490 } /* msadpcm_seek */
491
492 /*==========================================================================================
493 ** MS ADPCM Write Functions.
494 */
495
496 void
497 msadpcm_write_adapt_coeffs      (SF_PRIVATE *psf)
498 {       int k ;
499
500         for (k = 0 ; k < MSADPCM_ADAPT_COEFF_COUNT ; k++)
501                 psf_binheader_writef (psf, "22", AdaptCoeff1 [k], AdaptCoeff2 [k]) ;
502 } /* msadpcm_write_adapt_coeffs */
503
504 /*==========================================================================================
505 */
506
507 static int
508 msadpcm_encode_block    (SF_PRIVATE *psf, MSADPCM_PRIVATE *pms)
509 {       unsigned int    blockindx ;
510         unsigned char   byte ;
511         int                             chan, k, predict, bpred [2], idelta [2], errordelta, newsamp ;
512
513         choose_predictor (pms->channels, pms->samples, bpred, idelta) ;
514
515         /* Write the block header. */
516
517         if (pms->channels == 1)
518         {       pms->block [0]  = bpred [0] ;
519                 pms->block [1]  = idelta [0] & 0xFF ;
520                 pms->block [2]  = idelta [0] >> 8 ;
521                 pms->block [3]  = pms->samples [1] & 0xFF ;
522                 pms->block [4]  = pms->samples [1] >> 8 ;
523                 pms->block [5]  = pms->samples [0] & 0xFF ;
524                 pms->block [6]  = pms->samples [0] >> 8 ;
525
526                 blockindx = 7 ;
527                 byte = 0 ;
528
529                 /* Encode the samples as 4 bit. */
530
531                 for (k = 2 ; k < pms->samplesperblock ; k++)
532                 {       predict = (pms->samples [k-1] * AdaptCoeff1 [bpred [0]] + pms->samples [k-2] * AdaptCoeff2 [bpred [0]]) >> 8 ;
533                         errordelta = (pms->samples [k] - predict) / idelta [0] ;
534                         if (errordelta < -8)
535                                 errordelta = -8 ;
536                         else if (errordelta > 7)
537                                 errordelta = 7 ;
538                         newsamp = predict + (idelta [0] * errordelta) ;
539                         if (newsamp > 32767)
540                                 newsamp = 32767 ;
541                         else if (newsamp < -32768)
542                                 newsamp = -32768 ;
543                         if (errordelta < 0)
544                                 errordelta += 0x10 ;
545
546                         byte = (byte << 4) | (errordelta & 0xF) ;
547                         if (k % 2)
548                         {       pms->block [blockindx++] = byte ;
549                                 byte = 0 ;
550                                 } ;
551
552                         idelta [0] = (idelta [0] * AdaptationTable [errordelta]) >> 8 ;
553                         if (idelta [0] < 16)
554                                 idelta [0] = 16 ;
555                         pms->samples [k] = newsamp ;
556                         } ;
557                 }
558         else
559         {       /* Stereo file. */
560                 pms->block [0]  = bpred [0] ;
561                 pms->block [1]  = bpred [1] ;
562
563                 pms->block [2]  = idelta [0] & 0xFF ;
564                 pms->block [3]  = idelta [0] >> 8 ;
565                 pms->block [4]  = idelta [1] & 0xFF ;
566                 pms->block [5]  = idelta [1] >> 8 ;
567
568                 pms->block [6]  = pms->samples [2] & 0xFF ;
569                 pms->block [7]  = pms->samples [2] >> 8 ;
570                 pms->block [8]  = pms->samples [3] & 0xFF ;
571                 pms->block [9]  = pms->samples [3] >> 8 ;
572
573                 pms->block [10] = pms->samples [0] & 0xFF ;
574                 pms->block [11] = pms->samples [0] >> 8 ;
575                 pms->block [12] = pms->samples [1] & 0xFF ;
576                 pms->block [13] = pms->samples [1] >> 8 ;
577
578                 blockindx = 14 ;
579                 byte = 0 ;
580                 chan = 1 ;
581
582                 for (k = 4 ; k < 2 * pms->samplesperblock ; k++)
583                 {       chan = k & 1 ;
584
585                         predict = (pms->samples [k-2] * AdaptCoeff1 [bpred [chan]] + pms->samples [k-4] * AdaptCoeff2 [bpred [chan]]) >> 8 ;
586                         errordelta = (pms->samples [k] - predict) / idelta [chan] ;
587
588
589                         if (errordelta < -8)
590                                 errordelta = -8 ;
591                         else if (errordelta > 7)
592                                 errordelta = 7 ;
593                         newsamp = predict + (idelta [chan] * errordelta) ;
594                         if (newsamp > 32767)
595                                 newsamp = 32767 ;
596                         else if (newsamp < -32768)
597                                 newsamp = -32768 ;
598                         if (errordelta < 0)
599                                 errordelta += 0x10 ;
600
601                         byte = (byte << 4) | (errordelta & 0xF) ;
602
603                         if (chan)
604                         {       pms->block [blockindx++] = byte ;
605                                 byte = 0 ;
606                                 } ;
607
608                         idelta [chan] = (idelta [chan] * AdaptationTable [errordelta]) >> 8 ;
609                         if (idelta [chan] < 16)
610                                 idelta [chan] = 16 ;
611                         pms->samples [k] = newsamp ;
612                         } ;
613                 } ;
614
615         /* Write the block to disk. */
616
617         if ((k = psf_fwrite (pms->block, 1, pms->blocksize, psf)) != pms->blocksize)
618                 psf_log_printf (psf, "*** Warning : short write (%d != %d).\n", k, pms->blocksize) ;
619
620         memset (pms->samples, 0, pms->samplesperblock * sizeof (short)) ;
621
622         pms->blockcount ++ ;
623         pms->samplecount = 0 ;
624
625         return 1 ;
626 } /* msadpcm_encode_block */
627
628 static sf_count_t
629 msadpcm_write_block     (SF_PRIVATE *psf, MSADPCM_PRIVATE *pms, const short *ptr, int len)
630 {       int             count, total = 0, indx = 0 ;
631
632         while (indx < len)
633         {       count = (pms->samplesperblock - pms->samplecount) * pms->channels ;
634
635                 if (count > len - indx)
636                         count = len - indx ;
637
638                 memcpy (&(pms->samples [pms->samplecount * pms->channels]), &(ptr [total]), count * sizeof (short)) ;
639                 indx += count ;
640                 pms->samplecount += count / pms->channels ;
641                 total = indx ;
642
643                 if (pms->samplecount >= pms->samplesperblock)
644                         msadpcm_encode_block (psf, pms) ;
645                 } ;
646
647         return total ;
648 } /* msadpcm_write_block */
649
650 static sf_count_t
651 msadpcm_write_s (SF_PRIVATE *psf, const short *ptr, sf_count_t len)
652 {       MSADPCM_PRIVATE *pms ;
653         int                     writecount, count ;
654         sf_count_t      total = 0 ;
655
656         if (! psf->codec_data)
657                 return 0 ;
658         pms = (MSADPCM_PRIVATE*) psf->codec_data ;
659
660         while (len > 0)
661         {       writecount = (len > 0x10000000) ? 0x10000000 : (int) len ;
662
663                 count = msadpcm_write_block (psf, pms, ptr, writecount) ;
664
665                 total += count ;
666                 len -= count ;
667                 if (count != writecount)
668                         break ;
669                 } ;
670
671         return total ;
672 } /* msadpcm_write_s */
673
674 static sf_count_t
675 msadpcm_write_i (SF_PRIVATE *psf, const int *ptr, sf_count_t len)
676 {       MSADPCM_PRIVATE *pms ;
677         short           *sptr ;
678         int                     k, bufferlen, writecount, count ;
679         sf_count_t      total = 0 ;
680
681         if (! psf->codec_data)
682                 return 0 ;
683         pms = (MSADPCM_PRIVATE*) psf->codec_data ;
684
685         sptr = psf->u.sbuf ;
686         bufferlen = ARRAY_LEN (psf->u.sbuf) ;
687         while (len > 0)
688         {       writecount = (len >= bufferlen) ? bufferlen : len ;
689                 for (k = 0 ; k < writecount ; k++)
690                         sptr [k] = ptr [total + k] >> 16 ;
691                 count = msadpcm_write_block (psf, pms, sptr, writecount) ;
692                 total += count ;
693                 len -= writecount ;
694                 if (count != writecount)
695                         break ;
696                 } ;
697         return total ;
698 } /* msadpcm_write_i */
699
700 static sf_count_t
701 msadpcm_write_f (SF_PRIVATE *psf, const float *ptr, sf_count_t len)
702 {       MSADPCM_PRIVATE *pms ;
703         short           *sptr ;
704         int                     k, bufferlen, writecount, count ;
705         sf_count_t      total = 0 ;
706         float           normfact ;
707
708         if (! psf->codec_data)
709                 return 0 ;
710         pms = (MSADPCM_PRIVATE*) psf->codec_data ;
711
712         normfact = (psf->norm_float == SF_TRUE) ? (1.0 * 0x7FFF) : 1.0 ;
713
714         sptr = psf->u.sbuf ;
715         bufferlen = ARRAY_LEN (psf->u.sbuf) ;
716         while (len > 0)
717         {       writecount = (len >= bufferlen) ? bufferlen : len ;
718                 for (k = 0 ; k < writecount ; k++)
719                         sptr [k] = lrintf (normfact * ptr [total + k]) ;
720                 count = msadpcm_write_block (psf, pms, sptr, writecount) ;
721                 total += count ;
722                 len -= writecount ;
723                 if (count != writecount)
724                         break ;
725                 } ;
726         return total ;
727 } /* msadpcm_write_f */
728
729 static sf_count_t
730 msadpcm_write_d (SF_PRIVATE *psf, const double *ptr, sf_count_t len)
731 {       MSADPCM_PRIVATE *pms ;
732         short           *sptr ;
733         int                     k, bufferlen, writecount, count ;
734         sf_count_t      total = 0 ;
735         double          normfact ;
736
737         normfact = (psf->norm_double == SF_TRUE) ? (1.0 * 0x7FFF) : 1.0 ;
738
739         if (! psf->codec_data)
740                 return 0 ;
741         pms = (MSADPCM_PRIVATE*) psf->codec_data ;
742
743         sptr = psf->u.sbuf ;
744         bufferlen = ARRAY_LEN (psf->u.sbuf) ;
745         while (len > 0)
746         {       writecount = (len >= bufferlen) ? bufferlen : len ;
747                 for (k = 0 ; k < writecount ; k++)
748                         sptr [k] = lrint (normfact * ptr [total + k]) ;
749                 count = msadpcm_write_block (psf, pms, sptr, writecount) ;
750                 total += count ;
751                 len -= writecount ;
752                 if (count != writecount)
753                         break ;
754                 } ;
755         return total ;
756 } /* msadpcm_write_d */
757
758 /*========================================================================================
759 */
760
761 static int
762 msadpcm_close   (SF_PRIVATE *psf)
763 {       MSADPCM_PRIVATE *pms ;
764
765         pms = (MSADPCM_PRIVATE*) psf->codec_data ;
766
767         if (psf->file.mode == SFM_WRITE)
768         {       /*  Now we know static int for certain the length of the file we can
769                 **  re-write the header.
770                 */
771
772                 if (pms->samplecount && pms->samplecount < pms->samplesperblock)
773                         msadpcm_encode_block (psf, pms) ;
774                 } ;
775
776         return 0 ;
777 } /* msadpcm_close */
778
779 /*========================================================================================
780 ** Static functions.
781 */
782
783 /*----------------------------------------------------------------------------------------
784 **      Choosing the block predictor.
785 **      Each block requires a predictor and an idelta for each channel.
786 **      The predictor is in the range [0..6] which is an indx into the  two AdaptCoeff tables.
787 **      The predictor is chosen by trying all of the possible predictors on a small set of
788 **      samples at the beginning of the block. The predictor with the smallest average
789 **      abs (idelta) is chosen as the best predictor for this block.
790 **      The value of idelta is chosen to to give a 4 bit code value of +/- 4 (approx. half the
791 **      max. code value). If the average abs (idelta) is zero, the sixth predictor is chosen.
792 **      If the value of idelta is less then 16 it is set to 16.
793 **
794 **      Microsoft uses an IDELTA_COUNT (number of sample pairs used to choose best predictor)
795 **      value of 3. The best possible results would be obtained by using all the samples to
796 **      choose the predictor.
797 */
798
799 #define         IDELTA_COUNT    3
800
801 static  void
802 choose_predictor (unsigned int channels, short *data, int *block_pred, int *idelta)
803 {       unsigned int    chan, k, bpred, idelta_sum, best_bpred, best_idelta ;
804
805         for (chan = 0 ; chan < channels ; chan++)
806         {       best_bpred = best_idelta = 0 ;
807
808                 for (bpred = 0 ; bpred < 7 ; bpred++)
809                 {       idelta_sum = 0 ;
810                         for (k = 2 ; k < 2 + IDELTA_COUNT ; k++)
811                                 idelta_sum += abs (data [k * channels] - ((data [(k - 1) * channels] * AdaptCoeff1 [bpred] + data [(k - 2) * channels] * AdaptCoeff2 [bpred]) >> 8)) ;
812                         idelta_sum /= (4 * IDELTA_COUNT) ;
813
814                         if (bpred == 0 || idelta_sum < best_idelta)
815                         {       best_bpred = bpred ;
816                                 best_idelta = idelta_sum ;
817                                 } ;
818
819                         if (! idelta_sum)
820                         {       best_bpred = bpred ;
821                                 best_idelta = 16 ;
822                                 break ;
823                                 } ;
824
825                         } ; /* for bpred ... */
826                 if (best_idelta < 16)
827                         best_idelta = 16 ;
828
829                 block_pred [chan]       = best_bpred ;
830                 idelta [chan]           = best_idelta ;
831                 } ;
832
833         return ;
834 } /* choose_predictor */
835