Browse Source

code tidyup

richarddobson 2 years ago
parent
commit
16d02b625c
1 changed files with 134 additions and 156 deletions
  1. 134 156
      dev/externals/paprogs/recsf/recsf.c

+ 134 - 156
dev/externals/paprogs/recsf/recsf.c

@@ -41,16 +41,17 @@
 #endif
 
 #ifdef unix
-#include <aaio.h>
+
 #include <sys/types.h>
 #include <sys/timeb.h>
 #endif
 
 #include <signal.h>
 
-#ifdef MAC
-
+#if defined unix || defined linux
 #include <aaio.h>
+#endif
+#ifdef MAC
 #include <libkern/OSAtomic.h>
 #endif
 
@@ -93,7 +94,7 @@ HANDLE ghEvent;
 typedef struct {
     PaUtilRingBuffer ringbuf;
     PaStream *stream;
-	float *ringbufData;
+    float *ringbufData;
     char  peakstr[(DBRANGE/2)+1];
     PaTime startTime;
     PaTime lastTime;
@@ -106,7 +107,7 @@ typedef struct {
     pthread_t hThread;
 #endif
     double peak;
-	unsigned long frames_written;
+    unsigned long frames_written;
     unsigned long frames_to_write; // for optional duration arg
     unsigned long current_frame;
     int srate;
@@ -125,8 +126,8 @@ int show_devices(void);
 
 void playhandler(int sig)
 {
-	if(sig == SIGINT)
-		file_recording = 0;
+    if(sig == SIGINT)
+        file_recording = 0;
 }
 
 
@@ -141,7 +142,6 @@ void alarm_wakeup (int i)
     if(file_recording && g_pdata->stream) {
         double dBpeak  = (int)( 20.0 * log10(sqrt(g_pdata->peak)));
         int dBmin = -DBRANGE;
-        int dBval = dBmin;
         int i;
         for(i=0;i < DBRANGE/2;i++){
             g_pdata->peakstr[i] = dBpeak > dBmin+(i*2) ? '*' : '.';    
@@ -181,7 +181,6 @@ VOID CALLBACK TimerCallback(PVOID lpParam, BOOLEAN TimerOrWaitFired)
 {
     psfdata *pdata = (psfdata*) lpParam;
     
-    
     if(file_recording && pdata->stream) {
         //printf("%.4f secs\r",(float)(g_pdata->frames_played /(double) g_pdata->srate));
         double dBpeak  = (int)( 20.0 * log10(sqrt(pdata->peak)));
@@ -191,9 +190,7 @@ VOID CALLBACK TimerCallback(PVOID lpParam, BOOLEAN TimerOrWaitFired)
         for(i=0;i < DBRANGE/2;i++) {
             pdata->peakstr[i] = dBpeak > dBmin+(i*2) ? '*' : '.';    
         }
-        
         pdata->lastTime = Pa_GetStreamTime(pdata->stream ) - pdata->startTime;
-        
         printf("%.2f secs\t\t%s\r", pdata->lastTime,pdata->peakstr ); 
         fflush(stdout);
         SetEvent(ghEvent);
@@ -214,23 +211,23 @@ static unsigned int __stdcall threadFunctionWriteFile(void* ptr)
 #endif
 {
     psfdata* pData = (psfdata*)ptr;
-    
+
     /* Mark thread started */
     pData->flag = 0;
-    
+
     while (1) {
         ring_buffer_size_t elementsInBuffer = PaUtil_GetRingBufferReadAvailable(&pData->ringbuf);
         if(file_recording == 0){
             //write out whatever remains in ring buffer
             void* ptr[2] = {0};
             ring_buffer_size_t sizes[2] = {0};
-            
+
             //printf("flushing ring buffer...\n");
-            
+
             ring_buffer_size_t elementsRead = PaUtil_GetRingBufferReadRegions(&pData->ringbuf, elementsInBuffer, ptr + 0, sizes + 0, ptr + 1, sizes + 1);
             if (elementsRead > 0) {       
                 int i;
-                
+
                 for (i = 0; i < 2 && ptr[i] != NULL; ++i)  {
                     unsigned long towrite = sizes[i];
                     if(pData->frames_to_write){  
@@ -263,7 +260,7 @@ static unsigned int __stdcall threadFunctionWriteFile(void* ptr)
             ring_buffer_size_t elementsRead = PaUtil_GetRingBufferReadRegions(&pData->ringbuf, elementsInBuffer, ptr + 0, sizes + 0, ptr + 1, sizes + 1);
             if (elementsRead > 0) {       
                 int i;
-                
+
                 for (i = 0; i < 2 && ptr[i] != NULL; ++i)  {
                     unsigned long towrite = sizes[i];
                     if(pData->frames_to_write){  
@@ -290,11 +287,9 @@ static unsigned int __stdcall threadFunctionWriteFile(void* ptr)
                 break;
             }
         }
-        
         /* Sleep a little while... */
         Pa_Sleep(10);
     }
-       
     return 0;
 }
 
@@ -331,10 +326,11 @@ static PaError startThread( psfdata* pdata, threadfunc fn )
         Pa_Sleep(10);
     } 
 #endif
-#endif   
+#endif
     return paNoError;
 }
-// for sake of completion - curently NOT USED 
+// for sake of completion - curently NOT USED
+#if 0
 static int stopThread( psfdata* pdata )
 {
     // RWD: just called when all data played; must be called before StopStream
@@ -347,13 +343,14 @@ static int stopThread( psfdata* pdata )
     CloseHandle(pdata->hThread);
     pdata->hThread = 0;
 #else
-    
+
 #if defined(__APPLE__) || defined(__GNUC__)
     pthread_cancel(pdata->hThread);
 #endif
 #endif
     return paNoError;
 }
+#endif
 
 static int recordCallback( const void *inputBuffer, void *outputBuffer,
                           unsigned long framesPerBuffer,
@@ -370,9 +367,9 @@ static int recordCallback( const void *inputBuffer, void *outputBuffer,
     (void) timeInfo;
     (void) statusFlags;
     (void) userData;
-    
+
     data->current_frame += PaUtil_WriteRingBuffer(&data->ringbuf, rptr, framesPerBuffer);
-    
+
     // simple level meter!
     val = rptr[0];
     val  =  val * val;
@@ -426,33 +423,30 @@ static unsigned NextPowerOf2(unsigned val)
 
 int main(int argc,char **argv)
 {
-	PaStreamParameters inputParameters;
+    PaStreamParameters inputParameters;
 #ifdef _WIN32
     /* portaudio sets default channel masks we can't use; we must do all this to set default mask = 0! */
     PaWinDirectSoundStreamInfo directSoundStreamInfo;
     //    PaWinMmeStreamInfo winmmeStreamInfo;
-    
+
 #endif
     PaDeviceInfo *devinfo = NULL;
     PaStream *stream = NULL;
-    PaStreamCallback *callback = recordCallback; 
-	PaError err = paNoError;
-	psfdata sfdata;
-	PSF_CHPEAK *fpeaks = NULL;
+//    PaStreamCallback *callback = recordCallback;
+    PaError err = paNoError;
+    psfdata sfdata;
+    PSF_CHPEAK *fpeaks = NULL;
     PSF_PROPS props;
     const char* outfilename = NULL;
-    time_t in_peaktime = 0;
     MYLONG lpeaktime;
-	int waitkey = 1;
+    int waitkey = 1;
     int showlevels = 1;
     double duration = 0.0;
-    double framedurms;
-    int i,j= 0;
+    int i;
     int res;
     int samptype = DEFAULT_STYPE;
     char* ext = NULL;
-	PaDeviceIndex device;
-    long framesize = 0;   // Apr 2010 to be scaled by sample rate
+    PaDeviceIndex device;
     unsigned long ringframelen = RINGBUF_NFRAMES;  // length of ring buffer in m/c frames
     unsigned long frames_per_buffer = 0;
     unsigned int frameBlocksize = 0;
@@ -460,7 +454,7 @@ int main(int argc,char **argv)
     unsigned long LmaxdurFrames = 0;
     unsigned long LmaxdurSecs = 0;
     unsigned long LmaxdurMins = 0;
-    
+
 #ifdef unix
     struct itimerval tout_val;    
     tout_val.it_interval.tv_sec = 0;
@@ -468,7 +462,7 @@ int main(int argc,char **argv)
     tout_val.it_value.tv_sec = 0; 
     tout_val.it_value.tv_usec = 200000;
 #endif
-    
+
 #ifdef _WIN32
     HANDLE hTimerQueue;
     ghEvent = CreateEvent(NULL,TRUE,FALSE,NULL);
@@ -482,45 +476,43 @@ int main(int argc,char **argv)
         return 1;
     }
 #endif
-    
-    
+
+
     props.chans = DEFAULT_CHANS;
     props.srate = DEFAULT_SRATE;
     props.samptype = samptype;
-    
-    
-	signal(SIGINT,playhandler);
-    
-	sfdata.ringbufData = NULL;
+
+
+    signal(SIGINT,playhandler);
+
+    sfdata.ringbufData = NULL;
     sfdata.frames_to_write = 0;
     printf("RECSF: multi-channel record to file. v 1.1.0 RWD,CDP 2013\n");
     file_recording = 0;
     err = Pa_Initialize();
-	if( err != paNoError ) {
-		printf("Failed to initialize Portaudio.\n");
+    if( err != paNoError ) {
+        printf("Failed to initialize Portaudio.\n");
         Pa_Terminate();
         return 1;
     }
-	device =  Pa_GetDefaultInputDevice();
-    
+    device =  Pa_GetDefaultInputDevice();
+
     /* CDP version number */
     if(argc==2 && (stricmp(argv[1],"--version")==0)){
         printf("1.1.0\n");
         return 0;
     }
-    
     if(argc < ARG_DUR) {
         printf("insufficient args\n");
         usage();
         show_devices();
-		Pa_Terminate();
+        Pa_Terminate();
         return 1;
     }
-    
     while(argv[1][0]=='-'){
         int err = 0;
         unsigned long userbuflen = 0;
-		switch(argv[1][1]){
+        switch(argv[1][1]){
             case 'c':
                 if(argv[1][2]=='\0'){
                     printf("-c flag requires parameter\n");
@@ -606,22 +598,21 @@ int main(int argc,char **argv)
                 printf("unrecognised flag option\n");
                 err++;
                 break;
-		}
+        }
         if(err){
             Pa_Terminate();
             return 1;
         }
-		argv++;	 argc--;
-	}
+        argv++;  argc--;
+    }
 
     if(argc < ARG_DUR || argc > ARG_DUR+1) {
         usage();
         show_devices();
-		Pa_Terminate();
+        Pa_Terminate();
         return 1;
     }
     outfilename = argv[ARG_OUTFILE];
-    
     switch(samptype){
         case 0:
             props.samptype = PSF_SAMP_16;
@@ -640,7 +631,6 @@ int main(int argc,char **argv)
             Pa_Terminate();
             return 1;
     }
-    
     // find max recording time, with safety margin
     frameBlocksize *= props.chans; 
     maxdurFrames = (pow(2.0,32.0) / frameBlocksize) - 1000;
@@ -648,7 +638,7 @@ int main(int argc,char **argv)
     LmaxdurSecs =  LmaxdurFrames / props.srate;
     LmaxdurMins =  LmaxdurSecs / 60;
     printf("Max recording time: %lu mins, %lu secs\n",LmaxdurMins,LmaxdurSecs - (LmaxdurMins * 60));
-    
+
     if(argc==ARG_DUR+1){
         duration = atof(argv[ARG_DUR]);
         if(duration <=0.0){
@@ -663,20 +653,18 @@ int main(int argc,char **argv)
         }
         sfdata.frames_to_write = (unsigned long) (duration * props.srate);
     }
-    
     ext = strrchr(outfilename,'.');
     if(ext && stricmp(ext,".amb")==0) {
         int matched = 0;
-		for(i=0;i < N_BFORMATS;i++)	{
-			if(props.chans == bformats[i]){
-				matched = 1;
-				break;
-			}
-		}
-		if(!matched){
-			printf("WARNING: No Bformat definition for %d-channel file.\n",props.chans);
-		}
-		
+        for(i=0;i < N_BFORMATS;i++) {
+            if(props.chans == bformats[i]){
+                matched = 1;
+                break;
+            }
+        }
+        if(!matched){
+            printf("WARNING: No Bformat definition for %d-channel file.\n",props.chans);
+        }
         props.format = PSF_WAVE_EX;
         props.chformat = MC_BFMT;
     }
@@ -686,20 +674,19 @@ int main(int argc,char **argv)
         props.format = psf_getFormatExt(outfilename);
         if(props.chans > 2 || props.samptype > PSF_SAMP_16 || props.srate > 48000)
             props.format = PSF_WAVE_EX;
-            
+
     }
     sfdata.ofd = psf_sndCreate(outfilename,&props,0,0,PSF_CREATE_RDWR);
     if(sfdata.ofd < 0){
         printf("Sorry - unable to create outfile\n");
         goto error;
     } 
-    
+
     fpeaks = (PSF_CHPEAK *) calloc(props.chans,sizeof(PSF_CHPEAK));
-	if(fpeaks==NULL){
-		puts("no memory for PEAK data\n");
-		goto error;
-	}
-    
+    if(fpeaks==NULL){
+        puts("no memory for PEAK data\n");
+        goto error;
+    }
     if(props.srate > 48000)
         ringframelen <<= 1;
     printf("File buffer size = %ld\n",ringframelen);
@@ -720,35 +707,34 @@ int main(int argc,char **argv)
     if(frames_per_buffer > 0)
         printf("Audio buffer size = %lu frames\n",frames_per_buffer);
 
-	sfdata.chans      = props.chans;
-	sfdata.frames_written  = 0;
+    sfdata.chans      = props.chans;
+    sfdata.frames_written  = 0;
     sfdata.current_frame = 0;
     sfdata.srate = props.srate;
     sfdata.peakstr[DBRANGE/2] = '\0';
-    
     sfdata.finished = 0;
     sfdata.showlevels = showlevels;
     g_pdata = &sfdata;
-    
+
     inputParameters.device = device;   /*Pa_GetDefaultOutputDevice(); */ /* default output device */
     inputParameters.channelCount = props.chans;                     
     inputParameters.sampleFormat = paFloat32;             /* 32 bit floating point output */
     inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency;
     inputParameters.hostApiSpecificStreamInfo = NULL;
-    
+
     devinfo = (PaDeviceInfo *) Pa_GetDeviceInfo(device);
 #ifdef MAC
     if(devinfo){
         printf("Using device %d: %s\n",device,devinfo->name);
     }
 #endif
-    
+
 #ifdef WIN32
     if(devinfo) {
         int apitype = devinfo->hostApi;
         const PaHostApiInfo *apiinfo = Pa_GetHostApiInfo(apitype);
         printf("Using device %d: %s:\n",device,devinfo->name);
-        
+
         if(apiinfo->type  == paDirectSound ){
             printf("(DS)\n");
             /* set this IF we are using Dsound device. */
@@ -764,8 +750,8 @@ int main(int argc,char **argv)
         // else
         //    printf("API unknown!);
     }
-    
-#endif  
+
+#endif
     // TODO; move this up to before file is created?
     err = Pa_IsFormatSupported(&inputParameters, NULL,props.srate);
     if(err != paNoError){
@@ -778,13 +764,12 @@ int main(int argc,char **argv)
                         &inputParameters, 
                         NULL,  /* No output */
                         props.srate,
-                        frames_per_buffer,			
+                        frames_per_buffer,          
                         paClipOff,  
                         recordCallback,
                         &sfdata );
-    
-    
-	if( err != paNoError ) {
+
+    if( err != paNoError ) {
         printf("Unable to open output device for %d-channel file.\n",props.chans);
         goto error;
     }
@@ -793,23 +778,23 @@ int main(int argc,char **argv)
         printf("Internal error: unable to set finish callback\n");
         goto error;
     }
-	sfdata.stream = stream;
-    
-    
- 
+    sfdata.stream = stream;
+
+
+
     file_recording = 1;
     if(waitkey){
-		printf("Press any key to start:\n");	
-		while (!kbhit()){	
-			if(!file_recording)	 //check for instant CTRL-C
-                goto error;		
+        printf("Press any key to start:\n");    
+        while (!kbhit()){   
+            if(!file_recording)  //check for instant CTRL-C
+                goto error;     
         };
 #ifdef WIN32
-		if(kbhit())
-			_getch();			 //prevent display of char
+        if(kbhit())
+            _getch();            //prevent display of char
 #endif
-	}
-    
+    }
+
     // set up timer
 #ifdef unix   
     setitimer(ITIMER_REAL, &tout_val,0);
@@ -819,7 +804,7 @@ int main(int argc,char **argv)
     sfdata.startTime = Pa_GetStreamTime(stream );
     err = startThread(&sfdata, threadFunctionWriteFile);
     if( err != paNoError ) goto error;
-    
+
 #ifdef WIN32
     if(!CreateTimerQueueTimer(&sfdata.hTimer, hTimerQueue,
                               (WAITORTIMERCALLBACK) TimerCallback, &sfdata,200,200,0)) {
@@ -827,52 +812,52 @@ int main(int argc,char **argv)
         return 1;
     }
 #endif
-	err = Pa_StartStream( stream );
-	if( err != paNoError ) 
-		goto error;
-    
-	printf("Hit CTRL-C to stop.\n");
-    
+    err = Pa_StartStream( stream );
+    if( err != paNoError ) 
+        goto error;
+
+    printf("Hit CTRL-C to stop.\n");
+
     while((!sfdata.finished) && file_recording){
         // nothing to do!
-		Pa_Sleep(10);
-	}
+        Pa_Sleep(10);
+    }
     // note to programmer: any bug in audio buffer arithmetic will likely cause crash here!
     err = Pa_StopStream( stream );
     if( err != paNoError ) {
         printf("Error stopping stream\n");
-		goto error;
+        goto error;
     }
-    
+
     // need to stop thread explicitly?
-    
+
     err = Pa_CloseStream( stream ); 
-	if( err != paNoError ) {
+    if( err != paNoError ) {
         printf("Error closing stream\n");
-		goto error;
+        goto error;
     }
 #ifdef WIN32
     CloseHandle(ghEvent);
     DeleteTimerQueue(hTimerQueue);
 #endif
     printf("%.2f secs\n",(float)(sfdata.lastTime));
-	fflush(stdout);
-	printf("Recording finished.\n");
+    fflush(stdout);
+    printf("Recording finished.\n");
     res = psf_sndReadPeaks(sfdata.ofd,fpeaks,(MYLONG *) &lpeaktime);
-	if(res==0) {
-		printf("no PEAK data in this soundfile\n");
-	}
-	else if(res < 0){
-		printf("Error reading PEAK data\n");
-		goto error;
-	}
-	else{
+    if(res==0) {
+        printf("no PEAK data in this soundfile\n");
+    }
+    else if(res < 0){
+        printf("Error reading PEAK data\n");
+        goto error;
+    }
+    else{
         // creation time not available until file closed; don't need it here!
-		printf("PEAK data:\n");
-		for(i=0;i < sfdata.chans;i++){
+        printf("PEAK data:\n");
+        for(i=0;i < sfdata.chans;i++){
             if(fpeaks[i].val > 0.0){
                 double dBval = 20.0 * log10(fpeaks[i].val);
-			    printf("CH %d: %.4f (%.2lfdB) at frame %u: \t%.4f secs\n",
+                printf("CH %d: %.4f (%.2lfdB) at frame %u: \t%.4f secs\n",
                    i,fpeaks[i].val,dBval,fpeaks[i].pos,(double)(fpeaks[i].pos / (double) props.srate));
             }
             else {
@@ -880,35 +865,32 @@ int main(int argc,char **argv)
                    i,fpeaks[i].val,fpeaks[i].pos,(double)(fpeaks[i].pos / (double) props.srate));
 
             }
-		}
-	}
-    
+        }
+    }
+
 error:
-	Pa_Terminate();
-    
+    Pa_Terminate();
+
 //#ifdef _WIN32
 //    CloseHandle(ghEvent);
 //    DeleteTimerQueue(hTimerQueue);
 //#endif
     if( sfdata.ringbufData )       
         PaUtil_FreeMemory(sfdata.ringbufData);
-    
-	if(sfdata.ofd >=0)
-		psf_sndClose(sfdata.ofd);
-	if(fpeaks)
-		free(fpeaks);
-
-	psf_finish();
-	
-	return 0;    
-    
+    if(sfdata.ofd >=0)
+        psf_sndClose(sfdata.ofd);
+    if(fpeaks)
+        free(fpeaks);
+
+    psf_finish();
+    return 0;
 }
 
 
 
 int show_devices(void)
 {
-    int i,j;
+//    int i,j;
     PaDeviceIndex numDevices,p;
     const    PaDeviceInfo *pdi;
 #ifdef _WIN32
@@ -917,9 +899,9 @@ int show_devices(void)
 #endif
     PaError  err;
     int nInputDevices = 0;
-    
+
 #ifdef USE_ASIO
-    printf("For ASIO multi-channel, you may need to select the highest device no.\n");		
+    printf("For ASIO multi-channel, you may need to select the highest device no.\n");
 #endif
     /*Pa_Initialize();*/
     numDevices =  Pa_GetDeviceCount();
@@ -940,12 +922,11 @@ int show_devices(void)
         pdi = Pa_GetDeviceInfo( p );
         
         //#ifdef _WIN32
-        //			/*RWD: skip, info on inputs */
-        //			if(pdi->maxOutputChannels == 0)
-        //				continue;
+        //          /*RWD: skip, info on inputs */
+        //          if(pdi->maxOutputChannels == 0)
+        //              continue;
         //#endif
         nInputDevices++;
-        
         if( p == Pa_GetDefaultInputDevice() ) 
             printf("*");
         else
@@ -958,17 +939,14 @@ int show_devices(void)
         printf("(%s)\t%d\t%d\t%d\t%s\n",apiname,p,
                pdi->maxInputChannels,
                pdi->maxOutputChannels,
-               pdi->name);	
+               pdi->name);  
 #else
         printf("%d\t%d\t%d\t%s\n",p,
                pdi->maxInputChannels,
                pdi->maxOutputChannels,
                pdi->name);
-        
-        
 #endif
     }
-    
     return 0;
 }