1 /*
2     TiMidity++ -- MIDI to WAVE converter and player
3     Copyright (C) 1999-2002 Masanao Izumo <mo@goice.co.jp>
4     Copyright (C) 1995 Tuukka Toivonen <tt@cgs.fi>
5 
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10 
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15 
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19 
20     resample.c
21 */
22 
23 #include <math.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 
28 #include "timidity.h"
29 #include "common.h"
30 #include "instrum.h"
31 #include "playmidi.h"
32 #include "tables.h"
33 #include "resample.h"
34 #include "recache.h"
35 
36 namespace TimidityPlus
37 {
38 
39 
40 /* for start/end of samples */
41 static float newt_coeffs[58][58];
42 static int sample_bounds_min, sample_bounds_max; /* min/max bounds for sample data */
43 
44 #define DEFAULT_GAUSS_ORDER	25
45 std::vector<float> gauss_table_data;
46 static float *gauss_table[(1 << FRACTION_BITS)] = { 0 };	/* don't need doubles */
47 static int gauss_n = DEFAULT_GAUSS_ORDER;
48 
49 
initialize_newton_coeffs()50 static void initialize_newton_coeffs()
51 {
52 	int i, j, n = 57;
53 	int sign;
54 
55 	newt_coeffs[0][0] = 1;
56 	for (i = 0; i <= n; i++)
57 	{
58 		newt_coeffs[i][0] = 1;
59 		newt_coeffs[i][i] = 1;
60 
61 		if (i > 1)
62 		{
63 			newt_coeffs[i][0] = newt_coeffs[i - 1][0] / i;
64 			newt_coeffs[i][i] = newt_coeffs[i - 1][0] / i;
65 		}
66 
67 		for (j = 1; j < i; j++)
68 		{
69 			newt_coeffs[i][j] = newt_coeffs[i - 1][j - 1] + newt_coeffs[i - 1][j];
70 
71 			if (i > 1)
72 				newt_coeffs[i][j] /= i;
73 		}
74 	}
75 	for (i = 0; i <= n; i++)
76 		for (j = 0, sign = pow(-1, i); j <= i; j++, sign *= -1)
77 			newt_coeffs[i][j] *= sign;
78 
79 }
80 
81 
82 
83 /* Very fast and accurate table based interpolation.  Better speed and higher
84 	accuracy than Newton.  This isn't *quite* true Gauss interpolation; it's
85 	more a slightly modified Gauss interpolation that I accidently stumbled
86 	upon.  Rather than normalize all x values in the window to be in the range
87 	[0 to 2*PI], it simply divides them all by 2*PI instead.  I don't know why
88 	this works, but it does.  Gauss should only work on periodic data with the
89 	window spanning exactly one period, so it is no surprise that regular Gauss
90 	interpolation doesn't work too well on general audio data.  But dividing
91 	the x values by 2*PI magically does.  Any other scaling produces degraded
92 	results or total garbage.  If anyone can work out the theory behind why
93 	this works so well (at first glance, it shouldn't ??), please contact me
94 	(Eric A. Welsh, ewelsh@ccb.wustl.edu), as I would really like to have some
95 	mathematical justification for doing this.  Despite the lack of any sound
96 	theoretical basis, this method DOES result in highly accurate interpolation
97 	(or possibly approximaton, not sure yet if it truly interpolates, but it
98 	looks like it does).  -N 34 is as high as it can go before errors start
99 	appearing.  But even at -N 34, it is more accurate than Newton at -N 57.
100 	-N 34 has no problem running in realtime on my system, but -N 25 is the
101 	default, since that is the optimal compromise between speed and accuracy.
102 	I strongly recommend using Gauss interpolation.  It is the highest
103 	quality interpolation option available, and is much faster than using
104 	Newton polynomials. */
105 
106 
resample_gauss(sample_t * src,splen_t ofs,resample_rec_t * rec)107 static resample_t resample_gauss(sample_t *src, splen_t ofs, resample_rec_t *rec)
108 {
109 	sample_t *sptr;
110 	int32_t left, right, temp_n;
111 
112 	left = (ofs >> FRACTION_BITS);
113 	right = (rec->data_length >> FRACTION_BITS) - left - 1;
114 	temp_n = (right << 1) - 1;
115 	if (temp_n > (left << 1) + 1)
116 		temp_n = (left << 1) + 1;
117 	if (temp_n < gauss_n) {
118 		int ii, jj;
119 		float xd, y;
120 		if (temp_n <= 0)
121 			temp_n = 1;
122 		xd = ofs & FRACTION_MASK;
123 		xd /= (1L << FRACTION_BITS);
124 		xd += temp_n >> 1;
125 		y = 0;
126 		sptr = src + (ofs >> FRACTION_BITS) - (temp_n >> 1);
127 		for (ii = temp_n; ii;) {
128 			for (jj = 0; jj <= ii; jj++)
129 				y += sptr[jj] * newt_coeffs[ii][jj];
130 			y *= xd - --ii;
131 		}
132 		y += *sptr;
133 		return ((y > sample_bounds_max) ? sample_bounds_max :
134 			((y < sample_bounds_min) ? sample_bounds_min : y));
135 	}
136 	else {
137 		float *gptr, *gend;
138 		float y;
139 		y = 0;
140 		sptr = src + left - (gauss_n >> 1);
141 		gptr = gauss_table[ofs&FRACTION_MASK];
142 		if (gauss_n == DEFAULT_GAUSS_ORDER) {
143 			/* expanding the loop for the default case.
144 				* this will allow intensive optimization when compiled
145 				* with SSE2 capability.
146 				*/
147 #define do_gauss  y += *(sptr++) * *(gptr++);
148 			do_gauss;
149 			do_gauss;
150 			do_gauss;
151 			do_gauss;
152 			do_gauss;
153 			do_gauss;
154 			do_gauss;
155 			do_gauss;
156 			do_gauss;
157 			do_gauss;
158 			do_gauss;
159 			do_gauss;
160 			do_gauss;
161 			do_gauss;
162 			do_gauss;
163 			do_gauss;
164 			do_gauss;
165 			do_gauss;
166 			do_gauss;
167 			do_gauss;
168 			do_gauss;
169 			do_gauss;
170 			do_gauss;
171 			do_gauss;
172 			do_gauss;
173 			y += *sptr * *gptr;
174 #undef do_gauss
175 		}
176 		else {
177 			gend = gptr + gauss_n;
178 			do {
179 				y += *(sptr++) * *(gptr++);
180 			} while (gptr <= gend);
181 		}
182 		return ((y > sample_bounds_max) ? sample_bounds_max :
183 			((y < sample_bounds_min) ? sample_bounds_min : y));
184 	}
185 }
186 
187 
188 #define RESAMPLATION *dest++ = resample_gauss(src, ofs, &resrc);
189 
190 /* exported for recache.c */
do_resamplation(sample_t * src,splen_t ofs,resample_rec_t * rec)191 resample_t do_resamplation(sample_t *src, splen_t ofs, resample_rec_t *rec)
192 {
193 	return resample_gauss(src, ofs, rec);
194 }
195 
196 #define PRECALC_LOOP_COUNT(start, end, incr) (int32_t)(((int64_t)((end) - (start) + (incr) - 1)) / (incr))
197 
initialize_gauss_table(int n)198 void initialize_gauss_table(int n)
199 {
200 	int m, i, k, n_half = (n >> 1);
201 	double ck;
202 	double x, x_inc, xz;
203 	double z[35], zsin_[34 + 35], *zsin, xzsin[35];
204 	float *gptr;
205 
206 	for (i = 0; i <= n; i++)
207 		z[i] = i / (4 * M_PI);
208 	zsin = &zsin_[34];
209 	for (i = -n; i <= n; i++)
210 		zsin[i] = sin(i / (4 * M_PI));
211 
212 	x_inc = 1.0 / (1 << FRACTION_BITS);
213 
214 	gauss_table_data.resize((n + 1) * sizeof(float) * (1 << FRACTION_BITS));
215 	gptr = gauss_table_data.data();
216 	for (m = 0, x = 0.0; m < (1 << FRACTION_BITS); m++, x += x_inc)
217 	{
218 		xz = (x + n_half) / (4 * M_PI);
219 		for (i = 0; i <= n; i++)
220 			xzsin[i] = sin(xz - z[i]);
221 		gauss_table[m] = gptr;
222 
223 		for (k = 0; k <= n; k++)
224 		{
225 			ck = 1.0;
226 
227 			for (i = 0; i <= n; i++)
228 			{
229 				if (i == k)
230 					continue;
231 
232 				ck *= xzsin[i] / zsin[k - i];
233 			}
234 
235 			*gptr++ = ck;
236 		}
237 	}
238 }
239 
free_gauss_table(void)240 void free_gauss_table(void)
241 {
242 	if (gauss_table[0] != 0)
243 		free(gauss_table[0]);
244 	gauss_table[0] = NULL;
245 }
246 
247 /* initialize the coefficients of the current resampling algorithm */
initialize_resampler_coeffs(void)248 void initialize_resampler_coeffs(void)
249 {
250 	// Only needs to be done once.
251 	static bool done = false;
252 	if (done) return;
253 	done = true;
254 
255 	initialize_newton_coeffs();
256 	initialize_gauss_table(gauss_n);
257 
258 	sample_bounds_min = -32768;
259 	sample_bounds_max = 32767;
260 }
261 
262 
263 /*************** resampling with fixed increment *****************/
264 
rs_plain_c(int v,int32_t * countptr)265 resample_t *Resampler::rs_plain_c(int v, int32_t *countptr)
266 {
267 	Voice *vp = &player->voice[v];
268 	resample_t *dest = resample_buffer + resample_buffer_offset;
269 	sample_t *src = vp->sample->data;
270 	int32_t ofs, count = *countptr, i, le;
271 
272 	le = (int32_t)(vp->sample->loop_end >> FRACTION_BITS);
273 	ofs = (int32_t)(vp->sample_offset >> FRACTION_BITS);
274 
275 	i = ofs + count;
276 	if (i > le)
277 		i = le;
278 	count = i - ofs;
279 
280 	for (i = 0; i < count; i++) {
281 		dest[i] = src[i + ofs];
282 	}
283 
284 	ofs += count;
285 	if (ofs == le)
286 	{
287 		vp->timeout = 1;
288 		*countptr = count;
289 	}
290 	vp->sample_offset = ((splen_t)ofs << FRACTION_BITS);
291 	return resample_buffer + resample_buffer_offset;
292 }
293 
rs_plain(int v,int32_t * countptr)294 resample_t *Resampler::rs_plain(int v, int32_t *countptr)
295 {
296 	/* Play sample until end, then free the voice. */
297 	Voice *vp = &player->voice[v];
298 	resample_t *dest = resample_buffer + resample_buffer_offset;
299 	sample_t *src = vp->sample->data;
300 	splen_t
301 		ofs = vp->sample_offset,
302 		ls = 0,
303 		le = vp->sample->data_length;
304 	resample_rec_t resrc;
305 	int32_t count = *countptr, incr = vp->sample_increment;
306 	int32_t i, j;
307 
308 	if (vp->cache && incr == (1 << FRACTION_BITS))
309 		return rs_plain_c(v, countptr);
310 
311 	resrc.loop_start = ls;
312 	resrc.loop_end = le;
313 	resrc.data_length = vp->sample->data_length;
314 	if (incr < 0) incr = -incr; /* In case we're coming out of a bidir loop */
315 
316 	/* Precalc how many times we should go through the loop.
317 		NOTE: Assumes that incr > 0 and that ofs <= le */
318 	i = PRECALC_LOOP_COUNT(ofs, le, incr);
319 
320 	if (i > count)
321 	{
322 		i = count;
323 		count = 0;
324 	}
325 	else count -= i;
326 
327 	for (j = 0; j < i; j++)
328 	{
329 		RESAMPLATION;
330 		ofs += incr;
331 	}
332 
333 	if (ofs >= le)
334 	{
335 		vp->timeout = 1;
336 		*countptr -= count;
337 	}
338 
339 	vp->sample_offset = ofs; /* Update offset */
340 	return resample_buffer + resample_buffer_offset;
341 }
342 
rs_loop_c(Voice * vp,int32_t count)343 resample_t *Resampler::rs_loop_c(Voice *vp, int32_t count)
344 {
345 	int32_t
346 		ofs = (int32_t)(vp->sample_offset >> FRACTION_BITS),
347 		le = (int32_t)(vp->sample->loop_end >> FRACTION_BITS),
348 		ll = le - (int32_t)(vp->sample->loop_start >> FRACTION_BITS);
349 	resample_t *dest = resample_buffer + resample_buffer_offset;
350 	sample_t *src = vp->sample->data;
351 	int32_t i, j;
352 
353 	while (count)
354 	{
355 		while (ofs >= le)
356 			ofs -= ll;
357 		/* Precalc how many times we should go through the loop */
358 		i = le - ofs;
359 		if (i > count)
360 			i = count;
361 		count -= i;
362 		for (j = 0; j < i; j++) {
363 			dest[j] = src[j + ofs];
364 		}
365 		dest += i;
366 		ofs += i;
367 	}
368 	vp->sample_offset = ((splen_t)ofs << FRACTION_BITS);
369 	return resample_buffer + resample_buffer_offset;
370 }
371 
rs_loop(Voice * vp,int32_t count)372 resample_t *Resampler::rs_loop(Voice *vp, int32_t count)
373 {
374 	/* Play sample until end-of-loop, skip back and continue. */
375 	splen_t
376 		ofs = vp->sample_offset,
377 		ls, le, ll;
378 	resample_rec_t resrc;
379 	resample_t *dest = resample_buffer + resample_buffer_offset;
380 	sample_t *src = vp->sample->data;
381 	int32_t i, j;
382 	int32_t incr = vp->sample_increment;
383 
384 	if (vp->cache && incr == (1 << FRACTION_BITS))
385 		return rs_loop_c(vp, count);
386 
387 	resrc.loop_start = ls = vp->sample->loop_start;
388 	resrc.loop_end = le = vp->sample->loop_end;
389 	ll = le - ls;
390 	resrc.data_length = vp->sample->data_length;
391 
392 	while (count)
393 	{
394 		while (ofs >= le) { ofs -= ll; }
395 		/* Precalc how many times we should go through the loop */
396 		i = PRECALC_LOOP_COUNT(ofs, le, incr);
397 		if (i > count) {
398 			i = count;
399 			count = 0;
400 		}
401 		else { count -= i; }
402 		for (j = 0; j < i; j++) {
403 			RESAMPLATION;
404 			ofs += incr;
405 		}
406 	}
407 
408 	vp->sample_offset = ofs; /* Update offset */
409 	return resample_buffer + resample_buffer_offset;
410 }
411 
rs_bidir(Voice * vp,int32_t count)412 resample_t *Resampler::rs_bidir(Voice *vp, int32_t count)
413 {
414 	int32_t
415 		ofs = vp->sample_offset,
416 		le = vp->sample->loop_end,
417 		ls = vp->sample->loop_start;
418 	resample_t *dest = resample_buffer + resample_buffer_offset;
419 	sample_t *src = vp->sample->data;
420 	int32_t incr = vp->sample_increment;
421 	resample_rec_t resrc;
422 
423 	int32_t
424 		le2 = le << 1,
425 		ls2 = ls << 1;
426 	int32_t i, j;
427 	/* Play normally until inside the loop region */
428 
429 	resrc.loop_start = ls;
430 	resrc.loop_end = le;
431 	resrc.data_length = vp->sample->data_length;
432 
433 	if (incr > 0 && ofs < ls)
434 	{
435 		/* NOTE: Assumes that incr > 0, which is NOT always the case
436 		when doing bidirectional looping.  I have yet to see a case
437 		where both ofs <= ls AND incr < 0, however. */
438 		i = PRECALC_LOOP_COUNT(ofs, ls, incr);
439 		if (i > count)
440 		{
441 			i = count;
442 			count = 0;
443 		}
444 		else count -= i;
445 		for (j = 0; j < i; j++)
446 		{
447 			RESAMPLATION;
448 			ofs += incr;
449 		}
450 	}
451 
452 	/* Then do the bidirectional looping */
453 
454 	while (count)
455 	{
456 		/* Precalc how many times we should go through the loop */
457 		i = PRECALC_LOOP_COUNT(ofs, incr > 0 ? le : ls, incr);
458 		if (i > count)
459 		{
460 			i = count;
461 			count = 0;
462 		}
463 		else count -= i;
464 		for (j = 0; j < i; j++)
465 		{
466 			RESAMPLATION;
467 			ofs += incr;
468 		}
469 		if (ofs >= 0 && ofs >= le)
470 		{
471 			/* fold the overshoot back in */
472 			ofs = le2 - ofs;
473 			incr *= -1;
474 		}
475 		else if (ofs <= 0 || ofs <= ls)
476 		{
477 			ofs = ls2 - ofs;
478 			incr *= -1;
479 		}
480 	}
481 	vp->sample_increment = incr;
482 	vp->sample_offset = ofs; /* Update offset */
483 	return resample_buffer + resample_buffer_offset;
484 }
485 
486 /*********************** vibrato versions ***************************/
487 
488 /* We only need to compute one half of the vibrato sine cycle */
vib_phase_to_inc_ptr(int phase)489 static int vib_phase_to_inc_ptr(int phase)
490 {
491 	if (phase < VIBRATO_SAMPLE_INCREMENTS / 2)
492 		return VIBRATO_SAMPLE_INCREMENTS / 2 - 1 - phase;
493 	else if (phase >= 3 * VIBRATO_SAMPLE_INCREMENTS / 2)
494 		return 5 * VIBRATO_SAMPLE_INCREMENTS / 2 - 1 - phase;
495 	else
496 		return phase - VIBRATO_SAMPLE_INCREMENTS / 2;
497 }
498 
update_vibrato(Voice * vp,int sign)499 int32_t Resampler::update_vibrato(Voice *vp, int sign)
500 {
501 	int32_t depth;
502 	int phase, pb;
503 	double a;
504 	int ch = vp->channel;
505 
506 	if (vp->vibrato_delay > 0)
507 	{
508 		vp->vibrato_delay -= vp->vibrato_control_ratio;
509 		if (vp->vibrato_delay > 0)
510 			return vp->sample_increment;
511 	}
512 
513 	if (vp->vibrato_phase++ >= 2 * VIBRATO_SAMPLE_INCREMENTS - 1)
514 		vp->vibrato_phase = 0;
515 	phase = vib_phase_to_inc_ptr(vp->vibrato_phase);
516 
517 	if (vp->vibrato_sample_increment[phase])
518 	{
519 		if (sign)
520 			return -vp->vibrato_sample_increment[phase];
521 		else
522 			return vp->vibrato_sample_increment[phase];
523 	}
524 
525 	/* Need to compute this sample increment. */
526 
527 	depth = vp->vibrato_depth;
528 	depth <<= 7;
529 
530 	if (vp->vibrato_sweep && !player->channel[ch].mod.val)
531 	{
532 		/* Need to update sweep */
533 		vp->vibrato_sweep_position += vp->vibrato_sweep;
534 		if (vp->vibrato_sweep_position >= (1 << SWEEP_SHIFT))
535 			vp->vibrato_sweep = 0;
536 		else
537 		{
538 			/* Adjust depth */
539 			depth *= vp->vibrato_sweep_position;
540 			depth >>= SWEEP_SHIFT;
541 		}
542 	}
543 
544 	if (vp->sample->inst_type == INST_SF2) {
545 		pb = (int)((lookup_triangular(vp->vibrato_phase *
546 			(SINE_CYCLE_LENGTH / (2 * VIBRATO_SAMPLE_INCREMENTS)))
547 			* (double)(depth)* VIBRATO_AMPLITUDE_TUNING));
548 	}
549 	else {
550 		pb = (int)((lookup_sine(vp->vibrato_phase *
551 			(SINE_CYCLE_LENGTH / (2 * VIBRATO_SAMPLE_INCREMENTS)))
552 			* (double)(depth)* VIBRATO_AMPLITUDE_TUNING));
553 	}
554 
555 	a = TIM_FSCALE(((double)(vp->sample->sample_rate) *
556 		(double)(vp->frequency)) /
557 		((double)(vp->sample->root_freq) *
558 		(double)(playback_rate)),
559 		FRACTION_BITS);
560 
561 	if (pb < 0) {
562 		pb = -pb;
563 		a /= bend_fine[(pb >> 5) & 0xFF] * bend_coarse[pb >> 13];
564 		pb = -pb;
565 	}
566 	else {
567 		a *= bend_fine[(pb >> 5) & 0xFF] * bend_coarse[pb >> 13];
568 	}
569 	a += 0.5;
570 
571 	/* If the sweep's over, we can store the newly computed sample_increment */
572 	if (!vp->vibrato_sweep || player->channel[ch].mod.val)
573 		vp->vibrato_sample_increment[phase] = (int32_t)a;
574 
575 	if (sign)
576 		a = -a; /* need to preserve the loop direction */
577 
578 	return (int32_t)a;
579 }
580 
rs_vib_plain(int v,int32_t * countptr)581 resample_t *Resampler::rs_vib_plain(int v, int32_t *countptr)
582 {
583 	/* Play sample until end, then free the voice. */
584 	Voice *vp = &player->voice[v];
585 	resample_t *dest = resample_buffer + resample_buffer_offset;
586 	sample_t *src = vp->sample->data;
587 	splen_t
588 		ls = 0,
589 		le = vp->sample->data_length,
590 		ofs = vp->sample_offset;
591 	resample_rec_t resrc;
592 
593 	int32_t count = *countptr, incr = vp->sample_increment;
594 	int cc = vp->vibrato_control_counter;
595 
596 	resrc.loop_start = ls;
597 	resrc.loop_end = le;
598 	resrc.data_length = vp->sample->data_length;
599 	/* This has never been tested */
600 
601 	if (incr < 0) incr = -incr; /* In case we're coming out of a bidir loop */
602 
603 	while (count--)
604 	{
605 		if (!cc--)
606 		{
607 			cc = vp->vibrato_control_ratio;
608 			incr = update_vibrato(vp, 0);
609 		}
610 		RESAMPLATION;
611 		ofs += incr;
612 		if (ofs >= le)
613 		{
614 			vp->timeout = 1;
615 			*countptr -= count;
616 			break;
617 		}
618 	}
619 
620 	vp->vibrato_control_counter = cc;
621 	vp->sample_increment = incr;
622 	vp->sample_offset = ofs; /* Update offset */
623 	return resample_buffer + resample_buffer_offset;
624 }
625 
rs_vib_loop(Voice * vp,int32_t count)626 resample_t *Resampler::rs_vib_loop(Voice *vp, int32_t count)
627 {
628 	/* Play sample until end-of-loop, skip back and continue. */
629 	splen_t
630 		ofs = vp->sample_offset,
631 		ls = vp->sample->loop_start,
632 		le = vp->sample->loop_end,
633 		ll = le - vp->sample->loop_start;
634 	resample_t *dest = resample_buffer + resample_buffer_offset;
635 	sample_t *src = vp->sample->data;
636 	int cc = vp->vibrato_control_counter;
637 	int32_t incr = vp->sample_increment;
638 	resample_rec_t resrc;
639 	int32_t i, j;
640 	int vibflag = 0;
641 
642 	resrc.loop_start = ls;
643 	resrc.loop_end = le;
644 	resrc.data_length = vp->sample->data_length;
645 
646 	while (count)
647 	{
648 		/* Hopefully the loop is longer than an increment */
649 		while (ofs >= le) { ofs -= ll; }
650 		/* Precalc how many times to go through the loop, taking
651 		the vibrato control ratio into account this time. */
652 		i = PRECALC_LOOP_COUNT(ofs, le, incr);
653 		if (i > count) {
654 			i = count;
655 		}
656 		if (i > cc) {
657 			i = cc;
658 			vibflag = 1;
659 		}
660 		else { cc -= i; }
661 		count -= i;
662 		if (vibflag) {
663 			cc = vp->vibrato_control_ratio;
664 			incr = update_vibrato(vp, 0);
665 			vibflag = 0;
666 		}
667 		for (j = 0; j < i; j++) {
668 			RESAMPLATION;
669 			ofs += incr;
670 		}
671 	}
672 
673 	vp->vibrato_control_counter = cc;
674 	vp->sample_increment = incr;
675 	vp->sample_offset = ofs; /* Update offset */
676 	return resample_buffer + resample_buffer_offset;
677 }
678 
rs_vib_bidir(Voice * vp,int32_t count)679 resample_t *Resampler::rs_vib_bidir(Voice *vp, int32_t count)
680 {
681 	int32_t
682 		ofs = vp->sample_offset,
683 		le = vp->sample->loop_end,
684 		ls = vp->sample->loop_start;
685 	resample_t *dest = resample_buffer + resample_buffer_offset;
686 	sample_t *src = vp->sample->data;
687 	int cc = vp->vibrato_control_counter;
688 	int32_t incr = vp->sample_increment;
689 	resample_rec_t resrc;
690 
691 
692 	resrc.loop_start = ls;
693 	resrc.loop_end = le;
694 	resrc.data_length = vp->sample->data_length;
695 	/* Play normally until inside the loop region */
696 
697 	if (ofs < ls)
698 	{
699 		while (count--)
700 		{
701 			if (!cc--)
702 			{
703 				cc = vp->vibrato_control_ratio;
704 				incr = update_vibrato(vp, 0);
705 			}
706 			RESAMPLATION;
707 			ofs += incr;
708 			if (ofs >= ls)
709 				break;
710 		}
711 	}
712 
713 	/* Then do the bidirectional looping */
714 
715 	if (count > 0)
716 		while (count--)
717 		{
718 			if (!cc--)
719 			{
720 				cc = vp->vibrato_control_ratio;
721 				incr = update_vibrato(vp, (incr < 0));
722 			}
723 			RESAMPLATION;
724 			ofs += incr;
725 			if (ofs >= le)
726 			{
727 				/* fold the overshoot back in */
728 				ofs = le - (ofs - le);
729 				incr = -incr;
730 			}
731 			else if (ofs <= ls)
732 			{
733 				ofs = ls + (ls - ofs);
734 				incr = -incr;
735 			}
736 		}
737 
738 	/* Update changed values */
739 	vp->vibrato_control_counter = cc;
740 	vp->sample_increment = incr;
741 	vp->sample_offset = ofs;
742 	return resample_buffer + resample_buffer_offset;
743 }
744 
745 /*********************** portamento versions ***************************/
746 
rs_update_porta(int v)747 int Resampler::rs_update_porta(int v)
748 {
749 	Voice *vp = &player->voice[v];
750 	int32_t d;
751 
752 	d = vp->porta_dpb;
753 	if (vp->porta_pb < 0)
754 	{
755 		if (d > -vp->porta_pb)
756 			d = -vp->porta_pb;
757 	}
758 	else
759 	{
760 		if (d > vp->porta_pb)
761 			d = -vp->porta_pb;
762 		else
763 			d = -d;
764 	}
765 
766 	vp->porta_pb += d;
767 	if (vp->porta_pb == 0)
768 	{
769 		vp->porta_control_ratio = 0;
770 		vp->porta_pb = 0;
771 	}
772 	player->recompute_freq(v);
773 	return vp->porta_control_ratio;
774 }
775 
porta_resample_voice(int v,int32_t * countptr,int mode)776 resample_t *Resampler::porta_resample_voice(int v, int32_t *countptr, int mode)
777 {
778 	Voice *vp = &player->voice[v];
779 	int32_t n = *countptr, i;
780 	resample_t *(Resampler::*resampler)(int, int32_t *, int);
781 	int cc = vp->porta_control_counter;
782 	int loop;
783 
784 	if (vp->vibrato_control_ratio)
785 		resampler = &Resampler::vib_resample_voice;
786 	else
787 		resampler = &Resampler::normal_resample_voice;
788 	if (mode != 1)
789 		loop = 1;
790 	else
791 		loop = 0;
792 
793 	vp->cache = NULL;
794 	resample_buffer_offset = 0;
795 	while (resample_buffer_offset < n)
796 	{
797 		if (cc == 0)
798 		{
799 			if ((cc = rs_update_porta(v)) == 0)
800 			{
801 				i = n - resample_buffer_offset;
802 				(this->*resampler)(v, &i, mode);
803 				resample_buffer_offset += i;
804 				break;
805 			}
806 		}
807 
808 		i = n - resample_buffer_offset;
809 		if (i > cc)
810 			i = cc;
811 		(this->*resampler)(v, &i, mode);
812 		resample_buffer_offset += i;
813 
814 		if (!loop && (i == 0 || vp->status == VOICE_FREE))
815 			break;
816 		cc -= i;
817 	}
818 	*countptr = resample_buffer_offset;
819 	resample_buffer_offset = 0;
820 	vp->porta_control_counter = cc;
821 	return resample_buffer;
822 }
823 
824 /* interface function */
vib_resample_voice(int v,int32_t * countptr,int mode)825 resample_t *Resampler::vib_resample_voice(int v, int32_t *countptr, int mode)
826 {
827 	Voice *vp = &player->voice[v];
828 
829 	vp->cache = NULL;
830 	if (mode == 0)
831 		return rs_vib_loop(vp, *countptr);
832 	if (mode == 1)
833 		return rs_vib_plain(v, countptr);
834 	return rs_vib_bidir(vp, *countptr);
835 }
836 
837 /* interface function */
normal_resample_voice(int v,int32_t * countptr,int mode)838 resample_t *Resampler::normal_resample_voice(int v, int32_t *countptr, int mode)
839 {
840 	Voice *vp = &player->voice[v];
841 	if (mode == 0)
842 		return rs_loop(vp, *countptr);
843 	if (mode == 1)
844 		return rs_plain(v, countptr);
845 	return rs_bidir(vp, *countptr);
846 }
847 
848 /* interface function */
resample_voice(int v,int32_t * countptr)849 resample_t *Resampler::resample_voice(int v, int32_t *countptr)
850 {
851 	Voice *vp = &player->voice[v];
852 	int mode;
853 	resample_t *result;
854 	int32_t i;
855 
856 	if (vp->sample->sample_rate == playback_rate &&
857 		vp->sample->root_freq == get_note_freq(vp->sample, vp->sample->note_to_use) &&
858 		vp->frequency == vp->orig_frequency)
859 	{
860 		int32_t ofs;
861 
862 		/* Pre-resampled data -- just update the offset and check if
863 			we're out of data. */
864 		ofs = (int32_t)(vp->sample_offset >> FRACTION_BITS); /* Kind of silly to use
865 								FRACTION_BITS here... */
866 		if (*countptr >= (int32_t)((vp->sample->data_length >> FRACTION_BITS) - ofs))
867 		{
868 			/* Note finished. Free the voice. */
869 			vp->timeout = 1;
870 
871 			/* Let the caller know how much data we had left */
872 			*countptr = (int32_t)(vp->sample->data_length >> FRACTION_BITS) - ofs;
873 		}
874 		else
875 			vp->sample_offset += *countptr << FRACTION_BITS;
876 
877 		for (i = 0; i < *countptr; i++) {
878 			resample_buffer[i] = vp->sample->data[i + ofs];
879 		}
880 		return resample_buffer;
881 	}
882 
883 	mode = vp->sample->modes;
884 	if ((mode & MODES_LOOPING) &&
885 		((mode & MODES_ENVELOPE) ||
886 		(vp->status & (VOICE_ON | VOICE_SUSTAINED))))
887 	{
888 		if (mode & MODES_PINGPONG)
889 		{
890 			vp->cache = NULL;
891 			mode = 2;	/* Bidir loop */
892 		}
893 		else
894 			mode = 0;	/* loop */
895 	}
896 	else
897 		mode = 1;	/* no loop */
898 
899 	if (vp->porta_control_ratio)
900 		result = porta_resample_voice(v, countptr, mode);
901 	else if (vp->vibrato_control_ratio)
902 		result = vib_resample_voice(v, countptr, mode);
903 	else
904 		result = normal_resample_voice(v, countptr, mode);
905 
906 	return result;
907 }
908 
909 
pre_resample(Sample * sp)910 void pre_resample(Sample * sp)
911 {
912 	double a, b;
913 	splen_t ofs, newlen;
914 	sample_t *newdata, *dest, *src = (sample_t *)sp->data;
915 	int32_t i, count, incr, f, x;
916 	resample_rec_t resrc;
917 
918 	f = get_note_freq(sp, sp->note_to_use);
919 	a = b = ((double)(sp->root_freq) * playback_rate) /
920 		((double)(sp->sample_rate) * f);
921 	if ((int64_t)sp->data_length * a >= 0x7fffffffL)
922 	{
923 		/* Too large to compute */
924 		printMessage(CMSG_INFO, VERB_DEBUG, " *** Can't pre-resampling for note %d",
925 			sp->note_to_use);
926 		return;
927 	}
928 	newlen = (splen_t)(sp->data_length * a);
929 	count = (newlen >> FRACTION_BITS);
930 	ofs = incr = (sp->data_length - 1) / (count - 1);
931 
932 	if ((double)newlen + incr >= 0x7fffffffL)
933 	{
934 		/* Too large to compute */
935 		printMessage(CMSG_INFO, VERB_DEBUG, " *** Can't pre-resampling for note %d",
936 			sp->note_to_use);
937 		return;
938 	}
939 
940 	// [EP] Fix the bad allocation count.
941 	dest = newdata = (sample_t *)safe_malloc(((int32_t)(newlen >> (FRACTION_BITS - 1)) + 2)*sizeof(sample_t));
942 	dest[newlen >> FRACTION_BITS] = 0;
943 
944 	*dest++ = src[0];
945 
946 	resrc.loop_start = 0;
947 	resrc.loop_end = sp->data_length;
948 	resrc.data_length = sp->data_length;
949 
950 	/* Since we're pre-processing and this doesn't have to be done in
951 		real-time, we go ahead and do the higher order interpolation. */
952 	for (i = 1; i < count; i++)
953 	{
954 		x = resample_gauss(src, ofs, &resrc);
955 		*dest++ = (int16_t)((x > 32767) ? 32767 : ((x < -32768) ? -32768 : x));
956 		ofs += incr;
957 	}
958 
959 	sp->data_length = newlen;
960 	sp->loop_start = (splen_t)(sp->loop_start * b);
961 	sp->loop_end = (splen_t)(sp->loop_end * b);
962 	free(sp->data);
963 	sp->data = (sample_t *)newdata;
964 	sp->root_freq = f;
965 	sp->sample_rate = playback_rate;
966 	sp->low_freq = freq_table[0];
967 	sp->high_freq = freq_table[127];
968 }
969 
970 }