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