Path: blob/a-new-beginning/Cherry/Core/audio/Blip_Buffer.cpp
2 views
// Blip_Buffer 0.4.1. http://www.slack.net/~ant/12#include "Blip_Buffer.h"34#include <assert.h>5#include <limits.h>6#include <string.h>7#include <stdlib.h>8#include <math.h>910/* Copyright (C) 2003-2007 Shay Green. This module is free software; you11can redistribute it and/or modify it under the terms of the GNU Lesser12General Public License as published by the Free Software Foundation; either13version 2.1 of the License, or (at your option) any later version. This14module is distributed in the hope that it will be useful, but WITHOUT ANY15WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS16FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more17details. You should have received a copy of the GNU Lesser General Public18License along with this module; if not, write to the Free Software Foundation,19Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */2021// TODO: use scoped for variables in treble_eq()2223#ifdef BLARGG_ENABLE_OPTIMIZER24#include BLARGG_ENABLE_OPTIMIZER25#endif2627int const silent_buf_size = 1; // size used for Silent_Blip_Buffer2829Blip_Buffer::Blip_Buffer()30{31factor_ = (blip_ulong)LONG_MAX;32buffer_ = 0;33buffer_size_ = 0;34sample_rate_ = 0;35bass_shift_ = 0;36clock_rate_ = 0;37bass_freq_ = 16;38length_ = 0;3940// assumptions code makes about implementation-defined features41#ifndef NDEBUG42// right shift of negative value preserves sign43buf_t_ i = -0x7FFFFFFE;44assert( (i >> 1) == -0x3FFFFFFF );4546// casting to short truncates to 16 bits and sign-extends47i = 0x18000;48assert( (short) i == -0x8000 );49#endif5051clear();52}5354Blip_Buffer::~Blip_Buffer()55{56if ( buffer_size_ != silent_buf_size )57free( buffer_ );58}5960Silent_Blip_Buffer::Silent_Blip_Buffer()61{62factor_ = 0;63buffer_ = buf;64buffer_size_ = silent_buf_size;65clear();66}6768void Blip_Buffer::clear( int entire_buffer )69{70offset_ = 0;71reader_accum_ = 0;72modified_ = 0;73if ( buffer_ )74{75long count = (entire_buffer ? buffer_size_ : samples_avail());76memset( buffer_, 0, (count + blip_buffer_extra_) * sizeof (buf_t_) );77}78}7980Blip_Buffer::blargg_err_t Blip_Buffer::set_sample_rate( long new_rate, int msec )81{82if ( buffer_size_ == silent_buf_size )83{84assert( 0 );85return "Internal (tried to resize Silent_Blip_Buffer)";86}8788// start with maximum length that resampled time can represent89long new_size = (ULONG_MAX >> BLIP_BUFFER_ACCURACY) - blip_buffer_extra_ - 64;90if ( msec != blip_max_length )91{92long s = (new_rate * (msec + 1) + 999) / 1000;93if ( s < new_size )94new_size = s;95else96assert( 0 ); // fails if requested buffer length exceeds limit97}9899if ( buffer_size_ != new_size )100{101void* p = realloc( buffer_, (new_size + blip_buffer_extra_) * sizeof *buffer_ );102if ( !p )103return "Out of memory";104buffer_ = (buf_t_*) p;105}106107buffer_size_ = (int)new_size;108assert( buffer_size_ != silent_buf_size ); // size should never happen to match this109110// update things based on the sample rate111sample_rate_ = new_rate;112length_ = (int)(new_size * 1000 / new_rate - 1);113if ( msec )114assert( length_ == msec ); // ensure length is same as that passed in115116// update these since they depend on sample rate117if ( clock_rate_ )118clock_rate( clock_rate_ );119bass_freq( bass_freq_ );120121clear();122123return 0; // success124}125126blip_resampled_time_t Blip_Buffer::clock_rate_factor( long rate ) const127{128double ratio = (double) sample_rate_ / rate;129blip_long factor = (blip_long) floor( ratio * (1L << BLIP_BUFFER_ACCURACY) + 0.5 );130assert( factor > 0 || !sample_rate_ ); // fails if clock/output ratio is too large131return (blip_resampled_time_t) factor;132}133134void Blip_Buffer::bass_freq( int freq )135{136bass_freq_ = freq;137int shift = 31;138if ( freq > 0 )139{140shift = 13;141long f = (freq << 16) / sample_rate_;142while ( (f >>= 1) && --shift ) { }143}144bass_shift_ = shift;145}146147void Blip_Buffer::end_frame( blip_time_t t )148{149offset_ += t * factor_;150assert( samples_avail() <= (long) buffer_size_ ); // fails if time is past end of buffer151}152153long Blip_Buffer::count_samples( blip_time_t t ) const154{155blip_resampled_time_t last_sample = resampled_time( t ) >> BLIP_BUFFER_ACCURACY;156blip_resampled_time_t first_sample = offset_ >> BLIP_BUFFER_ACCURACY;157return long (last_sample - first_sample);158}159160blip_time_t Blip_Buffer::count_clocks( long count ) const161{162if ( !factor_ )163{164assert( 0 ); // sample rate and clock rates must be set first165return 0;166}167168if ( count > buffer_size_ )169count = buffer_size_;170blip_resampled_time_t time = (blip_resampled_time_t) count << BLIP_BUFFER_ACCURACY;171return (blip_time_t) ((time - offset_ + factor_ - 1) / factor_);172}173174void Blip_Buffer::remove_samples( long count )175{176if ( count )177{178remove_silence( count );179180// copy remaining samples to beginning and clear old samples181long remain = samples_avail() + blip_buffer_extra_;182memmove( buffer_, buffer_ + count, remain * sizeof *buffer_ );183memset( buffer_ + remain, 0, count * sizeof *buffer_ );184}185}186187// Blip_Synth_188189Blip_Synth_Fast_::Blip_Synth_Fast_()190{191buf = 0;192last_amp = 0;193delta_factor = 0;194}195196void Blip_Synth_Fast_::volume_unit( double new_unit )197{198delta_factor = int (new_unit * (1L << blip_sample_bits) + 0.5);199}200201#if !BLIP_BUFFER_FAST202203Blip_Synth_::Blip_Synth_( short* p, int w ) :204impulses( p ),205width( w )206{207volume_unit_ = 0.0;208kernel_unit = 0;209buf = 0;210last_amp = 0;211delta_factor = 0;212}213214#undef PI215#define PI 3.1415926535897932384626433832795029216217static void gen_sinc( float* out, int count, double oversample, double treble, double cutoff )218{219if ( cutoff >= 0.999 )220cutoff = 0.999;221222if ( treble < -300.0 )223treble = -300.0;224if ( treble > 5.0 )225treble = 5.0;226227double const maxh = 4096.0;228double const rolloff = pow( 10.0, 1.0 / (maxh * 20.0) * treble / (1.0 - cutoff) );229double const pow_a_n = pow( rolloff, maxh - maxh * cutoff );230double const to_angle = PI / 2 / maxh / oversample;231for ( int i = 0; i < count; i++ )232{233double angle = ((i - count) * 2 + 1) * to_angle;234double c = rolloff * cos( (maxh - 1.0) * angle ) - cos( maxh * angle );235double cos_nc_angle = cos( maxh * cutoff * angle );236double cos_nc1_angle = cos( (maxh * cutoff - 1.0) * angle );237double cos_angle = cos( angle );238239c = c * pow_a_n - rolloff * cos_nc1_angle + cos_nc_angle;240double d = 1.0 + rolloff * (rolloff - cos_angle - cos_angle);241double b = 2.0 - cos_angle - cos_angle;242double a = 1.0 - cos_angle - cos_nc_angle + cos_nc1_angle;243244out [i] = (float) ((a * d + c * b) / (b * d)); // a / b + c / d245}246}247248void blip_eq_t::generate( float* out, int count ) const249{250// lower cutoff freq for narrow kernels with their wider transition band251// (8 points->1.49, 16 points->1.15)252double oversample = blip_res * 2.25 / count + 0.85;253double half_rate = sample_rate * 0.5;254if ( cutoff_freq )255oversample = half_rate / cutoff_freq;256double cutoff = rolloff_freq * oversample / half_rate;257258gen_sinc( out, count, blip_res * oversample, treble, cutoff );259260// apply (half of) hamming window261double to_fraction = PI / (count - 1);262for ( int i = count; i--; )263out [i] *= 0.54f - 0.46f * (float) cos( i * to_fraction );264}265266void Blip_Synth_::adjust_impulse()267{268// sum pairs for each phase and add error correction to end of first half269int const size = impulses_size();270for ( int p = blip_res; p-- >= blip_res / 2; )271{272int p2 = blip_res - 2 - p;273long error = kernel_unit;274for ( int i = 1; i < size; i += blip_res )275{276error -= impulses [i + p ];277error -= impulses [i + p2];278}279if ( p == p2 )280error /= 2; // phase = 0.5 impulse uses same half for both sides281impulses [size - blip_res + p] += (short) error;282//printf( "error: %ld\n", error );283}284285//for ( int i = blip_res; i--; printf( "\n" ) )286// for ( int j = 0; j < width / 2; j++ )287// printf( "%5ld,", impulses [j * blip_res + i + 1] );288}289290void Blip_Synth_::treble_eq( blip_eq_t const& eq )291{292float fimpulse [blip_res / 2 * (blip_widest_impulse_ - 1) + blip_res * 2];293294int const half_size = blip_res / 2 * (width - 1);295eq.generate( &fimpulse [blip_res], half_size );296297int i;298299// need mirror slightly past center for calculation300for ( i = blip_res; i--; )301fimpulse [blip_res + half_size + i] = fimpulse [blip_res + half_size - 1 - i];302303// starts at 0304for ( i = 0; i < blip_res; i++ )305fimpulse [i] = 0.0f;306307// find rescale factor308double total = 0.0;309for ( i = 0; i < half_size; i++ )310total += fimpulse [blip_res + i];311312//double const base_unit = 44800.0 - 128 * 18; // allows treble up to +0 dB313//double const base_unit = 37888.0; // allows treble to +5 dB314double const base_unit = 32768.0; // necessary for blip_unscaled to work315double rescale = base_unit / 2 / total;316kernel_unit = (long) base_unit;317318// integrate, first difference, rescale, convert to int319double sum = 0.0;320double next = 0.0;321int const size = this->impulses_size();322for ( i = 0; i < size; i++ )323{324impulses [i] = (short) (int) floor( (next - sum) * rescale + 0.5 );325sum += fimpulse [i];326next += fimpulse [i + blip_res];327}328adjust_impulse();329330// volume might require rescaling331double vol = volume_unit_;332if ( vol )333{334volume_unit_ = 0.0;335volume_unit( vol );336}337}338339void Blip_Synth_::volume_unit( double new_unit )340{341if ( new_unit != volume_unit_ )342{343// use default eq if it hasn't been set yet344if ( !kernel_unit )345treble_eq( -8.0 );346347volume_unit_ = new_unit;348double factor = new_unit * (1L << blip_sample_bits) / kernel_unit;349350if ( factor > 0.0 )351{352int shift = 0;353354// if unit is really small, might need to attenuate kernel355while ( factor < 2.0 )356{357shift++;358factor *= 2.0;359}360361if ( shift )362{363kernel_unit >>= shift;364assert( kernel_unit > 0 ); // fails if volume unit is too low365366// keep values positive to avoid round-towards-zero of sign-preserving367// right shift for negative values368long offset = 0x8000 + (1 << (shift - 1));369long offset2 = 0x8000 >> shift;370for ( int i = impulses_size(); i--; )371impulses [i] = (short) (int) (((impulses [i] + offset) >> shift) - offset2);372adjust_impulse();373}374}375delta_factor = (int) floor( factor + 0.5 );376//printf( "delta_factor: %d, kernel_unit: %d\n", delta_factor, kernel_unit );377}378}379#endif380381long Blip_Buffer::read_samples( blip_sample_t* out_, long max_samples, int stereo )382{383long count = samples_avail();384if ( count > max_samples )385count = max_samples;386387if ( count )388{389int const bass = BLIP_READER_BASS( *this );390BLIP_READER_BEGIN( reader, *this );391BLIP_READER_ADJ_( reader, count );392blip_sample_t* BLIP_RESTRICT out = out_ + count;393blip_long offset = (blip_long) -count;394395if ( !stereo )396{397do398{399blip_long s = BLIP_READER_READ( reader );400BLIP_READER_NEXT_IDX_( reader, bass, offset );401BLIP_CLAMP( s, s );402out [offset] = (blip_sample_t) s;403}404while ( ++offset );405}406else407{408do409{410blip_long s = BLIP_READER_READ( reader );411BLIP_READER_NEXT_IDX_( reader, bass, offset );412BLIP_CLAMP( s, s );413out [offset * 2] = (blip_sample_t) s;414}415while ( ++offset );416}417418BLIP_READER_END( reader, *this );419420remove_samples( count );421}422return count;423}424425void Blip_Buffer::mix_samples( blip_sample_t const* in, long count )426{427if ( buffer_size_ == silent_buf_size )428{429assert( 0 );430return;431}432433buf_t_* out = buffer_ + (offset_ >> BLIP_BUFFER_ACCURACY) + blip_widest_impulse_ / 2;434435int const sample_shift = blip_sample_bits - 16;436int prev = 0;437while ( count-- )438{439blip_long s = (blip_long) *in++ << sample_shift;440*out += s - prev;441prev = s;442++out;443}444*out -= prev;445}446447void Blip_Buffer::save_state( blip_buffer_state_t* out )448{449assert( samples_avail() == 0 );450out->offset_ = offset_;451out->reader_accum_ = reader_accum_;452memcpy( out->buf, &buffer_ [offset_ >> BLIP_BUFFER_ACCURACY], sizeof out->buf );453}454455void Blip_Buffer::load_state( blip_buffer_state_t const& in )456{457clear( false );458459offset_ = in.offset_;460reader_accum_ = in.reader_accum_;461memcpy( buffer_, in.buf, sizeof in.buf );462}463464465