cannam@124: /** @file paex_pink.c cannam@124: @ingroup examples_src cannam@124: @brief Generate Pink Noise using Gardner method. cannam@124: cannam@124: Optimization suggested by James McCartney uses a tree cannam@124: to select which random value to replace. cannam@124:
cannam@124: 	x x x x x x x x x x x x x x x x 
cannam@124: 	x   x   x   x   x   x   x   x   
cannam@124: 	x       x       x       x       
cannam@124: 	 x               x               
cannam@124: 	   x   
cannam@124: 
cannam@124: Tree is generated by counting trailing zeros in an increasing index. cannam@124: When the index is zero, no random number is selected. cannam@124: cannam@124: @author Phil Burk http://www.softsynth.com cannam@124: */ cannam@124: /* cannam@124: * $Id: paex_pink.c 1752 2011-09-08 03:21:55Z philburk $ cannam@124: * cannam@124: * This program uses the PortAudio Portable Audio Library. cannam@124: * For more information see: http://www.portaudio.com cannam@124: * Copyright (c) 1999-2000 Ross Bencina and Phil Burk cannam@124: * cannam@124: * Permission is hereby granted, free of charge, to any person obtaining cannam@124: * a copy of this software and associated documentation files cannam@124: * (the "Software"), to deal in the Software without restriction, cannam@124: * including without limitation the rights to use, copy, modify, merge, cannam@124: * publish, distribute, sublicense, and/or sell copies of the Software, cannam@124: * and to permit persons to whom the Software is furnished to do so, cannam@124: * subject to the following conditions: cannam@124: * cannam@124: * The above copyright notice and this permission notice shall be cannam@124: * included in all copies or substantial portions of the Software. cannam@124: * cannam@124: * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, cannam@124: * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF cannam@124: * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. cannam@124: * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR cannam@124: * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF cannam@124: * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION cannam@124: * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. cannam@124: */ cannam@124: cannam@124: /* cannam@124: * The text above constitutes the entire PortAudio license; however, cannam@124: * the PortAudio community also makes the following non-binding requests: cannam@124: * cannam@124: * Any person wishing to distribute modifications to the Software is cannam@124: * requested to send the modifications to the original developer so that cannam@124: * they can be incorporated into the canonical version. It is also cannam@124: * requested that these non-binding requests be included along with the cannam@124: * license above. cannam@124: */ cannam@124: cannam@124: #include cannam@124: #include cannam@124: #include "portaudio.h" cannam@124: cannam@124: #define PINK_MAX_RANDOM_ROWS (30) cannam@124: #define PINK_RANDOM_BITS (24) cannam@124: #define PINK_RANDOM_SHIFT ((sizeof(long)*8)-PINK_RANDOM_BITS) cannam@124: cannam@124: typedef struct cannam@124: { cannam@124: long pink_Rows[PINK_MAX_RANDOM_ROWS]; cannam@124: long pink_RunningSum; /* Used to optimize summing of generators. */ cannam@124: int pink_Index; /* Incremented each sample. */ cannam@124: int pink_IndexMask; /* Index wrapped by ANDing with this mask. */ cannam@124: float pink_Scalar; /* Used to scale within range of -1.0 to +1.0 */ cannam@124: } cannam@124: PinkNoise; cannam@124: cannam@124: /* Prototypes */ cannam@124: static unsigned long GenerateRandomNumber( void ); cannam@124: void InitializePinkNoise( PinkNoise *pink, int numRows ); cannam@124: float GeneratePinkNoise( PinkNoise *pink ); cannam@124: cannam@124: /************************************************************/ cannam@124: /* Calculate pseudo-random 32 bit number based on linear congruential method. */ cannam@124: static unsigned long GenerateRandomNumber( void ) cannam@124: { cannam@124: /* Change this seed for different random sequences. */ cannam@124: static unsigned long randSeed = 22222; cannam@124: randSeed = (randSeed * 196314165) + 907633515; cannam@124: return randSeed; cannam@124: } cannam@124: cannam@124: /************************************************************/ cannam@124: /* Setup PinkNoise structure for N rows of generators. */ cannam@124: void InitializePinkNoise( PinkNoise *pink, int numRows ) cannam@124: { cannam@124: int i; cannam@124: long pmax; cannam@124: pink->pink_Index = 0; cannam@124: pink->pink_IndexMask = (1<pink_Scalar = 1.0f / pmax; cannam@124: /* Initialize rows. */ cannam@124: for( i=0; ipink_Rows[i] = 0; cannam@124: pink->pink_RunningSum = 0; cannam@124: } cannam@124: cannam@124: #define PINK_MEASURE cannam@124: #ifdef PINK_MEASURE cannam@124: float pinkMax = -999.0; cannam@124: float pinkMin = 999.0; cannam@124: #endif cannam@124: cannam@124: /* Generate Pink noise values between -1.0 and +1.0 */ cannam@124: float GeneratePinkNoise( PinkNoise *pink ) cannam@124: { cannam@124: long newRandom; cannam@124: long sum; cannam@124: float output; cannam@124: /* Increment and mask index. */ cannam@124: pink->pink_Index = (pink->pink_Index + 1) & pink->pink_IndexMask; cannam@124: /* If index is zero, don't update any random values. */ cannam@124: if( pink->pink_Index != 0 ) cannam@124: { cannam@124: /* Determine how many trailing zeros in PinkIndex. */ cannam@124: /* This algorithm will hang if n==0 so test first. */ cannam@124: int numZeros = 0; cannam@124: int n = pink->pink_Index; cannam@124: while( (n & 1) == 0 ) cannam@124: { cannam@124: n = n >> 1; cannam@124: numZeros++; cannam@124: } cannam@124: /* Replace the indexed ROWS random value. cannam@124: * Subtract and add back to RunningSum instead of adding all the random cannam@124: * values together. Only one changes each time. cannam@124: */ cannam@124: pink->pink_RunningSum -= pink->pink_Rows[numZeros]; cannam@124: newRandom = ((long)GenerateRandomNumber()) >> PINK_RANDOM_SHIFT; cannam@124: pink->pink_RunningSum += newRandom; cannam@124: pink->pink_Rows[numZeros] = newRandom; cannam@124: } cannam@124: cannam@124: /* Add extra white noise value. */ cannam@124: newRandom = ((long)GenerateRandomNumber()) >> PINK_RANDOM_SHIFT; cannam@124: sum = pink->pink_RunningSum + newRandom; cannam@124: /* Scale to range of -1.0 to 0.9999. */ cannam@124: output = pink->pink_Scalar * sum; cannam@124: #ifdef PINK_MEASURE cannam@124: /* Check Min/Max */ cannam@124: if( output > pinkMax ) pinkMax = output; cannam@124: else if( output < pinkMin ) pinkMin = output; cannam@124: #endif cannam@124: return output; cannam@124: } cannam@124: cannam@124: /*******************************************************************/ cannam@124: #define PINK_TEST cannam@124: #ifdef PINK_TEST cannam@124: cannam@124: /* Context for callback routine. */ cannam@124: typedef struct cannam@124: { cannam@124: PinkNoise leftPink; cannam@124: PinkNoise rightPink; cannam@124: unsigned int sampsToGo; cannam@124: } cannam@124: paTestData; cannam@124: cannam@124: /* This routine will be called by the PortAudio engine when audio is needed. cannam@124: ** It may called at interrupt level on some machines so don't do anything cannam@124: ** that could mess up the system like calling malloc() or free(). cannam@124: */ cannam@124: static int patestCallback(const void* inputBuffer, cannam@124: void* outputBuffer, cannam@124: unsigned long framesPerBuffer, cannam@124: const PaStreamCallbackTimeInfo* timeInfo, cannam@124: PaStreamCallbackFlags statusFlags, cannam@124: void* userData) cannam@124: { cannam@124: int finished; cannam@124: int i; cannam@124: int numFrames; cannam@124: paTestData *data = (paTestData*)userData; cannam@124: float *out = (float*)outputBuffer; cannam@124: (void) inputBuffer; /* Prevent "unused variable" warnings. */ cannam@124: cannam@124: /* Are we almost at end. */ cannam@124: if( data->sampsToGo < framesPerBuffer ) cannam@124: { cannam@124: numFrames = data->sampsToGo; cannam@124: finished = 1; cannam@124: } cannam@124: else cannam@124: { cannam@124: numFrames = framesPerBuffer; cannam@124: finished = 0; cannam@124: } cannam@124: for( i=0; ileftPink ); cannam@124: *out++ = GeneratePinkNoise( &data->rightPink ); cannam@124: } cannam@124: data->sampsToGo -= numFrames; cannam@124: return finished; cannam@124: } cannam@124: cannam@124: /*******************************************************************/ cannam@124: int main(void); cannam@124: int main(void) cannam@124: { cannam@124: PaStream* stream; cannam@124: PaError err; cannam@124: paTestData data; cannam@124: PaStreamParameters outputParameters; cannam@124: int totalSamps; cannam@124: static const double SR = 44100.0; cannam@124: static const int FPB = 2048; /* Frames per buffer: 46 ms buffers. */ cannam@124: cannam@124: /* Initialize two pink noise signals with different numbers of rows. */ cannam@124: InitializePinkNoise( &data.leftPink, 12 ); cannam@124: InitializePinkNoise( &data.rightPink, 16 ); cannam@124: cannam@124: /* Look at a few values. */ cannam@124: { cannam@124: int i; cannam@124: float pink; cannam@124: for( i=0; i<20; i++ ) cannam@124: { cannam@124: pink = GeneratePinkNoise( &data.leftPink ); cannam@124: printf("Pink = %f\n", pink ); cannam@124: } cannam@124: } cannam@124: cannam@124: data.sampsToGo = totalSamps = (int)(60.0 * SR); /* Play a whole minute. */ cannam@124: err = Pa_Initialize(); cannam@124: if( err != paNoError ) goto error; cannam@124: cannam@124: /* Open a stereo PortAudio stream so we can hear the result. */ cannam@124: outputParameters.device = Pa_GetDefaultOutputDevice(); /* Take the default output device. */ cannam@124: if (outputParameters.device == paNoDevice) { cannam@124: fprintf(stderr,"Error: No default output device.\n"); cannam@124: goto error; cannam@124: } cannam@124: outputParameters.channelCount = 2; /* Stereo output, most likely supported. */ cannam@124: outputParameters.hostApiSpecificStreamInfo = NULL; cannam@124: outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output. */ cannam@124: outputParameters.suggestedLatency = cannam@124: Pa_GetDeviceInfo(outputParameters.device)->defaultLowOutputLatency; cannam@124: err = Pa_OpenStream(&stream, cannam@124: NULL, /* No input. */ cannam@124: &outputParameters, cannam@124: SR, /* Sample rate. */ cannam@124: FPB, /* Frames per buffer. */ cannam@124: paClipOff, /* we won't output out of range samples so don't bother clipping them */ cannam@124: patestCallback, cannam@124: &data); cannam@124: if( err != paNoError ) goto error; cannam@124: cannam@124: err = Pa_StartStream( stream ); cannam@124: if( err != paNoError ) goto error; cannam@124: cannam@124: printf("Stereo pink noise for one minute...\n"); cannam@124: cannam@124: while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Pa_Sleep(100); cannam@124: if( err < 0 ) goto error; cannam@124: cannam@124: err = Pa_CloseStream( stream ); cannam@124: if( err != paNoError ) goto error; cannam@124: #ifdef PINK_MEASURE cannam@124: printf("Pink min = %f, max = %f\n", pinkMin, pinkMax ); cannam@124: #endif cannam@124: Pa_Terminate(); cannam@124: return 0; cannam@124: error: cannam@124: Pa_Terminate(); cannam@124: fprintf( stderr, "An error occured while using the portaudio stream\n" ); cannam@124: fprintf( stderr, "Error number: %d\n", err ); cannam@124: fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); cannam@124: return 0; cannam@124: } cannam@124: #endif /* PINK_TEST */