open un-writable sessions without complaining, and desensitize all/most actions that...
[ardour.git] / libs / libsndfile / src / ms_adpcm.c
1 /*
2 ** Copyright (C) 1999-2005 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
25 #include        "sndfile.h"
26 #include        "sfendian.h"
27 #include        "float_cast.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->fdata != NULL)
136         {       psf_log_printf (psf, "*** psf->fdata is not NULL.\n") ;
137                 return SFE_INTERNAL ;
138                 } ;
139
140         if (psf->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->fdata = malloc (pmssize)))
146                 return SFE_MALLOC_FAILED ;
147         pms = (MSADPCM_PRIVATE*) psf->fdata ;
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 (psf->mode == SFM_READ)
158         {       pms->dataremaining       = psf->datalength ;
159
160                 if (psf->datalength % pms->blocksize)
161                         pms->blocks = psf->datalength / pms->blocksize + 1 ;
162                 else
163                         pms->blocks = psf->datalength / pms->blocksize ;
164
165                 count = 2 * (pms->blocksize - 6 * pms->channels) / pms->channels ;
166                 if (pms->samplesperblock != count)
167                         psf_log_printf (psf, "*** Warning : samplesperblock shoud be %d.\n", count) ;
168
169                 psf->sf.frames = (psf->datalength / pms->blocksize) * pms->samplesperblock ;
170
171                 psf_log_printf (psf, " bpred   idelta\n") ;
172
173                 msadpcm_decode_block (psf, pms) ;
174
175                 psf->read_short         = msadpcm_read_s ;
176                 psf->read_int           = msadpcm_read_i ;
177                 psf->read_float         = msadpcm_read_f ;
178                 psf->read_double        = msadpcm_read_d ;
179                 } ;
180
181         if (psf->mode == SFM_WRITE)
182         {       pms->samples = pms->dummydata ;
183
184                 pms->samplecount = 0 ;
185
186                 psf->write_short        = msadpcm_write_s ;
187                 psf->write_int          = msadpcm_write_i ;
188                 psf->write_float        = msadpcm_write_f ;
189                 psf->write_double       = msadpcm_write_d ;
190                 } ;
191
192         psf->codec_close = msadpcm_close ;
193         psf->seek = msadpcm_seek ;
194
195         return 0 ;
196 } /* wav_w64_msadpcm_init */
197
198 static int
199 msadpcm_decode_block    (SF_PRIVATE *psf, MSADPCM_PRIVATE *pms)
200 {       int             chan, k, blockindx, sampleindx ;
201         short   bytecode, bpred [2], chan_idelta [2] ;
202
203     int predict ;
204     int current ;
205     int idelta ;
206
207         pms->blockcount ++ ;
208         pms->samplecount = 0 ;
209
210         if (pms->blockcount > pms->blocks)
211         {       memset (pms->samples, 0, pms->samplesperblock * pms->channels) ;
212                 return 1 ;
213                 } ;
214
215         if ((k = psf_fread (pms->block, 1, pms->blocksize, psf)) != pms->blocksize)
216                 psf_log_printf (psf, "*** Warning : short read (%d != %d).\n", k, pms->blocksize) ;
217
218         /* Read and check the block header. */
219
220         if (pms->channels == 1)
221         {       bpred [0] = pms->block [0] ;
222
223                 if (bpred [0] >= 7)
224                         psf_log_printf (psf, "MS ADPCM synchronisation error (%d).\n", bpred [0]) ;
225
226                 chan_idelta [0] = pms->block [1] | (pms->block [2] << 8) ;
227                 chan_idelta [1] = 0 ;
228
229                 psf_log_printf (psf, "(%d) (%d)\n", bpred [0], chan_idelta [0]) ;
230
231                 pms->samples [1] = pms->block [3] | (pms->block [4] << 8) ;
232                 pms->samples [0] = pms->block [5] | (pms->block [6] << 8) ;
233                 blockindx = 7 ;
234                 }
235         else
236         {       bpred [0] = pms->block [0] ;
237                 bpred [1] = pms->block [1] ;
238
239                 if (bpred [0] >= 7 || bpred [1] >= 7)
240                         psf_log_printf (psf, "MS ADPCM synchronisation error (%d %d).\n", bpred [0], bpred [1]) ;
241
242                 chan_idelta [0] = pms->block [2] | (pms->block [3] << 8) ;
243                 chan_idelta [1] = pms->block [4] | (pms->block [5] << 8) ;
244
245                 psf_log_printf (psf, "(%d, %d) (%d, %d)\n", bpred [0], bpred [1], chan_idelta [0], chan_idelta [1]) ;
246
247                 pms->samples [2] = pms->block [6] | (pms->block [7] << 8) ;
248                 pms->samples [3] = pms->block [8] | (pms->block [9] << 8) ;
249
250                 pms->samples [0] = pms->block [10] | (pms->block [11] << 8) ;
251                 pms->samples [1] = pms->block [12] | (pms->block [13] << 8) ;
252
253                 blockindx = 14 ;
254                 } ;
255
256         /*--------------------------------------------------------
257         This was left over from a time when calculations were done
258         as ints rather than shorts. Keep this around as a reminder
259         in case I ever find a file which decodes incorrectly.
260
261     if (chan_idelta [0] & 0x8000)
262                 chan_idelta [0] -= 0x10000 ;
263     if (chan_idelta [1] & 0x8000)
264                 chan_idelta [1] -= 0x10000 ;
265         --------------------------------------------------------*/
266
267         /* Pull apart the packed 4 bit samples and store them in their
268         ** correct sample positions.
269         */
270
271         sampleindx = 2 * pms->channels ;
272         while (blockindx < pms->blocksize)
273         {       bytecode = pms->block [blockindx++] ;
274                 pms->samples [sampleindx++] = (bytecode >> 4) & 0x0F ;
275                 pms->samples [sampleindx++] = bytecode & 0x0F ;
276                 } ;
277
278         /* Decode the encoded 4 bit samples. */
279
280         for (k = 2 * pms->channels ; k < (pms->samplesperblock * pms->channels) ; k ++)
281         {       chan = (pms->channels > 1) ? (k % 2) : 0 ;
282
283                 bytecode = pms->samples [k] & 0xF ;
284
285                 /* Compute next Adaptive Scale Factor (ASF) */
286                 idelta = chan_idelta [chan] ;
287                 chan_idelta [chan] = (AdaptationTable [bytecode] * idelta) >> 8 ;       /* => / 256 => FIXED_POINT_ADAPTATION_BASE == 256 */
288                 if (chan_idelta [chan] < 16)
289                         chan_idelta [chan] = 16 ;
290                 if (bytecode & 0x8)
291                         bytecode -= 0x10 ;
292
293         predict = ((pms->samples [k - pms->channels] * AdaptCoeff1 [bpred [chan]])
294                                         + (pms->samples [k - 2 * pms->channels] * AdaptCoeff2 [bpred [chan]])) >> 8 ; /* => / 256 => FIXED_POINT_COEFF_BASE == 256 */
295                 current = (bytecode * idelta) + predict ;
296
297                 if (current > 32767)
298                         current = 32767 ;
299                 else if (current < -32768)
300                         current = -32768 ;
301
302                 pms->samples [k] = current ;
303                 } ;
304
305         return 1 ;
306 } /* msadpcm_decode_block */
307
308 static sf_count_t
309 msadpcm_read_block      (SF_PRIVATE *psf, MSADPCM_PRIVATE *pms, short *ptr, int len)
310 {       int     count, total = 0, indx = 0 ;
311
312         while (indx < len)
313         {       if (pms->blockcount >= pms->blocks && pms->samplecount >= pms->samplesperblock)
314                 {       memset (&(ptr [indx]), 0, (size_t) ((len - indx) * sizeof (short))) ;
315                         return total ;
316                         } ;
317
318                 if (pms->samplecount >= pms->samplesperblock)
319                         msadpcm_decode_block (psf, pms) ;
320
321                 count = (pms->samplesperblock - pms->samplecount) * pms->channels ;
322                 count = (len - indx > count) ? count : len - indx ;
323
324                 memcpy (&(ptr [indx]), &(pms->samples [pms->samplecount * pms->channels]), count * sizeof (short)) ;
325                 indx += count ;
326                 pms->samplecount += count / pms->channels ;
327                 total = indx ;
328                 } ;
329
330         return total ;
331 } /* msadpcm_read_block */
332
333 static sf_count_t
334 msadpcm_read_s  (SF_PRIVATE *psf, short *ptr, sf_count_t len)
335 {       MSADPCM_PRIVATE         *pms ;
336         int                     readcount, count ;
337         sf_count_t      total = 0 ;
338
339         if (! psf->fdata)
340                 return 0 ;
341         pms = (MSADPCM_PRIVATE*) psf->fdata ;
342
343         while (len > 0)
344         {       readcount = (len > 0x10000000) ? 0x10000000 : (int) len ;
345
346                 count = msadpcm_read_block (psf, pms, ptr, readcount) ;
347
348                 total += count ;
349                 len -= count ;
350                 if (count != readcount)
351                         break ;
352                 } ;
353
354         return total ;
355 } /* msadpcm_read_s */
356
357 static sf_count_t
358 msadpcm_read_i  (SF_PRIVATE *psf, int *ptr, sf_count_t len)
359 {       MSADPCM_PRIVATE *pms ;
360         short           *sptr ;
361         int                     k, bufferlen, readcount = 0, count ;
362         sf_count_t      total = 0 ;
363
364         if (! psf->fdata)
365                 return 0 ;
366         pms = (MSADPCM_PRIVATE*) psf->fdata ;
367
368         sptr = psf->u.sbuf ;
369         bufferlen = ARRAY_LEN (psf->u.sbuf) ;
370         while (len > 0)
371         {       readcount = (len >= bufferlen) ? bufferlen : len ;
372                 count = msadpcm_read_block (psf, pms, sptr, readcount) ;
373                 for (k = 0 ; k < readcount ; k++)
374                         ptr [total + k] = sptr [k] << 16 ;
375                 total += count ;
376                 len -= readcount ;
377                 if (count != readcount)
378                         break ;
379                 } ;
380         return total ;
381 } /* msadpcm_read_i */
382
383 static sf_count_t
384 msadpcm_read_f  (SF_PRIVATE *psf, float *ptr, sf_count_t len)
385 {       MSADPCM_PRIVATE *pms ;
386         short           *sptr ;
387         int                     k, bufferlen, readcount = 0, count ;
388         sf_count_t      total = 0 ;
389         float           normfact ;
390
391         if (! psf->fdata)
392                 return 0 ;
393         pms = (MSADPCM_PRIVATE*) psf->fdata ;
394
395         normfact = (psf->norm_float == SF_TRUE) ? 1.0 / ((float) 0x8000) : 1.0 ;
396         sptr = psf->u.sbuf ;
397         bufferlen = ARRAY_LEN (psf->u.sbuf) ;
398         while (len > 0)
399         {       readcount = (len >= bufferlen) ? bufferlen : len ;
400                 count = msadpcm_read_block (psf, pms, sptr, readcount) ;
401                 for (k = 0 ; k < readcount ; k++)
402                         ptr [total + k] = normfact * (float) (sptr [k]) ;
403                 total += count ;
404                 len -= readcount ;
405                 if (count != readcount)
406                         break ;
407                 } ;
408         return total ;
409 } /* msadpcm_read_f */
410
411 static sf_count_t
412 msadpcm_read_d  (SF_PRIVATE *psf, double *ptr, sf_count_t len)
413 {       MSADPCM_PRIVATE *pms ;
414         short           *sptr ;
415         int                     k, bufferlen, readcount = 0, count ;
416         sf_count_t      total = 0 ;
417         double          normfact ;
418
419         normfact = (psf->norm_double == SF_TRUE) ? 1.0 / ((double) 0x8000) : 1.0 ;
420
421         if (! psf->fdata)
422                 return 0 ;
423         pms = (MSADPCM_PRIVATE*) psf->fdata ;
424
425         sptr = psf->u.sbuf ;
426         bufferlen = ARRAY_LEN (psf->u.sbuf) ;
427         while (len > 0)
428         {       readcount = (len >= bufferlen) ? bufferlen : len ;
429                 count = msadpcm_read_block (psf, pms, sptr, readcount) ;
430                 for (k = 0 ; k < readcount ; k++)
431                         ptr [total + k] = normfact * (double) (sptr [k]) ;
432                 total += count ;
433                 len -= readcount ;
434                 if (count != readcount)
435                         break ;
436                 } ;
437         return total ;
438 } /* msadpcm_read_d */
439
440 static sf_count_t
441 msadpcm_seek    (SF_PRIVATE *psf, int mode, sf_count_t offset)
442 {       MSADPCM_PRIVATE *pms ;
443         int                     newblock, newsample ;
444
445         if (! psf->fdata)
446                 return 0 ;
447         pms = (MSADPCM_PRIVATE*) psf->fdata ;
448
449         if (psf->datalength < 0 || psf->dataoffset < 0)
450         {       psf->error = SFE_BAD_SEEK ;
451                 return  PSF_SEEK_ERROR ;
452                 } ;
453
454         if (offset == 0)
455         {       psf_fseek (psf, psf->dataoffset, SEEK_SET) ;
456                 pms->blockcount = 0 ;
457                 msadpcm_decode_block (psf, pms) ;
458                 pms->samplecount = 0 ;
459                 return 0 ;
460                 } ;
461
462         if (offset < 0 || offset > pms->blocks * pms->samplesperblock)
463         {       psf->error = SFE_BAD_SEEK ;
464                 return  PSF_SEEK_ERROR ;
465                 } ;
466
467         newblock        = offset / pms->samplesperblock ;
468         newsample       = offset % pms->samplesperblock ;
469
470         if (mode == SFM_READ)
471         {       psf_fseek (psf, psf->dataoffset + newblock * pms->blocksize, SEEK_SET) ;
472                 pms->blockcount = newblock ;
473                 msadpcm_decode_block (psf, pms) ;
474                 pms->samplecount = newsample ;
475                 }
476         else
477         {       /* What to do about write??? */
478                 psf->error = SFE_BAD_SEEK ;
479                 return  PSF_SEEK_ERROR ;
480                 } ;
481
482         return newblock * pms->samplesperblock + newsample ;
483 } /* msadpcm_seek */
484
485 /*==========================================================================================
486 ** MS ADPCM Write Functions.
487 */
488
489 void
490 msadpcm_write_adapt_coeffs      (SF_PRIVATE *psf)
491 {       int k ;
492
493         for (k = 0 ; k < MSADPCM_ADAPT_COEFF_COUNT ; k++)
494                 psf_binheader_writef (psf, "22", AdaptCoeff1 [k], AdaptCoeff2 [k]) ;
495 } /* msadpcm_write_adapt_coeffs */
496
497 /*==========================================================================================
498 */
499
500 static int
501 msadpcm_encode_block    (SF_PRIVATE *psf, MSADPCM_PRIVATE *pms)
502 {       unsigned int    blockindx ;
503         unsigned char   byte ;
504         int                             chan, k, predict, bpred [2], idelta [2], errordelta, newsamp ;
505
506         choose_predictor (pms->channels, pms->samples, bpred, idelta) ;
507
508         /* Write the block header. */
509
510         if (pms->channels == 1)
511         {       pms->block [0]  = bpred [0] ;
512                 pms->block [1]  = idelta [0] & 0xFF ;
513                 pms->block [2]  = idelta [0] >> 8 ;
514                 pms->block [3]  = pms->samples [1] & 0xFF ;
515                 pms->block [4]  = pms->samples [1] >> 8 ;
516                 pms->block [5]  = pms->samples [0] & 0xFF ;
517                 pms->block [6]  = pms->samples [0] >> 8 ;
518
519                 blockindx = 7 ;
520                 byte = 0 ;
521
522                 /* Encode the samples as 4 bit. */
523
524                 for (k = 2 ; k < pms->samplesperblock ; k++)
525                 {       predict = (pms->samples [k-1] * AdaptCoeff1 [bpred [0]] + pms->samples [k-2] * AdaptCoeff2 [bpred [0]]) >> 8 ;
526                         errordelta = (pms->samples [k] - predict) / idelta [0] ;
527                         if (errordelta < -8)
528                                 errordelta = -8 ;
529                         else if (errordelta > 7)
530                                 errordelta = 7 ;
531                         newsamp = predict + (idelta [0] * errordelta) ;
532                         if (newsamp > 32767)
533                                 newsamp = 32767 ;
534                         else if (newsamp < -32768)
535                                 newsamp = -32768 ;
536                         if (errordelta < 0)
537                                 errordelta += 0x10 ;
538
539                         byte = (byte << 4) | (errordelta & 0xF) ;
540                         if (k % 2)
541                         {       pms->block [blockindx++] = byte ;
542                                 byte = 0 ;
543                                 } ;
544
545                         idelta [0] = (idelta [0] * AdaptationTable [errordelta]) >> 8 ;
546                         if (idelta [0] < 16)
547                                 idelta [0] = 16 ;
548                         pms->samples [k] = newsamp ;
549                         } ;
550                 }
551         else
552         {       /* Stereo file. */
553                 pms->block [0]  = bpred [0] ;
554                 pms->block [1]  = bpred [1] ;
555
556                 pms->block [2]  = idelta [0] & 0xFF ;
557                 pms->block [3]  = idelta [0] >> 8 ;
558                 pms->block [4]  = idelta [1] & 0xFF ;
559                 pms->block [5]  = idelta [1] >> 8 ;
560
561                 pms->block [6]  = pms->samples [2] & 0xFF ;
562                 pms->block [7]  = pms->samples [2] >> 8 ;
563                 pms->block [8]  = pms->samples [3] & 0xFF ;
564                 pms->block [9]  = pms->samples [3] >> 8 ;
565
566                 pms->block [10] = pms->samples [0] & 0xFF ;
567                 pms->block [11] = pms->samples [0] >> 8 ;
568                 pms->block [12] = pms->samples [1] & 0xFF ;
569                 pms->block [13] = pms->samples [1] >> 8 ;
570
571                 blockindx = 14 ;
572                 byte = 0 ;
573                 chan = 1 ;
574
575                 for (k = 4 ; k < 2 * pms->samplesperblock ; k++)
576                 {       chan = k & 1 ;
577
578                         predict = (pms->samples [k-2] * AdaptCoeff1 [bpred [chan]] + pms->samples [k-4] * AdaptCoeff2 [bpred [chan]]) >> 8 ;
579                         errordelta = (pms->samples [k] - predict) / idelta [chan] ;
580
581
582                         if (errordelta < -8)
583                                 errordelta = -8 ;
584                         else if (errordelta > 7)
585                                 errordelta = 7 ;
586                         newsamp = predict + (idelta [chan] * errordelta) ;
587                         if (newsamp > 32767)
588                                 newsamp = 32767 ;
589                         else if (newsamp < -32768)
590                                 newsamp = -32768 ;
591                         if (errordelta < 0)
592                                 errordelta += 0x10 ;
593
594                         byte = (byte << 4) | (errordelta & 0xF) ;
595
596                         if (chan)
597                         {       pms->block [blockindx++] = byte ;
598                                 byte = 0 ;
599                                 } ;
600
601                         idelta [chan] = (idelta [chan] * AdaptationTable [errordelta]) >> 8 ;
602                         if (idelta [chan] < 16)
603                                 idelta [chan] = 16 ;
604                         pms->samples [k] = newsamp ;
605                         } ;
606                 } ;
607
608         /* Write the block to disk. */
609
610         if ((k = psf_fwrite (pms->block, 1, pms->blocksize, psf)) != pms->blocksize)
611                 psf_log_printf (psf, "*** Warning : short write (%d != %d).\n", k, pms->blocksize) ;
612
613         memset (pms->samples, 0, pms->samplesperblock * sizeof (short)) ;
614
615         pms->blockcount ++ ;
616         pms->samplecount = 0 ;
617
618         return 1 ;
619 } /* msadpcm_encode_block */
620
621 static sf_count_t
622 msadpcm_write_block     (SF_PRIVATE *psf, MSADPCM_PRIVATE *pms, const short *ptr, int len)
623 {       int             count, total = 0, indx = 0 ;
624
625         while (indx < len)
626         {       count = (pms->samplesperblock - pms->samplecount) * pms->channels ;
627
628                 if (count > len - indx)
629                         count = len - indx ;
630
631                 memcpy (&(pms->samples [pms->samplecount * pms->channels]), &(ptr [total]), count * sizeof (short)) ;
632                 indx += count ;
633                 pms->samplecount += count / pms->channels ;
634                 total = indx ;
635
636                 if (pms->samplecount >= pms->samplesperblock)
637                         msadpcm_encode_block (psf, pms) ;
638                 } ;
639
640         return total ;
641 } /* msadpcm_write_block */
642
643 static sf_count_t
644 msadpcm_write_s (SF_PRIVATE *psf, const short *ptr, sf_count_t len)
645 {       MSADPCM_PRIVATE *pms ;
646         int                     writecount, count ;
647         sf_count_t      total = 0 ;
648
649         if (! psf->fdata)
650                 return 0 ;
651         pms = (MSADPCM_PRIVATE*) psf->fdata ;
652
653         while (len > 0)
654         {       writecount = (len > 0x10000000) ? 0x10000000 : (int) len ;
655
656                 count = msadpcm_write_block (psf, pms, ptr, writecount) ;
657
658                 total += count ;
659                 len -= count ;
660                 if (count != writecount)
661                         break ;
662                 } ;
663
664         return total ;
665 } /* msadpcm_write_s */
666
667 static sf_count_t
668 msadpcm_write_i (SF_PRIVATE *psf, const int *ptr, sf_count_t len)
669 {       MSADPCM_PRIVATE *pms ;
670         short           *sptr ;
671         int                     k, bufferlen, writecount, count ;
672         sf_count_t      total = 0 ;
673
674         if (! psf->fdata)
675                 return 0 ;
676         pms = (MSADPCM_PRIVATE*) psf->fdata ;
677
678         sptr = psf->u.sbuf ;
679         bufferlen = ARRAY_LEN (psf->u.sbuf) ;
680         while (len > 0)
681         {       writecount = (len >= bufferlen) ? bufferlen : len ;
682                 for (k = 0 ; k < writecount ; k++)
683                         sptr [k] = ptr [total + k] >> 16 ;
684                 count = msadpcm_write_block (psf, pms, sptr, writecount) ;
685                 total += count ;
686                 len -= writecount ;
687                 if (count != writecount)
688                         break ;
689                 } ;
690         return total ;
691 } /* msadpcm_write_i */
692
693 static sf_count_t
694 msadpcm_write_f (SF_PRIVATE *psf, const float *ptr, sf_count_t len)
695 {       MSADPCM_PRIVATE *pms ;
696         short           *sptr ;
697         int                     k, bufferlen, writecount, count ;
698         sf_count_t      total = 0 ;
699         float           normfact ;
700
701         if (! psf->fdata)
702                 return 0 ;
703         pms = (MSADPCM_PRIVATE*) psf->fdata ;
704
705         normfact = (psf->norm_float == SF_TRUE) ? (1.0 * 0x7FFF) : 1.0 ;
706
707         sptr = psf->u.sbuf ;
708         bufferlen = ARRAY_LEN (psf->u.sbuf) ;
709         while (len > 0)
710         {       writecount = (len >= bufferlen) ? bufferlen : len ;
711                 for (k = 0 ; k < writecount ; k++)
712                         sptr [k] = lrintf (normfact * ptr [total + k]) ;
713                 count = msadpcm_write_block (psf, pms, sptr, writecount) ;
714                 total += count ;
715                 len -= writecount ;
716                 if (count != writecount)
717                         break ;
718                 } ;
719         return total ;
720 } /* msadpcm_write_f */
721
722 static sf_count_t
723 msadpcm_write_d (SF_PRIVATE *psf, const double *ptr, sf_count_t len)
724 {       MSADPCM_PRIVATE *pms ;
725         short           *sptr ;
726         int                     k, bufferlen, writecount, count ;
727         sf_count_t      total = 0 ;
728         double          normfact ;
729
730         normfact = (psf->norm_double == SF_TRUE) ? (1.0 * 0x7FFF) : 1.0 ;
731
732         if (! psf->fdata)
733                 return 0 ;
734         pms = (MSADPCM_PRIVATE*) psf->fdata ;
735
736         sptr = psf->u.sbuf ;
737         bufferlen = ARRAY_LEN (psf->u.sbuf) ;
738         while (len > 0)
739         {       writecount = (len >= bufferlen) ? bufferlen : len ;
740                 for (k = 0 ; k < writecount ; k++)
741                         sptr [k] = lrint (normfact * ptr [total + k]) ;
742                 count = msadpcm_write_block (psf, pms, sptr, writecount) ;
743                 total += count ;
744                 len -= writecount ;
745                 if (count != writecount)
746                         break ;
747                 } ;
748         return total ;
749 } /* msadpcm_write_d */
750
751 /*========================================================================================
752 */
753
754 static int
755 msadpcm_close   (SF_PRIVATE *psf)
756 {       MSADPCM_PRIVATE *pms ;
757
758         pms = (MSADPCM_PRIVATE*) psf->fdata ;
759
760         if (psf->mode == SFM_WRITE)
761         {       /*  Now we know static int for certain the length of the file we can
762                 **  re-write the header.
763                 */
764
765                 if (pms->samplecount && pms->samplecount < pms->samplesperblock)
766                         msadpcm_encode_block (psf, pms) ;
767                 } ;
768
769         return 0 ;
770 } /* msadpcm_close */
771
772 /*========================================================================================
773 ** Static functions.
774 */
775
776 /*----------------------------------------------------------------------------------------
777 **      Choosing the block predictor.
778 **      Each block requires a predictor and an idelta for each channel.
779 **      The predictor is in the range [0..6] which is an indx into the  two AdaptCoeff tables.
780 **      The predictor is chosen by trying all of the possible predictors on a small set of
781 **      samples at the beginning of the block. The predictor with the smallest average
782 **      abs (idelta) is chosen as the best predictor for this block.
783 **      The value of idelta is chosen to to give a 4 bit code value of +/- 4 (approx. half the
784 **      max. code value). If the average abs (idelta) is zero, the sixth predictor is chosen.
785 **      If the value of idelta is less then 16 it is set to 16.
786 **
787 **      Microsoft uses an IDELTA_COUNT (number of sample pairs used to choose best predictor)
788 **      value of 3. The best possible results would be obtained by using all the samples to
789 **      choose the predictor.
790 */
791
792 #define         IDELTA_COUNT    3
793
794 static  void
795 choose_predictor (unsigned int channels, short *data, int *block_pred, int *idelta)
796 {       unsigned int    chan, k, bpred, idelta_sum, best_bpred, best_idelta ;
797
798         for (chan = 0 ; chan < channels ; chan++)
799         {       best_bpred = best_idelta = 0 ;
800
801                 for (bpred = 0 ; bpred < 7 ; bpred++)
802                 {       idelta_sum = 0 ;
803                         for (k = 2 ; k < 2 + IDELTA_COUNT ; k++)
804                                 idelta_sum += abs (data [k * channels] - ((data [(k - 1) * channels] * AdaptCoeff1 [bpred] + data [(k - 2) * channels] * AdaptCoeff2 [bpred]) >> 8)) ;
805                         idelta_sum /= (4 * IDELTA_COUNT) ;
806
807                         if (bpred == 0 || idelta_sum < best_idelta)
808                         {       best_bpred = bpred ;
809                                 best_idelta = idelta_sum ;
810                                 } ;
811
812                         if (! idelta_sum)
813                         {       best_bpred = bpred ;
814                                 best_idelta = 16 ;
815                                 break ;
816                                 } ;
817
818                         } ; /* for bpred ... */
819                 if (best_idelta < 16)
820                         best_idelta = 16 ;
821
822                 block_pred [chan]       = best_bpred ;
823                 idelta [chan]           = best_idelta ;
824                 } ;
825
826         return ;
827 } /* choose_predictor */
828 /*
829 ** Do not edit or modify anything in this comment block.
830 ** The arch-tag line is a file identity tag for the GNU Arch 
831 ** revision control system.
832 **
833 ** arch-tag: a98908a3-5305-4935-872b-77d6a86c330f
834 */