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