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