Blip_Buffer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. // Blip_Buffer 0.4.1. http://www.slack.net/~ant/
  2. #include "Blip_Buffer.h"
  3. #include <assert.h>
  4. #include <limits.h>
  5. #include <string.h>
  6. #include <stdlib.h>
  7. #include <math.h>
  8. /* Copyright (C) 2003-2006 Shay Green. This module is free software; you
  9. can redistribute it and/or modify it under the terms of the GNU Lesser
  10. General Public License as published by the Free Software Foundation; either
  11. version 2.1 of the License, or (at your option) any later version. This
  12. module is distributed in the hope that it will be useful, but WITHOUT ANY
  13. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  14. FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  15. details. You should have received a copy of the GNU Lesser General Public
  16. License along with this module; if not, write to the Free Software Foundation,
  17. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */
  18. #ifdef BLARGG_ENABLE_OPTIMIZER
  19. #include BLARGG_ENABLE_OPTIMIZER
  20. #endif
  21. int const silent_buf_size = 1; // size used for Silent_Blip_Buffer
  22. Blip_Buffer::Blip_Buffer()
  23. {
  24. factor_ = (blip_ulong)-1 / 2;
  25. offset_ = 0;
  26. buffer_ = 0;
  27. buffer_size_ = 0;
  28. sample_rate_ = 0;
  29. reader_accum_ = 0;
  30. bass_shift_ = 0;
  31. clock_rate_ = 0;
  32. bass_freq_ = 16;
  33. length_ = 0;
  34. // assumptions code makes about implementation-defined features
  35. #ifndef NDEBUG
  36. // right shift of negative value preserves sign
  37. buf_t_ i = -0x7FFFFFFE;
  38. assert( (i >> 1) == -0x3FFFFFFF );
  39. // casting to short truncates to 16 bits and sign-extends
  40. i = 0x18000;
  41. assert( (short) i == -0x8000 );
  42. #endif
  43. }
  44. Blip_Buffer::~Blip_Buffer()
  45. {
  46. if ( buffer_size_ != silent_buf_size )
  47. free( buffer_ );
  48. }
  49. Silent_Blip_Buffer::Silent_Blip_Buffer()
  50. {
  51. factor_ = 0;
  52. buffer_ = buf;
  53. buffer_size_ = silent_buf_size;
  54. memset( buf, 0, sizeof buf ); // in case machine takes exception for signed overflow
  55. }
  56. void Blip_Buffer::clear( int entire_buffer )
  57. {
  58. offset_ = 0;
  59. reader_accum_ = 0;
  60. modified_ = 0;
  61. if ( buffer_ )
  62. {
  63. long count = (entire_buffer ? buffer_size_ : samples_avail());
  64. memset( buffer_, 0, (count + blip_buffer_extra_) * sizeof (buf_t_) );
  65. }
  66. }
  67. Blip_Buffer::blargg_err_t Blip_Buffer::set_sample_rate( long new_rate, int msec )
  68. {
  69. if ( buffer_size_ == silent_buf_size )
  70. {
  71. assert( 0 );
  72. return "Internal (tried to resize Silent_Blip_Buffer)";
  73. }
  74. // start with maximum length that resampled time can represent
  75. long new_size = (UINT_MAX >> BLIP_BUFFER_ACCURACY) - blip_buffer_extra_ - 64;
  76. if ( msec != blip_max_length )
  77. {
  78. long s = (new_rate * (msec + 1) + 999) / 1000;
  79. if ( s < new_size )
  80. new_size = s;
  81. else
  82. assert( 0 ); // fails if requested buffer length exceeds limit
  83. }
  84. if ( buffer_size_ != new_size )
  85. {
  86. void* p = realloc( buffer_, (new_size + blip_buffer_extra_) * sizeof *buffer_ );
  87. if ( !p )
  88. return "Out of memory";
  89. buffer_ = (buf_t_*) p;
  90. }
  91. buffer_size_ = new_size;
  92. assert( buffer_size_ != silent_buf_size );
  93. // update things based on the sample rate
  94. sample_rate_ = new_rate;
  95. length_ = new_size * 1000 / new_rate - 1;
  96. if ( msec )
  97. assert( length_ == msec ); // ensure length is same as that passed in
  98. if ( clock_rate_ )
  99. clock_rate( clock_rate_ );
  100. bass_freq( bass_freq_ );
  101. clear();
  102. return 0; // success
  103. }
  104. blip_resampled_time_t Blip_Buffer::clock_rate_factor( long rate ) const
  105. {
  106. double ratio = (double) sample_rate_ / rate;
  107. blip_long factor = (blip_long) floor( ratio * (1L << BLIP_BUFFER_ACCURACY) + 0.5 );
  108. assert( factor > 0 || !sample_rate_ ); // fails if clock/output ratio is too large
  109. return (blip_resampled_time_t) factor;
  110. }
  111. void Blip_Buffer::bass_freq( int freq )
  112. {
  113. bass_freq_ = freq;
  114. int shift = 31;
  115. if ( freq > 0 )
  116. {
  117. shift = 13;
  118. long f = (freq << 16) / sample_rate_;
  119. while ( (f >>= 1) && --shift ) { }
  120. }
  121. bass_shift_ = shift;
  122. }
  123. void Blip_Buffer::end_frame( blip_time_t t )
  124. {
  125. offset_ += t * factor_;
  126. assert( samples_avail() <= (long) buffer_size_ ); // time outside buffer length
  127. }
  128. void Blip_Buffer::remove_silence( long count )
  129. {
  130. assert( count <= samples_avail() ); // tried to remove more samples than available
  131. offset_ -= (blip_resampled_time_t) count << BLIP_BUFFER_ACCURACY;
  132. }
  133. long Blip_Buffer::count_samples( blip_time_t t ) const
  134. {
  135. unsigned long last_sample = resampled_time( t ) >> BLIP_BUFFER_ACCURACY;
  136. unsigned long first_sample = offset_ >> BLIP_BUFFER_ACCURACY;
  137. return (long) (last_sample - first_sample);
  138. }
  139. blip_time_t Blip_Buffer::count_clocks( long count ) const
  140. {
  141. if ( !factor_ )
  142. {
  143. assert( 0 ); // sample rate and clock rates must be set first
  144. return 0;
  145. }
  146. if ( count > buffer_size_ )
  147. count = buffer_size_;
  148. blip_resampled_time_t time = (blip_resampled_time_t) count << BLIP_BUFFER_ACCURACY;
  149. return (blip_time_t) ((time - offset_ + factor_ - 1) / factor_);
  150. }
  151. void Blip_Buffer::remove_samples( long count )
  152. {
  153. if ( count )
  154. {
  155. remove_silence( count );
  156. // copy remaining samples to beginning and clear old samples
  157. long remain = samples_avail() + blip_buffer_extra_;
  158. memmove( buffer_, buffer_ + count, remain * sizeof *buffer_ );
  159. memset( buffer_ + remain, 0, count * sizeof *buffer_ );
  160. }
  161. }
  162. // Blip_Synth_
  163. Blip_Synth_Fast_::Blip_Synth_Fast_()
  164. {
  165. buf = 0;
  166. last_amp = 0;
  167. delta_factor = 0;
  168. }
  169. void Blip_Synth_Fast_::volume_unit( double new_unit )
  170. {
  171. delta_factor = int (new_unit * (1L << blip_sample_bits) + 0.5);
  172. }
  173. #if !BLIP_BUFFER_FAST
  174. Blip_Synth_::Blip_Synth_( short* p, int w ) :
  175. impulses( p ),
  176. width( w )
  177. {
  178. volume_unit_ = 0.0;
  179. kernel_unit = 0;
  180. buf = 0;
  181. last_amp = 0;
  182. delta_factor = 0;
  183. }
  184. #undef PI
  185. #define PI 3.1415926535897932384626433832795029
  186. static void gen_sinc( float* out, int count, double oversample, double treble, double cutoff )
  187. {
  188. if ( cutoff >= 0.999 )
  189. cutoff = 0.999;
  190. if ( treble < -300.0 )
  191. treble = -300.0;
  192. if ( treble > 5.0 )
  193. treble = 5.0;
  194. double const maxh = 4096.0;
  195. double const rolloff = pow( 10.0, 1.0 / (maxh * 20.0) * treble / (1.0 - cutoff) );
  196. double const pow_a_n = pow( rolloff, maxh - maxh * cutoff );
  197. double const to_angle = PI / 2 / maxh / oversample;
  198. for ( int i = 0; i < count; i++ )
  199. {
  200. double angle = ((i - count) * 2 + 1) * to_angle;
  201. double angle_maxh = angle * maxh;
  202. double angle_maxh_mid = angle_maxh * cutoff;
  203. double y = maxh;
  204. // 0 to Fs/2*cutoff, flat
  205. if ( angle_maxh_mid ) // unstable at t=0
  206. y *= sin( angle_maxh_mid ) / angle_maxh_mid;
  207. // Fs/2*cutoff to Fs/2, logarithmic rolloff
  208. double cosa = cos( angle );
  209. double den = 1 + rolloff * (rolloff - cosa - cosa);
  210. // Becomes unstable when rolloff is near 1.0 and t is near 0,
  211. // which is the only time den becomes small
  212. if ( den > 1e-13 )
  213. {
  214. double num =
  215. (cos( angle_maxh - angle ) * rolloff - cos( angle_maxh )) * pow_a_n -
  216. cos( angle_maxh_mid - angle ) * rolloff + cos( angle_maxh_mid );
  217. y = y * cutoff + num / den;
  218. }
  219. out [i] = (float) y;
  220. }
  221. }
  222. void blip_eq_t::generate( float* out, int count ) const
  223. {
  224. // lower cutoff freq for narrow kernels with their wider transition band
  225. // (8 points->1.49, 16 points->1.15)
  226. double oversample = blip_res * 2.25 / count + 0.85;
  227. double half_rate = sample_rate * 0.5;
  228. if ( cutoff_freq )
  229. oversample = half_rate / cutoff_freq;
  230. double cutoff = rolloff_freq * oversample / half_rate;
  231. gen_sinc( out, count, blip_res * oversample, treble, cutoff );
  232. // apply (half of) hamming window
  233. double to_fraction = PI / (count - 1);
  234. for ( int i = count; i--; )
  235. out [i] *= 0.54f - 0.46f * (float) cos( i * to_fraction );
  236. }
  237. void Blip_Synth_::adjust_impulse()
  238. {
  239. // sum pairs for each phase and add error correction to end of first half
  240. int const size = impulses_size();
  241. for ( int p = blip_res; p-- >= blip_res / 2; )
  242. {
  243. int p2 = blip_res - 2 - p;
  244. long error = kernel_unit;
  245. for ( int i = 1; i < size; i += blip_res )
  246. {
  247. error -= impulses [i + p ];
  248. error -= impulses [i + p2];
  249. }
  250. if ( p == p2 )
  251. error /= 2; // phase = 0.5 impulse uses same half for both sides
  252. impulses [size - blip_res + p] += (short) error;
  253. //printf( "error: %ld\n", error );
  254. }
  255. //for ( int i = blip_res; i--; printf( "\n" ) )
  256. // for ( int j = 0; j < width / 2; j++ )
  257. // printf( "%5ld,", impulses [j * blip_res + i + 1] );
  258. }
  259. void Blip_Synth_::treble_eq( blip_eq_t const& eq )
  260. {
  261. float fimpulse [blip_res / 2 * (blip_widest_impulse_ - 1) + blip_res * 2];
  262. int const half_size = blip_res / 2 * (width - 1);
  263. eq.generate( &fimpulse [blip_res], half_size );
  264. int i;
  265. // need mirror slightly past center for calculation
  266. for ( i = blip_res; i--; )
  267. fimpulse [blip_res + half_size + i] = fimpulse [blip_res + half_size - 1 - i];
  268. // starts at 0
  269. for ( i = 0; i < blip_res; i++ )
  270. fimpulse [i] = 0.0f;
  271. // find rescale factor
  272. double total = 0.0;
  273. for ( i = 0; i < half_size; i++ )
  274. total += fimpulse [blip_res + i];
  275. //double const base_unit = 44800.0 - 128 * 18; // allows treble up to +0 dB
  276. //double const base_unit = 37888.0; // allows treble to +5 dB
  277. double const base_unit = 32768.0; // necessary for blip_unscaled to work
  278. double rescale = base_unit / 2 / total;
  279. kernel_unit = (long) base_unit;
  280. // integrate, first difference, rescale, convert to int
  281. double sum = 0.0;
  282. double next = 0.0;
  283. int const impulses_size = this->impulses_size();
  284. for ( i = 0; i < impulses_size; i++ )
  285. {
  286. impulses [i] = (short) floor( (next - sum) * rescale + 0.5 );
  287. sum += fimpulse [i];
  288. next += fimpulse [i + blip_res];
  289. }
  290. adjust_impulse();
  291. // volume might require rescaling
  292. double vol = volume_unit_;
  293. if ( vol )
  294. {
  295. volume_unit_ = 0.0;
  296. volume_unit( vol );
  297. }
  298. }
  299. void Blip_Synth_::volume_unit( double new_unit )
  300. {
  301. if ( new_unit != volume_unit_ )
  302. {
  303. // use default eq if it hasn't been set yet
  304. if ( !kernel_unit )
  305. treble_eq( -8.0 );
  306. volume_unit_ = new_unit;
  307. double factor = new_unit * (1L << blip_sample_bits) / kernel_unit;
  308. if ( factor > 0.0 )
  309. {
  310. int shift = 0;
  311. // if unit is really small, might need to attenuate kernel
  312. while ( factor < 2.0 )
  313. {
  314. shift++;
  315. factor *= 2.0;
  316. }
  317. if ( shift )
  318. {
  319. kernel_unit >>= shift;
  320. assert( kernel_unit > 0 ); // fails if volume unit is too low
  321. // keep values positive to avoid round-towards-zero of sign-preserving
  322. // right shift for negative values
  323. long offset = 0x8000 + (1 << (shift - 1));
  324. long offset2 = 0x8000 >> shift;
  325. for ( int i = impulses_size(); i--; )
  326. impulses [i] = (short) (((impulses [i] + offset) >> shift) - offset2);
  327. adjust_impulse();
  328. }
  329. }
  330. delta_factor = (int) floor( factor + 0.5 );
  331. //printf( "delta_factor: %d, kernel_unit: %d\n", delta_factor, kernel_unit );
  332. }
  333. }
  334. #endif
  335. long Blip_Buffer::read_samples( blip_sample_t* BLIP_RESTRICT out, long max_samples, int stereo )
  336. {
  337. long count = samples_avail();
  338. if ( count > max_samples )
  339. count = max_samples;
  340. if ( count )
  341. {
  342. int const bass = BLIP_READER_BASS( *this );
  343. BLIP_READER_BEGIN( reader, *this );
  344. if ( !stereo )
  345. {
  346. for ( blip_long n = count; n; --n )
  347. {
  348. blip_long s = BLIP_READER_READ( reader );
  349. if ( (blip_sample_t) s != s )
  350. s = 0x7FFF - (s >> 24);
  351. *out++ = (blip_sample_t) s;
  352. BLIP_READER_NEXT( reader, bass );
  353. }
  354. }
  355. else
  356. {
  357. for ( blip_long n = count; n; --n )
  358. {
  359. blip_long s = BLIP_READER_READ( reader );
  360. if ( (blip_sample_t) s != s )
  361. s = 0x7FFF - (s >> 24);
  362. *out = (blip_sample_t) s;
  363. out += 2;
  364. BLIP_READER_NEXT( reader, bass );
  365. }
  366. }
  367. BLIP_READER_END( reader, *this );
  368. remove_samples( count );
  369. }
  370. return count;
  371. }
  372. void Blip_Buffer::mix_samples( blip_sample_t const* in, long count )
  373. {
  374. if ( buffer_size_ == silent_buf_size )
  375. {
  376. assert( 0 );
  377. return;
  378. }
  379. buf_t_* out = buffer_ + (offset_ >> BLIP_BUFFER_ACCURACY) + blip_widest_impulse_ / 2;
  380. int const sample_shift = blip_sample_bits - 16;
  381. int prev = 0;
  382. while ( count-- )
  383. {
  384. blip_long s = (blip_long) *in++ << sample_shift;
  385. *out += s - prev;
  386. prev = s;
  387. ++out;
  388. }
  389. *out -= prev;
  390. }