Blip_Buffer.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. // Band-limited sound synthesis buffer
  2. // Blip_Buffer 0.4.1
  3. #ifndef BLIP_BUFFER_H
  4. #define BLIP_BUFFER_H
  5. // internal
  6. #include <limits.h>
  7. #if INT_MAX < 0x7FFFFFFF
  8. #error "int must be at least 32 bits"
  9. #endif
  10. typedef int blip_long;
  11. typedef unsigned blip_ulong;
  12. // Time unit at source clock rate
  13. typedef blip_long blip_time_t;
  14. // Output samples are 16-bit signed, with a range of -32768 to 32767
  15. typedef short blip_sample_t;
  16. enum { blip_sample_max = 32767 };
  17. class Blip_Buffer {
  18. public:
  19. typedef const char* blargg_err_t;
  20. // Set output sample rate and buffer length in milliseconds (1/1000 sec, defaults
  21. // to 1/4 second), then clear buffer. Returns NULL on success, otherwise if there
  22. // isn't enough memory, returns error without affecting current buffer setup.
  23. blargg_err_t set_sample_rate( long samples_per_sec, int msec_length = 1000 / 4 );
  24. // Set number of source time units per second
  25. void clock_rate( long );
  26. // End current time frame of specified duration and make its samples available
  27. // (along with any still-unread samples) for reading with read_samples(). Begins
  28. // a new time frame at the end of the current frame.
  29. void end_frame( blip_time_t time );
  30. // Read at most 'max_samples' out of buffer into 'dest', removing them from from
  31. // the buffer. Returns number of samples actually read and removed. If stereo is
  32. // true, increments 'dest' one extra time after writing each sample, to allow
  33. // easy interleving of two channels into a stereo output buffer.
  34. long read_samples( blip_sample_t* dest, long max_samples, int stereo = 0 );
  35. // Additional optional features
  36. // Current output sample rate
  37. long sample_rate() const;
  38. // Length of buffer, in milliseconds
  39. int length() const;
  40. // Number of source time units per second
  41. long clock_rate() const;
  42. // Set frequency high-pass filter frequency, where higher values reduce bass more
  43. void bass_freq( int frequency );
  44. // Number of samples delay from synthesis to samples read out
  45. int output_latency() const;
  46. // Remove all available samples and clear buffer to silence. If 'entire_buffer' is
  47. // false, just clears out any samples waiting rather than the entire buffer.
  48. void clear( int entire_buffer = 1 );
  49. // Number of samples available for reading with read_samples()
  50. long samples_avail() const;
  51. // Remove 'count' samples from those waiting to be read
  52. void remove_samples( long count );
  53. // Experimental features
  54. // Count number of clocks needed until 'count' samples will be available.
  55. // If buffer can't even hold 'count' samples, returns number of clocks until
  56. // buffer becomes full.
  57. blip_time_t count_clocks( long count ) const;
  58. // Number of raw samples that can be mixed within frame of specified duration.
  59. long count_samples( blip_time_t duration ) const;
  60. // Mix 'count' samples from 'buf' into buffer.
  61. void mix_samples( blip_sample_t const* buf, long count );
  62. // not documented yet
  63. void set_modified() { modified_ = 1; }
  64. int clear_modified() { int b = modified_; modified_ = 0; return b; }
  65. typedef blip_ulong blip_resampled_time_t;
  66. void remove_silence( long count );
  67. blip_resampled_time_t resampled_duration( int t ) const { return t * factor_; }
  68. blip_resampled_time_t resampled_time( blip_time_t t ) const { return t * factor_ + offset_; }
  69. blip_resampled_time_t clock_rate_factor( long clock_rate ) const;
  70. public:
  71. Blip_Buffer();
  72. ~Blip_Buffer();
  73. // Deprecated
  74. typedef blip_resampled_time_t resampled_time_t;
  75. blargg_err_t sample_rate( long r ) { return set_sample_rate( r ); }
  76. blargg_err_t sample_rate( long r, int msec ) { return set_sample_rate( r, msec ); }
  77. private:
  78. // noncopyable
  79. Blip_Buffer( const Blip_Buffer& );
  80. Blip_Buffer& operator = ( const Blip_Buffer& );
  81. public:
  82. typedef blip_time_t buf_t_;
  83. blip_ulong factor_;
  84. blip_resampled_time_t offset_;
  85. buf_t_* buffer_;
  86. blip_long buffer_size_;
  87. blip_long reader_accum_;
  88. int bass_shift_;
  89. private:
  90. long sample_rate_;
  91. long clock_rate_;
  92. int bass_freq_;
  93. int length_;
  94. int modified_;
  95. friend class Blip_Reader;
  96. };
  97. #ifdef HAVE_CONFIG_H
  98. #include "config.h"
  99. #endif
  100. // Number of bits in resample ratio fraction. Higher values give a more accurate ratio
  101. // but reduce maximum buffer size.
  102. #ifndef BLIP_BUFFER_ACCURACY
  103. #define BLIP_BUFFER_ACCURACY 16
  104. #endif
  105. // Number bits in phase offset. Fewer than 6 bits (64 phase offsets) results in
  106. // noticeable broadband noise when synthesizing high frequency square waves.
  107. // Affects size of Blip_Synth objects since they store the waveform directly.
  108. #ifndef BLIP_PHASE_BITS
  109. #if BLIP_BUFFER_FAST
  110. #define BLIP_PHASE_BITS 8
  111. #else
  112. #define BLIP_PHASE_BITS 6
  113. #endif
  114. #endif
  115. // Internal
  116. typedef blip_ulong blip_resampled_time_t;
  117. int const blip_widest_impulse_ = 16;
  118. int const blip_buffer_extra_ = blip_widest_impulse_ + 2;
  119. int const blip_res = 1 << BLIP_PHASE_BITS;
  120. class blip_eq_t;
  121. class Blip_Synth_Fast_ {
  122. public:
  123. Blip_Buffer* buf;
  124. int last_amp;
  125. int delta_factor;
  126. void volume_unit( double );
  127. Blip_Synth_Fast_();
  128. void treble_eq( blip_eq_t const& ) { }
  129. };
  130. class Blip_Synth_ {
  131. public:
  132. Blip_Buffer* buf;
  133. int last_amp;
  134. int delta_factor;
  135. void volume_unit( double );
  136. Blip_Synth_( short* impulses, int width );
  137. void treble_eq( blip_eq_t const& );
  138. private:
  139. double volume_unit_;
  140. short* const impulses;
  141. int const width;
  142. blip_long kernel_unit;
  143. int impulses_size() const { return blip_res / 2 * width + 1; }
  144. void adjust_impulse();
  145. };
  146. // Quality level. Start with blip_good_quality.
  147. const int blip_med_quality = 8;
  148. const int blip_good_quality = 12;
  149. const int blip_high_quality = 16;
  150. // Range specifies the greatest expected change in amplitude. Calculate it
  151. // by finding the difference between the maximum and minimum expected
  152. // amplitudes (max - min).
  153. template<int quality,int range>
  154. class Blip_Synth {
  155. public:
  156. // Set overall volume of waveform
  157. void volume( double v ) { impl.volume_unit( v * (1.0 / (range < 0 ? -range : range)) ); }
  158. // Configure low-pass filter (see blip_buffer.txt)
  159. void treble_eq( blip_eq_t const& eq ) { impl.treble_eq( eq ); }
  160. // Get/set Blip_Buffer used for output
  161. Blip_Buffer* output() const { return impl.buf; }
  162. void output( Blip_Buffer* b ) { impl.buf = b; impl.last_amp = 0; }
  163. // Update amplitude of waveform at given time. Using this requires a separate
  164. // Blip_Synth for each waveform.
  165. void update( blip_time_t time, int amplitude );
  166. // Low-level interface
  167. // Add an amplitude transition of specified delta, optionally into specified buffer
  168. // rather than the one set with output(). Delta can be positive or negative.
  169. // The actual change in amplitude is delta * (volume / range)
  170. void offset( blip_time_t, int delta, Blip_Buffer* ) const;
  171. void offset( blip_time_t t, int delta ) const { offset( t, delta, impl.buf ); }
  172. // Works directly in terms of fractional output samples. Contact author for more info.
  173. void offset_resampled( blip_resampled_time_t, int delta, Blip_Buffer* ) const;
  174. // Same as offset(), except code is inlined for higher performance
  175. void offset_inline( blip_time_t t, int delta, Blip_Buffer* buf ) const {
  176. offset_resampled( t * buf->factor_ + buf->offset_, delta, buf );
  177. }
  178. void offset_inline( blip_time_t t, int delta ) const {
  179. offset_resampled( t * impl.buf->factor_ + impl.buf->offset_, delta, impl.buf );
  180. }
  181. private:
  182. #if BLIP_BUFFER_FAST
  183. Blip_Synth_Fast_ impl;
  184. #else
  185. Blip_Synth_ impl;
  186. typedef short imp_t;
  187. imp_t impulses [blip_res * (quality / 2) + 1];
  188. public:
  189. Blip_Synth() : impl( impulses, quality ) { }
  190. #endif
  191. };
  192. // Low-pass equalization parameters
  193. class blip_eq_t {
  194. public:
  195. // Logarithmic rolloff to treble dB at half sampling rate. Negative values reduce
  196. // treble, small positive values (0 to 5.0) increase treble.
  197. blip_eq_t( double treble_db = 0 );
  198. // See blip_buffer.txt
  199. blip_eq_t( double treble, long rolloff_freq, long sample_rate, long cutoff_freq = 0 );
  200. private:
  201. double treble;
  202. long rolloff_freq;
  203. long sample_rate;
  204. long cutoff_freq;
  205. void generate( float* out, int count ) const;
  206. friend class Blip_Synth_;
  207. };
  208. int const blip_sample_bits = 30;
  209. // Dummy Blip_Buffer to direct sound output to, for easy muting without
  210. // having to stop sound code.
  211. class Silent_Blip_Buffer : public Blip_Buffer {
  212. buf_t_ buf [blip_buffer_extra_ + 1];
  213. public:
  214. // The following cannot be used (an assertion will fail if attempted):
  215. blargg_err_t set_sample_rate( long samples_per_sec, int msec_length );
  216. blip_time_t count_clocks( long count ) const;
  217. void mix_samples( blip_sample_t const* buf, long count );
  218. Silent_Blip_Buffer();
  219. };
  220. #if defined (__GNUC__) || _MSC_VER >= 1100
  221. #define BLIP_RESTRICT __restrict
  222. #else
  223. #define BLIP_RESTRICT
  224. #endif
  225. // Optimized reading from Blip_Buffer, for use in custom sample output
  226. // Begin reading from buffer. Name should be unique to the current block.
  227. #define BLIP_READER_BEGIN( name, blip_buffer ) \
  228. const Blip_Buffer::buf_t_* BLIP_RESTRICT name##_reader_buf = (blip_buffer).buffer_;\
  229. blip_long name##_reader_accum = (blip_buffer).reader_accum_
  230. // Get value to pass to BLIP_READER_NEXT()
  231. #define BLIP_READER_BASS( blip_buffer ) ((blip_buffer).bass_shift_)
  232. // Constant value to use instead of BLIP_READER_BASS(), for slightly more optimal
  233. // code at the cost of having no bass control
  234. int const blip_reader_default_bass = 9;
  235. // Current sample
  236. #define BLIP_READER_READ( name ) (name##_reader_accum >> (blip_sample_bits - 16))
  237. // Current raw sample in full internal resolution
  238. #define BLIP_READER_READ_RAW( name ) (name##_reader_accum)
  239. // Advance to next sample
  240. #define BLIP_READER_NEXT( name, bass ) \
  241. (void) (name##_reader_accum += *name##_reader_buf++ - (name##_reader_accum >> (bass)))
  242. // End reading samples from buffer. The number of samples read must now be removed
  243. // using Blip_Buffer::remove_samples().
  244. #define BLIP_READER_END( name, blip_buffer ) \
  245. (void) ((blip_buffer).reader_accum_ = name##_reader_accum)
  246. // Compatibility with older version
  247. const long blip_unscaled = 65535;
  248. const int blip_low_quality = blip_med_quality;
  249. const int blip_best_quality = blip_high_quality;
  250. // Deprecated; use BLIP_READER macros as follows:
  251. // Blip_Reader r; r.begin( buf ); -> BLIP_READER_BEGIN( r, buf );
  252. // int bass = r.begin( buf ) -> BLIP_READER_BEGIN( r, buf ); int bass = BLIP_READER_BASS( buf );
  253. // r.read() -> BLIP_READER_READ( r )
  254. // r.read_raw() -> BLIP_READER_READ_RAW( r )
  255. // r.next( bass ) -> BLIP_READER_NEXT( r, bass )
  256. // r.next() -> BLIP_READER_NEXT( r, blip_reader_default_bass )
  257. // r.end( buf ) -> BLIP_READER_END( r, buf )
  258. class Blip_Reader {
  259. public:
  260. int begin( Blip_Buffer& );
  261. blip_long read() const { return accum >> (blip_sample_bits - 16); }
  262. blip_long read_raw() const { return accum; }
  263. void next( int bass_shift = 9 ) { accum += *buf++ - (accum >> bass_shift); }
  264. void end( Blip_Buffer& b ) { b.reader_accum_ = accum; }
  265. private:
  266. const Blip_Buffer::buf_t_* buf;
  267. blip_long accum;
  268. };
  269. // End of public interface
  270. #include <assert.h>
  271. template<int quality,int range>
  272. inline void Blip_Synth<quality,range>::offset_resampled( blip_resampled_time_t time,
  273. int delta, Blip_Buffer* blip_buf ) const
  274. {
  275. // Fails if time is beyond end of Blip_Buffer, due to a bug in caller code or the
  276. // need for a longer buffer as set by set_sample_rate().
  277. assert( (blip_long) (time >> BLIP_BUFFER_ACCURACY) < blip_buf->buffer_size_ );
  278. delta *= impl.delta_factor;
  279. blip_long* BLIP_RESTRICT buf = blip_buf->buffer_ + (time >> BLIP_BUFFER_ACCURACY);
  280. int phase = (int) (time >> (BLIP_BUFFER_ACCURACY - BLIP_PHASE_BITS) & (blip_res - 1));
  281. #if BLIP_BUFFER_FAST
  282. blip_long left = buf [0] + delta;
  283. // Kind of crappy, but doing shift after multiply results in overflow.
  284. // Alternate way of delaying multiply by delta_factor results in worse
  285. // sub-sample resolution.
  286. blip_long right = (delta >> BLIP_PHASE_BITS) * phase;
  287. left -= right;
  288. right += buf [1];
  289. buf [0] = left;
  290. buf [1] = right;
  291. #else
  292. int const fwd = (blip_widest_impulse_ - quality) / 2;
  293. int const rev = fwd + quality - 2;
  294. int const mid = quality / 2 - 1;
  295. imp_t const* BLIP_RESTRICT imp = impulses + blip_res - phase;
  296. #if defined (_M_IX86) || defined (_M_IA64) || defined (__i486__) || \
  297. defined (__x86_64__) || defined (__ia64__) || defined (__i386__)
  298. // straight forward implementation resulted in better code on GCC for x86
  299. #define ADD_IMP( out, in ) \
  300. buf [out] += (blip_long) imp [blip_res * (in)] * delta
  301. #define BLIP_FWD( i ) {\
  302. ADD_IMP( fwd + i, i );\
  303. ADD_IMP( fwd + 1 + i, i + 1 );\
  304. }
  305. #define BLIP_REV( r ) {\
  306. ADD_IMP( rev - r, r + 1 );\
  307. ADD_IMP( rev + 1 - r, r );\
  308. }
  309. BLIP_FWD( 0 )
  310. if ( quality > 8 ) BLIP_FWD( 2 )
  311. if ( quality > 12 ) BLIP_FWD( 4 )
  312. {
  313. ADD_IMP( fwd + mid - 1, mid - 1 );
  314. ADD_IMP( fwd + mid , mid );
  315. imp = impulses + phase;
  316. }
  317. if ( quality > 12 ) BLIP_REV( 6 )
  318. if ( quality > 8 ) BLIP_REV( 4 )
  319. BLIP_REV( 2 )
  320. ADD_IMP( rev , 1 );
  321. ADD_IMP( rev + 1, 0 );
  322. #else
  323. // for RISC processors, help compiler by reading ahead of writes
  324. #define BLIP_FWD( i ) {\
  325. blip_long t0 = i0 * delta + buf [fwd + i];\
  326. blip_long t1 = imp [blip_res * (i + 1)] * delta + buf [fwd + 1 + i];\
  327. i0 = imp [blip_res * (i + 2)];\
  328. buf [fwd + i] = t0;\
  329. buf [fwd + 1 + i] = t1;\
  330. }
  331. #define BLIP_REV( r ) {\
  332. blip_long t0 = i0 * delta + buf [rev - r];\
  333. blip_long t1 = imp [blip_res * r] * delta + buf [rev + 1 - r];\
  334. i0 = imp [blip_res * (r - 1)];\
  335. buf [rev - r] = t0;\
  336. buf [rev + 1 - r] = t1;\
  337. }
  338. blip_long i0 = *imp;
  339. BLIP_FWD( 0 )
  340. if ( quality > 8 ) BLIP_FWD( 2 )
  341. if ( quality > 12 ) BLIP_FWD( 4 )
  342. {
  343. blip_long t0 = i0 * delta + buf [fwd + mid - 1];
  344. blip_long t1 = imp [blip_res * mid] * delta + buf [fwd + mid ];
  345. imp = impulses + phase;
  346. i0 = imp [blip_res * mid];
  347. buf [fwd + mid - 1] = t0;
  348. buf [fwd + mid ] = t1;
  349. }
  350. if ( quality > 12 ) BLIP_REV( 6 )
  351. if ( quality > 8 ) BLIP_REV( 4 )
  352. BLIP_REV( 2 )
  353. blip_long t0 = i0 * delta + buf [rev ];
  354. blip_long t1 = *imp * delta + buf [rev + 1];
  355. buf [rev ] = t0;
  356. buf [rev + 1] = t1;
  357. #endif
  358. #endif
  359. }
  360. #undef BLIP_FWD
  361. #undef BLIP_REV
  362. template<int quality,int range>
  363. #if BLIP_BUFFER_FAST
  364. inline
  365. #endif
  366. void Blip_Synth<quality,range>::offset( blip_time_t t, int delta, Blip_Buffer* buf ) const
  367. {
  368. offset_resampled( t * buf->factor_ + buf->offset_, delta, buf );
  369. }
  370. template<int quality,int range>
  371. #if BLIP_BUFFER_FAST
  372. inline
  373. #endif
  374. void Blip_Synth<quality,range>::update( blip_time_t t, int amp )
  375. {
  376. int delta = amp - impl.last_amp;
  377. impl.last_amp = amp;
  378. offset_resampled( t * impl.buf->factor_ + impl.buf->offset_, delta, impl.buf );
  379. }
  380. inline blip_eq_t::blip_eq_t( double t ) :
  381. treble( t ), rolloff_freq( 0 ), sample_rate( 44100 ), cutoff_freq( 0 ) { }
  382. inline blip_eq_t::blip_eq_t( double t, long rf, long sr, long cf ) :
  383. treble( t ), rolloff_freq( rf ), sample_rate( sr ), cutoff_freq( cf ) { }
  384. inline int Blip_Buffer::length() const { return length_; }
  385. inline long Blip_Buffer::samples_avail() const { return (long) (offset_ >> BLIP_BUFFER_ACCURACY); }
  386. inline long Blip_Buffer::sample_rate() const { return sample_rate_; }
  387. inline int Blip_Buffer::output_latency() const { return blip_widest_impulse_ / 2; }
  388. inline long Blip_Buffer::clock_rate() const { return clock_rate_; }
  389. inline void Blip_Buffer::clock_rate( long cps ) { factor_ = clock_rate_factor( clock_rate_ = cps ); }
  390. inline int Blip_Reader::begin( Blip_Buffer& blip_buf )
  391. {
  392. buf = blip_buf.buffer_;
  393. accum = blip_buf.reader_accum_;
  394. return blip_buf.bass_shift_;
  395. }
  396. int const blip_max_length = 0;
  397. int const blip_default_length = 250;
  398. #endif