DOSBox-X
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines
src/hardware/reSID/sid.cpp
00001 //  ---------------------------------------------------------------------------
00002 //  This file is part of reSID, a MOS6581 SID emulator engine.
00003 //  Copyright (C) 2004  Dag Lem <resid@nimrod.no>
00004 //
00005 //  This program is free software; you can redistribute it and/or modify
00006 //  it under the terms of the GNU General Public License as published by
00007 //  the Free Software Foundation; either version 2 of the License, or
00008 //  (at your option) any later version.
00009 //
00010 //  This program is distributed in the hope that it will be useful,
00011 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
00012 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013 //  GNU General Public License for more details.
00014 //
00015 //  You should have received a copy of the GNU General Public License along
00016 //  with this program; if not, write to the Free Software Foundation, Inc.,
00017 //  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00018 //  ---------------------------------------------------------------------------
00019 
00020 #include "sid.h"
00021 #include <math.h>
00022 
00023 // ----------------------------------------------------------------------------
00024 // Constructor.
00025 // ----------------------------------------------------------------------------
00026 SID2::SID2()
00027 {
00028   // Initialize pointers.
00029   sample = 0;
00030   fir = 0;
00031 
00032   voice[0].set_sync_source(&voice[2]);
00033   voice[1].set_sync_source(&voice[0]);
00034   voice[2].set_sync_source(&voice[1]);
00035 
00036   set_sampling_parameters(985248, SAMPLE_FAST, 44100, -1, 0.97);
00037 
00038   bus_value = 0;
00039   bus_value_ttl = 0;
00040 
00041   ext_in = 0;
00042 }
00043 
00044 
00045 // ----------------------------------------------------------------------------
00046 // Destructor.
00047 // ----------------------------------------------------------------------------
00048 SID2::~SID2()
00049 {
00050   delete[] sample;
00051   delete[] fir;
00052 }
00053 
00054 
00055 // ----------------------------------------------------------------------------
00056 // Set chip model.
00057 // ----------------------------------------------------------------------------
00058 void SID2::set_chip_model(chip_model model)
00059 {
00060   for (int i = 0; i < 3; i++) {
00061     voice[i].set_chip_model(model);
00062   }
00063 
00064   filter.set_chip_model(model);
00065   extfilt.set_chip_model(model);
00066 }
00067 
00068 
00069 // ----------------------------------------------------------------------------
00070 // SID reset.
00071 // ----------------------------------------------------------------------------
00072 void SID2::reset()
00073 {
00074   for (int i = 0; i < 3; i++) {
00075     voice[i].reset();
00076   }
00077   filter.reset();
00078   extfilt.reset();
00079 
00080   bus_value = 0;
00081   bus_value_ttl = 0;
00082 }
00083 
00084 
00085 // ----------------------------------------------------------------------------
00086 // Write 16-bit sample to audio input.
00087 // NB! The caller is responsible for keeping the value within 16 bits.
00088 // Note that to mix in an external audio signal, the signal should be
00089 // resampled to 1MHz first to avoid sampling noise.
00090 // ----------------------------------------------------------------------------
00091 void SID2::input(int sample)
00092 {
00093   // Voice outputs are 20 bits. Scale up to match three voices in order
00094   // to facilitate simulation of the MOS8580 "digi boost" hardware hack.
00095   ext_in = (sample << 4)*3;
00096 }
00097 
00098 // ----------------------------------------------------------------------------
00099 // Read sample from audio output.
00100 // Both 16-bit and n-bit output is provided.
00101 // ----------------------------------------------------------------------------
00102 int SID2::output()
00103 {
00104   const int range = 1 << 16;
00105   const int half = range >> 1;
00106   int sample = extfilt.output()/((4095*255 >> 7)*3*15*2/range);
00107   if (sample >= half) {
00108     return half - 1;
00109   }
00110   if (sample < -half) {
00111     return -half;
00112   }
00113   return sample;
00114 }
00115 
00116 int SID2::output(int bits)
00117 {
00118   const int range = 1 << bits;
00119   const int half = range >> 1;
00120   int sample = extfilt.output()/((4095*255 >> 7)*3*15*2/range);
00121   if (sample >= half) {
00122     return half - 1;
00123   }
00124   if (sample < -half) {
00125     return -half;
00126   }
00127   return sample;
00128 }
00129 
00130 
00131 // ----------------------------------------------------------------------------
00132 // Read registers.
00133 //
00134 // Reading a write only register returns the last byte written to any SID
00135 // register. The individual bits in this value start to fade down towards
00136 // zero after a few cycles. All bits reach zero within approximately
00137 // $2000 - $4000 cycles.
00138 // It has been claimed that this fading happens in an orderly fashion, however
00139 // sampling of write only registers reveals that this is not the case.
00140 // NB! This is not correctly modeled.
00141 // The actual use of write only registers has largely been made in the belief
00142 // that all SID registers are readable. To support this belief the read
00143 // would have to be done immediately after a write to the same register
00144 // (remember that an intermediate write to another register would yield that
00145 // value instead). With this in mind we return the last value written to
00146 // any SID register for $2000 cycles without modeling the bit fading.
00147 // ----------------------------------------------------------------------------
00148 reg8 SID2::read(reg8 offset)
00149 {
00150   switch (offset) {
00151   case 0x19:
00152     return potx.readPOT();
00153   case 0x1a:
00154     return poty.readPOT();
00155   case 0x1b:
00156     return voice[2].wave.readOSC();
00157   case 0x1c:
00158     return voice[2].envelope.readENV();
00159   default:
00160     return bus_value;
00161   }
00162 }
00163 
00164 
00165 // ----------------------------------------------------------------------------
00166 // Write registers.
00167 // ----------------------------------------------------------------------------
00168 void SID2::write(reg8 offset, reg8 value)
00169 {
00170   bus_value = value;
00171   bus_value_ttl = 0x2000;
00172 
00173   switch (offset) {
00174   case 0x00:
00175     voice[0].wave.writeFREQ_LO(value);
00176     break;
00177   case 0x01:
00178     voice[0].wave.writeFREQ_HI(value);
00179     break;
00180   case 0x02:
00181     voice[0].wave.writePW_LO(value);
00182     break;
00183   case 0x03:
00184     voice[0].wave.writePW_HI(value);
00185     break;
00186   case 0x04:
00187     voice[0].writeCONTROL_REG(value);
00188     break;
00189   case 0x05:
00190     voice[0].envelope.writeATTACK_DECAY(value);
00191     break;
00192   case 0x06:
00193     voice[0].envelope.writeSUSTAIN_RELEASE(value);
00194     break;
00195   case 0x07:
00196     voice[1].wave.writeFREQ_LO(value);
00197     break;
00198   case 0x08:
00199     voice[1].wave.writeFREQ_HI(value);
00200     break;
00201   case 0x09:
00202     voice[1].wave.writePW_LO(value);
00203     break;
00204   case 0x0a:
00205     voice[1].wave.writePW_HI(value);
00206     break;
00207   case 0x0b:
00208     voice[1].writeCONTROL_REG(value);
00209     break;
00210   case 0x0c:
00211     voice[1].envelope.writeATTACK_DECAY(value);
00212     break;
00213   case 0x0d:
00214     voice[1].envelope.writeSUSTAIN_RELEASE(value);
00215     break;
00216   case 0x0e:
00217     voice[2].wave.writeFREQ_LO(value);
00218     break;
00219   case 0x0f:
00220     voice[2].wave.writeFREQ_HI(value);
00221     break;
00222   case 0x10:
00223     voice[2].wave.writePW_LO(value);
00224     break;
00225   case 0x11:
00226     voice[2].wave.writePW_HI(value);
00227     break;
00228   case 0x12:
00229     voice[2].writeCONTROL_REG(value);
00230     break;
00231   case 0x13:
00232     voice[2].envelope.writeATTACK_DECAY(value);
00233     break;
00234   case 0x14:
00235     voice[2].envelope.writeSUSTAIN_RELEASE(value);
00236     break;
00237   case 0x15:
00238     filter.writeFC_LO(value);
00239     break;
00240   case 0x16:
00241     filter.writeFC_HI(value);
00242     break;
00243   case 0x17:
00244     filter.writeRES_FILT(value);
00245     break;
00246   case 0x18:
00247     filter.writeMODE_VOL(value);
00248     break;
00249   default:
00250     break;
00251   }
00252 }
00253 
00254 
00255 // ----------------------------------------------------------------------------
00256 // Constructor.
00257 // ----------------------------------------------------------------------------
00258 SID2::State::State()
00259 {
00260   int i;
00261 
00262   for (i = 0; i < 0x20; i++) {
00263     sid_register[i] = 0;
00264   }
00265 
00266   bus_value = 0;
00267   bus_value_ttl = 0;
00268 
00269   for (i = 0; i < 3; i++) {
00270     accumulator[i] = 0;
00271     shift_register[i] = 0x7ffff8;
00272     rate_counter[i] = 0;
00273     rate_counter_period[i] = 9;
00274     exponential_counter[i] = 0;
00275     exponential_counter_period[i] = 1;
00276     envelope_counter[i] = 0;
00277     envelope_state[i] = EnvelopeGenerator::RELEASE;
00278     hold_zero[i] = true;
00279   }
00280 }
00281 
00282 
00283 // ----------------------------------------------------------------------------
00284 // Read state.
00285 // ----------------------------------------------------------------------------
00286 SID2::State SID2::read_state()
00287 {
00288   unsigned int i, j;
00289   State state;
00290 
00291   for (i = 0, j = 0; i < 3; i++, j += 7) {
00292     WaveformGenerator& wave = voice[i].wave;
00293     EnvelopeGenerator& envelope = voice[i].envelope;
00294     state.sid_register[j + 0] = wave.freq & 0xff;
00295     state.sid_register[j + 1] = wave.freq >> 8;
00296     state.sid_register[j + 2] = wave.pw & 0xff;
00297     state.sid_register[j + 3] = wave.pw >> 8;
00298     state.sid_register[j + 4] =
00299       (wave.waveform << 4)
00300       | (wave.test ? 0x08 : 0)
00301       | (wave.ring_mod ? 0x04 : 0)
00302       | (wave.sync ? 0x02 : 0)
00303       | (envelope.gate ? 0x01 : 0);
00304     state.sid_register[j + 5] = (envelope.attack << 4) | envelope.decay;
00305     state.sid_register[j + 6] = (envelope.sustain << 4) | envelope.release;
00306   }
00307 
00308   state.sid_register[j++] = filter.fc & 0x007;
00309   state.sid_register[j++] = filter.fc >> 3;
00310   state.sid_register[j++] = (filter.res << 4) | filter.filt;
00311   state.sid_register[j++] =
00312     (filter.voice3off ? 0x80 : 0)
00313     | (filter.hp_bp_lp << 4)
00314     | filter.vol;
00315 
00316   // These registers are superfluous, but included for completeness.
00317   for (; j < 0x1d; j++) {
00318     state.sid_register[j] = read(j);
00319   }
00320   for (; j < 0x20; j++) {
00321     state.sid_register[j] = 0;
00322   }
00323 
00324   state.bus_value = bus_value;
00325   state.bus_value_ttl = bus_value_ttl;
00326 
00327   for (i = 0; i < 3; i++) {
00328     state.accumulator[i] = voice[i].wave.accumulator;
00329     state.shift_register[i] = voice[i].wave.shift_register;
00330     state.rate_counter[i] = voice[i].envelope.rate_counter;
00331     state.rate_counter_period[i] = voice[i].envelope.rate_period;
00332     state.exponential_counter[i] = voice[i].envelope.exponential_counter;
00333     state.exponential_counter_period[i] = voice[i].envelope.exponential_counter_period;
00334     state.envelope_counter[i] = voice[i].envelope.envelope_counter;
00335     state.envelope_state[i] = voice[i].envelope.state;
00336     state.hold_zero[i] = voice[i].envelope.hold_zero;
00337   }
00338 
00339   return state;
00340 }
00341 
00342 
00343 // ----------------------------------------------------------------------------
00344 // Write state.
00345 // ----------------------------------------------------------------------------
00346 void SID2::write_state(const State& state)
00347 {
00348   unsigned int i;
00349 
00350   for (i = 0; i <= 0x18; i++) {
00351     write(i, (unsigned char)state.sid_register[i]);
00352   }
00353 
00354   bus_value = state.bus_value;
00355   bus_value_ttl = state.bus_value_ttl;
00356 
00357   for (i = 0; i < 3; i++) {
00358     voice[i].wave.accumulator = state.accumulator[i];
00359     voice[i].wave.shift_register = state.shift_register[i];
00360     voice[i].envelope.rate_counter = state.rate_counter[i];
00361     voice[i].envelope.rate_period = state.rate_counter_period[i];
00362     voice[i].envelope.exponential_counter = state.exponential_counter[i];
00363     voice[i].envelope.exponential_counter_period = state.exponential_counter_period[i];
00364     voice[i].envelope.envelope_counter = state.envelope_counter[i];
00365     voice[i].envelope.state = state.envelope_state[i];
00366     voice[i].envelope.hold_zero = state.hold_zero[i];
00367   }
00368 }
00369 
00370 
00371 // ----------------------------------------------------------------------------
00372 // Enable filter.
00373 // ----------------------------------------------------------------------------
00374 void SID2::enable_filter(bool enable)
00375 {
00376   filter.enable_filter(enable);
00377 }
00378 
00379 
00380 // ----------------------------------------------------------------------------
00381 // Enable external filter.
00382 // ----------------------------------------------------------------------------
00383 void SID2::enable_external_filter(bool enable)
00384 {
00385   extfilt.enable_filter(enable);
00386 }
00387 
00388 
00389 // ----------------------------------------------------------------------------
00390 // I0() computes the 0th order modified Bessel function of the first kind.
00391 // This function is originally from resample-1.5/filterkit.c by J. O. Smith.
00392 // ----------------------------------------------------------------------------
00393 double SID2::I0(double x)
00394 {
00395   // Max error acceptable in I0.
00396   const double I0e = 1e-6;
00397 
00398   double sum, u, halfx;
00399   int n;
00400 
00401   sum = u = n = 1;
00402   halfx = x/2.0;
00403 
00404   do {
00405     double temp = halfx/n++;
00406     u *= temp*temp;
00407     sum += u;
00408   } while (u >= I0e*sum);
00409 
00410   return sum;
00411 }
00412 
00413 
00414 // ----------------------------------------------------------------------------
00415 // Setting of SID sampling parameters.
00416 //
00417 // Use a clock freqency of 985248Hz for PAL C64, 1022730Hz for NTSC C64.
00418 // The default end of passband frequency is pass_freq = 0.9*sample_freq/2
00419 // for sample frequencies up to ~ 44.1kHz, and 20kHz for higher sample
00420 // frequencies.
00421 //
00422 // For resampling, the ratio between the clock frequency and the sample
00423 // frequency is limited as follows:
00424 //   125*clock_freq/sample_freq < 16384
00425 // E.g. provided a clock frequency of ~ 1MHz, the sample frequency can not
00426 // be set lower than ~ 8kHz. A lower sample frequency would make the
00427 // resampling code overfill its 16k sample ring buffer.
00428 // 
00429 // The end of passband frequency is also limited:
00430 //   pass_freq <= 0.9*sample_freq/2
00431 
00432 // E.g. for a 44.1kHz sampling rate the end of passband frequency is limited
00433 // to slightly below 20kHz. This constraint ensures that the FIR table is
00434 // not overfilled.
00435 // ----------------------------------------------------------------------------
00436 bool SID2::set_sampling_parameters(double clock_freq, sampling_method method,
00437                                   double sample_freq, double pass_freq,
00438                                   double filter_scale)
00439 {
00440   // Check resampling constraints.
00441   if (method == SAMPLE_RESAMPLE_INTERPOLATE || method == SAMPLE_RESAMPLE_FAST)
00442   {
00443     // Check whether the sample ring buffer would overfill.
00444     if (FIR_N*clock_freq/sample_freq >= RINGSIZE) {
00445       return false;
00446     }
00447 
00448     // The default passband limit is 0.9*sample_freq/2 for sample
00449     // frequencies below ~ 44.1kHz, and 20kHz for higher sample frequencies.
00450     if (pass_freq < 0) {
00451       pass_freq = 20000;
00452       if (2*pass_freq/sample_freq >= 0.9) {
00453         pass_freq = 0.9*sample_freq/2;
00454       }
00455     }
00456     // Check whether the FIR table would overfill.
00457     else if (pass_freq > 0.9*sample_freq/2) {
00458       return false;
00459     }
00460 
00461     // The filter scaling is only included to avoid clipping, so keep
00462     // it sane.
00463     if (filter_scale < 0.9 || filter_scale > 1.0) {
00464       return false;
00465     }
00466   }
00467 
00468   clock_frequency = clock_freq;
00469   sampling = method;
00470 
00471   cycles_per_sample =
00472     cycle_count(clock_freq/sample_freq*(1 << FIXP_SHIFT) + 0.5);
00473 
00474   sample_offset = 0;
00475   sample_prev = 0;
00476 
00477   // FIR initialization is only necessary for resampling.
00478   if (method != SAMPLE_RESAMPLE_INTERPOLATE && method != SAMPLE_RESAMPLE_FAST)
00479   {
00480     delete[] sample;
00481     delete[] fir;
00482     sample = 0;
00483     fir = 0;
00484     return true;
00485   }
00486 
00487   const double pi = 3.1415926535897932385;
00488 
00489   // 16 bits -> -96dB stopband attenuation.
00490   const double A = -20*log10(1.0/(1 << 16));
00491   // A fraction of the bandwidth is allocated to the transition band,
00492   double dw = (1 - 2*pass_freq/sample_freq)*pi;
00493   // The cutoff frequency is midway through the transition band.
00494   double wc = (2*pass_freq/sample_freq + 1)*pi/2;
00495 
00496   // For calculation of beta and N see the reference for the kaiserord
00497   // function in the MATLAB Signal Processing Toolbox:
00498   // http://www.mathworks.com/access/helpdesk/help/toolbox/signal/kaiserord.html
00499   const double beta = 0.1102*(A - 8.7);
00500   const double I0beta = I0(beta);
00501 
00502   // The filter order will maximally be 124 with the current constraints.
00503   // N >= (96.33 - 7.95)/(2.285*0.1*pi) -> N >= 123
00504   // The filter order is equal to the number of zero crossings, i.e.
00505   // it should be an even number (sinc is symmetric about x = 0).
00506   int N = int((A - 7.95)/(2.285*dw) + 0.5);
00507   N += N & 1;
00508 
00509   double f_samples_per_cycle = sample_freq/clock_freq;
00510   double f_cycles_per_sample = clock_freq/sample_freq;
00511 
00512   // The filter length is equal to the filter order + 1.
00513   // The filter length must be an odd number (sinc is symmetric about x = 0).
00514   fir_N = int(N*f_cycles_per_sample) + 1;
00515   fir_N |= 1;
00516 
00517   // We clamp the filter table resolution to 2^n, making the fixpoint
00518   // sample_offset a whole multiple of the filter table resolution.
00519   int res = method == SAMPLE_RESAMPLE_INTERPOLATE ?
00520     FIR_RES_INTERPOLATE : FIR_RES_FAST;
00521   int n = (int)ceil(log(res/f_cycles_per_sample)/log(2.));
00522   fir_RES = 1 << n;
00523 
00524   // Allocate memory for FIR tables.
00525   delete[] fir;
00526   fir = new short[fir_N*fir_RES];
00527 
00528   // Calculate fir_RES FIR tables for linear interpolation.
00529   for (int i = 0; i < fir_RES; i++) {
00530     int fir_offset = i*fir_N + fir_N/2;
00531     double j_offset = double(i)/fir_RES;
00532     // Calculate FIR table. This is the sinc function, weighted by the
00533     // Kaiser window.
00534     for (int j = -fir_N/2; j <= fir_N/2; j++) {
00535       double jx = j - j_offset;
00536       double wt = wc*jx/f_cycles_per_sample;
00537       double temp = jx/(fir_N/2);
00538       double Kaiser =
00539         fabs(temp) <= 1 ? I0(beta*sqrt(1 - temp*temp))/I0beta : 0;
00540       double sincwt =
00541         fabs(wt) >= 1e-6 ? sin(wt)/wt : 1;
00542       double val =
00543         (1 << FIR_SHIFT)*filter_scale*f_samples_per_cycle*wc/pi*sincwt*Kaiser;
00544       fir[fir_offset + j] = short(val + 0.5);
00545     }
00546   }
00547 
00548   // Allocate sample buffer.
00549   if (!sample) {
00550     sample = new short[RINGSIZE*2];
00551   }
00552   // Clear sample buffer.
00553   for (int j = 0; j < RINGSIZE*2; j++) {
00554     sample[j] = 0;
00555   }
00556   sample_index = 0;
00557 
00558   return true;
00559 }
00560 
00561 
00562 // ----------------------------------------------------------------------------
00563 // Adjustment of SID sampling frequency.
00564 //
00565 // In some applications, e.g. a C64 emulator, it can be desirable to
00566 // synchronize sound with a timer source. This is supported by adjustment of
00567 // the SID sampling frequency.
00568 //
00569 // NB! Adjustment of the sampling frequency may lead to noticeable shifts in
00570 // frequency, and should only be used for interactive applications. Note also
00571 // that any adjustment of the sampling frequency will change the
00572 // characteristics of the resampling filter, since the filter is not rebuilt.
00573 // ----------------------------------------------------------------------------
00574 void SID2::adjust_sampling_frequency(double sample_freq)
00575 {
00576   cycles_per_sample =
00577     cycle_count(clock_frequency/sample_freq*(1 << FIXP_SHIFT) + 0.5);
00578 }
00579 
00580 
00581 // ----------------------------------------------------------------------------
00582 // Return array of default spline interpolation points to map FC to
00583 // filter cutoff frequency.
00584 // ----------------------------------------------------------------------------
00585 void SID2::fc_default(const fc_point*& points, int& count)
00586 {
00587   filter.fc_default(points, count);
00588 }
00589 
00590 
00591 // ----------------------------------------------------------------------------
00592 // Return FC spline plotter object.
00593 // ----------------------------------------------------------------------------
00594 PointPlotter<sound_sample> SID2::fc_plotter()
00595 {
00596   return filter.fc_plotter();
00597 }
00598 
00599 
00600 // ----------------------------------------------------------------------------
00601 // SID clocking - 1 cycle.
00602 // ----------------------------------------------------------------------------
00603 void SID2::clock()
00604 {
00605   int i;
00606 
00607   // Age bus value.
00608   if (--bus_value_ttl <= 0) {
00609     bus_value = 0;
00610     bus_value_ttl = 0;
00611   }
00612 
00613   // Clock amplitude modulators.
00614   for (i = 0; i < 3; i++) {
00615     voice[i].envelope.clock();
00616   }
00617 
00618   // Clock oscillators.
00619   for (i = 0; i < 3; i++) {
00620     voice[i].wave.clock();
00621   }
00622 
00623   // Synchronize oscillators.
00624   for (i = 0; i < 3; i++) {
00625     voice[i].wave.synchronize();
00626   }
00627 
00628   // Clock filter.
00629   filter.clock(voice[0].output(), voice[1].output(), voice[2].output(), ext_in);
00630 
00631   // Clock external filter.
00632   extfilt.clock(filter.output());
00633 }
00634 
00635 
00636 // ----------------------------------------------------------------------------
00637 // SID clocking - delta_t cycles.
00638 // ----------------------------------------------------------------------------
00639 void SID2::clock(cycle_count delta_t)
00640 {
00641   int i;
00642 
00643   if (delta_t <= 0) {
00644     return;
00645   }
00646 
00647   // Age bus value.
00648   bus_value_ttl -= delta_t;
00649   if (bus_value_ttl <= 0) {
00650     bus_value = 0;
00651     bus_value_ttl = 0;
00652   }
00653 
00654   // Clock amplitude modulators.
00655   for (i = 0; i < 3; i++) {
00656     voice[i].envelope.clock(delta_t);
00657   }
00658 
00659   // Clock and synchronize oscillators.
00660   // Loop until we reach the current cycle.
00661   cycle_count delta_t_osc = delta_t;
00662   while (delta_t_osc) {
00663     cycle_count delta_t_min = delta_t_osc;
00664 
00665     // Find minimum number of cycles to an oscillator accumulator MSB toggle.
00666     // We have to clock on each MSB on / MSB off for hard sync to operate
00667     // correctly.
00668     for (i = 0; i < 3; i++) {
00669       WaveformGenerator& wave = voice[i].wave;
00670 
00671       // It is only necessary to clock on the MSB of an oscillator that is
00672       // a sync source and has freq != 0.
00673       if (!(wave.sync_dest->sync && wave.freq)) {
00674         continue;
00675       }
00676 
00677       reg16 freq = wave.freq;
00678       reg24 accumulator = wave.accumulator;
00679 
00680       // Clock on MSB off if MSB is on, clock on MSB on if MSB is off.
00681       reg24 delta_accumulator =
00682         ((accumulator & 0x800000) ? 0x1000000 : 0x800000) - accumulator;
00683 
00684       cycle_count delta_t_next = (cycle_count)((unsigned int)delta_accumulator / (unsigned int)freq);
00685       if (delta_accumulator%freq) {
00686         ++delta_t_next;
00687       }
00688 
00689       if (delta_t_next < delta_t_min) {
00690         delta_t_min = delta_t_next;
00691       }
00692     }
00693 
00694     // Clock oscillators.
00695     for (i = 0; i < 3; i++) {
00696       voice[i].wave.clock(delta_t_min);
00697     }
00698 
00699     // Synchronize oscillators.
00700     for (i = 0; i < 3; i++) {
00701       voice[i].wave.synchronize();
00702     }
00703 
00704     delta_t_osc -= delta_t_min;
00705   }
00706 
00707   // Clock filter.
00708   filter.clock(delta_t,
00709                voice[0].output(), voice[1].output(), voice[2].output(), ext_in);
00710 
00711   // Clock external filter.
00712   extfilt.clock(delta_t, filter.output());
00713 }
00714 
00715 
00716 // ----------------------------------------------------------------------------
00717 // SID clocking with audio sampling.
00718 // Fixpoint arithmetics is used.
00719 //
00720 // The example below shows how to clock the SID a specified amount of cycles
00721 // while producing audio output:
00722 //
00723 // while (delta_t) {
00724 //   bufindex += sid.clock(delta_t, buf + bufindex, buflength - bufindex);
00725 //   write(dsp, buf, bufindex*2);
00726 //   bufindex = 0;
00727 // }
00728 // 
00729 // ----------------------------------------------------------------------------
00730 int SID2::clock(cycle_count& delta_t, short* buf, int n, int interleave)
00731 {
00732   switch (sampling) {
00733   default:
00734   case SAMPLE_FAST:
00735     return clock_fast(delta_t, buf, n, interleave);
00736   case SAMPLE_INTERPOLATE:
00737     return clock_interpolate(delta_t, buf, n, interleave);
00738   case SAMPLE_RESAMPLE_INTERPOLATE:
00739     return clock_resample_interpolate(delta_t, buf, n, interleave);
00740   case SAMPLE_RESAMPLE_FAST:
00741     return clock_resample_fast(delta_t, buf, n, interleave);
00742   }
00743 }
00744 
00745 // ----------------------------------------------------------------------------
00746 // SID clocking with audio sampling - delta clocking picking nearest sample.
00747 // ----------------------------------------------------------------------------
00748 RESID_INLINE
00749 int SID2::clock_fast(cycle_count& delta_t, short* buf, int n,
00750                     int interleave)
00751 {
00752   int s = 0;
00753 
00754   for (;;) {
00755     cycle_count next_sample_offset = sample_offset + cycles_per_sample + (1 << (FIXP_SHIFT - 1));
00756     cycle_count delta_t_sample = next_sample_offset >> FIXP_SHIFT;
00757     if (delta_t_sample > delta_t) {
00758       break;
00759     }
00760     if (s >= n) {
00761       return s;
00762     }
00763     clock(delta_t_sample);
00764     delta_t -= delta_t_sample;
00765     sample_offset = (next_sample_offset & FIXP_MASK) - (1 << (FIXP_SHIFT - 1));
00766     buf[s++*interleave] = output();
00767   }
00768 
00769   clock(delta_t);
00770   sample_offset -= delta_t << FIXP_SHIFT;
00771   delta_t = 0;
00772   return s;
00773 }
00774 
00775 
00776 // ----------------------------------------------------------------------------
00777 // SID clocking with audio sampling - cycle based with linear sample
00778 // interpolation.
00779 //
00780 // Here the chip is clocked every cycle. This yields higher quality
00781 // sound since the samples are linearly interpolated, and since the
00782 // external filter attenuates frequencies above 16kHz, thus reducing
00783 // sampling noise.
00784 // ----------------------------------------------------------------------------
00785 RESID_INLINE
00786 int SID2::clock_interpolate(cycle_count& delta_t, short* buf, int n,
00787                            int interleave)
00788 {
00789   int s = 0;
00790   int i;
00791 
00792   for (;;) {
00793     cycle_count next_sample_offset = sample_offset + cycles_per_sample;
00794     cycle_count delta_t_sample = next_sample_offset >> FIXP_SHIFT;
00795     if (delta_t_sample > delta_t) {
00796       break;
00797     }
00798     if (s >= n) {
00799       return s;
00800     }
00801     for (i = 0; i < delta_t_sample - 1; i++) {
00802       clock();
00803     }
00804     if (i < delta_t_sample) {
00805       sample_prev = output();
00806       clock();
00807     }
00808 
00809     delta_t -= delta_t_sample;
00810     sample_offset = next_sample_offset & FIXP_MASK;
00811 
00812     short sample_now = output();
00813     buf[s++*interleave] =
00814       sample_prev + (sample_offset*(sample_now - sample_prev) >> FIXP_SHIFT);
00815     sample_prev = sample_now;
00816   }
00817 
00818   for (i = 0; i < delta_t - 1; i++) {
00819     clock();
00820   }
00821   if (i < delta_t) {
00822     sample_prev = output();
00823     clock();
00824   }
00825   sample_offset -= delta_t << FIXP_SHIFT;
00826   delta_t = 0;
00827   return s;
00828 }
00829 
00830 
00831 // ----------------------------------------------------------------------------
00832 // SID clocking with audio sampling - cycle based with audio resampling.
00833 //
00834 // This is the theoretically correct (and computationally intensive) audio
00835 // sample generation. The samples are generated by resampling to the specified
00836 // sampling frequency. The work rate is inversely proportional to the
00837 // percentage of the bandwidth allocated to the filter transition band.
00838 //
00839 // This implementation is based on the paper "A Flexible Sampling-Rate
00840 // Conversion Method", by J. O. Smith and P. Gosset, or rather on the
00841 // expanded tutorial on the "Digital Audio Resampling Home Page":
00842 // http://www-ccrma.stanford.edu/~jos/resample/
00843 //
00844 // By building shifted FIR tables with samples according to the
00845 // sampling frequency, this implementation dramatically reduces the
00846 // computational effort in the filter convolutions, without any loss
00847 // of accuracy. The filter convolutions are also vectorizable on
00848 // current hardware.
00849 //
00850 // Further possible optimizations are:
00851 // * An equiripple filter design could yield a lower filter order, see
00852 //   http://www.mwrf.com/Articles/ArticleID/7229/7229.html
00853 // * The Convolution Theorem could be used to bring the complexity of
00854 //   convolution down from O(n*n) to O(n*log(n)) using the Fast Fourier
00855 //   Transform, see http://en.wikipedia.org/wiki/Convolution_theorem
00856 // * Simply resampling in two steps can also yield computational
00857 //   savings, since the transition band will be wider in the first step
00858 //   and the required filter order is thus lower in this step.
00859 //   Laurent Ganier has found the optimal intermediate sampling frequency
00860 //   to be (via derivation of sum of two steps):
00861 //     2 * pass_freq + sqrt [ 2 * pass_freq * orig_sample_freq
00862 //       * (dest_sample_freq - 2 * pass_freq) / dest_sample_freq ]
00863 //
00864 // NB! the result of right shifting negative numbers is really
00865 // implementation dependent in the C++ standard.
00866 // ----------------------------------------------------------------------------
00867 RESID_INLINE
00868 int SID2::clock_resample_interpolate(cycle_count& delta_t, short* buf, int n,
00869                                     int interleave)
00870 {
00871   int s = 0;
00872 
00873   for (;;) {
00874     cycle_count next_sample_offset = sample_offset + cycles_per_sample;
00875     cycle_count delta_t_sample = next_sample_offset >> FIXP_SHIFT;
00876     if (delta_t_sample > delta_t) {
00877       break;
00878     }
00879     if (s >= n) {
00880       return s;
00881     }
00882     for (int i = 0; i < delta_t_sample; i++) {
00883       clock();
00884       sample[sample_index] = sample[sample_index + RINGSIZE] = output();
00885       ++sample_index;
00886       sample_index &= 0x3fff;
00887     }
00888     delta_t -= delta_t_sample;
00889     sample_offset = next_sample_offset & FIXP_MASK;
00890 
00891     int fir_offset = sample_offset*fir_RES >> FIXP_SHIFT;
00892     int fir_offset_rmd = sample_offset*fir_RES & FIXP_MASK;
00893     short* fir_start = fir + fir_offset*fir_N;
00894     short* sample_start = sample + sample_index - fir_N + RINGSIZE;
00895 
00896     // Convolution with filter impulse response.
00897     int v1 = 0;
00898     for (int j = 0; j < fir_N; j++) {
00899       v1 += sample_start[j]*fir_start[j];
00900     }
00901 
00902     // Use next FIR table, wrap around to first FIR table using
00903     // previous sample.
00904     if (++fir_offset == fir_RES) {
00905       fir_offset = 0;
00906       --sample_start;
00907     }
00908     fir_start = fir + fir_offset*fir_N;
00909 
00910     // Convolution with filter impulse response.
00911     int v2 = 0;
00912     for (int j = 0; j < fir_N; j++) {
00913       v2 += sample_start[j]*fir_start[j];
00914     }
00915 
00916     // Linear interpolation.
00917     // fir_offset_rmd is equal for all samples, it can thus be factorized out:
00918     // sum(v1 + rmd*(v2 - v1)) = sum(v1) + rmd*(sum(v2) - sum(v1))
00919     int v = v1 + (fir_offset_rmd*(v2 - v1) >> FIXP_SHIFT);
00920 
00921     v >>= FIR_SHIFT;
00922 
00923     // Saturated arithmetics to guard against 16 bit sample overflow.
00924     const int half = 1 << 15;
00925     if (v >= half) {
00926       v = half - 1;
00927     }
00928     else if (v < -half) {
00929       v = -half;
00930     }
00931 
00932     buf[s++*interleave] = v;
00933   }
00934 
00935   for (int i = 0; i < delta_t; i++) {
00936     clock();
00937     sample[sample_index] = sample[sample_index + RINGSIZE] = output();
00938     ++sample_index;
00939     sample_index &= 0x3fff;
00940   }
00941   sample_offset -= delta_t << FIXP_SHIFT;
00942   delta_t = 0;
00943   return s;
00944 }
00945 
00946 
00947 // ----------------------------------------------------------------------------
00948 // SID clocking with audio sampling - cycle based with audio resampling.
00949 // ----------------------------------------------------------------------------
00950 RESID_INLINE
00951 int SID2::clock_resample_fast(cycle_count& delta_t, short* buf, int n,
00952                              int interleave)
00953 {
00954   int s = 0;
00955 
00956   for (;;) {
00957     cycle_count next_sample_offset = sample_offset + cycles_per_sample;
00958     cycle_count delta_t_sample = next_sample_offset >> FIXP_SHIFT;
00959     if (delta_t_sample > delta_t) {
00960       break;
00961     }
00962     if (s >= n) {
00963       return s;
00964     }
00965     for (int i = 0; i < delta_t_sample; i++) {
00966       clock();
00967       sample[sample_index] = sample[sample_index + RINGSIZE] = output();
00968       ++sample_index;
00969       sample_index &= 0x3fff;
00970     }
00971     delta_t -= delta_t_sample;
00972     sample_offset = next_sample_offset & FIXP_MASK;
00973 
00974     int fir_offset = sample_offset*fir_RES >> FIXP_SHIFT;
00975     short* fir_start = fir + fir_offset*fir_N;
00976     short* sample_start = sample + sample_index - fir_N + RINGSIZE;
00977 
00978     // Convolution with filter impulse response.
00979     int v = 0;
00980     for (int j = 0; j < fir_N; j++) {
00981       v += sample_start[j]*fir_start[j];
00982     }
00983 
00984     v >>= FIR_SHIFT;
00985 
00986     // Saturated arithmetics to guard against 16 bit sample overflow.
00987     const int half = 1 << 15;
00988     if (v >= half) {
00989       v = half - 1;
00990     }
00991     else if (v < -half) {
00992       v = -half;
00993     }
00994 
00995     buf[s++*interleave] = v;
00996   }
00997 
00998   for (int i = 0; i < delta_t; i++) {
00999     clock();
01000     sample[sample_index] = sample[sample_index + RINGSIZE] = output();
01001     ++sample_index;
01002     sample_index &= 0x3fff;
01003   }
01004   sample_offset -= delta_t << FIXP_SHIFT;
01005   delta_t = 0;
01006   return s;
01007 }
01008