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