1 //  ---------------------------------------------------------------------------
2 //  This file is part of reSID, a MOS6581 SID emulator engine.
3 //  Copyright (C) 2004  Dag Lem <resid@nimrod.no>
4 //
5 //  This program is free software; you can redistribute it and/or modify
6 //  it under the terms of the GNU General Public License as published by
7 //  the Free Software Foundation; either version 2 of the License, or
8 //  (at your option) any later version.
9 //
10 //  This program is distributed in the hope that it will be useful,
11 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
12 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 //  GNU General Public License for more details.
14 //
15 //  You should have received a copy of the GNU General Public License
16 //  along with this program; if not, write to the Free Software
17 //  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18 //  ---------------------------------------------------------------------------
19 
20 #include "sid.h"
21 #include <math.h>
22 
23 // Resampling constants.
24 // The error in interpolated lookup is bounded by 1.234/L^2,
25 // while the error in non-interpolated lookup is bounded by
26 // 0.7854/L + 0.4113/L^2, see
27 // http://www-ccrma.stanford.edu/~jos/resample/Choice_Table_Size.html
28 // For a resolution of 16 bits this yields L >= 285 and L >= 51473,
29 // respectively.
30 #define FIR_N 125
31 #define FIR_RES_INTERPOLATE 285
32 #define FIR_RES_FAST 51473
33 #define FIR_SHIFT 15
34 #define RINGSIZE 16384
35 
36 // Fixpoint constants (16.16 bits).
37 #define FIXP_SHIFT 16
38 #define FIXP_MASK 0xffff
39 
40 // ----------------------------------------------------------------------------
41 // Constructor.
42 // ----------------------------------------------------------------------------
SID()43 SID::SID()
44 {
45   // Initialize pointers.
46   sample = 0;
47   fir = 0;
48 
49   voice[0].set_sync_source(&voice[2]);
50   voice[1].set_sync_source(&voice[0]);
51   voice[2].set_sync_source(&voice[1]);
52 
53   set_sampling_parameters(985248, SAMPLE_FAST, 44100);
54 
55   bus_value = 0;
56   bus_value_ttl = 0;
57 
58   ext_in = 0;
59 }
60 
61 
62 // ----------------------------------------------------------------------------
63 // Destructor.
64 // ----------------------------------------------------------------------------
~SID()65 SID::~SID()
66 {
67   delete[] sample;
68   delete[] fir;
69 }
70 
71 
72 // ----------------------------------------------------------------------------
73 // Set chip model.
74 // ----------------------------------------------------------------------------
set_chip_model(chip_model model)75 void SID::set_chip_model(chip_model model)
76 {
77   for (int i = 0; i < 3; i++) {
78     voice[i].set_chip_model(model);
79   }
80 
81   filter.set_chip_model(model);
82   extfilt.set_chip_model(model);
83 }
84 
85 
86 // ----------------------------------------------------------------------------
87 // SID reset.
88 // ----------------------------------------------------------------------------
reset()89 void SID::reset()
90 {
91   for (int i = 0; i < 3; i++) {
92     voice[i].reset();
93   }
94   filter.reset();
95   extfilt.reset();
96 
97   bus_value = 0;
98   bus_value_ttl = 0;
99 }
100 
101 
102 // ----------------------------------------------------------------------------
103 // Write 16-bit sample to audio input.
104 // NB! The caller is responsible for keeping the value within 16 bits.
105 // Note that to mix in an external audio signal, the signal should be
106 // resampled to 1MHz first to avoid sampling noise.
107 // ----------------------------------------------------------------------------
input(int sample)108 void SID::input(int sample)
109 {
110   // Voice outputs are 20 bits. Scale up to match three voices in order
111   // to facilitate simulation of the MOS8580 "digi boost" hardware hack.
112   ext_in = (sample << 4)*3;
113 }
114 
115 // ----------------------------------------------------------------------------
116 // Read sample from audio output.
117 // Both 16-bit and n-bit output is provided.
118 // ----------------------------------------------------------------------------
output()119 int SID::output()
120 {
121   const int range = 1 << 16;
122   const int half = range >> 1;
123   int sample = extfilt.output()/((4095*255 >> 7)*3*15*2/range);
124   if (sample >= half) {
125     return half - 1;
126   }
127   if (sample < -half) {
128     return -half;
129   }
130   return sample;
131 }
132 
output(int bits)133 int SID::output(int bits)
134 {
135   const int range = 1 << bits;
136   const int half = range >> 1;
137   int sample = extfilt.output()/((4095*255 >> 7)*3*15*2/range);
138   if (sample >= half) {
139     return half - 1;
140   }
141   if (sample < -half) {
142     return -half;
143   }
144   return sample;
145 }
146 
147 
148 // ----------------------------------------------------------------------------
149 // Read registers.
150 //
151 // Reading a write only register returns the last byte written to any SID
152 // register. The individual bits in this value start to fade down towards
153 // zero after a few cycles. All bits reach zero within approximately
154 // $2000 - $4000 cycles.
155 // It has been claimed that this fading happens in an orderly fashion, however
156 // sampling of write only registers reveals that this is not the case.
157 // NB! This is not correctly modeled.
158 // The actual use of write only registers has largely been made in the belief
159 // that all SID registers are readable. To support this belief the read
160 // would have to be done immediately after a write to the same register
161 // (remember that an intermediate write to another register would yield that
162 // value instead). With this in mind we return the last value written to
163 // any SID register for $2000 cycles without modeling the bit fading.
164 // ----------------------------------------------------------------------------
read(reg8 offset)165 reg8 SID::read(reg8 offset)
166 {
167   switch (offset) {
168   case 0x19:
169     return potx.readPOT();
170   case 0x1a:
171     return poty.readPOT();
172   case 0x1b:
173     return voice[2].wave.readOSC();
174   case 0x1c:
175     return voice[2].envelope.readENV();
176   default:
177     return bus_value;
178   }
179 }
180 
181 
182 // ----------------------------------------------------------------------------
183 // Write registers.
184 // ----------------------------------------------------------------------------
write(reg8 offset,reg8 value)185 void SID::write(reg8 offset, reg8 value)
186 {
187   bus_value = value;
188   bus_value_ttl = 0x2000;
189 
190   switch (offset) {
191   case 0x00:
192     voice[0].wave.writeFREQ_LO(value);
193     break;
194   case 0x01:
195     voice[0].wave.writeFREQ_HI(value);
196     break;
197   case 0x02:
198     voice[0].wave.writePW_LO(value);
199     break;
200   case 0x03:
201     voice[0].wave.writePW_HI(value);
202     break;
203   case 0x04:
204     voice[0].writeCONTROL_REG(value);
205     break;
206   case 0x05:
207     voice[0].envelope.writeATTACK_DECAY(value);
208     break;
209   case 0x06:
210     voice[0].envelope.writeSUSTAIN_RELEASE(value);
211     break;
212   case 0x07:
213     voice[1].wave.writeFREQ_LO(value);
214     break;
215   case 0x08:
216     voice[1].wave.writeFREQ_HI(value);
217     break;
218   case 0x09:
219     voice[1].wave.writePW_LO(value);
220     break;
221   case 0x0a:
222     voice[1].wave.writePW_HI(value);
223     break;
224   case 0x0b:
225     voice[1].writeCONTROL_REG(value);
226     break;
227   case 0x0c:
228     voice[1].envelope.writeATTACK_DECAY(value);
229     break;
230   case 0x0d:
231     voice[1].envelope.writeSUSTAIN_RELEASE(value);
232     break;
233   case 0x0e:
234     voice[2].wave.writeFREQ_LO(value);
235     break;
236   case 0x0f:
237     voice[2].wave.writeFREQ_HI(value);
238     break;
239   case 0x10:
240     voice[2].wave.writePW_LO(value);
241     break;
242   case 0x11:
243     voice[2].wave.writePW_HI(value);
244     break;
245   case 0x12:
246     voice[2].writeCONTROL_REG(value);
247     break;
248   case 0x13:
249     voice[2].envelope.writeATTACK_DECAY(value);
250     break;
251   case 0x14:
252     voice[2].envelope.writeSUSTAIN_RELEASE(value);
253     break;
254   case 0x15:
255     filter.writeFC_LO(value);
256     break;
257   case 0x16:
258     filter.writeFC_HI(value);
259     break;
260   case 0x17:
261     filter.writeRES_FILT(value);
262     break;
263   case 0x18:
264     filter.writeMODE_VOL(value);
265     break;
266   default:
267     break;
268   }
269 }
270 
271 
272 // ----------------------------------------------------------------------------
273 // Constructor.
274 // ----------------------------------------------------------------------------
State()275 SID::State::State()
276 {
277   int i;
278 
279   for (i = 0; i < 0x20; i++) {
280     sid_register[i] = 0;
281   }
282 
283   bus_value = 0;
284   bus_value_ttl = 0;
285 
286   for (i = 0; i < 3; i++) {
287     accumulator[i] = 0;
288     shift_register[i] = 0x7ffff8;
289     rate_counter[i] = 0;
290     rate_counter_period[i] = 9;
291     exponential_counter[i] = 0;
292     exponential_counter_period[i] = 1;
293     envelope_counter[i] = 0;
294     envelope_state[i] = EnvelopeGenerator::RELEASE;
295     hold_zero[i] = true;
296   }
297 }
298 
299 
300 // ----------------------------------------------------------------------------
301 // Read state.
302 // ----------------------------------------------------------------------------
read_state()303 SID::State SID::read_state()
304 {
305   State state;
306   int i, j;
307 
308   for (i = 0, j = 0; i < 3; i++, j += 7) {
309     WaveformGenerator& wave = voice[i].wave;
310     EnvelopeGenerator& envelope = voice[i].envelope;
311     state.sid_register[j + 0] = wave.freq & 0xff;
312     state.sid_register[j + 1] = wave.freq >> 8;
313     state.sid_register[j + 2] = wave.pw & 0xff;
314     state.sid_register[j + 3] = wave.pw >> 8;
315     state.sid_register[j + 4] =
316       (wave.waveform << 4)
317       | (wave.test ? 0x08 : 0)
318       | (wave.ring_mod ? 0x04 : 0)
319       | (wave.sync ? 0x02 : 0)
320       | (envelope.gate ? 0x01 : 0);
321     state.sid_register[j + 5] = (envelope.attack << 4) | envelope.decay;
322     state.sid_register[j + 6] = (envelope.sustain << 4) | envelope.release;
323   }
324 
325   state.sid_register[j++] = filter.fc & 0x007;
326   state.sid_register[j++] = filter.fc >> 3;
327   state.sid_register[j++] = (filter.res << 4) | filter.filt;
328   state.sid_register[j++] =
329     (filter.voice3off ? 0x80 : 0)
330     | (filter.hp_bp_lp << 4)
331     | filter.vol;
332 
333   // These registers are superfluous, but included for completeness.
334   for (; j < 0x1d; j++) {
335     state.sid_register[j] = read(j);
336   }
337   for (; j < 0x20; j++) {
338     state.sid_register[j] = 0;
339   }
340 
341   state.bus_value = bus_value;
342   state.bus_value_ttl = bus_value_ttl;
343 
344   for (i = 0; i < 3; i++) {
345     state.accumulator[i] = voice[i].wave.accumulator;
346     state.shift_register[i] = voice[i].wave.shift_register;
347     state.rate_counter[i] = voice[i].envelope.rate_counter;
348     state.rate_counter_period[i] = voice[i].envelope.rate_period;
349     state.exponential_counter[i] = voice[i].envelope.exponential_counter;
350     state.exponential_counter_period[i] = voice[i].envelope.exponential_counter_period;
351     state.envelope_counter[i] = voice[i].envelope.envelope_counter;
352     state.envelope_state[i] = voice[i].envelope.state;
353     state.hold_zero[i] = voice[i].envelope.hold_zero;
354   }
355 
356   return state;
357 }
358 
359 
360 // ----------------------------------------------------------------------------
361 // Write state.
362 // ----------------------------------------------------------------------------
write_state(const State & state)363 void SID::write_state(const State& state)
364 {
365   int i;
366 
367   for (i = 0; i <= 0x18; i++) {
368     write(i, state.sid_register[i]);
369   }
370 
371   bus_value = state.bus_value;
372   bus_value_ttl = state.bus_value_ttl;
373 
374   for (i = 0; i < 3; i++) {
375     voice[i].wave.accumulator = state.accumulator[i];
376     voice[i].wave.shift_register = state.shift_register[i];
377     voice[i].envelope.rate_counter = state.rate_counter[i];
378     voice[i].envelope.rate_period = state.rate_counter_period[i];
379     voice[i].envelope.exponential_counter = state.exponential_counter[i];
380     voice[i].envelope.exponential_counter_period = state.exponential_counter_period[i];
381     voice[i].envelope.envelope_counter = state.envelope_counter[i];
382     voice[i].envelope.state = state.envelope_state[i];
383     voice[i].envelope.hold_zero = state.hold_zero[i];
384   }
385 }
386 
387 
388 // ----------------------------------------------------------------------------
389 // Enable filter.
390 // ----------------------------------------------------------------------------
enable_filter(bool enable)391 void SID::enable_filter(bool enable)
392 {
393   filter.enable_filter(enable);
394 }
395 
396 
397 // ----------------------------------------------------------------------------
398 // Enable external filter.
399 // ----------------------------------------------------------------------------
enable_external_filter(bool enable)400 void SID::enable_external_filter(bool enable)
401 {
402   extfilt.enable_filter(enable);
403 }
404 
405 
406 // ----------------------------------------------------------------------------
407 // I0() computes the 0th order modified Bessel function of the first kind.
408 // This function is originally from resample-1.5/filterkit.c by J. O. Smith.
409 // ----------------------------------------------------------------------------
I0(double x)410 double SID::I0(double x)
411 {
412   // Max error acceptable in I0.
413   const double I0e = 1e-6;
414 
415   double sum, u, halfx, temp;
416   int n;
417 
418   sum = u = n = 1;
419   halfx = x/2.0;
420 
421   do {
422     temp = halfx/n++;
423     u *= temp*temp;
424     sum += u;
425   } while (u >= I0e*sum);
426 
427   return sum;
428 }
429 
430 
431 // ----------------------------------------------------------------------------
432 // Setting of SID sampling parameters.
433 //
434 // Use a clock freqency of 985248Hz for PAL C64, 1022730Hz for NTSC C64.
435 // The default end of passband frequency is pass_freq = 0.9*sample_freq/2
436 // for sample frequencies up to ~ 44.1kHz, and 20kHz for higher sample
437 // frequencies.
438 //
439 // For resampling, the ratio between the clock frequency and the sample
440 // frequency is limited as follows:
441 //   125*clock_freq/sample_freq < 16384
442 // E.g. provided a clock frequency of ~ 1MHz, the sample frequency can not
443 // be set lower than ~ 8kHz. A lower sample frequency would make the
444 // resampling code overfill its 16k sample ring buffer.
445 //
446 // The end of passband frequency is also limited:
447 //   pass_freq <= 0.9*sample_freq/2
448 
449 // E.g. for a 44.1kHz sampling rate the end of passband frequency is limited
450 // to slightly below 20kHz. This constraint ensures that the FIR table is
451 // not overfilled.
452 // ----------------------------------------------------------------------------
set_sampling_parameters(double clock_freq,sampling_method method,double sample_freq,double pass_freq,double filter_scale)453 bool SID::set_sampling_parameters(double clock_freq, sampling_method method,
454           double sample_freq, double pass_freq,
455           double filter_scale)
456 {
457   // Check resampling constraints.
458   if (method == SAMPLE_RESAMPLE_INTERPOLATE || method == SAMPLE_RESAMPLE_FAST)
459   {
460     // Check whether the sample ring buffer would overfill.
461     if (FIR_N*clock_freq/sample_freq >= RINGSIZE) {
462       return false;
463     }
464 
465     // The default passband limit is 0.9*sample_freq/2 for sample
466     // frequencies below ~ 44.1kHz, and 20kHz for higher sample frequencies.
467     if (pass_freq < 0) {
468       pass_freq = 20000;
469       if (2*pass_freq/sample_freq >= 0.9) {
470   pass_freq = 0.9*sample_freq/2;
471       }
472     }
473     // Check whether the FIR table would overfill.
474     else if (pass_freq > 0.9*sample_freq/2) {
475       return false;
476     }
477 
478     // The filter scaling is only included to avoid clipping, so keep
479     // it sane.
480     if (filter_scale < 0.9 || filter_scale > 1.0) {
481       return false;
482     }
483   }
484 
485   clock_frequency = clock_freq;
486   sampling = method;
487 
488   cycles_per_sample =
489     cycle_count(clock_freq/sample_freq*(1 << FIXP_SHIFT) + 0.5);
490 
491   sample_offset = 0;
492   sample_prev = 0;
493 
494   // FIR initialization is only necessary for resampling.
495   if (method != SAMPLE_RESAMPLE_INTERPOLATE && method != SAMPLE_RESAMPLE_FAST)
496   {
497     delete[] sample;
498     delete[] fir;
499     sample = 0;
500     fir = 0;
501     return true;
502   }
503 
504   const double pi = 3.1415926535897932385;
505 
506   // 16 bits -> -96dB stopband attenuation.
507   const double A = -20*log10(1.0/(1 << 16));
508   // A fraction of the bandwidth is allocated to the transition band,
509   double dw = (1 - 2*pass_freq/sample_freq)*pi;
510   // The cutoff frequency is midway through the transition band.
511   double wc = (2*pass_freq/sample_freq + 1)*pi/2;
512 
513   // For calculation of beta and N see the reference for the kaiserord
514   // function in the MATLAB Signal Processing Toolbox:
515   // http://www.mathworks.com/access/helpdesk/help/toolbox/signal/kaiserord.html
516   const double beta = 0.1102*(A - 8.7);
517   const double I0beta = I0(beta);
518 
519   // The filter order will maximally be 124 with the current constraints.
520   // N >= (96.33 - 7.95)/(2.285*0.1*pi) -> N >= 123
521   // The filter order is equal to the number of zero crossings, i.e.
522   // it should be an even number (sinc is symmetric about x = 0).
523   int N = int((A - 7.95)/(2.285*dw) + 0.5);
524   N += N & 1;
525 
526   double f_samples_per_cycle = sample_freq/clock_freq;
527   double f_cycles_per_sample = clock_freq/sample_freq;
528 
529   // The filter length is equal to the filter order + 1.
530   // The filter length must be an odd number (sinc is symmetric about x = 0).
531   fir_N = int(N*f_cycles_per_sample) + 1;
532   fir_N |= 1;
533 
534   // We clamp the filter table resolution to 2^n, making the fixpoint
535   // sample_offset a whole multiple of the filter table resolution.
536   int res = method == SAMPLE_RESAMPLE_INTERPOLATE ?
537     FIR_RES_INTERPOLATE : FIR_RES_FAST;
538   int n = (int)ceil(log(res/f_cycles_per_sample)/log(2));
539   fir_RES = 1 << n;
540 
541   // Allocate memory for FIR tables.
542   delete[] fir;
543   fir = new short[fir_N*fir_RES];
544 
545   // Calculate fir_RES FIR tables for linear interpolation.
546   for (int i = 0; i < fir_RES; i++) {
547     int fir_offset = i*fir_N + fir_N/2;
548     double j_offset = double(i)/fir_RES;
549     // Calculate FIR table. This is the sinc function, weighted by the
550     // Kaiser window.
551     for (int j = -fir_N/2; j <= fir_N/2; j++) {
552       double jx = j - j_offset;
553       double wt = wc*jx/f_cycles_per_sample;
554       double temp = jx/(fir_N/2);
555       double Kaiser =
556   fabs(temp) <= 1 ? I0(beta*sqrt(1 - temp*temp))/I0beta : 0;
557       double sincwt =
558   fabs(wt) >= 1e-6 ? sin(wt)/wt : 1;
559       double val =
560   (1 << FIR_SHIFT)*filter_scale*f_samples_per_cycle*wc/pi*sincwt*Kaiser;
561       fir[fir_offset + j] = short(val + 0.5);
562     }
563   }
564 
565   // Allocate sample buffer.
566   if (!sample) {
567     sample = new short[RINGSIZE*2];
568   }
569   // Clear sample buffer.
570   for (int j = 0; j < RINGSIZE*2; j++) {
571     sample[j] = 0;
572   }
573   sample_index = 0;
574 
575   return true;
576 }
577 
578 
579 // ----------------------------------------------------------------------------
580 // Adjustment of SID sampling frequency.
581 //
582 // In some applications, e.g. a C64 emulator, it can be desirable to
583 // synchronize sound with a timer source. This is supported by adjustment of
584 // the SID sampling frequency.
585 //
586 // NB! Adjustment of the sampling frequency may lead to noticeable shifts in
587 // frequency, and should only be used for interactive applications. Note also
588 // that any adjustment of the sampling frequency will change the
589 // characteristics of the resampling filter, since the filter is not rebuilt.
590 // ----------------------------------------------------------------------------
adjust_sampling_frequency(double sample_freq)591 void SID::adjust_sampling_frequency(double sample_freq)
592 {
593   cycles_per_sample =
594     cycle_count(clock_frequency/sample_freq*(1 << FIXP_SHIFT) + 0.5);
595 }
596 
597 
598 // ----------------------------------------------------------------------------
599 // Return array of default spline interpolation points to map FC to
600 // filter cutoff frequency.
601 // ----------------------------------------------------------------------------
fc_default(const fc_point * & points,int & count)602 void SID::fc_default(const fc_point*& points, int& count)
603 {
604   filter.fc_default(points, count);
605 }
606 
607 
608 // ----------------------------------------------------------------------------
609 // Return FC spline plotter object.
610 // ----------------------------------------------------------------------------
fc_plotter()611 PointPlotter<sound_sample> SID::fc_plotter()
612 {
613   return filter.fc_plotter();
614 }
615 
616 
617 // ----------------------------------------------------------------------------
618 // SID clocking - 1 cycle.
619 // ----------------------------------------------------------------------------
clock()620 void SID::clock()
621 {
622   int i;
623 
624   // Age bus value.
625   if (--bus_value_ttl <= 0) {
626     bus_value = 0;
627     bus_value_ttl = 0;
628   }
629 
630   // Clock amplitude modulators.
631   for (i = 0; i < 3; i++) {
632     voice[i].envelope.clock();
633   }
634 
635   // Clock oscillators.
636   for (i = 0; i < 3; i++) {
637     voice[i].wave.clock();
638   }
639 
640   // Synchronize oscillators.
641   for (i = 0; i < 3; i++) {
642     voice[i].wave.synchronize();
643   }
644 
645   // Clock filter.
646   filter.clock(voice[0].output(), voice[1].output(), voice[2].output(), ext_in);
647 
648   // Clock external filter.
649   extfilt.clock(filter.output());
650 }
651 
652 
653 // ----------------------------------------------------------------------------
654 // SID clocking - delta_t cycles.
655 // ----------------------------------------------------------------------------
clock(cycle_count delta_t)656 void SID::clock(cycle_count delta_t)
657 {
658   int i;
659 
660   if (delta_t <= 0) {
661     return;
662   }
663 
664   // Age bus value.
665   bus_value_ttl -= delta_t;
666   if (bus_value_ttl <= 0) {
667     bus_value = 0;
668     bus_value_ttl = 0;
669   }
670 
671   // Clock amplitude modulators.
672   for (i = 0; i < 3; i++) {
673     voice[i].envelope.clock(delta_t);
674   }
675 
676   // Clock and synchronize oscillators.
677   // Loop until we reach the current cycle.
678   cycle_count delta_t_osc = delta_t;
679   while (delta_t_osc) {
680     cycle_count delta_t_min = delta_t_osc;
681 
682     // Find minimum number of cycles to an oscillator accumulator MSB toggle.
683     // We have to clock on each MSB on / MSB off for hard sync to operate
684     // correctly.
685     for (i = 0; i < 3; i++) {
686       WaveformGenerator& wave = voice[i].wave;
687 
688       // It is only necessary to clock on the MSB of an oscillator that is
689       // a sync source and has freq != 0.
690       if (!(wave.sync_dest->sync && wave.freq)) {
691   continue;
692       }
693 
694       reg16 freq = wave.freq;
695       reg24 accumulator = wave.accumulator;
696 
697       // Clock on MSB off if MSB is on, clock on MSB on if MSB is off.
698       reg24 delta_accumulator =
699   (accumulator & 0x800000 ? 0x1000000 : 0x800000) - accumulator;
700 
701       cycle_count delta_t_next = delta_accumulator/freq;
702       if (delta_accumulator%freq) {
703   ++delta_t_next;
704       }
705 
706       if (delta_t_next < delta_t_min) {
707   delta_t_min = delta_t_next;
708       }
709     }
710 
711     // Clock oscillators.
712     for (i = 0; i < 3; i++) {
713       voice[i].wave.clock(delta_t_min);
714     }
715 
716     // Synchronize oscillators.
717     for (i = 0; i < 3; i++) {
718       voice[i].wave.synchronize();
719     }
720 
721     delta_t_osc -= delta_t_min;
722   }
723 
724   // Clock filter.
725   filter.clock(delta_t,
726          voice[0].output(), voice[1].output(), voice[2].output(), ext_in);
727 
728   // Clock external filter.
729   extfilt.clock(delta_t, filter.output());
730 }
731 
732 
733 // ----------------------------------------------------------------------------
734 // SID clocking with audio sampling.
735 // Fixpoint arithmetics is used.
736 //
737 // The example below shows how to clock the SID a specified amount of cycles
738 // while producing audio output:
739 //
740 // while (delta_t) {
741 //   bufindex += sid.clock(delta_t, buf + bufindex, buflength - bufindex);
742 //   write(dsp, buf, bufindex*2);
743 //   bufindex = 0;
744 // }
745 //
746 // ----------------------------------------------------------------------------
clock(cycle_count & delta_t,short * buf,int n,int interleave)747 int SID::clock(cycle_count& delta_t, short* buf, int n, int interleave)
748 {
749   switch (sampling) {
750   default:
751   case SAMPLE_FAST:
752     return clock_fast(delta_t, buf, n, interleave);
753   case SAMPLE_INTERPOLATE:
754     return clock_interpolate(delta_t, buf, n, interleave);
755   case SAMPLE_RESAMPLE_INTERPOLATE:
756     return clock_resample_interpolate(delta_t, buf, n, interleave);
757   case SAMPLE_RESAMPLE_FAST:
758     return clock_resample_fast(delta_t, buf, n, interleave);
759   }
760 }
761 
762 // ----------------------------------------------------------------------------
763 // SID clocking with audio sampling - delta clocking picking nearest sample.
764 // ----------------------------------------------------------------------------
765 RESID_INLINE
clock_fast(cycle_count & delta_t,short * buf,int n,int interleave)766 int SID::clock_fast(cycle_count& delta_t, short* buf, int n,
767         int interleave)
768 {
769   int s = 0;
770 
771   for (;;) {
772     cycle_count next_sample_offset = sample_offset + cycles_per_sample + (1 << (FIXP_SHIFT - 1));
773     cycle_count delta_t_sample = next_sample_offset >> FIXP_SHIFT;
774     if (delta_t_sample > delta_t) {
775       break;
776     }
777     if (s >= n) {
778       return s;
779     }
780     clock(delta_t_sample);
781     delta_t -= delta_t_sample;
782     sample_offset = (next_sample_offset & FIXP_MASK) - (1 << (FIXP_SHIFT - 1));
783     buf[s++*interleave] = output();
784   }
785 
786   clock(delta_t);
787   sample_offset -= delta_t << FIXP_SHIFT;
788   delta_t = 0;
789   return s;
790 }
791 
792 
793 // ----------------------------------------------------------------------------
794 // SID clocking with audio sampling - cycle based with linear sample
795 // interpolation.
796 //
797 // Here the chip is clocked every cycle. This yields higher quality
798 // sound since the samples are linearly interpolated, and since the
799 // external filter attenuates frequencies above 16kHz, thus reducing
800 // sampling noise.
801 // ----------------------------------------------------------------------------
802 RESID_INLINE
clock_interpolate(cycle_count & delta_t,short * buf,int n,int interleave)803 int SID::clock_interpolate(cycle_count& delta_t, short* buf, int n,
804          int interleave)
805 {
806   int s = 0;
807   int i;
808 
809   for (;;) {
810     cycle_count next_sample_offset = sample_offset + cycles_per_sample;
811     cycle_count delta_t_sample = next_sample_offset >> FIXP_SHIFT;
812     if (delta_t_sample > delta_t) {
813       break;
814     }
815     if (s >= n) {
816       return s;
817     }
818     for (i = 0; i < delta_t_sample - 1; i++) {
819       clock();
820     }
821     if (i < delta_t_sample) {
822       sample_prev = output();
823       clock();
824     }
825 
826     delta_t -= delta_t_sample;
827     sample_offset = next_sample_offset & FIXP_MASK;
828 
829     short sample_now = output();
830     buf[s++*interleave] =
831       sample_prev + (sample_offset*(sample_now - sample_prev) >> FIXP_SHIFT);
832     sample_prev = sample_now;
833   }
834 
835   for (i = 0; i < delta_t - 1; i++) {
836     clock();
837   }
838   if (i < delta_t) {
839     sample_prev = output();
840     clock();
841   }
842   sample_offset -= delta_t << FIXP_SHIFT;
843   delta_t = 0;
844   return s;
845 }
846 
847 
848 // ----------------------------------------------------------------------------
849 // SID clocking with audio sampling - cycle based with audio resampling.
850 //
851 // This is the theoretically correct (and computationally intensive) audio
852 // sample generation. The samples are generated by resampling to the specified
853 // sampling frequency. The work rate is inversely proportional to the
854 // percentage of the bandwidth allocated to the filter transition band.
855 //
856 // This implementation is based on the paper "A Flexible Sampling-Rate
857 // Conversion Method", by J. O. Smith and P. Gosset, or rather on the
858 // expanded tutorial on the "Digital Audio Resampling Home Page":
859 // http://www-ccrma.stanford.edu/~jos/resample/
860 //
861 // By building shifted FIR tables with samples according to the
862 // sampling frequency, this implementation dramatically reduces the
863 // computational effort in the filter convolutions, without any loss
864 // of accuracy. The filter convolutions are also vectorizable on
865 // current hardware.
866 //
867 // Further possible optimizations are:
868 // * An equiripple filter design could yield a lower filter order, see
869 //   http://www.mwrf.com/Articles/ArticleID/7229/7229.html
870 // * The Convolution Theorem could be used to bring the complexity of
871 //   convolution down from O(n*n) to O(n*log(n)) using the Fast Fourier
872 //   Transform, see http://en.wikipedia.org/wiki/Convolution_theorem
873 // * Simply resampling in two steps can also yield computational
874 //   savings, since the transition band will be wider in the first step
875 //   and the required filter order is thus lower in this step.
876 //   Laurent Ganier has found the optimal intermediate sampling frequency
877 //   to be (via derivation of sum of two steps):
878 //     2 * pass_freq + sqrt [ 2 * pass_freq * orig_sample_freq
879 //       * (dest_sample_freq - 2 * pass_freq) / dest_sample_freq ]
880 //
881 // NB! the result of right shifting negative numbers is really
882 // implementation dependent in the C++ standard.
883 // ----------------------------------------------------------------------------
884 RESID_INLINE
clock_resample_interpolate(cycle_count & delta_t,short * buf,int n,int interleave)885 int SID::clock_resample_interpolate(cycle_count& delta_t, short* buf, int n,
886             int interleave)
887 {
888   int s = 0;
889 
890   for (;;) {
891     cycle_count next_sample_offset = sample_offset + cycles_per_sample;
892     cycle_count delta_t_sample = next_sample_offset >> FIXP_SHIFT;
893     if (delta_t_sample > delta_t) {
894       break;
895     }
896     if (s >= n) {
897       return s;
898     }
899     for (int i = 0; i < delta_t_sample; i++) {
900       clock();
901       sample[sample_index] = sample[sample_index + RINGSIZE] = output();
902       ++sample_index;
903       sample_index &= 0x3fff;
904     }
905     delta_t -= delta_t_sample;
906     sample_offset = next_sample_offset & FIXP_MASK;
907 
908     int fir_offset = sample_offset*fir_RES >> FIXP_SHIFT;
909     int fir_offset_rmd = sample_offset*fir_RES & FIXP_MASK;
910     short* fir_start = fir + fir_offset*fir_N;
911     short* sample_start = sample + sample_index - fir_N + RINGSIZE;
912 
913     // Convolution with filter impulse response.
914     int v1 = 0;
915     for (int j = 0; j < fir_N; j++) {
916       v1 += sample_start[j]*fir_start[j];
917     }
918 
919     // Use next FIR table, wrap around to first FIR table using
920     // previous sample.
921     if (++fir_offset == fir_RES) {
922       fir_offset = 0;
923       --sample_start;
924     }
925     fir_start = fir + fir_offset*fir_N;
926 
927     // Convolution with filter impulse response.
928     int v2 = 0;
929     for (int j = 0; j < fir_N; j++) {
930       v2 += sample_start[j]*fir_start[j];
931     }
932 
933     // Linear interpolation.
934     // fir_offset_rmd is equal for all samples, it can thus be factorized out:
935     // sum(v1 + rmd*(v2 - v1)) = sum(v1) + rmd*(sum(v2) - sum(v1))
936     int v = v1 + (fir_offset_rmd*(v2 - v1) >> FIXP_SHIFT);
937 
938     v >>= FIR_SHIFT;
939 
940     // Saturated arithmetics to guard against 16 bit sample overflow.
941     const int half = 1 << 15;
942     if (v >= half) {
943       v = half - 1;
944     }
945     else if (v < -half) {
946       v = -half;
947     }
948 
949     buf[s++*interleave] = v;
950   }
951 
952   for (int i = 0; i < delta_t; i++) {
953     clock();
954     sample[sample_index] = sample[sample_index + RINGSIZE] = output();
955     ++sample_index;
956     sample_index &= 0x3fff;
957   }
958   sample_offset -= delta_t << FIXP_SHIFT;
959   delta_t = 0;
960   return s;
961 }
962 
963 
964 // ----------------------------------------------------------------------------
965 // SID clocking with audio sampling - cycle based with audio resampling.
966 // ----------------------------------------------------------------------------
967 RESID_INLINE
clock_resample_fast(cycle_count & delta_t,short * buf,int n,int interleave)968 int SID::clock_resample_fast(cycle_count& delta_t, short* buf, int n,
969            int interleave)
970 {
971   int s = 0;
972 
973   for (;;) {
974     cycle_count next_sample_offset = sample_offset + cycles_per_sample;
975     cycle_count delta_t_sample = next_sample_offset >> FIXP_SHIFT;
976     if (delta_t_sample > delta_t) {
977       break;
978     }
979     if (s >= n) {
980       return s;
981     }
982     for (int i = 0; i < delta_t_sample; i++) {
983       clock();
984       sample[sample_index] = sample[sample_index + RINGSIZE] = output();
985       ++sample_index;
986       sample_index &= 0x3fff;
987     }
988     delta_t -= delta_t_sample;
989     sample_offset = next_sample_offset & FIXP_MASK;
990 
991     int fir_offset = sample_offset*fir_RES >> FIXP_SHIFT;
992     short* fir_start = fir + fir_offset*fir_N;
993     short* sample_start = sample + sample_index - fir_N + RINGSIZE;
994 
995     // Convolution with filter impulse response.
996     int v = 0;
997     for (int j = 0; j < fir_N; j++) {
998       v += sample_start[j]*fir_start[j];
999     }
1000 
1001     v >>= FIR_SHIFT;
1002 
1003     // Saturated arithmetics to guard against 16 bit sample overflow.
1004     const int half = 1 << 15;
1005     if (v >= half) {
1006       v = half - 1;
1007     }
1008     else if (v < -half) {
1009       v = -half;
1010     }
1011 
1012     buf[s++*interleave] = v;
1013   }
1014 
1015   for (int i = 0; i < delta_t; i++) {
1016     clock();
1017     sample[sample_index] = sample[sample_index + RINGSIZE] = output();
1018     ++sample_index;
1019     sample_index &= 0x3fff;
1020   }
1021   sample_offset -= delta_t << FIXP_SHIFT;
1022   delta_t = 0;
1023   return s;
1024 }
1025