1 /* ScummVM - Graphic Adventure Engine
2  *
3  * ScummVM is the legal property of its developers, whose names
4  * are too numerous to list here. Please refer to the COPYRIGHT
5  * file distributed with this source distribution.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20  *
21  */
22 
23 /*
24  *  This file is based on reSID, a MOS6581 SID emulator engine.
25  *  Copyright (C) 2004  Dag Lem <resid@nimrod.no>
26  */
27 
28 #ifndef DISABLE_SID
29 
30 #include "audio/softsynth/sid.h"
31 #include "audio/null.h"
32 
33 namespace Resid {
34 
35 // Fixpoint constants (16.16 bits).
36 const int SID::FIXP_SHIFT = 16;
37 const int SID::FIXP_MASK = 0xffff;
38 
39 /*
40  * WaveformGenerator
41  */
42 
WaveformGenerator()43 WaveformGenerator::WaveformGenerator() {
44 	sync_source = this;
45 
46 	reset();
47 }
48 
set_sync_source(WaveformGenerator * source)49 void WaveformGenerator::set_sync_source(WaveformGenerator* source) {
50 	sync_source = source;
51 	source->sync_dest = this;
52 }
53 
writeFREQ_LO(reg8 freq_lo)54 void WaveformGenerator::writeFREQ_LO(reg8 freq_lo) {
55 	freq = (freq & 0xff00) | (freq_lo & 0x00ff);
56 }
57 
writeFREQ_HI(reg8 freq_hi)58 void WaveformGenerator::writeFREQ_HI(reg8 freq_hi) {
59 	freq = ((freq_hi << 8) & 0xff00) | (freq & 0x00ff);
60 }
61 
writePW_LO(reg8 pw_lo)62 void WaveformGenerator::writePW_LO(reg8 pw_lo) {
63 	pw = (pw & 0xf00) | (pw_lo & 0x0ff);
64 }
65 
writePW_HI(reg8 pw_hi)66 void WaveformGenerator::writePW_HI(reg8 pw_hi) {
67 	pw = ((pw_hi << 8) & 0xf00) | (pw & 0x0ff);
68 }
69 
writeCONTROL_REG(reg8 control)70 void WaveformGenerator::writeCONTROL_REG(reg8 control) {
71 	waveform = (control >> 4) & 0x0f;
72 	ring_mod = control & 0x04;
73 	sync = control & 0x02;
74 
75 	reg8 test_next = control & 0x08;
76 
77 	// Test bit set.
78 	if (test_next) {
79 		accumulator = 0;
80 		shift_register = 0;
81 	}
82 	// Test bit cleared.
83 	else if (test) {
84 		shift_register = 0x7ffff8;
85 	}
86 
87 	test = test_next;
88 
89 	// The gate bit is handled by the EnvelopeGenerator.
90 }
91 
readOSC()92 reg8 WaveformGenerator::readOSC() {
93 	return output() >> 4;
94 }
95 
reset()96 void WaveformGenerator::reset() {
97 	accumulator = 0;
98 	shift_register = 0x7ffff8;
99 	freq = 0;
100 	pw = 0;
101 
102 	test = 0;
103 	ring_mod = 0;
104 	sync = 0;
105 
106 	msb_rising = false;
107 }
108 
updateClock(cycle_count delta_t)109 RESID_INLINE void WaveformGenerator::updateClock(cycle_count delta_t) {
110 	// No operation if test bit is set.
111 	if (test) {
112 		return;
113 	}
114 
115 	reg24 accumulator_prev = accumulator;
116 
117 	// Calculate new accumulator value;
118 	reg24 delta_accumulator = delta_t*freq;
119 	accumulator += delta_accumulator;
120 	accumulator &= 0xffffff;
121 
122 	// Check whether the MSB is set high. This is used for synchronization.
123 	msb_rising = !(accumulator_prev & 0x800000) && (accumulator & 0x800000);
124 
125 	// Shift noise register once for each time accumulator bit 19 is set high.
126 	// Bit 19 is set high each time 2^20 (0x100000) is added to the accumulator.
127 	reg24 shift_period = 0x100000;
128 
129 	while (delta_accumulator) {
130 		if (delta_accumulator < shift_period) {
131 			shift_period = delta_accumulator;
132 			// Determine whether bit 19 is set on the last period.
133 			// NB! Requires two's complement integer.
134 			if (shift_period <= 0x080000) {
135 				// Check for flip from 0 to 1.
136 				if (((accumulator - shift_period) & 0x080000) || !(accumulator & 0x080000))
137 				{
138 					break;
139 				}
140 			}
141 			else {
142 				// Check for flip from 0 (to 1 or via 1 to 0) or from 1 via 0 to 1.
143 				if (((accumulator - shift_period) & 0x080000) && !(accumulator & 0x080000))
144 				{
145 					break;
146 				}
147 			}
148 		}
149 
150 		// Shift the noise/random register.
151 		// NB! The shift is actually delayed 2 cycles, this is not modeled.
152 		reg24 bit0 = ((shift_register >> 22) ^ (shift_register >> 17)) & 0x1;
153 		shift_register <<= 1;
154 		shift_register &= 0x7fffff;
155 		shift_register |= bit0;
156 
157 		delta_accumulator -= shift_period;
158 	}
159 }
160 
161 
162 /**
163  * Synchronize oscillators.
164  * This must be done after all the oscillators have been updateClock()'ed since the
165  * oscillators operate in parallel.
166  * Note that the oscillators must be clocked exactly on the cycle when the
167  * MSB is set high for hard sync to operate correctly. See SID::updateClock().
168  */
synchronize()169 RESID_INLINE void WaveformGenerator::synchronize() {
170 	// A special case occurs when a sync source is synced itself on the same
171 	// cycle as when its MSB is set high. In this case the destination will
172 	// not be synced. This has been verified by sampling OSC3.
173 	if (msb_rising && sync_dest->sync && !(sync && sync_source->msb_rising)) {
174 		sync_dest->accumulator = 0;
175 	}
176 }
177 
178 
179 /*
180  * Output functions
181  */
182 
183 // No waveform: Zero output.
output____()184 RESID_INLINE reg12 WaveformGenerator::output____() {
185 	return 0x000;
186 }
187 
188 // Triangle:
output___T()189 RESID_INLINE reg12 WaveformGenerator::output___T() {
190 	reg24 msb = (ring_mod ? accumulator ^ sync_source->accumulator : accumulator)
191 		& 0x800000;
192 	return ((msb ? ~accumulator : accumulator) >> 11) & 0xfff;
193 }
194 
195 // Sawtooth:
output__S_()196 RESID_INLINE reg12 WaveformGenerator::output__S_() {
197 	return accumulator >> 12;
198 }
199 
200 // Pulse:
output_P__()201 RESID_INLINE reg12 WaveformGenerator::output_P__() {
202 	return (test || (accumulator >> 12) >= pw) ? 0xfff : 0x000;
203 }
204 
205 // Noise:
outputN___()206 RESID_INLINE reg12 WaveformGenerator::outputN___() {
207 	return
208 		((shift_register & 0x400000) >> 11) |
209 		((shift_register & 0x100000) >> 10) |
210 		((shift_register & 0x010000) >> 7) |
211 		((shift_register & 0x002000) >> 5) |
212 		((shift_register & 0x000800) >> 4) |
213 		((shift_register & 0x000080) >> 1) |
214 		((shift_register & 0x000010) << 1) |
215 		((shift_register & 0x000004) << 2);
216 }
217 
218 // Combined waveforms:
219 
output__ST()220 RESID_INLINE reg12 WaveformGenerator::output__ST() {
221 	return wave6581__ST[output__S_()] << 4;
222 }
223 
output_P_T()224 RESID_INLINE reg12 WaveformGenerator::output_P_T() {
225 	return (wave6581_P_T[output___T() >> 1] << 4) & output_P__();
226 }
227 
output_PS_()228 RESID_INLINE reg12 WaveformGenerator::output_PS_() {
229 	return (wave6581_PS_[output__S_()] << 4) & output_P__();
230 }
231 
output_PST()232 RESID_INLINE reg12 WaveformGenerator::output_PST() {
233 	return (wave6581_PST[output__S_()] << 4) & output_P__();
234 }
235 
236 // Combined waveforms including noise:
237 
outputN__T()238 RESID_INLINE reg12 WaveformGenerator::outputN__T() {
239 	return 0;
240 }
241 
outputN_S_()242 RESID_INLINE reg12 WaveformGenerator::outputN_S_() {
243 	return 0;
244 }
245 
outputN_ST()246 RESID_INLINE reg12 WaveformGenerator::outputN_ST() {
247 	return 0;
248 }
249 
outputNP__()250 RESID_INLINE reg12 WaveformGenerator::outputNP__() {
251 	return 0;
252 }
253 
outputNP_T()254 RESID_INLINE reg12 WaveformGenerator::outputNP_T() {
255 	return 0;
256 }
257 
outputNPS_()258 RESID_INLINE reg12 WaveformGenerator::outputNPS_() {
259 	return 0;
260 }
261 
outputNPST()262 RESID_INLINE reg12 WaveformGenerator::outputNPST() {
263 	return 0;
264 }
265 
266 /**
267  * Select one of 16 possible combinations of waveforms.
268  */
output()269 RESID_INLINE reg12 WaveformGenerator::output() {
270 	// It may seem cleaner to use an array of member functions to return
271 	// waveform output; however a switch with inline functions is faster.
272 
273 	switch (waveform) {
274 	default:
275 	case 0x0:
276 		return output____();
277 	case 0x1:
278 		return output___T();
279 	case 0x2:
280 		return output__S_();
281 	case 0x3:
282 		return output__ST();
283 	case 0x4:
284 		return output_P__();
285 	case 0x5:
286 		return output_P_T();
287 	case 0x6:
288 		return output_PS_();
289 	case 0x7:
290 		return output_PST();
291 	case 0x8:
292 		return outputN___();
293 	case 0x9:
294 		return outputN__T();
295 	case 0xa:
296 		return outputN_S_();
297 	case 0xb:
298 		return outputN_ST();
299 	case 0xc:
300 		return outputNP__();
301 	case 0xd:
302 		return outputNP_T();
303 	case 0xe:
304 		return outputNPS_();
305 	case 0xf:
306 		return outputNPST();
307 	}
308 }
309 
310 /*
311  * Our objective is to construct a smooth interpolating single-valued function
312  * y = f(x).
313  * Our approach is to approximate the properties of Catmull-Rom splines for
314  * piecewice cubic polynomials.
315  */
316 
317 /**
318  * Calculation of coefficients.
319  */
cubic_coefficients(double x1,double y1,double x2,double y2,double k1,double k2,double & a,double & b,double & c,double & d)320 inline void cubic_coefficients(double x1, double y1, double x2, double y2,
321 						double k1, double k2,
322 						double& a, double& b, double& c, double& d)
323 {
324 	double dx = x2 - x1, dy = y2 - y1;
325 
326 	a = ((k1 + k2) - 2*dy/dx)/(dx*dx);
327 	b = ((k2 - k1)/dx - 3*(x1 + x2)*a)/2;
328 	c = k1 - (3*x1*a + 2*b)*x1;
329 	d = y1 - ((x1*a + b)*x1 + c)*x1;
330 }
331 
332 /**
333  * Evaluation of cubic polynomial by forward differencing.
334  */
335 template<class PointPlotter>
interpolate_segment(double x1,double y1,double x2,double y2,double k1,double k2,PointPlotter plot,double res)336 inline void interpolate_segment(double x1, double y1, double x2, double y2,
337 								double k1, double k2,
338 								PointPlotter plot, double res)
339 {
340 	double a, b, c, d;
341 	cubic_coefficients(x1, y1, x2, y2, k1, k2, a, b, c, d);
342 
343 	double y = ((a*x1 + b)*x1 + c)*x1 + d;
344 	double dy = (3*a*(x1 + res) + 2*b)*x1*res + ((a*res + b)*res + c)*res;
345 	double d2y = (6*a*(x1 + res) + 2*b)*res*res;
346 	double d3y = 6*a*res*res*res;
347 
348 	// Calculate each point.
349 	for (double x = x1; x <= x2; x += res) {
350 		plot(x, y);
351 		y += dy; dy += d2y; d2y += d3y;
352 	}
353 }
354 
355 template<class PointIter>
x(PointIter p)356 inline double x(PointIter p) {
357 	return (*p)[0];
358 }
359 
360 template<class PointIter>
y(PointIter p)361 inline double y(PointIter p) {
362 	return (*p)[1];
363 }
364 
365 /**
366  * Evaluation of complete interpolating function.
367  * Note that since each curve segment is controlled by four points, the
368  * end points will not be interpolated. If extra control points are not
369  * desirable, the end points can simply be repeated to ensure interpolation.
370  * Note also that points of non-differentiability and discontinuity can be
371  * introduced by repeating points.
372  */
373 template<class PointIter, class PointPlotter>
interpolate(PointIter p0,PointIter pn,PointPlotter plot,double res)374 inline void interpolate(PointIter p0, PointIter pn, PointPlotter plot, double res) {
375 	double k1, k2;
376 
377 	// Set up points for first curve segment.
378 	PointIter p1 = p0; ++p1;
379 	PointIter p2 = p1; ++p2;
380 	PointIter p3 = p2; ++p3;
381 
382 	// Draw each curve segment.
383 	for (; p2 != pn; ++p0, ++p1, ++p2, ++p3) {
384 		// p1 and p2 equal; single point.
385 		if (x(p1) == x(p2)) {
386 			continue;
387 		}
388 		// Both end points repeated; straight line.
389 		if (x(p0) == x(p1) && x(p2) == x(p3)) {
390 			k1 = k2 = (y(p2) - y(p1))/(x(p2) - x(p1));
391 		}
392 		// p0 and p1 equal; use f''(x1) = 0.
393 		else if (x(p0) == x(p1)) {
394 			k2 = (y(p3) - y(p1))/(x(p3) - x(p1));
395 			k1 = (3*(y(p2) - y(p1))/(x(p2) - x(p1)) - k2)/2;
396 		}
397 		// p2 and p3 equal; use f''(x2) = 0.
398 		else if (x(p2) == x(p3)) {
399 			k1 = (y(p2) - y(p0))/(x(p2) - x(p0));
400 			k2 = (3*(y(p2) - y(p1))/(x(p2) - x(p1)) - k1)/2;
401 		}
402 		// Normal curve.
403 		else {
404 			k1 = (y(p2) - y(p0))/(x(p2) - x(p0));
405 			k2 = (y(p3) - y(p1))/(x(p3) - x(p1));
406 		}
407 
408 		interpolate_segment(x(p1), y(p1), x(p2), y(p2), k1, k2, plot, res);
409 	}
410 }
411 
412 /**
413  * Class for plotting integers into an array.
414  */
415 template<class F>
416 class PointPlotter {
417 protected:
418 	F* f;
419 
420 public:
PointPlotter(F * arr)421 	PointPlotter(F* arr) : f(arr) {
422 	}
423 
operator ()(double x,double y)424 	void operator ()(double x, double y) {
425 		// Clamp negative values to zero.
426 		if (y < 0) {
427 			y = 0;
428 		}
429 
430 		f[F(x)] = F(y);
431 	}
432 };
433 
434 fc_point Filter::f0_points_6581[] = {
435 	//  FC      f         FCHI FCLO
436 	// ----------------------------
437 	{    0,   220 },   // 0x00      - repeated end point
438 	{    0,   220 },   // 0x00
439 	{  128,   230 },   // 0x10
440 	{  256,   250 },   // 0x20
441 	{  384,   300 },   // 0x30
442 	{  512,   420 },   // 0x40
443 	{  640,   780 },   // 0x50
444 	{  768,  1600 },   // 0x60
445 	{  832,  2300 },   // 0x68
446 	{  896,  3200 },   // 0x70
447 	{  960,  4300 },   // 0x78
448 	{  992,  5000 },   // 0x7c
449 	{ 1008,  5400 },   // 0x7e
450 	{ 1016,  5700 },   // 0x7f
451 	{ 1023,  6000 },   // 0x7f 0x07
452 	{ 1023,  6000 },   // 0x7f 0x07 - discontinuity
453 	{ 1024,  4600 },   // 0x80      -
454 	{ 1024,  4600 },   // 0x80
455 	{ 1032,  4800 },   // 0x81
456 	{ 1056,  5300 },   // 0x84
457 	{ 1088,  6000 },   // 0x88
458 	{ 1120,  6600 },   // 0x8c
459 	{ 1152,  7200 },   // 0x90
460 	{ 1280,  9500 },   // 0xa0
461 	{ 1408, 12000 },   // 0xb0
462 	{ 1536, 14500 },   // 0xc0
463 	{ 1664, 16000 },   // 0xd0
464 	{ 1792, 17100 },   // 0xe0
465 	{ 1920, 17700 },   // 0xf0
466 	{ 2047, 18000 },   // 0xff 0x07
467 	{ 2047, 18000 }    // 0xff 0x07 - repeated end point
468 };
469 
470 
471 /*
472  * Filter
473  */
474 
Filter()475 Filter::Filter() {
476 	fc = 0;
477 
478 	res = 0;
479 
480 	filt = 0;
481 
482 	voice3off = 0;
483 
484 	hp_bp_lp = 0;
485 
486 	vol = 0;
487 
488 	// State of filter.
489 	Vhp = 0;
490 	Vbp = 0;
491 	Vlp = 0;
492 	Vnf = 0;
493 
494 	enable_filter(true);
495 
496 	// Create mappings from FC to cutoff frequency.
497 	interpolate(f0_points_6581, f0_points_6581
498 		+ sizeof(f0_points_6581)/sizeof(*f0_points_6581) - 1,
499 		PointPlotter<sound_sample>(f0_6581), 1.0);
500 
501 	mixer_DC = (-0xfff*0xff/18) >> 7;
502 
503 	f0 = f0_6581;
504 	f0_points = f0_points_6581;
505 	f0_count = sizeof(f0_points_6581)/sizeof(*f0_points_6581);
506 
507 	set_w0();
508 	set_Q();
509 }
510 
enable_filter(bool enable)511 void Filter::enable_filter(bool enable) {
512 	enabled = enable;
513 }
514 
reset()515 void Filter::reset() {
516 	fc = 0;
517 
518 	res = 0;
519 
520 	filt = 0;
521 
522 	voice3off = 0;
523 
524 	hp_bp_lp = 0;
525 
526 	vol = 0;
527 
528 	// State of filter.
529 	Vhp = 0;
530 	Vbp = 0;
531 	Vlp = 0;
532 	Vnf = 0;
533 
534 	set_w0();
535 	set_Q();
536 }
537 
writeFC_LO(reg8 fc_lo)538 void Filter::writeFC_LO(reg8 fc_lo) {
539 	fc = (fc & 0x7f8) | (fc_lo & 0x007);
540 	set_w0();
541 }
542 
writeFC_HI(reg8 fc_hi)543 void Filter::writeFC_HI(reg8 fc_hi) {
544 	fc = ((fc_hi << 3) & 0x7f8) | (fc & 0x007);
545 	set_w0();
546 }
547 
writeRES_FILT(reg8 res_filt)548 void Filter::writeRES_FILT(reg8 res_filt) {
549 	res = (res_filt >> 4) & 0x0f;
550 	set_Q();
551 
552 	filt = res_filt & 0x0f;
553 }
554 
writeMODE_VOL(reg8 mode_vol)555 void Filter::writeMODE_VOL(reg8 mode_vol) {
556 	voice3off = mode_vol & 0x80;
557 
558 	hp_bp_lp = (mode_vol >> 4) & 0x07;
559 
560 	vol = mode_vol & 0x0f;
561 }
562 
563 // Set filter cutoff frequency.
set_w0()564 void Filter::set_w0() {
565 	const double pi = 3.1415926535897932385;
566 
567 	// Multiply with 1.048576 to facilitate division by 1 000 000 by right-
568 	// shifting 20 times (2 ^ 20 = 1048576).
569 	w0 = static_cast<sound_sample>(2*pi*f0[fc]*1.048576);
570 
571 	// Limit f0 to 16kHz to keep 1 cycle filter stable.
572 	const sound_sample w0_max_1 = static_cast<sound_sample>(2*pi*16000*1.048576);
573 	w0_ceil_1 = w0 <= w0_max_1 ? w0 : w0_max_1;
574 
575 	// Limit f0 to 4kHz to keep delta_t cycle filter stable.
576 	const sound_sample w0_max_dt = static_cast<sound_sample>(2*pi*4000*1.048576);
577 	w0_ceil_dt = w0 <= w0_max_dt ? w0 : w0_max_dt;
578 }
579 
580 // Set filter resonance.
set_Q()581 void Filter::set_Q() {
582 	// Q is controlled linearly by res. Q has approximate range [0.707, 1.7].
583 	// As resonance is increased, the filter must be clocked more often to keep
584 	// stable.
585 
586 	// The coefficient 1024 is dispensed of later by right-shifting 10 times
587 	// (2 ^ 10 = 1024).
588 	_1024_div_Q = static_cast<sound_sample>(1024.0/(0.707 + 1.0*res/0x0f));
589 }
590 
updateClock(cycle_count delta_t,sound_sample voice1,sound_sample voice2,sound_sample voice3)591 RESID_INLINE void Filter::updateClock(cycle_count delta_t,
592 				   sound_sample voice1,
593 				   sound_sample voice2,
594 				   sound_sample voice3)
595 {
596 	// Scale each voice down from 20 to 13 bits.
597 	voice1 >>= 7;
598 	voice2 >>= 7;
599 
600 	// NB! Voice 3 is not silenced by voice3off if it is routed through
601 	// the filter.
602 	if (voice3off && !(filt & 0x04)) {
603 		voice3 = 0;
604 	}
605 	else {
606 		voice3 >>= 7;
607 	}
608 
609 	// Enable filter on/off.
610 	// This is not really part of SID, but is useful for testing.
611 	// On slow CPUs it may be necessary to bypass the filter to lower the CPU
612 	// load.
613 	if (!enabled) {
614 		Vnf = voice1 + voice2 + voice3;
615 		Vhp = Vbp = Vlp = 0;
616 		return;
617 	}
618 
619 	// Route voices into or around filter.
620 	// The code below is expanded to a switch for faster execution.
621 	// (filt1 ? Vi : Vnf) += voice1;
622 	// (filt2 ? Vi : Vnf) += voice2;
623 	// (filt3 ? Vi : Vnf) += voice3;
624 
625 	sound_sample Vi;
626 
627 	switch (filt) {
628 	default:
629 	case 0x0:
630 		Vi = 0;
631 		Vnf = voice1 + voice2 + voice3;
632 		break;
633 	case 0x1:
634 		Vi = voice1;
635 		Vnf = voice2 + voice3;
636 		break;
637 	case 0x2:
638 		Vi = voice2;
639 		Vnf = voice1 + voice3;
640 		break;
641 	case 0x3:
642 		Vi = voice1 + voice2;
643 		Vnf = voice3;
644 		break;
645 	case 0x4:
646 		Vi = voice3;
647 		Vnf = voice1 + voice2;
648 		break;
649 	case 0x5:
650 		Vi = voice1 + voice3;
651 		Vnf = voice2;
652 		break;
653 	case 0x6:
654 		Vi = voice2 + voice3;
655 		Vnf = voice1;
656 		break;
657 	case 0x7:
658 		Vi = voice1 + voice2 + voice3;
659 		Vnf = 0;
660 		break;
661 	case 0x8:
662 		Vi = 0;
663 		Vnf = voice1 + voice2 + voice3;
664 		break;
665 	case 0x9:
666 		Vi = voice1;
667 		Vnf = voice2 + voice3;
668 		break;
669 	case 0xa:
670 		Vi = voice2;
671 		Vnf = voice1 + voice3;
672 		break;
673 	case 0xb:
674 		Vi = voice1 + voice2;
675 		Vnf = voice3;
676 		break;
677 	case 0xc:
678 		Vi = voice3;
679 		Vnf = voice1 + voice2;
680 		break;
681 	case 0xd:
682 		Vi = voice1 + voice3;
683 		Vnf = voice2;
684 		break;
685 	case 0xe:
686 		Vi = voice2 + voice3;
687 		Vnf = voice1;
688 		break;
689 	case 0xf:
690 		Vi = voice1 + voice2 + voice3;
691 		Vnf = 0;
692 		break;
693 	}
694 
695 	// Maximum delta cycles for the filter to work satisfactorily under current
696 	// cutoff frequency and resonance constraints is approximately 8.
697 	cycle_count delta_t_flt = 8;
698 
699 	while (delta_t) {
700 		if (delta_t < delta_t_flt) {
701 			delta_t_flt = delta_t;
702 		}
703 
704 		// delta_t is converted to seconds given a 1MHz clock by dividing
705 		// with 1 000 000. This is done in two operations to avoid integer
706 		// multiplication overflow.
707 
708 		// Calculate filter outputs.
709 		// Vhp = Vbp/Q - Vlp - Vi;
710 		// dVbp = -w0*Vhp*dt;
711 		// dVlp = -w0*Vbp*dt;
712 		sound_sample w0_delta_t = w0_ceil_dt*delta_t_flt >> 6;
713 
714 		sound_sample dVbp = (w0_delta_t*Vhp >> 14);
715 		sound_sample dVlp = (w0_delta_t*Vbp >> 14);
716 		Vbp -= dVbp;
717 		Vlp -= dVlp;
718 		Vhp = (Vbp*_1024_div_Q >> 10) - Vlp - Vi;
719 
720 		delta_t -= delta_t_flt;
721 	}
722 }
723 
output()724 RESID_INLINE sound_sample Filter::output() {
725 	// This is handy for testing.
726 	if (!enabled) {
727 		return (Vnf + mixer_DC)*static_cast<sound_sample>(vol);
728 	}
729 
730 	// Mix highpass, bandpass, and lowpass outputs. The sum is not
731 	// weighted, this can be confirmed by sampling sound output for
732 	// e.g. bandpass, lowpass, and bandpass+lowpass from a SID chip.
733 
734 	// The code below is expanded to a switch for faster execution.
735 	// if (hp) Vf += Vhp;
736 	// if (bp) Vf += Vbp;
737 	// if (lp) Vf += Vlp;
738 
739 	sound_sample Vf;
740 
741 	switch (hp_bp_lp) {
742 	default:
743 	case 0x0:
744 		Vf = 0;
745 		break;
746 	case 0x1:
747 		Vf = Vlp;
748 		break;
749 	case 0x2:
750 		Vf = Vbp;
751 		break;
752 	case 0x3:
753 		Vf = Vlp + Vbp;
754 		break;
755 	case 0x4:
756 		Vf = Vhp;
757 		break;
758 	case 0x5:
759 		Vf = Vlp + Vhp;
760 		break;
761 	case 0x6:
762 		Vf = Vbp + Vhp;
763 		break;
764 	case 0x7:
765 		Vf = Vlp + Vbp + Vhp;
766 		break;
767 	}
768 
769 	// Sum non-filtered and filtered output.
770 	// Multiply the sum with volume.
771 	return (Vnf + Vf + mixer_DC)*static_cast<sound_sample>(vol);
772 }
773 
774 
775 /*
776  * EnvelopeGenerator
777  */
778 
EnvelopeGenerator()779 EnvelopeGenerator::EnvelopeGenerator() {
780 	reset();
781 }
782 
reset()783 void EnvelopeGenerator::reset() {
784 	envelope_counter = 0;
785 
786 	attack = 0;
787 	decay = 0;
788 	sustain = 0;
789 	release = 0;
790 
791 	gate = 0;
792 
793 	rate_counter = 0;
794 	exponential_counter = 0;
795 	exponential_counter_period = 1;
796 
797 	state = RELEASE;
798 	rate_period = rate_counter_period[release];
799 	hold_zero = true;
800 }
801 
802 reg16 EnvelopeGenerator::rate_counter_period[] = {
803 	9,  //   2ms*1.0MHz/256 =     7.81
804 	32,  //   8ms*1.0MHz/256 =    31.25
805 	63,  //  16ms*1.0MHz/256 =    62.50
806 	95,  //  24ms*1.0MHz/256 =    93.75
807 	149,  //  38ms*1.0MHz/256 =   148.44
808 	220,  //  56ms*1.0MHz/256 =   218.75
809 	267,  //  68ms*1.0MHz/256 =   265.63
810 	313,  //  80ms*1.0MHz/256 =   312.50
811 	392,  // 100ms*1.0MHz/256 =   390.63
812 	977,  // 250ms*1.0MHz/256 =   976.56
813 	1954,  // 500ms*1.0MHz/256 =  1953.13
814 	3126,  // 800ms*1.0MHz/256 =  3125.00
815 	3907,  //   1 s*1.0MHz/256 =  3906.25
816 	11720,  //   3 s*1.0MHz/256 = 11718.75
817 	19532,  //   5 s*1.0MHz/256 = 19531.25
818 	31251   //   8 s*1.0MHz/256 = 31250.00
819 };
820 
821 
822 reg8 EnvelopeGenerator::sustain_level[] = {
823 	0x00,
824 	0x11,
825 	0x22,
826 	0x33,
827 	0x44,
828 	0x55,
829 	0x66,
830 	0x77,
831 	0x88,
832 	0x99,
833 	0xaa,
834 	0xbb,
835 	0xcc,
836 	0xdd,
837 	0xee,
838 	0xff,
839 };
840 
writeCONTROL_REG(reg8 control)841 void EnvelopeGenerator::writeCONTROL_REG(reg8 control) {
842 	reg8 gate_next = control & 0x01;
843 
844 	// The rate counter is never reset, thus there will be a delay before the
845 	// envelope counter starts counting up (attack) or down (release).
846 
847 	// Gate bit on: Start attack, decay, sustain.
848 	if (!gate && gate_next) {
849 		state = ATTACK;
850 		rate_period = rate_counter_period[attack];
851 
852 		// Switching to attack state unlocks the zero freeze.
853 		hold_zero = false;
854 	}
855 	// Gate bit off: Start release.
856 	else if (gate && !gate_next) {
857 		state = RELEASE;
858 		rate_period = rate_counter_period[release];
859 	}
860 
861 	gate = gate_next;
862 }
863 
writeATTACK_DECAY(reg8 attack_decay)864 void EnvelopeGenerator::writeATTACK_DECAY(reg8 attack_decay) {
865 	attack = (attack_decay >> 4) & 0x0f;
866 	decay = attack_decay & 0x0f;
867 	if (state == ATTACK) {
868 		rate_period = rate_counter_period[attack];
869 	}
870 	else if (state == DECAY_SUSTAIN) {
871 		rate_period = rate_counter_period[decay];
872 	}
873 }
874 
writeSUSTAIN_RELEASE(reg8 sustain_release)875 void EnvelopeGenerator::writeSUSTAIN_RELEASE(reg8 sustain_release) {
876 	sustain = (sustain_release >> 4) & 0x0f;
877 	release = sustain_release & 0x0f;
878 	if (state == RELEASE) {
879 		rate_period = rate_counter_period[release];
880 	}
881 }
882 
readENV()883 reg8 EnvelopeGenerator::readENV() {
884 	return output();
885 }
886 
updateClock(cycle_count delta_t)887 RESID_INLINE void EnvelopeGenerator::updateClock(cycle_count delta_t) {
888 	// Check for ADSR delay bug.
889 	// If the rate counter comparison value is set below the current value of the
890 	// rate counter, the counter will continue counting up until it wraps around
891 	// to zero at 2^15 = 0x8000, and then count rate_period - 1 before the
892 	// envelope can finally be stepped.
893 	// This has been verified by sampling ENV3.
894 	//
895 
896 	// NB! This requires two's complement integer.
897 	int rate_step = rate_period - rate_counter;
898 	if (rate_step <= 0) {
899 		rate_step += 0x7fff;
900 	}
901 
902 	while (delta_t) {
903 		if (delta_t < rate_step) {
904 			rate_counter += delta_t;
905 			if (rate_counter & 0x8000) {
906 				++rate_counter &= 0x7fff;
907 			}
908 			return;
909 		}
910 
911 		rate_counter = 0;
912 		delta_t -= rate_step;
913 
914 		// The first envelope step in the attack state also resets the exponential
915 		// counter. This has been verified by sampling ENV3.
916 		//
917 		if (state == ATTACK	|| ++exponential_counter == exponential_counter_period)
918 		{
919 			exponential_counter = 0;
920 
921 			// Check whether the envelope counter is frozen at zero.
922 			if (hold_zero) {
923 				rate_step = rate_period;
924 				continue;
925 			}
926 
927 			switch (state) {
928 			case ATTACK:
929 				// The envelope counter can flip from 0xff to 0x00 by changing state to
930 				// release, then to attack. The envelope counter is then frozen at
931 				// zero; to unlock this situation the state must be changed to release,
932 				// then to attack. This has been verified by sampling ENV3.
933 				//
934 				++envelope_counter &= 0xff;
935 				if (envelope_counter == 0xff) {
936 					state = DECAY_SUSTAIN;
937 					rate_period = rate_counter_period[decay];
938 				}
939 				break;
940 			case DECAY_SUSTAIN:
941 				if (envelope_counter != sustain_level[sustain]) {
942 					--envelope_counter;
943 				}
944 				break;
945 			case RELEASE:
946 				// The envelope counter can flip from 0x00 to 0xff by changing state to
947 				// attack, then to release. The envelope counter will then continue
948 				// counting down in the release state.
949 				// This has been verified by sampling ENV3.
950 				// NB! The operation below requires two's complement integer.
951 				//
952 				--envelope_counter &= 0xff;
953 				break;
954 			default:
955 				break;
956 			}
957 
958 			// Check for change of exponential counter period.
959 			switch (envelope_counter) {
960 			case 0xff:
961 				exponential_counter_period = 1;
962 				break;
963 			case 0x5d:
964 				exponential_counter_period = 2;
965 				break;
966 			case 0x36:
967 				exponential_counter_period = 4;
968 				break;
969 			case 0x1a:
970 				exponential_counter_period = 8;
971 				break;
972 			case 0x0e:
973 				exponential_counter_period = 16;
974 				break;
975 			case 0x06:
976 				exponential_counter_period = 30;
977 				break;
978 			case 0x00:
979 				exponential_counter_period = 1;
980 
981 				// When the envelope counter is changed to zero, it is frozen at zero.
982 				// This has been verified by sampling ENV3.
983 				hold_zero = true;
984 				break;
985 			default:
986 				break;
987 			}
988 		}
989 
990 		rate_step = rate_period;
991 	}
992 }
993 
output()994 RESID_INLINE reg8 EnvelopeGenerator::output() {
995 	return envelope_counter;
996 }
997 
998 
999 /*
1000  * ExternalFilter
1001  */
1002 
ExternalFilter()1003 ExternalFilter::ExternalFilter() {
1004 	reset();
1005 	enable_filter(true);
1006 	set_sampling_parameter(15915.6);
1007 	mixer_DC = ((((0x800 - 0x380) + 0x800)*0xff*3 - 0xfff*0xff/18) >> 7)*0x0f;
1008 }
1009 
enable_filter(bool enable)1010 void ExternalFilter::enable_filter(bool enable) {
1011 	enabled = enable;
1012 }
1013 
set_sampling_parameter(double pass_freq)1014 void ExternalFilter::set_sampling_parameter(double pass_freq) {
1015 	static const double pi = 3.1415926535897932385;
1016 
1017 	w0hp = 105;
1018 	w0lp = (sound_sample) (pass_freq * (2.0 * pi * 1.048576));
1019 	if (w0lp > 104858)
1020 		w0lp = 104858;
1021 }
1022 
reset()1023 void ExternalFilter::reset() {
1024 	// State of filter.
1025 	Vlp = 0;
1026 	Vhp = 0;
1027 	Vo = 0;
1028 }
1029 
updateClock(cycle_count delta_t,sound_sample Vi)1030 RESID_INLINE void ExternalFilter::updateClock(cycle_count delta_t, sound_sample Vi) {
1031 	// This is handy for testing.
1032 	if (!enabled) {
1033 		// Remove maximum DC level since there is no filter to do it.
1034 		Vlp = Vhp = 0;
1035 		Vo = Vi - mixer_DC;
1036 		return;
1037 	}
1038 
1039 	// Maximum delta cycles for the external filter to work satisfactorily
1040 	// is approximately 8.
1041 	cycle_count delta_t_flt = 8;
1042 
1043 	while (delta_t) {
1044 		if (delta_t < delta_t_flt) {
1045 			delta_t_flt = delta_t;
1046 		}
1047 
1048 		// delta_t is converted to seconds given a 1MHz clock by dividing
1049 		// with 1 000 000.
1050 
1051 		// Calculate filter outputs.
1052 		// Vo  = Vlp - Vhp;
1053 		// Vlp = Vlp + w0lp*(Vi - Vlp)*delta_t;
1054 		// Vhp = Vhp + w0hp*(Vlp - Vhp)*delta_t;
1055 
1056 		sound_sample dVlp = (w0lp*delta_t_flt >> 8)*(Vi - Vlp) >> 12;
1057 		sound_sample dVhp = w0hp*delta_t_flt*(Vlp - Vhp) >> 20;
1058 		Vo = Vlp - Vhp;
1059 		Vlp += dVlp;
1060 		Vhp += dVhp;
1061 
1062 		delta_t -= delta_t_flt;
1063 	}
1064 }
1065 
output()1066 RESID_INLINE sound_sample ExternalFilter::output() {
1067 	return Vo;
1068 }
1069 
1070 
1071 /*
1072  * Voice
1073  */
1074 
Voice()1075 Voice::Voice() {
1076 	wave_zero = 0x380;
1077 	voice_DC = 0x800*0xff;
1078 }
1079 
set_sync_source(Voice * source)1080 void Voice::set_sync_source(Voice* source) {
1081 	wave.set_sync_source(&source->wave);
1082 }
1083 
writeCONTROL_REG(reg8 control)1084 void Voice::writeCONTROL_REG(reg8 control) {
1085 	wave.writeCONTROL_REG(control);
1086 	envelope.writeCONTROL_REG(control);
1087 }
1088 
reset()1089 void Voice::reset() {
1090 	wave.reset();
1091 	envelope.reset();
1092 }
1093 
1094 
1095 /*
1096  * SID
1097  */
1098 
SID()1099 SID::SID() {
1100 	voice[0].set_sync_source(&voice[2]);
1101 	voice[1].set_sync_source(&voice[0]);
1102 	voice[2].set_sync_source(&voice[1]);
1103 
1104 	set_sampling_parameters(985248, 44100);
1105 
1106 	bus_value = 0;
1107 	bus_value_ttl = 0;
1108 }
1109 
~SID()1110 SID::~SID() {}
1111 
reset()1112 void SID::reset() {
1113 	for (int i = 0; i < 3; i++) {
1114 		voice[i].reset();
1115 	}
1116 	filter.reset();
1117 	extfilt.reset();
1118 
1119 	bus_value = 0;
1120 	bus_value_ttl = 0;
1121 }
1122 
output()1123 int SID::output() {
1124 	const int range = 1 << 16;
1125 	const int half = range >> 1;
1126 	int sample = extfilt.output()/((4095*255 >> 7)*3*15*2/range);
1127 	if (sample >= half) {
1128 		return half - 1;
1129 	}
1130 	if (sample < -half) {
1131 		return -half;
1132 	}
1133 	return sample;
1134 }
1135 
1136 
1137 /**
1138  * Read registers.
1139  *
1140  * Reading a write only register returns the last byte written to any SID
1141  * register. The individual bits in this value start to fade down towards
1142  * zero after a few cycles. All bits reach zero within approximately
1143  * $2000 - $4000 cycles.
1144  * It has been claimed that this fading happens in an orderly fashion, however
1145  * sampling of write only registers reveals that this is not the case.
1146  * NB! This is not correctly modeled.
1147  * The actual use of write only registers has largely been made in the belief
1148  * that all SID registers are readable. To support this belief the read
1149  * would have to be done immediately after a write to the same register
1150  * (remember that an intermediate write to another register would yield that
1151  * value instead). With this in mind we return the last value written to
1152  * any SID register for $2000 cycles without modeling the bit fading.
1153  */
read(reg8 offset)1154 reg8 SID::read(reg8 offset) {
1155 	switch (offset) {
1156 		case 0x19:
1157 		case 0x1a:
1158 			return 0; //readPOT();
1159 		case 0x1b:
1160 			return voice[2].wave.readOSC();
1161 		case 0x1c:
1162 			return voice[2].envelope.readENV();
1163 		default:
1164 			return bus_value;
1165 	}
1166 }
1167 
write(reg8 offset,reg8 value)1168 void SID::write(reg8 offset, reg8 value) {
1169 	bus_value = value;
1170 	bus_value_ttl = 0x2000;
1171 
1172 	switch (offset) {
1173 	  case 0x00:
1174 		  voice[0].wave.writeFREQ_LO(value);
1175 		  break;
1176 	  case 0x01:
1177 		  voice[0].wave.writeFREQ_HI(value);
1178 		  break;
1179 	  case 0x02:
1180 		  voice[0].wave.writePW_LO(value);
1181 		  break;
1182 	  case 0x03:
1183 		  voice[0].wave.writePW_HI(value);
1184 		  break;
1185 	  case 0x04:
1186 		  voice[0].writeCONTROL_REG(value);
1187 		  break;
1188 	  case 0x05:
1189 		  voice[0].envelope.writeATTACK_DECAY(value);
1190 		  break;
1191 	  case 0x06:
1192 		  voice[0].envelope.writeSUSTAIN_RELEASE(value);
1193 		  break;
1194 	  case 0x07:
1195 		  voice[1].wave.writeFREQ_LO(value);
1196 		  break;
1197 	  case 0x08:
1198 		  voice[1].wave.writeFREQ_HI(value);
1199 		  break;
1200 	  case 0x09:
1201 		  voice[1].wave.writePW_LO(value);
1202 		  break;
1203 	  case 0x0a:
1204 		  voice[1].wave.writePW_HI(value);
1205 		  break;
1206 	  case 0x0b:
1207 		  voice[1].writeCONTROL_REG(value);
1208 		  break;
1209 	  case 0x0c:
1210 		  voice[1].envelope.writeATTACK_DECAY(value);
1211 		  break;
1212 	  case 0x0d:
1213 		  voice[1].envelope.writeSUSTAIN_RELEASE(value);
1214 		  break;
1215 	  case 0x0e:
1216 		  voice[2].wave.writeFREQ_LO(value);
1217 		  break;
1218 	  case 0x0f:
1219 		  voice[2].wave.writeFREQ_HI(value);
1220 		  break;
1221 	  case 0x10:
1222 		  voice[2].wave.writePW_LO(value);
1223 		  break;
1224 	  case 0x11:
1225 		  voice[2].wave.writePW_HI(value);
1226 		  break;
1227 	  case 0x12:
1228 		  voice[2].writeCONTROL_REG(value);
1229 		  break;
1230 	  case 0x13:
1231 		  voice[2].envelope.writeATTACK_DECAY(value);
1232 		  break;
1233 	  case 0x14:
1234 		  voice[2].envelope.writeSUSTAIN_RELEASE(value);
1235 		  break;
1236 	  case 0x15:
1237 		  filter.writeFC_LO(value);
1238 		  break;
1239 	  case 0x16:
1240 		  filter.writeFC_HI(value);
1241 		  break;
1242 	  case 0x17:
1243 		  filter.writeRES_FILT(value);
1244 		  break;
1245 	  case 0x18:
1246 		  filter.writeMODE_VOL(value);
1247 		  break;
1248 	  default:
1249 		  break;
1250 	}
1251 }
1252 
enable_filter(bool enable)1253 void SID::enable_filter(bool enable) {
1254 	filter.enable_filter(enable);
1255 }
1256 
enable_external_filter(bool enable)1257 void SID::enable_external_filter(bool enable) {
1258 	extfilt.enable_filter(enable);
1259 }
1260 
1261 
1262 /**
1263  * Setting of SID sampling parameters.
1264  *
1265  * Use a clock freqency of 985248Hz for PAL C64, 1022730Hz for NTSC C64.
1266  * The default end of passband frequency is pass_freq = 0.9*sample_freq/2
1267  * for sample frequencies up to ~ 44.1kHz, and 20kHz for higher sample
1268  * frequencies.
1269  *
1270  * For resampling, the ratio between the clock frequency and the sample
1271  * frequency is limited as follows:
1272  *   125*clock_freq/sample_freq < 16384
1273  * E.g. provided a clock frequency of ~ 1MHz, the sample frequency can not
1274  * be set lower than ~ 8kHz. A lower sample frequency would make the
1275  * resampling code overfill its 16k sample ring buffer.
1276  *
1277  * The end of passband frequency is also limited:
1278  *   pass_freq <= 0.9*sample_freq/2
1279  *
1280  * E.g. for a 44.1kHz sampling rate the end of passband frequency is limited
1281  * to slightly below 20kHz. This constraint ensures that the FIR table is
1282  * not overfilled.
1283  */
set_sampling_parameters(double clock_freq,double sample_freq,double pass_freq,double filter_scale)1284 bool SID::set_sampling_parameters(double clock_freq,
1285 								  double sample_freq, double pass_freq,
1286 								  double filter_scale)
1287 {
1288 	// The default passband limit is 0.9*sample_freq/2 for sample
1289 	// frequencies below ~ 44.1kHz, and 20kHz for higher sample frequencies.
1290 	if (pass_freq < 0) {
1291 		pass_freq = 20000;
1292 		if (2*pass_freq/sample_freq >= 0.9) {
1293 			pass_freq = 0.9*sample_freq/2;
1294 		}
1295 	}
1296 	// Check whether the FIR table would overfill.
1297 	else if (pass_freq > 0.9*sample_freq/2) {
1298 		return false;
1299 	}
1300 
1301 	// The filter scaling is only included to avoid clipping, so keep
1302 	// it sane.
1303 	if (filter_scale < 0.9 || filter_scale > 1.0) {
1304 		return false;
1305 	}
1306 
1307 	// Set the external filter to the pass freq
1308 	extfilt.set_sampling_parameter (pass_freq);
1309 	clock_frequency = clock_freq;
1310 
1311 	cycles_per_sample =
1312 		cycle_count(clock_freq/sample_freq*(1 << FIXP_SHIFT) + 0.5);
1313 
1314 	sample_offset = 0;
1315 	sample_prev = 0;
1316 
1317 	return true;
1318 }
1319 
updateClock(cycle_count delta_t)1320 void SID::updateClock(cycle_count delta_t) {
1321 	int i;
1322 
1323 	if (delta_t <= 0) {
1324 		return;
1325 	}
1326 
1327 	// Age bus value.
1328 	bus_value_ttl -= delta_t;
1329 	if (bus_value_ttl <= 0) {
1330 		bus_value = 0;
1331 		bus_value_ttl = 0;
1332 	}
1333 
1334 	// Clock amplitude modulators.
1335 	for (i = 0; i < 3; i++) {
1336 		voice[i].envelope.updateClock(delta_t);
1337 	}
1338 
1339 	// Clock and synchronize oscillators.
1340 	// Loop until we reach the current cycle.
1341 	cycle_count delta_t_osc = delta_t;
1342 	while (delta_t_osc) {
1343 		cycle_count delta_t_min = delta_t_osc;
1344 
1345 		// Find minimum number of cycles to an oscillator accumulator MSB toggle.
1346 		// We have to clock on each MSB on / MSB off for hard sync to operate
1347 		// correctly.
1348 		for (i = 0; i < 3; i++) {
1349 			WaveformGenerator& wave = voice[i].wave;
1350 
1351 			// It is only necessary to clock on the MSB of an oscillator that is
1352 			// a sync source and has freq != 0.
1353 			if (!(wave.sync_dest->sync && wave.freq)) {
1354 				continue;
1355 			}
1356 
1357 			reg16 freq = wave.freq;
1358 			reg24 accumulator = wave.accumulator;
1359 
1360 			// Clock on MSB off if MSB is on, clock on MSB on if MSB is off.
1361 			reg24 delta_accumulator =
1362 				(accumulator & 0x800000 ? 0x1000000 : 0x800000) - accumulator;
1363 
1364 			cycle_count delta_t_next = delta_accumulator/freq;
1365 			if (delta_accumulator%freq) {
1366 				++delta_t_next;
1367 			}
1368 
1369 			if (delta_t_next < delta_t_min) {
1370 				delta_t_min = delta_t_next;
1371 			}
1372 		}
1373 
1374 		// Clock oscillators.
1375 		for (i = 0; i < 3; i++) {
1376 			voice[i].wave.updateClock(delta_t_min);
1377 		}
1378 
1379 		// Synchronize oscillators.
1380 		for (i = 0; i < 3; i++) {
1381 			voice[i].wave.synchronize();
1382 		}
1383 
1384 		delta_t_osc -= delta_t_min;
1385 	}
1386 
1387 	// Clock filter.
1388 	filter.updateClock(delta_t,
1389 		voice[0].output(), voice[1].output(), voice[2].output());
1390 
1391 	// Clock external filter.
1392 	extfilt.updateClock(delta_t, filter.output());
1393 }
1394 
1395 
1396 /**
1397  * SID clocking with audio sampling.
1398  * Fixpoint arithmetics is used.
1399  */
updateClock(cycle_count & delta_t,short * buf,int n,int interleave)1400 int SID::updateClock(cycle_count& delta_t, short* buf, int n, int interleave) {
1401 	int s = 0;
1402 
1403 	for (;;) {
1404 		cycle_count next_sample_offset = sample_offset + cycles_per_sample + (1 << (FIXP_SHIFT - 1));
1405 		cycle_count delta_t_sample = next_sample_offset >> FIXP_SHIFT;
1406 		if (delta_t_sample > delta_t) {
1407 			break;
1408 		}
1409 		if (s >= n) {
1410 			return s;
1411 		}
1412 		updateClock(delta_t_sample);
1413 		delta_t -= delta_t_sample;
1414 		sample_offset = (next_sample_offset & FIXP_MASK) - (1 << (FIXP_SHIFT - 1));
1415 		buf[s++*interleave] = output();
1416 	}
1417 
1418 	updateClock(delta_t);
1419 	sample_offset -= delta_t << FIXP_SHIFT;
1420 	delta_t = 0;
1421 	return s;
1422 }
1423 
1424 }
1425 
1426 //	Plugin interface
1427 //	(This can only create a null driver since C64 audio support is not part of the
1428 //	midi driver architecture. But we need the plugin for the options menu in the launcher
1429 //	and for MidiDriver::detectDevice() which is more or less used by all engines.)
1430 
1431 class C64MusicPlugin : public NullMusicPlugin {
1432 public:
getName() const1433 	const char *getName() const {
1434 		return _s("C64 Audio emulator");
1435 	}
1436 
getId() const1437 	const char *getId() const {
1438 		return "C64";
1439 	}
1440 
1441 	MusicDevices getDevices() const;
1442 };
1443 
getDevices() const1444 MusicDevices C64MusicPlugin::getDevices() const {
1445 	MusicDevices devices;
1446 	devices.push_back(MusicDevice(this, "", MT_C64));
1447 	return devices;
1448 }
1449 
1450 //#if PLUGIN_ENABLED_DYNAMIC(C64)
1451 	//REGISTER_PLUGIN_DYNAMIC(C64, PLUGIN_TYPE_MUSIC, C64MusicPlugin);
1452 //#else
1453 	REGISTER_PLUGIN_STATIC(C64, PLUGIN_TYPE_MUSIC, C64MusicPlugin);
1454 //#endif
1455 
1456 #endif
1457