1 /*
2  * $Id: patest_maxsines.c,v 1.1 2006/04/30 16:23:59 jcr13 Exp $
3  * patest_maxsines.c
4  * How many sine waves can we calculate and play in less than 80% CPU Load.
5  *
6  * Authors:
7  *    Ross Bencina <rossb@audiomulch.com>
8  *    Phil Burk <philburk@softsynth.com>
9  *
10  * This program uses the PortAudio Portable Audio Library.
11  * For more information see: http://www.audiomulch.com/portaudio/
12  * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
13  *
14  * Permission is hereby granted, free of charge, to any person obtaining
15  * a copy of this software and associated documentation files
16  * (the "Software"), to deal in the Software without restriction,
17  * including without limitation the rights to use, copy, modify, merge,
18  * publish, distribute, sublicense, and/or sell copies of the Software,
19  * and to permit persons to whom the Software is furnished to do so,
20  * subject to the following conditions:
21  *
22  * The above copyright notice and this permission notice shall be
23  * included in all copies or substantial portions of the Software.
24  *
25  * Any person wishing to distribute modifications to the Software is
26  * requested to send the modifications to the original developer so that
27  * they can be incorporated into the canonical version.
28  *
29  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
30  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
32  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
33  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
34  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
35  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36  *
37  */
38 #include <stdio.h>
39 #include <math.h>
40 #include "portaudio.h"
41 
42 #define MAX_SINES     (500)
43 #define MAX_USAGE     (0.8)
44 #define SAMPLE_RATE   (44100)
45 #define FREQ_TO_PHASE_INC(freq)   (freq/(float)SAMPLE_RATE)
46 
47 #define MIN_PHASE_INC  FREQ_TO_PHASE_INC(200.0f)
48 #define MAX_PHASE_INC  (MIN_PHASE_INC * (1 << 5))
49 
50 #define FRAMES_PER_BUFFER  (512)
51 #ifndef M_PI
52 #define M_PI  (3.14159265)
53 #endif
54 #define TWOPI (M_PI * 2.0)
55 
56 #define TABLE_SIZE   (512)
57 
58 typedef struct paTestData
59 {
60     int numSines;
61     float sine[TABLE_SIZE + 1]; /* add one for guard point for interpolation */
62     float phases[MAX_SINES];
63 }
64 paTestData;
65 
66 /* Convert phase between and 1.0 to sine value
67  * using linear interpolation.
68  */
69 float LookupSine( paTestData *data, float phase );
LookupSine(paTestData * data,float phase)70 float LookupSine( paTestData *data, float phase )
71 {
72     float fIndex = phase*TABLE_SIZE;
73     int   index = (int) fIndex;
74     float fract = fIndex - index;
75     float lo = data->sine[index];
76     float hi = data->sine[index+1];
77     float val = lo + fract*(hi-lo);
78     return val;
79 }
80 
81 /* This routine will be called by the PortAudio engine when audio is needed.
82 ** It may called at interrupt level on some machines so don't do anything
83 ** that could mess up the system like calling malloc() or free().
84 */
patestCallback(void * inputBuffer,void * outputBuffer,unsigned long framesPerBuffer,PaTimestamp outTime,void * userData)85 static int patestCallback(   void *inputBuffer, void *outputBuffer,
86                              unsigned long framesPerBuffer,
87                              PaTimestamp outTime, void *userData )
88 {
89     paTestData *data = (paTestData*)userData;
90     float *out = (float*)outputBuffer;
91     float outSample;
92     float scaler;
93     int numForScale;
94     unsigned long i;
95     int j;
96     int finished = 0;
97     (void) outTime; /* Prevent unused variable warnings. */
98     (void) inputBuffer;
99 
100 /* Detemine amplitude scaling factor */
101     numForScale = data->numSines;
102     if( numForScale < 8 ) numForScale = 8;  /* prevent pops at beginning */
103     scaler = 1.0f / numForScale;
104 
105     for( i=0; i<framesPerBuffer; i++ )
106     {
107         float output = 0.0;
108         float phaseInc = MIN_PHASE_INC;
109         float phase;
110         for( j=0; j<data->numSines; j++ )
111         {
112             /* Advance phase of next oscillator. */
113             phase = data->phases[j];
114             phase += phaseInc;
115             if( phase >= 1.0 ) phase -= 1.0;
116 
117             output += LookupSine(data, phase);
118             data->phases[j] = phase;
119 
120             phaseInc *= 1.02f;
121             if( phaseInc > MAX_PHASE_INC ) phaseInc = MIN_PHASE_INC;
122         }
123 
124         outSample = (float) (output * scaler);
125         *out++ = outSample; /* Left */
126         *out++ = outSample; /* Right */
127     }
128     return finished;
129 }
130 
131 /*******************************************************************/
132 int main(void);
main(void)133 int main(void)
134 {
135 	int i;
136     PortAudioStream *stream;
137     PaError err;
138     paTestData data = {0};
139     double load;
140     printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER);
141 
142     /* initialise sinusoidal wavetable */
143     for( i=0; i<TABLE_SIZE; i++ )
144     {
145         data.sine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. );
146     }
147     data.sine[TABLE_SIZE] = data.sine[0]; /* set guard point */
148 
149     err = Pa_Initialize();
150     if( err != paNoError ) goto error;
151     err = Pa_OpenStream(
152               &stream,
153               paNoDevice,
154               0,              /* no input */
155               paFloat32,
156               NULL,
157               Pa_GetDefaultOutputDeviceID(), /* default output device */
158               2,              /* stereo output */
159               paFloat32,      /* 32 bit floating point output */
160               NULL,
161               SAMPLE_RATE,
162               FRAMES_PER_BUFFER,
163               0,              /* number of buffers, if zero then use default minimum */
164               paClipOff,      /* we won't output out of range samples so don't bother clipping them */
165               patestCallback,
166               &data );
167     if( err != paNoError ) goto error;
168     err = Pa_StartStream( stream );
169     if( err != paNoError ) goto error;
170 
171 /* Play an increasing number of sine waves until we hit MAX_USAGE */
172     do
173     {
174         data.numSines++;
175         Pa_Sleep( 200 );
176 
177         load = Pa_GetCPULoad( stream );
178         printf("numSines = %d, CPU load = %f\n", data.numSines, load );
179         fflush( stdout );
180     }
181     while( (load < MAX_USAGE) && (data.numSines < MAX_SINES) );
182 
183     printf("Press ENTER to stop.\n" ); fflush(stdout);
184     getchar();
185 
186 	printf("CPU load = %f\n", Pa_GetCPULoad( stream ) );
187     err = Pa_StopStream( stream );
188     if( err != paNoError ) goto error;
189     err = Pa_CloseStream( stream );
190     if( err != paNoError ) goto error;
191     Pa_Terminate();
192     printf("Test finished.\n");
193     fflush( stdout );
194     return err;
195 error:
196     Pa_Terminate();
197     fprintf( stderr, "An error occured while using the portaudio stream\n" );
198     fprintf( stderr, "Error number: %d\n", err );
199     fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
200     return err;
201 }
202