Chris@55: /** @file paex_ocean_shore.c Chris@55: @ingroup examples_src Chris@55: @brief Generate Pink Noise using Gardner method, and make "waves". Provides an example of how to Chris@55: post stuff to/from the audio callback using lock-free FIFOs implemented by the PA ringbuffer. Chris@55: Chris@55: Optimization suggested by James McCartney uses a tree Chris@55: to select which random value to replace. Chris@55:
Chris@55: 	x x x x x x x x x x x x x x x x 
Chris@55: 	x   x   x   x   x   x   x   x   
Chris@55: 	x       x       x       x       
Chris@55: 	 x               x               
Chris@55: 	   x   
Chris@55: 
Chris@55: Tree is generated by counting trailing zeros in an increasing index. Chris@55: When the index is zero, no random number is selected. Chris@55: Chris@55: @author Phil Burk http://www.softsynth.com Chris@55: Robert Bielik Chris@55: */ Chris@55: /* Chris@55: * $Id$ Chris@55: * Chris@55: * This program uses the PortAudio Portable Audio Library. Chris@55: * For more information see: http://www.portaudio.com Chris@55: * Copyright (c) 1999-2000 Ross Bencina and Phil Burk Chris@55: * Chris@55: * Permission is hereby granted, free of charge, to any person obtaining Chris@55: * a copy of this software and associated documentation files Chris@55: * (the "Software"), to deal in the Software without restriction, Chris@55: * including without limitation the rights to use, copy, modify, merge, Chris@55: * publish, distribute, sublicense, and/or sell copies of the Software, Chris@55: * and to permit persons to whom the Software is furnished to do so, Chris@55: * subject to the following conditions: Chris@55: * Chris@55: * The above copyright notice and this permission notice shall be Chris@55: * included in all copies or substantial portions of the Software. Chris@55: * Chris@55: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, Chris@55: * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF Chris@55: * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. Chris@55: * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR Chris@55: * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF Chris@55: * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION Chris@55: * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Chris@55: */ Chris@55: Chris@55: /* Chris@55: * The text above constitutes the entire PortAudio license; however, Chris@55: * the PortAudio community also makes the following non-binding requests: Chris@55: * Chris@55: * Any person wishing to distribute modifications to the Software is Chris@55: * requested to send the modifications to the original developer so that Chris@55: * they can be incorporated into the canonical version. It is also Chris@55: * requested that these non-binding requests be included along with the Chris@55: * license above. Chris@55: */ Chris@55: Chris@55: #include Chris@55: #include Chris@55: #include Chris@55: #include Chris@55: #include Chris@55: Chris@55: #include "portaudio.h" Chris@55: #include "pa_ringbuffer.h" Chris@55: #include "pa_util.h" Chris@55: Chris@55: #define PINK_MAX_RANDOM_ROWS (30) Chris@55: #define PINK_RANDOM_BITS (24) Chris@55: #define PINK_RANDOM_SHIFT ((sizeof(long)*8)-PINK_RANDOM_BITS) Chris@55: Chris@55: typedef struct Chris@55: { Chris@55: long pink_Rows[PINK_MAX_RANDOM_ROWS]; Chris@55: long pink_RunningSum; /* Used to optimize summing of generators. */ Chris@55: int pink_Index; /* Incremented each sample. */ Chris@55: int pink_IndexMask; /* Index wrapped by ANDing with this mask. */ Chris@55: float pink_Scalar; /* Used to scale within range of -1.0 to +1.0 */ Chris@55: } Chris@55: PinkNoise; Chris@55: Chris@55: typedef struct Chris@55: { Chris@55: float bq_b0; Chris@55: float bq_b1; Chris@55: float bq_b2; Chris@55: float bq_a1; Chris@55: float bq_a2; Chris@55: } BiQuad; Chris@55: Chris@55: typedef enum Chris@55: { Chris@55: State_kAttack, Chris@55: State_kPreDecay, Chris@55: State_kDecay, Chris@55: State_kCnt, Chris@55: } EnvState; Chris@55: Chris@55: typedef struct Chris@55: { Chris@55: PinkNoise wave_left; Chris@55: PinkNoise wave_right; Chris@55: Chris@55: BiQuad wave_bq_coeffs; Chris@55: float wave_bq_left[2]; Chris@55: float wave_bq_right[2]; Chris@55: Chris@55: EnvState wave_envelope_state; Chris@55: float wave_envelope_level; Chris@55: float wave_envelope_max_level; Chris@55: float wave_pan_left; Chris@55: float wave_pan_right; Chris@55: float wave_attack_incr; Chris@55: float wave_decay_incr; Chris@55: Chris@55: } OceanWave; Chris@55: Chris@55: /* Prototypes */ Chris@55: static unsigned long GenerateRandomNumber( void ); Chris@55: void InitializePinkNoise( PinkNoise *pink, int numRows ); Chris@55: float GeneratePinkNoise( PinkNoise *pink ); Chris@55: unsigned GenerateWave( OceanWave* wave, float* output, unsigned noOfFrames); Chris@55: Chris@55: /************************************************************/ Chris@55: /* Calculate pseudo-random 32 bit number based on linear congruential method. */ Chris@55: static unsigned long GenerateRandomNumber( void ) Chris@55: { Chris@55: /* Change this seed for different random sequences. */ Chris@55: static unsigned long randSeed = 22222; Chris@55: randSeed = (randSeed * 196314165) + 907633515; Chris@55: return randSeed; Chris@55: } Chris@55: Chris@55: /************************************************************/ Chris@55: /* Setup PinkNoise structure for N rows of generators. */ Chris@55: void InitializePinkNoise( PinkNoise *pink, int numRows ) Chris@55: { Chris@55: int i; Chris@55: long pmax; Chris@55: pink->pink_Index = 0; Chris@55: pink->pink_IndexMask = (1<pink_Scalar = 1.0f / pmax; Chris@55: /* Initialize rows. */ Chris@55: for( i=0; ipink_Rows[i] = 0; Chris@55: pink->pink_RunningSum = 0; Chris@55: } Chris@55: Chris@55: /* Generate Pink noise values between -1.0 and +1.0 */ Chris@55: float GeneratePinkNoise( PinkNoise *pink ) Chris@55: { Chris@55: long newRandom; Chris@55: long sum; Chris@55: float output; Chris@55: /* Increment and mask index. */ Chris@55: pink->pink_Index = (pink->pink_Index + 1) & pink->pink_IndexMask; Chris@55: /* If index is zero, don't update any random values. */ Chris@55: if( pink->pink_Index != 0 ) Chris@55: { Chris@55: /* Determine how many trailing zeros in PinkIndex. */ Chris@55: /* This algorithm will hang if n==0 so test first. */ Chris@55: int numZeros = 0; Chris@55: int n = pink->pink_Index; Chris@55: while( (n & 1) == 0 ) Chris@55: { Chris@55: n = n >> 1; Chris@55: numZeros++; Chris@55: } Chris@55: /* Replace the indexed ROWS random value. Chris@55: * Subtract and add back to RunningSum instead of adding all the random Chris@55: * values together. Only one changes each time. Chris@55: */ Chris@55: pink->pink_RunningSum -= pink->pink_Rows[numZeros]; Chris@55: newRandom = ((long)GenerateRandomNumber()) >> PINK_RANDOM_SHIFT; Chris@55: pink->pink_RunningSum += newRandom; Chris@55: pink->pink_Rows[numZeros] = newRandom; Chris@55: } Chris@55: Chris@55: /* Add extra white noise value. */ Chris@55: newRandom = ((long)GenerateRandomNumber()) >> PINK_RANDOM_SHIFT; Chris@55: sum = pink->pink_RunningSum + newRandom; Chris@55: /* Scale to range of -1.0 to 0.9999. */ Chris@55: output = pink->pink_Scalar * sum; Chris@55: return output; Chris@55: } Chris@55: Chris@55: float ProcessBiquad(const BiQuad* coeffs, float* memory, float input) Chris@55: { Chris@55: float w = input - coeffs->bq_a1 * memory[0] - coeffs->bq_a2 * memory[1]; Chris@55: float out = coeffs->bq_b1 * memory[0] + coeffs->bq_b2 * memory[1] + coeffs->bq_b0 * w; Chris@55: memory[1] = memory[0]; Chris@55: memory[0] = w; Chris@55: return out; Chris@55: } Chris@55: Chris@55: static const float one_over_2Q_LP = 0.3f; Chris@55: static const float one_over_2Q_HP = 1.0f; Chris@55: Chris@55: unsigned GenerateWave( OceanWave* wave, float* output, unsigned noOfFrames ) Chris@55: { Chris@55: unsigned retval=0,i; Chris@55: float targetLevel, levelIncr, currentLevel; Chris@55: switch (wave->wave_envelope_state) Chris@55: { Chris@55: case State_kAttack: Chris@55: targetLevel = noOfFrames * wave->wave_attack_incr + wave->wave_envelope_level; Chris@55: if (targetLevel >= wave->wave_envelope_max_level) Chris@55: { Chris@55: /* Go to decay state */ Chris@55: wave->wave_envelope_state = State_kPreDecay; Chris@55: targetLevel = wave->wave_envelope_max_level; Chris@55: } Chris@55: /* Calculate lowpass biquad coeffs Chris@55: Chris@55: alpha = sin(w0)/(2*Q) Chris@55: Chris@55: b0 = (1 - cos(w0))/2 Chris@55: b1 = 1 - cos(w0) Chris@55: b2 = (1 - cos(w0))/2 Chris@55: a0 = 1 + alpha Chris@55: a1 = -2*cos(w0) Chris@55: a2 = 1 - alpha Chris@55: Chris@55: w0 = [0 - pi[ Chris@55: */ Chris@55: { Chris@55: const float w0 = 3.141592654f * targetLevel / wave->wave_envelope_max_level; Chris@55: const float alpha = sinf(w0) * one_over_2Q_LP; Chris@55: const float cosw0 = cosf(w0); Chris@55: const float a0_fact = 1.0f / (1.0f + alpha); Chris@55: wave->wave_bq_coeffs.bq_b1 = (1.0f - cosw0) * a0_fact; Chris@55: wave->wave_bq_coeffs.bq_b0 = wave->wave_bq_coeffs.bq_b1 * 0.5f; Chris@55: wave->wave_bq_coeffs.bq_b2 = wave->wave_bq_coeffs.bq_b0; Chris@55: wave->wave_bq_coeffs.bq_a2 = (1.0f - alpha) * a0_fact; Chris@55: wave->wave_bq_coeffs.bq_a1 = -2.0f * cosw0 * a0_fact; Chris@55: } Chris@55: break; Chris@55: Chris@55: case State_kPreDecay: Chris@55: /* Reset biquad state */ Chris@55: memset(wave->wave_bq_left, 0, 2 * sizeof(float)); Chris@55: memset(wave->wave_bq_right, 0, 2 * sizeof(float)); Chris@55: wave->wave_envelope_state = State_kDecay; Chris@55: Chris@55: /* Deliberate fall-through */ Chris@55: Chris@55: case State_kDecay: Chris@55: targetLevel = noOfFrames * wave->wave_decay_incr + wave->wave_envelope_level; Chris@55: if (targetLevel < 0.001f) Chris@55: { Chris@55: /* < -60 dB, we're done */ Chris@55: wave->wave_envelope_state = 3; Chris@55: retval = 1; Chris@55: } Chris@55: /* Calculate highpass biquad coeffs Chris@55: Chris@55: alpha = sin(w0)/(2*Q) Chris@55: Chris@55: b0 = (1 + cos(w0))/2 Chris@55: b1 = -(1 + cos(w0)) Chris@55: b2 = (1 + cos(w0))/2 Chris@55: a0 = 1 + alpha Chris@55: a1 = -2*cos(w0) Chris@55: a2 = 1 - alpha Chris@55: Chris@55: w0 = [0 - pi/2[ Chris@55: */ Chris@55: { Chris@55: const float v = targetLevel / wave->wave_envelope_max_level; Chris@55: const float w0 = 1.5707963f * (1.0f - (v*v)); Chris@55: const float alpha = sinf(w0) * one_over_2Q_HP; Chris@55: const float cosw0 = cosf(w0); Chris@55: const float a0_fact = 1.0f / (1.0f + alpha); Chris@55: wave->wave_bq_coeffs.bq_b1 = (float)(- (1 + cosw0) * a0_fact); Chris@55: wave->wave_bq_coeffs.bq_b0 = -wave->wave_bq_coeffs.bq_b1 * 0.5f; Chris@55: wave->wave_bq_coeffs.bq_b2 = wave->wave_bq_coeffs.bq_b0; Chris@55: wave->wave_bq_coeffs.bq_a2 = (float)((1.0 - alpha) * a0_fact); Chris@55: wave->wave_bq_coeffs.bq_a1 = (float)(-2.0 * cosw0 * a0_fact); Chris@55: } Chris@55: break; Chris@55: Chris@55: default: Chris@55: break; Chris@55: } Chris@55: Chris@55: currentLevel = wave->wave_envelope_level; Chris@55: wave->wave_envelope_level = targetLevel; Chris@55: levelIncr = (targetLevel - currentLevel) / noOfFrames; Chris@55: Chris@55: for (i = 0; i < noOfFrames; ++i, currentLevel += levelIncr) Chris@55: { Chris@55: (*output++) += ProcessBiquad(&wave->wave_bq_coeffs, wave->wave_bq_left, (GeneratePinkNoise(&wave->wave_left))) * currentLevel * wave->wave_pan_left; Chris@55: (*output++) += ProcessBiquad(&wave->wave_bq_coeffs, wave->wave_bq_right, (GeneratePinkNoise(&wave->wave_right))) * currentLevel * wave->wave_pan_right; Chris@55: } Chris@55: Chris@55: return retval; Chris@55: } Chris@55: Chris@55: Chris@55: /*******************************************************************/ Chris@55: Chris@55: /* Context for callback routine. */ Chris@55: typedef struct Chris@55: { Chris@55: OceanWave* waves[16]; /* Maximum 16 waves */ Chris@55: unsigned noOfActiveWaves; Chris@55: Chris@55: /* Ring buffer (FIFO) for "communicating" towards audio callback */ Chris@55: PaUtilRingBuffer rBufToRT; Chris@55: void* rBufToRTData; Chris@55: Chris@55: /* Ring buffer (FIFO) for "communicating" from audio callback */ Chris@55: PaUtilRingBuffer rBufFromRT; Chris@55: void* rBufFromRTData; Chris@55: } Chris@55: paTestData; Chris@55: Chris@55: /* This routine will be called by the PortAudio engine when audio is needed. Chris@55: ** It may called at interrupt level on some machines so don't do anything Chris@55: ** that could mess up the system like calling malloc() or free(). Chris@55: */ Chris@55: static int patestCallback(const void* inputBuffer, Chris@55: void* outputBuffer, Chris@55: unsigned long framesPerBuffer, Chris@55: const PaStreamCallbackTimeInfo* timeInfo, Chris@55: PaStreamCallbackFlags statusFlags, Chris@55: void* userData) Chris@55: { Chris@55: int i; Chris@55: paTestData *data = (paTestData*)userData; Chris@55: float *out = (float*)outputBuffer; Chris@55: (void) inputBuffer; /* Prevent "unused variable" warnings. */ Chris@55: Chris@55: /* Reset output data first */ Chris@55: memset(out, 0, framesPerBuffer * 2 * sizeof(float)); Chris@55: Chris@55: for (i = 0; i < 16; ++i) Chris@55: { Chris@55: /* Consume the input queue */ Chris@55: if (data->waves[i] == 0 && PaUtil_GetRingBufferReadAvailable(&data->rBufToRT)) Chris@55: { Chris@55: OceanWave* ptr = 0; Chris@55: PaUtil_ReadRingBuffer(&data->rBufToRT, &ptr, 1); Chris@55: data->waves[i] = ptr; Chris@55: } Chris@55: Chris@55: if (data->waves[i] != 0) Chris@55: { Chris@55: if (GenerateWave(data->waves[i], out, framesPerBuffer)) Chris@55: { Chris@55: /* If wave is "done", post it back to the main thread for deletion */ Chris@55: PaUtil_WriteRingBuffer(&data->rBufFromRT, &data->waves[i], 1); Chris@55: data->waves[i] = 0; Chris@55: } Chris@55: } Chris@55: } Chris@55: return paContinue; Chris@55: } Chris@55: Chris@55: #define NEW_ROW_SIZE (12 + (8*rand())/RAND_MAX) Chris@55: Chris@55: OceanWave* InitializeWave(double SR, float attackInSeconds, float maxLevel, float positionLeftRight) Chris@55: { Chris@55: OceanWave* wave = NULL; Chris@55: static unsigned lastNoOfRows = 12; Chris@55: unsigned newNoOfRows; Chris@55: Chris@55: wave = (OceanWave*)PaUtil_AllocateMemory(sizeof(OceanWave)); Chris@55: if (wave != NULL) Chris@55: { Chris@55: InitializePinkNoise(&wave->wave_left, lastNoOfRows); Chris@55: while ((newNoOfRows = NEW_ROW_SIZE) == lastNoOfRows); Chris@55: InitializePinkNoise(&wave->wave_right, newNoOfRows); Chris@55: lastNoOfRows = newNoOfRows; Chris@55: Chris@55: wave->wave_envelope_state = State_kAttack; Chris@55: wave->wave_envelope_level = 0.f; Chris@55: wave->wave_envelope_max_level = maxLevel; Chris@55: wave->wave_attack_incr = wave->wave_envelope_max_level / (attackInSeconds * (float)SR); Chris@55: wave->wave_decay_incr = - wave->wave_envelope_max_level / (attackInSeconds * 4 * (float)SR); Chris@55: Chris@55: wave->wave_pan_left = sqrtf(1.0f - positionLeftRight); Chris@55: wave->wave_pan_right = sqrtf(positionLeftRight); Chris@55: } Chris@55: return wave; Chris@55: } Chris@55: Chris@55: static float GenerateFloatRandom(float minValue, float maxValue) Chris@55: { Chris@55: return minValue + ((maxValue - minValue) * rand()) / RAND_MAX; Chris@55: } Chris@55: Chris@55: /*******************************************************************/ Chris@55: int main(void); Chris@55: int main(void) Chris@55: { Chris@55: PaStream* stream; Chris@55: PaError err; Chris@55: paTestData data = {0}; Chris@55: PaStreamParameters outputParameters; Chris@55: double tstamp; Chris@55: double tstart; Chris@55: double tdelta = 0; Chris@55: static const double SR = 44100.0; Chris@55: static const int FPB = 128; /* Frames per buffer: 2.9 ms buffers. */ Chris@55: Chris@55: /* Initialize communication buffers (queues) */ Chris@55: data.rBufToRTData = PaUtil_AllocateMemory(sizeof(OceanWave*) * 256); Chris@55: if (data.rBufToRTData == NULL) Chris@55: { Chris@55: return 1; Chris@55: } Chris@55: PaUtil_InitializeRingBuffer(&data.rBufToRT, sizeof(OceanWave*), 256, data.rBufToRTData); Chris@55: Chris@55: data.rBufFromRTData = PaUtil_AllocateMemory(sizeof(OceanWave*) * 256); Chris@55: if (data.rBufFromRTData == NULL) Chris@55: { Chris@55: return 1; Chris@55: } Chris@55: PaUtil_InitializeRingBuffer(&data.rBufFromRT, sizeof(OceanWave*), 256, data.rBufFromRTData); Chris@55: Chris@55: err = Pa_Initialize(); Chris@55: if( err != paNoError ) goto error; Chris@55: Chris@55: /* Open a stereo PortAudio stream so we can hear the result. */ Chris@55: outputParameters.device = Pa_GetDefaultOutputDevice(); /* Take the default output device. */ Chris@55: if (outputParameters.device == paNoDevice) { Chris@55: fprintf(stderr,"Error: No default output device.\n"); Chris@55: goto error; Chris@55: } Chris@55: outputParameters.channelCount = 2; /* Stereo output, most likely supported. */ Chris@55: outputParameters.hostApiSpecificStreamInfo = NULL; Chris@55: outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output. */ Chris@55: outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency; Chris@55: err = Pa_OpenStream(&stream, Chris@55: NULL, /* No input. */ Chris@55: &outputParameters, Chris@55: SR, /* Sample rate. */ Chris@55: FPB, /* Frames per buffer. */ Chris@55: paDitherOff, /* Clip but don't dither */ Chris@55: patestCallback, Chris@55: &data); Chris@55: if( err != paNoError ) goto error; Chris@55: Chris@55: err = Pa_StartStream( stream ); Chris@55: if( err != paNoError ) goto error; Chris@55: Chris@55: printf("Stereo \"ocean waves\" for one minute...\n"); Chris@55: Chris@55: tstart = PaUtil_GetTime(); Chris@55: tstamp = tstart; Chris@55: srand( (unsigned)time(NULL) ); Chris@55: Chris@55: while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Chris@55: { Chris@55: const double tcurrent = PaUtil_GetTime(); Chris@55: Chris@55: /* Delete "waves" that the callback is finished with */ Chris@55: while (PaUtil_GetRingBufferReadAvailable(&data.rBufFromRT) > 0) Chris@55: { Chris@55: OceanWave* ptr = 0; Chris@55: PaUtil_ReadRingBuffer(&data.rBufFromRT, &ptr, 1); Chris@55: if (ptr != 0) Chris@55: { Chris@55: printf("Wave is deleted...\n"); Chris@55: PaUtil_FreeMemory(ptr); Chris@55: --data.noOfActiveWaves; Chris@55: } Chris@55: } Chris@55: Chris@55: if (tcurrent - tstart < 60.0) /* Only start new "waves" during one minute */ Chris@55: { Chris@55: if (tcurrent >= tstamp) Chris@55: { Chris@55: double tdelta = GenerateFloatRandom(1.0f, 4.0f); Chris@55: tstamp += tdelta; Chris@55: Chris@55: if (data.noOfActiveWaves<16) Chris@55: { Chris@55: const float attackTime = GenerateFloatRandom(2.0f, 6.0f); Chris@55: const float level = GenerateFloatRandom(0.1f, 1.0f); Chris@55: const float pos = GenerateFloatRandom(0.0f, 1.0f); Chris@55: OceanWave* p = InitializeWave(SR, attackTime, level, pos); Chris@55: if (p != NULL) Chris@55: { Chris@55: /* Post wave to audio callback */ Chris@55: PaUtil_WriteRingBuffer(&data.rBufToRT, &p, 1); Chris@55: ++data.noOfActiveWaves; Chris@55: Chris@55: printf("Starting wave at level = %.2f, attack = %.2lf, pos = %.2lf\n", level, attackTime, pos); Chris@55: } Chris@55: } Chris@55: } Chris@55: } Chris@55: else Chris@55: { Chris@55: if (data.noOfActiveWaves == 0) Chris@55: { Chris@55: printf("All waves finished!\n"); Chris@55: break; Chris@55: } Chris@55: } Chris@55: Chris@55: Pa_Sleep(100); Chris@55: } Chris@55: if( err < 0 ) goto error; Chris@55: Chris@55: err = Pa_CloseStream( stream ); Chris@55: if( err != paNoError ) goto error; Chris@55: Chris@55: if (data.rBufToRTData) Chris@55: { Chris@55: PaUtil_FreeMemory(data.rBufToRTData); Chris@55: } Chris@55: if (data.rBufFromRTData) Chris@55: { Chris@55: PaUtil_FreeMemory(data.rBufFromRTData); Chris@55: } Chris@55: Chris@55: Pa_Sleep(1000); Chris@55: Chris@55: Pa_Terminate(); Chris@55: return 0; Chris@55: Chris@55: error: Chris@55: Pa_Terminate(); Chris@55: fprintf( stderr, "An error occured while using the portaudio stream\n" ); Chris@55: fprintf( stderr, "Error number: %d\n", err ); Chris@55: fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); Chris@55: return 0; Chris@55: }