PortAudio 2.0

paex_record_file.c

Go to the documentation of this file.
00001 
00006 /*
00007  * $Id: paex_record_file.c 1752 2011-09-08 03:21:55Z philburk $
00008  *
00009  * This program uses the PortAudio Portable Audio Library.
00010  * For more information see: http://www.portaudio.com
00011  * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
00012  *
00013  * Permission is hereby granted, free of charge, to any person obtaining
00014  * a copy of this software and associated documentation files
00015  * (the "Software"), to deal in the Software without restriction,
00016  * including without limitation the rights to use, copy, modify, merge,
00017  * publish, distribute, sublicense, and/or sell copies of the Software,
00018  * and to permit persons to whom the Software is furnished to do so,
00019  * subject to the following conditions:
00020  *
00021  * The above copyright notice and this permission notice shall be
00022  * included in all copies or substantial portions of the Software.
00023  *
00024  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
00025  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
00026  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
00027  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
00028  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
00029  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
00030  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
00031  */
00032 
00033 /*
00034  * The text above constitutes the entire PortAudio license; however, 
00035  * the PortAudio community also makes the following non-binding requests:
00036  *
00037  * Any person wishing to distribute modifications to the Software is
00038  * requested to send the modifications to the original developer so that
00039  * they can be incorporated into the canonical version. It is also 
00040  * requested that these non-binding requests be included along with the 
00041  * license above.
00042  */
00043 
00044 #include <stdio.h>
00045 #include <stdlib.h>
00046 #include "portaudio.h"
00047 #include "pa_ringbuffer.h"
00048 #include "pa_util.h"
00049 
00050 #ifdef _WIN32
00051 #include <windows.h>
00052 #include <process.h>
00053 #endif
00054 
00055 static ring_buffer_size_t rbs_min(ring_buffer_size_t a, ring_buffer_size_t b)
00056 {
00057     return (a < b) ? a : b;
00058 }
00059 
00060 /* #define SAMPLE_RATE  (17932) // Test failure to open with this value. */
00061 #define FILE_NAME       "audio_data.raw"
00062 #define SAMPLE_RATE  (44100)
00063 #define FRAMES_PER_BUFFER (512)
00064 #define NUM_SECONDS     (10)
00065 #define NUM_CHANNELS    (2)
00066 #define NUM_WRITES_PER_BUFFER   (4)
00067 /* #define DITHER_FLAG     (paDitherOff) */
00068 #define DITHER_FLAG     (0) 
00069 
00070 
00071 /* Select sample format. */
00072 #if 1
00073 #define PA_SAMPLE_TYPE  paFloat32
00074 typedef float SAMPLE;
00075 #define SAMPLE_SILENCE  (0.0f)
00076 #define PRINTF_S_FORMAT "%.8f"
00077 #elif 1
00078 #define PA_SAMPLE_TYPE  paInt16
00079 typedef short SAMPLE;
00080 #define SAMPLE_SILENCE  (0)
00081 #define PRINTF_S_FORMAT "%d"
00082 #elif 0
00083 #define PA_SAMPLE_TYPE  paInt8
00084 typedef char SAMPLE;
00085 #define SAMPLE_SILENCE  (0)
00086 #define PRINTF_S_FORMAT "%d"
00087 #else
00088 #define PA_SAMPLE_TYPE  paUInt8
00089 typedef unsigned char SAMPLE;
00090 #define SAMPLE_SILENCE  (128)
00091 #define PRINTF_S_FORMAT "%d"
00092 #endif
00093 
00094 typedef struct
00095 {
00096     unsigned            frameIndex;
00097     int                 threadSyncFlag;
00098     SAMPLE             *ringBufferData;
00099     PaUtilRingBuffer    ringBuffer;
00100     FILE               *file;
00101     void               *threadHandle;
00102 }
00103 paTestData;
00104 
00105 /* This routine is run in a separate thread to write data from the ring buffer into a file (during Recording) */
00106 static int threadFunctionWriteToRawFile(void* ptr)
00107 {
00108     paTestData* pData = (paTestData*)ptr;
00109 
00110     /* Mark thread started */
00111     pData->threadSyncFlag = 0;
00112 
00113     while (1)
00114     {
00115         ring_buffer_size_t elementsInBuffer = PaUtil_GetRingBufferReadAvailable(&pData->ringBuffer);
00116         if ( (elementsInBuffer >= pData->ringBuffer.bufferSize / NUM_WRITES_PER_BUFFER) ||
00117              pData->threadSyncFlag )
00118         {
00119             void* ptr[2] = {0};
00120             ring_buffer_size_t sizes[2] = {0};
00121 
00122             /* By using PaUtil_GetRingBufferReadRegions, we can read directly from the ring buffer */
00123             ring_buffer_size_t elementsRead = PaUtil_GetRingBufferReadRegions(&pData->ringBuffer, elementsInBuffer, ptr + 0, sizes + 0, ptr + 1, sizes + 1);
00124             if (elementsRead > 0)
00125             {
00126                 int i;
00127                 for (i = 0; i < 2 && ptr[i] != NULL; ++i)
00128                 {
00129                     fwrite(ptr[i], pData->ringBuffer.elementSizeBytes, sizes[i], pData->file);
00130                 }
00131                 PaUtil_AdvanceRingBufferReadIndex(&pData->ringBuffer, elementsRead);
00132             }
00133 
00134             if (pData->threadSyncFlag)
00135             {
00136                 break;
00137             }
00138         }
00139 
00140         /* Sleep a little while... */
00141         Pa_Sleep(20);
00142     }
00143 
00144     pData->threadSyncFlag = 0;
00145 
00146     return 0;
00147 }
00148 
00149 /* This routine is run in a separate thread to read data from file into the ring buffer (during Playback). When the file
00150    has reached EOF, a flag is set so that the play PA callback can return paComplete */
00151 static int threadFunctionReadFromRawFile(void* ptr)
00152 {
00153     paTestData* pData = (paTestData*)ptr;
00154 
00155     while (1)
00156     {
00157         ring_buffer_size_t elementsInBuffer = PaUtil_GetRingBufferWriteAvailable(&pData->ringBuffer);
00158 
00159         if (elementsInBuffer >= pData->ringBuffer.bufferSize / NUM_WRITES_PER_BUFFER)
00160         {
00161             void* ptr[2] = {0};
00162             ring_buffer_size_t sizes[2] = {0};
00163 
00164             /* By using PaUtil_GetRingBufferWriteRegions, we can write directly into the ring buffer */
00165             PaUtil_GetRingBufferWriteRegions(&pData->ringBuffer, elementsInBuffer, ptr + 0, sizes + 0, ptr + 1, sizes + 1);
00166 
00167             if (!feof(pData->file))
00168             {
00169                 ring_buffer_size_t itemsReadFromFile = 0;
00170                 int i;
00171                 for (i = 0; i < 2 && ptr[i] != NULL; ++i)
00172                 {
00173                     itemsReadFromFile += (ring_buffer_size_t)fread(ptr[i], pData->ringBuffer.elementSizeBytes, sizes[i], pData->file);
00174                 }
00175                 PaUtil_AdvanceRingBufferWriteIndex(&pData->ringBuffer, itemsReadFromFile);
00176 
00177                 /* Mark thread started here, that way we "prime" the ring buffer before playback */
00178                 pData->threadSyncFlag = 0;
00179             }
00180             else
00181             {
00182                 /* No more data to read */
00183                 pData->threadSyncFlag = 1;
00184                 break;
00185             }
00186         }
00187 
00188         /* Sleep a little while... */
00189         Pa_Sleep(20);
00190     }
00191 
00192     return 0;
00193 }
00194 
00195 typedef int (*ThreadFunctionType)(void*);
00196 
00197 /* Start up a new thread in the given function, at the moment only Windows, but should be very easy to extend
00198    to posix type OSs (Linux/Mac) */
00199 static PaError startThread( paTestData* pData, ThreadFunctionType fn )
00200 {
00201 #ifdef _WIN32
00202     typedef unsigned (__stdcall* WinThreadFunctionType)(void*);
00203     pData->threadHandle = (void*)_beginthreadex(NULL, 0, (WinThreadFunctionType)fn, pData, CREATE_SUSPENDED, NULL);
00204     if (pData->threadHandle == NULL) return paUnanticipatedHostError;
00205 
00206     /* Set file thread to a little higher prio than normal */
00207     SetThreadPriority(pData->threadHandle, THREAD_PRIORITY_ABOVE_NORMAL);
00208 
00209     /* Start it up */
00210     pData->threadSyncFlag = 1;
00211     ResumeThread(pData->threadHandle);
00212 
00213 #endif
00214 
00215     /* Wait for thread to startup */
00216     while (pData->threadSyncFlag) {
00217         Pa_Sleep(10);
00218     }
00219 
00220     return paNoError;
00221 }
00222 
00223 static int stopThread( paTestData* pData )
00224 {
00225     pData->threadSyncFlag = 1;
00226     /* Wait for thread to stop */
00227     while (pData->threadSyncFlag) {
00228         Pa_Sleep(10);
00229     }
00230 #ifdef _WIN32
00231     CloseHandle(pData->threadHandle);
00232     pData->threadHandle = 0;
00233 #endif
00234 
00235     return paNoError;
00236 }
00237 
00238 
00239 /* This routine will be called by the PortAudio engine when audio is needed.
00240 ** It may be called at interrupt level on some machines so don't do anything
00241 ** that could mess up the system like calling malloc() or free().
00242 */
00243 static int recordCallback( const void *inputBuffer, void *outputBuffer,
00244                            unsigned long framesPerBuffer,
00245                            const PaStreamCallbackTimeInfo* timeInfo,
00246                            PaStreamCallbackFlags statusFlags,
00247                            void *userData )
00248 {
00249     paTestData *data = (paTestData*)userData;
00250     ring_buffer_size_t elementsWriteable = PaUtil_GetRingBufferWriteAvailable(&data->ringBuffer);
00251     ring_buffer_size_t elementsToWrite = rbs_min(elementsWriteable, (ring_buffer_size_t)(framesPerBuffer * NUM_CHANNELS));
00252     const SAMPLE *rptr = (const SAMPLE*)inputBuffer;
00253 
00254     (void) outputBuffer; /* Prevent unused variable warnings. */
00255     (void) timeInfo;
00256     (void) statusFlags;
00257     (void) userData;
00258 
00259     data->frameIndex += PaUtil_WriteRingBuffer(&data->ringBuffer, rptr, elementsToWrite);
00260 
00261     return paContinue;
00262 }
00263 
00264 /* This routine will be called by the PortAudio engine when audio is needed.
00265 ** It may be called at interrupt level on some machines so don't do anything
00266 ** that could mess up the system like calling malloc() or free().
00267 */
00268 static int playCallback( const void *inputBuffer, void *outputBuffer,
00269                          unsigned long framesPerBuffer,
00270                          const PaStreamCallbackTimeInfo* timeInfo,
00271                          PaStreamCallbackFlags statusFlags,
00272                          void *userData )
00273 {
00274     paTestData *data = (paTestData*)userData;
00275     ring_buffer_size_t elementsToPlay = PaUtil_GetRingBufferReadAvailable(&data->ringBuffer);
00276     ring_buffer_size_t elementsToRead = rbs_min(elementsToPlay, (ring_buffer_size_t)(framesPerBuffer * NUM_CHANNELS));
00277     SAMPLE* wptr = (SAMPLE*)outputBuffer;
00278 
00279     (void) inputBuffer; /* Prevent unused variable warnings. */
00280     (void) timeInfo;
00281     (void) statusFlags;
00282     (void) userData;
00283 
00284     data->frameIndex += PaUtil_ReadRingBuffer(&data->ringBuffer, wptr, elementsToRead);
00285 
00286     return data->threadSyncFlag ? paComplete : paContinue;
00287 }
00288 
00289 static unsigned NextPowerOf2(unsigned val)
00290 {
00291     val--;
00292     val = (val >> 1) | val;
00293     val = (val >> 2) | val;
00294     val = (val >> 4) | val;
00295     val = (val >> 8) | val;
00296     val = (val >> 16) | val;
00297     return ++val;
00298 }
00299 
00300 /*******************************************************************/
00301 int main(void);
00302 int main(void)
00303 {
00304     PaStreamParameters  inputParameters,
00305                         outputParameters;
00306     PaStream*           stream;
00307     PaError             err = paNoError;
00308     paTestData          data = {0};
00309     unsigned            delayCntr;
00310     unsigned            numSamples;
00311     unsigned            numBytes;
00312 
00313     printf("patest_record.c\n"); fflush(stdout);
00314 
00315     /* We set the ring buffer size to about 500 ms */
00316     numSamples = NextPowerOf2((unsigned)(SAMPLE_RATE * 0.5 * NUM_CHANNELS));
00317     numBytes = numSamples * sizeof(SAMPLE);
00318     data.ringBufferData = (SAMPLE *) PaUtil_AllocateMemory( numBytes );
00319     if( data.ringBufferData == NULL )
00320     {
00321         printf("Could not allocate ring buffer data.\n");
00322         goto done;
00323     }
00324 
00325     if (PaUtil_InitializeRingBuffer(&data.ringBuffer, sizeof(SAMPLE), numSamples, data.ringBufferData) < 0)
00326     {
00327         printf("Failed to initialize ring buffer. Size is not power of 2 ??\n");
00328         goto done;
00329     }
00330 
00331     err = Pa_Initialize();
00332     if( err != paNoError ) goto done;
00333 
00334     inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
00335     if (inputParameters.device == paNoDevice) {
00336         fprintf(stderr,"Error: No default input device.\n");
00337         goto done;
00338     }
00339     inputParameters.channelCount = 2;                    /* stereo input */
00340     inputParameters.sampleFormat = PA_SAMPLE_TYPE;
00341     inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency;
00342     inputParameters.hostApiSpecificStreamInfo = NULL;
00343 
00344     /* Record some audio. -------------------------------------------- */
00345     err = Pa_OpenStream(
00346               &stream,
00347               &inputParameters,
00348               NULL,                  /* &outputParameters, */
00349               SAMPLE_RATE,
00350               FRAMES_PER_BUFFER,
00351               paClipOff,      /* we won't output out of range samples so don't bother clipping them */
00352               recordCallback,
00353               &data );
00354     if( err != paNoError ) goto done;
00355 
00356     /* Open the raw audio 'cache' file... */
00357     data.file = fopen(FILE_NAME, "wb");
00358     if (data.file == 0) goto done;
00359 
00360     /* Start the file writing thread */
00361     err = startThread(&data, threadFunctionWriteToRawFile);
00362     if( err != paNoError ) goto done;
00363 
00364     err = Pa_StartStream( stream );
00365     if( err != paNoError ) goto done;
00366     printf("\n=== Now recording to '" FILE_NAME "' for %d seconds!! Please speak into the microphone. ===\n", NUM_SECONDS); fflush(stdout);
00367 
00368     /* Note that the RECORDING part is limited with TIME, not size of the file and/or buffer, so you can
00369        increase NUM_SECONDS until you run out of disk */
00370     delayCntr = 0;
00371     while( delayCntr++ < NUM_SECONDS )
00372     {
00373         printf("index = %d\n", data.frameIndex ); fflush(stdout);
00374         Pa_Sleep(1000);
00375     }
00376     if( err < 0 ) goto done;
00377 
00378     err = Pa_CloseStream( stream );
00379     if( err != paNoError ) goto done;
00380 
00381     /* Stop the thread */
00382     err = stopThread(&data);
00383     if( err != paNoError ) goto done;
00384 
00385     /* Close file */
00386     fclose(data.file);
00387     data.file = 0;
00388 
00389     /* Playback recorded data.  -------------------------------------------- */
00390     data.frameIndex = 0;
00391 
00392     outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
00393     if (outputParameters.device == paNoDevice) {
00394         fprintf(stderr,"Error: No default output device.\n");
00395         goto done;
00396     }
00397     outputParameters.channelCount = 2;                     /* stereo output */
00398     outputParameters.sampleFormat =  PA_SAMPLE_TYPE;
00399     outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
00400     outputParameters.hostApiSpecificStreamInfo = NULL;
00401 
00402     printf("\n=== Now playing back from file '" FILE_NAME "' until end-of-file is reached ===\n"); fflush(stdout);
00403     err = Pa_OpenStream(
00404               &stream,
00405               NULL, /* no input */
00406               &outputParameters,
00407               SAMPLE_RATE,
00408               FRAMES_PER_BUFFER,
00409               paClipOff,      /* we won't output out of range samples so don't bother clipping them */
00410               playCallback,
00411               &data );
00412     if( err != paNoError ) goto done;
00413 
00414     if( stream )
00415     {
00416         /* Open file again for reading */
00417         data.file = fopen(FILE_NAME, "rb");
00418         if (data.file != 0)
00419         {
00420             /* Start the file reading thread */
00421             err = startThread(&data, threadFunctionReadFromRawFile);
00422             if( err != paNoError ) goto done;
00423 
00424             err = Pa_StartStream( stream );
00425             if( err != paNoError ) goto done;
00426 
00427             printf("Waiting for playback to finish.\n"); fflush(stdout);
00428 
00429             /* The playback will end when EOF is reached */
00430             while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) {
00431                 printf("index = %d\n", data.frameIndex ); fflush(stdout);
00432                 Pa_Sleep(1000);
00433             }
00434             if( err < 0 ) goto done;
00435         }
00436         
00437         err = Pa_CloseStream( stream );
00438         if( err != paNoError ) goto done;
00439 
00440         fclose(data.file);
00441         
00442         printf("Done.\n"); fflush(stdout);
00443     }
00444 
00445 done:
00446     Pa_Terminate();
00447     if( data.ringBufferData )       /* Sure it is NULL or valid. */
00448         PaUtil_FreeMemory( data.ringBufferData );
00449     if( err != paNoError )
00450     {
00451         fprintf( stderr, "An error occured while using the portaudio stream\n" );
00452         fprintf( stderr, "Error number: %d\n", err );
00453         fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
00454         err = 1;          /* Always return 0 or 1, but no other return codes. */
00455     }
00456     return err;
00457 }
00458