home *** CD-ROM | disk | FTP | other *** search
/ Large Pack of OldSkool DOS MOD Trackers / goattracker_2.68.zip / src / resid / sid.cpp < prev    next >
C/C++ Source or Header  |  2009-01-03  |  31KB  |  1,009 lines

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