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