PortAudio  2.0
paex_record_file.c
Go to the documentation of this file.
1 
6 /*
7  * $Id: paex_record_file.c 1752 2011-09-08 03:21:55Z philburk $
8  *
9  * This program uses the PortAudio Portable Audio Library.
10  * For more information see: http://www.portaudio.com
11  * Copyright (c) 1999-2000 Ross Bencina and Phil Burk
12  *
13  * Permission is hereby granted, free of charge, to any person obtaining
14  * a copy of this software and associated documentation files
15  * (the "Software"), to deal in the Software without restriction,
16  * including without limitation the rights to use, copy, modify, merge,
17  * publish, distribute, sublicense, and/or sell copies of the Software,
18  * and to permit persons to whom the Software is furnished to do so,
19  * subject to the following conditions:
20  *
21  * The above copyright notice and this permission notice shall be
22  * included in all copies or substantial portions of the Software.
23  *
24  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
27  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
28  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
29  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
30  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31  */
32 
33 /*
34  * The text above constitutes the entire PortAudio license; however,
35  * the PortAudio community also makes the following non-binding requests:
36  *
37  * Any person wishing to distribute modifications to the Software is
38  * requested to send the modifications to the original developer so that
39  * they can be incorporated into the canonical version. It is also
40  * requested that these non-binding requests be included along with the
41  * license above.
42  */
43 
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include "portaudio.h"
47 #include "pa_ringbuffer.h"
48 #include "pa_util.h"
49 
50 #ifdef _WIN32
51 #include <windows.h>
52 #include <process.h>
53 #endif
54 
55 static ring_buffer_size_t rbs_min(ring_buffer_size_t a, ring_buffer_size_t b)
56 {
57  return (a < b) ? a : b;
58 }
59 
60 /* #define SAMPLE_RATE (17932) // Test failure to open with this value. */
61 #define FILE_NAME "audio_data.raw"
62 #define SAMPLE_RATE (44100)
63 #define FRAMES_PER_BUFFER (512)
64 #define NUM_SECONDS (10)
65 #define NUM_CHANNELS (2)
66 #define NUM_WRITES_PER_BUFFER (4)
67 /* #define DITHER_FLAG (paDitherOff) */
68 #define DITHER_FLAG (0)
69 
70 
71 /* Select sample format. */
72 #if 1
73 #define PA_SAMPLE_TYPE paFloat32
74 typedef float SAMPLE;
75 #define SAMPLE_SILENCE (0.0f)
76 #define PRINTF_S_FORMAT "%.8f"
77 #elif 1
78 #define PA_SAMPLE_TYPE paInt16
79 typedef short SAMPLE;
80 #define SAMPLE_SILENCE (0)
81 #define PRINTF_S_FORMAT "%d"
82 #elif 0
83 #define PA_SAMPLE_TYPE paInt8
84 typedef char SAMPLE;
85 #define SAMPLE_SILENCE (0)
86 #define PRINTF_S_FORMAT "%d"
87 #else
88 #define PA_SAMPLE_TYPE paUInt8
89 typedef unsigned char SAMPLE;
90 #define SAMPLE_SILENCE (128)
91 #define PRINTF_S_FORMAT "%d"
92 #endif
93 
94 typedef struct
95 {
96  unsigned frameIndex;
97  int threadSyncFlag;
98  SAMPLE *ringBufferData;
99  PaUtilRingBuffer ringBuffer;
100  FILE *file;
101  void *threadHandle;
102 }
103 paTestData;
104 
105 /* This routine is run in a separate thread to write data from the ring buffer into a file (during Recording) */
106 static int threadFunctionWriteToRawFile(void* ptr)
107 {
108  paTestData* pData = (paTestData*)ptr;
109 
110  /* Mark thread started */
111  pData->threadSyncFlag = 0;
112 
113  while (1)
114  {
115  ring_buffer_size_t elementsInBuffer = PaUtil_GetRingBufferReadAvailable(&pData->ringBuffer);
116  if ( (elementsInBuffer >= pData->ringBuffer.bufferSize / NUM_WRITES_PER_BUFFER) ||
117  pData->threadSyncFlag )
118  {
119  void* ptr[2] = {0};
120  ring_buffer_size_t sizes[2] = {0};
121 
122  /* By using PaUtil_GetRingBufferReadRegions, we can read directly from the ring buffer */
123  ring_buffer_size_t elementsRead = PaUtil_GetRingBufferReadRegions(&pData->ringBuffer, elementsInBuffer, ptr + 0, sizes + 0, ptr + 1, sizes + 1);
124  if (elementsRead > 0)
125  {
126  int i;
127  for (i = 0; i < 2 && ptr[i] != NULL; ++i)
128  {
129  fwrite(ptr[i], pData->ringBuffer.elementSizeBytes, sizes[i], pData->file);
130  }
131  PaUtil_AdvanceRingBufferReadIndex(&pData->ringBuffer, elementsRead);
132  }
133 
134  if (pData->threadSyncFlag)
135  {
136  break;
137  }
138  }
139 
140  /* Sleep a little while... */
141  Pa_Sleep(20);
142  }
143 
144  pData->threadSyncFlag = 0;
145 
146  return 0;
147 }
148 
149 /* This routine is run in a separate thread to read data from file into the ring buffer (during Playback). When the file
150  has reached EOF, a flag is set so that the play PA callback can return paComplete */
151 static int threadFunctionReadFromRawFile(void* ptr)
152 {
153  paTestData* pData = (paTestData*)ptr;
154 
155  while (1)
156  {
157  ring_buffer_size_t elementsInBuffer = PaUtil_GetRingBufferWriteAvailable(&pData->ringBuffer);
158 
159  if (elementsInBuffer >= pData->ringBuffer.bufferSize / NUM_WRITES_PER_BUFFER)
160  {
161  void* ptr[2] = {0};
162  ring_buffer_size_t sizes[2] = {0};
163 
164  /* By using PaUtil_GetRingBufferWriteRegions, we can write directly into the ring buffer */
165  PaUtil_GetRingBufferWriteRegions(&pData->ringBuffer, elementsInBuffer, ptr + 0, sizes + 0, ptr + 1, sizes + 1);
166 
167  if (!feof(pData->file))
168  {
169  ring_buffer_size_t itemsReadFromFile = 0;
170  int i;
171  for (i = 0; i < 2 && ptr[i] != NULL; ++i)
172  {
173  itemsReadFromFile += (ring_buffer_size_t)fread(ptr[i], pData->ringBuffer.elementSizeBytes, sizes[i], pData->file);
174  }
175  PaUtil_AdvanceRingBufferWriteIndex(&pData->ringBuffer, itemsReadFromFile);
176 
177  /* Mark thread started here, that way we "prime" the ring buffer before playback */
178  pData->threadSyncFlag = 0;
179  }
180  else
181  {
182  /* No more data to read */
183  pData->threadSyncFlag = 1;
184  break;
185  }
186  }
187 
188  /* Sleep a little while... */
189  Pa_Sleep(20);
190  }
191 
192  return 0;
193 }
194 
195 typedef int (*ThreadFunctionType)(void*);
196 
197 /* Start up a new thread in the given function, at the moment only Windows, but should be very easy to extend
198  to posix type OSs (Linux/Mac) */
199 static PaError startThread( paTestData* pData, ThreadFunctionType fn )
200 {
201 #ifdef _WIN32
202  typedef unsigned (__stdcall* WinThreadFunctionType)(void*);
203  pData->threadHandle = (void*)_beginthreadex(NULL, 0, (WinThreadFunctionType)fn, pData, CREATE_SUSPENDED, NULL);
204  if (pData->threadHandle == NULL) return paUnanticipatedHostError;
205 
206  /* Set file thread to a little higher prio than normal */
207  SetThreadPriority(pData->threadHandle, THREAD_PRIORITY_ABOVE_NORMAL);
208 
209  /* Start it up */
210  pData->threadSyncFlag = 1;
211  ResumeThread(pData->threadHandle);
212 
213 #endif
214 
215  /* Wait for thread to startup */
216  while (pData->threadSyncFlag) {
217  Pa_Sleep(10);
218  }
219 
220  return paNoError;
221 }
222 
223 static int stopThread( paTestData* pData )
224 {
225  pData->threadSyncFlag = 1;
226  /* Wait for thread to stop */
227  while (pData->threadSyncFlag) {
228  Pa_Sleep(10);
229  }
230 #ifdef _WIN32
231  CloseHandle(pData->threadHandle);
232  pData->threadHandle = 0;
233 #endif
234 
235  return paNoError;
236 }
237 
238 
239 /* This routine will be called by the PortAudio engine when audio is needed.
240 ** It may be called at interrupt level on some machines so don't do anything
241 ** that could mess up the system like calling malloc() or free().
242 */
243 static int recordCallback( const void *inputBuffer, void *outputBuffer,
244  unsigned long framesPerBuffer,
245  const PaStreamCallbackTimeInfo* timeInfo,
246  PaStreamCallbackFlags statusFlags,
247  void *userData )
248 {
249  paTestData *data = (paTestData*)userData;
250  ring_buffer_size_t elementsWriteable = PaUtil_GetRingBufferWriteAvailable(&data->ringBuffer);
251  ring_buffer_size_t elementsToWrite = rbs_min(elementsWriteable, (ring_buffer_size_t)(framesPerBuffer * NUM_CHANNELS));
252 
253  (void) outputBuffer; /* Prevent unused variable warnings. */
254  (void) timeInfo;
255  (void) statusFlags;
256  (void) userData;
257 
258  data->frameIndex += PaUtil_WriteRingBuffer(&data->ringBuffer, inputBuffer, elementsToWrite);
259 
260  return paContinue;
261 }
262 
263 /* This routine will be called by the PortAudio engine when audio is needed.
264 ** It may be called at interrupt level on some machines so don't do anything
265 ** that could mess up the system like calling malloc() or free().
266 */
267 static int playCallback( const void *inputBuffer, void *outputBuffer,
268  unsigned long framesPerBuffer,
269  const PaStreamCallbackTimeInfo* timeInfo,
270  PaStreamCallbackFlags statusFlags,
271  void *userData )
272 {
273  paTestData *data = (paTestData*)userData;
274  ring_buffer_size_t elementsToPlay = PaUtil_GetRingBufferReadAvailable(&data->ringBuffer);
275  ring_buffer_size_t elementsToRead = rbs_min(elementsToPlay, (ring_buffer_size_t)(framesPerBuffer * NUM_CHANNELS));
276 
277  (void) inputBuffer; /* Prevent unused variable warnings. */
278  (void) timeInfo;
279  (void) statusFlags;
280  (void) userData;
281 
282  data->frameIndex += PaUtil_ReadRingBuffer(&data->ringBuffer, outputBuffer, elementsToRead);
283 
284  return data->threadSyncFlag ? paComplete : paContinue;
285 }
286 
287 static unsigned NextPowerOf2(unsigned val)
288 {
289  val--;
290  val = (val >> 1) | val;
291  val = (val >> 2) | val;
292  val = (val >> 4) | val;
293  val = (val >> 8) | val;
294  val = (val >> 16) | val;
295  return ++val;
296 }
297 
298 /*******************************************************************/
299 int main(void);
300 int main(void)
301 {
302  PaStreamParameters inputParameters,
303  outputParameters;
304  PaStream* stream;
305  PaError err = paNoError;
306  paTestData data = {0};
307  unsigned delayCntr;
308  unsigned numSamples;
309  unsigned numBytes;
310 
311  printf("patest_record.c\n"); fflush(stdout);
312 
313  /* We set the ring buffer size to about 500 ms */
314  numSamples = NextPowerOf2((unsigned)(SAMPLE_RATE * 0.5 * NUM_CHANNELS));
315  numBytes = numSamples * sizeof(SAMPLE);
316  data.ringBufferData = (SAMPLE *) PaUtil_AllocateZeroInitializedMemory( numBytes );
317  if( data.ringBufferData == NULL )
318  {
319  printf("Could not allocate ring buffer data.\n");
320  goto done;
321  }
322 
323  if (PaUtil_InitializeRingBuffer(&data.ringBuffer, sizeof(SAMPLE), numSamples, data.ringBufferData) < 0)
324  {
325  printf("Failed to initialize ring buffer. Size is not power of 2 ??\n");
326  goto done;
327  }
328 
329  err = Pa_Initialize();
330  if( err != paNoError ) goto done;
331 
332  inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
333  if (inputParameters.device == paNoDevice) {
334  fprintf(stderr,"Error: No default input device.\n");
335  goto done;
336  }
337  inputParameters.channelCount = NUM_CHANNELS;
338  inputParameters.sampleFormat = PA_SAMPLE_TYPE;
339  inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency;
340  inputParameters.hostApiSpecificStreamInfo = NULL;
341 
342  /* Record some audio. -------------------------------------------- */
343  err = Pa_OpenStream(
344  &stream,
345  &inputParameters,
346  NULL, /* &outputParameters, */
347  SAMPLE_RATE,
348  FRAMES_PER_BUFFER,
349  paClipOff, /* we won't output out of range samples so don't bother clipping them */
350  recordCallback,
351  &data );
352  if( err != paNoError ) goto done;
353 
354  /* Open the raw audio 'cache' file... */
355  data.file = fopen(FILE_NAME, "wb");
356  if (data.file == 0) goto done;
357 
358  /* Start the file writing thread */
359  err = startThread(&data, threadFunctionWriteToRawFile);
360  if( err != paNoError ) goto done;
361 
362  err = Pa_StartStream( stream );
363  if( err != paNoError ) goto done;
364  printf("\n=== Now recording to '" FILE_NAME "' for %d seconds!! Please speak into the microphone. ===\n", NUM_SECONDS); fflush(stdout);
365 
366  /* Note that the RECORDING part is limited with TIME, not size of the file and/or buffer, so you can
367  increase NUM_SECONDS until you run out of disk */
368  delayCntr = 0;
369  while( delayCntr++ < NUM_SECONDS )
370  {
371  printf("index = %d\n", data.frameIndex ); fflush(stdout);
372  Pa_Sleep(1000);
373  }
374  if( err < 0 ) goto done;
375 
376  err = Pa_CloseStream( stream );
377  if( err != paNoError ) goto done;
378 
379  /* Stop the thread */
380  err = stopThread(&data);
381  if( err != paNoError ) goto done;
382 
383  /* Close file */
384  fclose(data.file);
385  data.file = 0;
386 
387  /* Playback recorded data. -------------------------------------------- */
388  data.frameIndex = 0;
389 
390  outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */
391  if (outputParameters.device == paNoDevice) {
392  fprintf(stderr,"Error: No default output device.\n");
393  goto done;
394  }
395  outputParameters.channelCount = NUM_CHANNELS;
396  outputParameters.sampleFormat = PA_SAMPLE_TYPE;
397  outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
398  outputParameters.hostApiSpecificStreamInfo = NULL;
399 
400  printf("\n=== Now playing back from file '" FILE_NAME "' until end-of-file is reached ===\n"); fflush(stdout);
401  err = Pa_OpenStream(
402  &stream,
403  NULL, /* no input */
404  &outputParameters,
405  SAMPLE_RATE,
406  FRAMES_PER_BUFFER,
407  paClipOff, /* we won't output out of range samples so don't bother clipping them */
408  playCallback,
409  &data );
410  if( err != paNoError ) goto done;
411 
412  if( stream )
413  {
414  /* Open file again for reading */
415  data.file = fopen(FILE_NAME, "rb");
416  if (data.file != 0)
417  {
418  /* Start the file reading thread */
419  err = startThread(&data, threadFunctionReadFromRawFile);
420  if( err != paNoError ) goto done;
421 
422  err = Pa_StartStream( stream );
423  if( err != paNoError ) goto done;
424 
425  printf("Waiting for playback to finish.\n"); fflush(stdout);
426 
427  /* The playback will end when EOF is reached */
428  while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) {
429  printf("index = %d\n", data.frameIndex ); fflush(stdout);
430  Pa_Sleep(1000);
431  }
432  if( err < 0 ) goto done;
433  }
434 
435  err = Pa_CloseStream( stream );
436  if( err != paNoError ) goto done;
437 
438  fclose(data.file);
439 
440  printf("Done.\n"); fflush(stdout);
441  }
442 
443 done:
444  Pa_Terminate();
445  if( data.ringBufferData ) /* Sure it is NULL or valid. */
446  PaUtil_FreeMemory( data.ringBufferData );
447  if( err != paNoError )
448  {
449  fprintf( stderr, "An error occurred while using the portaudio stream\n" );
450  fprintf( stderr, "Error number: %d\n", err );
451  fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) );
452  err = 1; /* Always return 0 or 1, but no other return codes. */
453  }
454  return err;
455 }
PaError Pa_Initialize(void)
PaDeviceIndex Pa_GetDefaultInputDevice(void)
void PaStream
Definition: portaudio.h:644
PaError Pa_OpenStream(PaStream **stream, const PaStreamParameters *inputParameters, const PaStreamParameters *outputParameters, double sampleRate, unsigned long framesPerBuffer, PaStreamFlags streamFlags, PaStreamCallback *streamCallback, void *userData)
PaTime defaultLowInputLatency
Definition: portaudio.h:519
PaError Pa_StartStream(PaStream *stream)
void * hostApiSpecificStreamInfo
Definition: portaudio.h:588
The portable PortAudio API.
PaSampleFormat sampleFormat
Definition: portaudio.h:568
#define paClipOff
Definition: portaudio.h:670
int PaError
Definition: portaudio.h:122
PaError Pa_IsStreamActive(PaStream *stream)
PaTime suggestedLatency
Definition: portaudio.h:581
unsigned long PaStreamCallbackFlags
Definition: portaudio.h:721
#define paNoDevice
Definition: portaudio.h:222
const PaDeviceInfo * Pa_GetDeviceInfo(PaDeviceIndex device)
PaDeviceIndex Pa_GetDefaultOutputDevice(void)
PaDeviceIndex device
Definition: portaudio.h:555
void Pa_Sleep(long msec)
const char * Pa_GetErrorText(PaError errorCode)
PaError Pa_CloseStream(PaStream *stream)
PaError Pa_Terminate(void)