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