int main(void) { PaError err; paTestData data = { 0 }; long i; double rate; const PaDeviceInfo *pdi; PortAudioStream *outputStream; PortAudioStream *inputStream; err = Pa_Initialize(); if( err != paNoError ) goto error; pdi = Pa_GetDeviceInfo( INPUT_DEVICE_ID ); printf("Input device = %s\n", pdi->name ); pdi = Pa_GetDeviceInfo( OUTPUT_DEVICE_ID ); printf("Output device = %s\n", pdi->name ); /* Open input stream. */ err = Pa_OpenStream( &inputStream, INPUT_DEVICE_ID, SAMPLES_PER_FRAME, /* stereo input */ PA_SAMPLE_TYPE, NULL, paNoDevice, 0, PA_SAMPLE_TYPE, NULL, INPUT_SAMPLE_RATE, FRAMES_PER_BUFFER, /* frames per buffer */ NUM_REC_BUFS, /* number of buffers, if zero then use default minimum */ paClipOff, /* we won't output out of range samples so don't bother clipping them */ recordCallback, &data ); if( err != paNoError ) goto error; err = Pa_OpenStream( &outputStream, paNoDevice, 0, /* NO input */ PA_SAMPLE_TYPE, NULL, OUTPUT_DEVICE_ID, SAMPLES_PER_FRAME, /* stereo output */ PA_SAMPLE_TYPE, NULL, OUTPUT_SAMPLE_RATE, FRAMES_PER_BUFFER, /* frames per buffer */ 0, /* number of buffers, if zero then use default minimum */ paClipOff, /* we won't output out of range samples so don't bother clipping them */ playCallback, &data ); if( err != paNoError ) goto error; /* Record and playback multiple times. */ for( i=0; i<2; i++ ) { printf("Measuring INPUT ------------------------- \n"); err = MeasureStreamRate( inputStream, &data, &rate ); if( err != paNoError ) goto error; ReportRate( rate, INPUT_SAMPLE_RATE ); printf("Measuring OUTPUT ------------------------- \n"); err = MeasureStreamRate( outputStream, &data, &rate ); if( err != paNoError ) goto error; ReportRate( rate, OUTPUT_SAMPLE_RATE ); } /* Clean up. */ err = Pa_CloseStream( inputStream ); if( err != paNoError ) goto error; err = Pa_CloseStream( outputStream ); if( err != paNoError ) goto error; if( err != paNoError ) goto error; Pa_Terminate(); printf("Test complete.\n"); fflush(stdout); return 0; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); if( err == paHostError ) { fprintf( stderr, "Host Error number: %d\n", Pa_GetHostError() ); } return -1; }
static int TestAdvance( int mode, PaDeviceIndex deviceID, double sampleRate, int numChannels, PaSampleFormat format ) { PaStreamParameters inputParameters, outputParameters, *ipp, *opp; PaStream *stream = NULL; PaError result = paNoError; PaQaData myData; #define FRAMES_PER_BUFFER (64) /* Setup data for synthesis thread. */ myData.framesLeft = (unsigned long) (sampleRate * 100); /* 100 seconds */ myData.numChannels = numChannels; myData.mode = mode; myData.format = format; switch( format ) { case paFloat32: case paInt32: case paInt24: myData.bytesPerSample = 4; break; /* case paPackedInt24: myData.bytesPerSample = 3; break; */ default: myData.bytesPerSample = 2; break; } if( mode == MODE_INPUT ) { inputParameters.device = deviceID; inputParameters.channelCount = numChannels; inputParameters.sampleFormat = format; inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; inputParameters.hostApiSpecificStreamInfo = NULL; ipp = &inputParameters; } else ipp = NULL; if( mode == MODE_OUTPUT ) /* Pa_GetDeviceInfo(paNoDevice) COREDUMPS!!! */ { outputParameters.device = deviceID; outputParameters.channelCount = numChannels; outputParameters.sampleFormat = format; outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; opp = &outputParameters; } else opp = NULL; if(paFormatIsSupported == Pa_IsFormatSupported( ipp, opp, sampleRate )) { printf("------ TestAdvance: %s, device = %d, rate = %g, numChannels = %d, format = %lu -------\n", ( mode == MODE_INPUT ) ? "INPUT" : "OUTPUT", deviceID, sampleRate, numChannels, (unsigned long)format); EXPECT( ((result = Pa_OpenStream( &stream, ipp, opp, sampleRate, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ QaCallback, &myData ) ) == 0) ); if( stream ) { PaTime oldStamp, newStamp; unsigned long oldFrames; int minDelay = ( mode == MODE_INPUT ) ? 1000 : 400; /* Was: int minNumBuffers = Pa_GetMinNumBuffers( FRAMES_PER_BUFFER, sampleRate ); int msec = (int) ((minNumBuffers * 3 * 1000.0 * FRAMES_PER_BUFFER) / sampleRate); */ int msec = (int)( 3.0 * (( mode == MODE_INPUT ) ? inputParameters.suggestedLatency : outputParameters.suggestedLatency )); if( msec < minDelay ) msec = minDelay; printf("msec = %d\n", msec); /**/ EXPECT( ((result=Pa_StartStream( stream )) == 0) ); /* Check to make sure PortAudio is advancing timeStamp. */ oldStamp = Pa_GetStreamTime(stream); Pa_Sleep(msec); newStamp = Pa_GetStreamTime(stream); printf("oldStamp = %g,newStamp = %g\n", oldStamp, newStamp ); /**/ EXPECT( (oldStamp < newStamp) ); /* Check to make sure callback is decrementing framesLeft. */ oldFrames = myData.framesLeft; Pa_Sleep(msec); printf("oldFrames = %lu, myData.framesLeft = %lu\n", oldFrames, myData.framesLeft ); /**/ EXPECT( (oldFrames > myData.framesLeft) ); EXPECT( ((result=Pa_CloseStream( stream )) == 0) ); stream = NULL; } } error: if( stream != NULL ) Pa_CloseStream( stream ); return result; }
int main(void) { PaStreamParameters outputParameters; PaStream *stream; PaError err; int safeSineCount, stressedSineCount; int safeUnderflowCount, stressedUnderflowCount; paTestData data = {0}; double load; printf("PortAudio Test: output sine waves, count underflows. SR = %d, BufSize = %d. MAX_LOAD = %f\n", SAMPLE_RATE, FRAMES_PER_BUFFER, (float)MAX_LOAD ); err = Pa_Initialize(); if( err != paNoError ) goto error; outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ if (outputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default output device.\n"); goto error; } outputParameters.channelCount = 1; /* mono output */ outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Establishing load conditions...\n" ); /* Determine number of sines required to get to 50% */ do { data.sineCount++; Pa_Sleep( 100 ); load = Pa_GetStreamCpuLoad( stream ); printf("sineCount = %d, CPU load = %f\n", data.sineCount, load ); } while( load < 0.5 && data.sineCount < (MAX_SINES-1)); safeSineCount = data.sineCount; /* Calculate target stress value then ramp up to that level*/ stressedSineCount = (int) (2.0 * data.sineCount * MAX_LOAD ); if( stressedSineCount > MAX_SINES ) stressedSineCount = MAX_SINES; for( ; data.sineCount < stressedSineCount; data.sineCount++ ) { Pa_Sleep( 100 ); load = Pa_GetStreamCpuLoad( stream ); printf("STRESSING: sineCount = %d, CPU load = %f\n", data.sineCount, load ); } printf("Counting underflows for 5 seconds.\n"); data.countUnderflows = 1; Pa_Sleep( 5000 ); stressedUnderflowCount = data.outputUnderflowCount; data.countUnderflows = 0; data.sineCount = safeSineCount; printf("Resuming safe load...\n"); Pa_Sleep( 1500 ); data.outputUnderflowCount = 0; Pa_Sleep( 1500 ); load = Pa_GetStreamCpuLoad( stream ); printf("sineCount = %d, CPU load = %f\n", data.sineCount, load ); printf("Counting underflows for 5 seconds.\n"); data.countUnderflows = 1; Pa_Sleep( 5000 ); safeUnderflowCount = data.outputUnderflowCount; printf("Stop stream.\n"); err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); if( stressedUnderflowCount == 0 ) printf("Test failed, no output underflows detected under stress.\n"); else if( safeUnderflowCount != 0 ) printf("Test failed, %d unexpected underflows detected under safe load.\n", safeUnderflowCount); else printf("Test passed, %d expected output underflows detected under stress, 0 unexpected underflows detected under safe load.\n", stressedUnderflowCount ); return err; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
int main( int argc, char **argv ) { PaStreamParameters outputParameters; PaStream *stream; PaError err; paTestData data; int go; int outLatency = 0; int minLatency = DEFAULT_BUFFER_SIZE * 2; int framesPerBuffer; double sampleRate = 44100.0; char str[256]; printf("pa_minlat - Determine minimum latency for your computer.\n"); printf(" usage: pa_minlat {userBufferSize}\n"); printf(" for example: pa_minlat 64\n"); printf("Adjust your stereo until you hear a smooth tone in each speaker.\n"); printf("Then try to find the smallest number of frames that still sounds smooth.\n"); printf("Note that the sound will stop momentarily when you change the number of buffers.\n"); /* Get bufferSize from command line. */ framesPerBuffer = ( argc > 1 ) ? atol( argv[1] ) : DEFAULT_BUFFER_SIZE; printf("Frames per buffer = %d\n", framesPerBuffer ); data.left_phase = data.right_phase = 0.0; err = Pa_Initialize(); if( err != paNoError ) goto error; outLatency = sampleRate * 200.0 / 1000.0; /* 200 msec. */ /* Try different numBuffers in a loop. */ go = 1; while( go ) { outputParameters.device = Pa_GetDefaultOutputDevice(); /* Default output device. */ outputParameters.channelCount = 2; /* Stereo output */ outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output. */ outputParameters.suggestedLatency = (double)outLatency / sampleRate; /* In seconds. */ outputParameters.hostApiSpecificStreamInfo = NULL; printf("Latency = %d frames = %6.1f msec.\n", outLatency, outputParameters.suggestedLatency * 1000.0 ); err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, sampleRate, framesPerBuffer, paClipOff, /* we won't output out of range samples so don't bother clipping them */ paminlatCallback, &data ); if( err != paNoError ) goto error; if( stream == NULL ) goto error; /* Start audio. */ err = Pa_StartStream( stream ); if( err != paNoError ) goto error; /* Ask user for a new nlatency. */ printf("\nMove windows around to see if the sound glitches.\n"); printf("Latency now %d, enter new number of frames, or 'q' to quit: ", outLatency ); fgets( str, 256, stdin ); { /* Get rid of newline */ size_t l = strlen( str ) - 1; if( str[ l ] == '\n') str[ l ] = '\0'; } if( str[0] == 'q' ) go = 0; else { outLatency = atol( str ); if( outLatency < minLatency ) { printf( "Latency below minimum of %d! Set to minimum!!!\n", minLatency ); outLatency = minLatency; } } /* Stop sound until ENTER hit. */ err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; } printf("A good setting for latency would be somewhat higher than\n"); printf("the minimum latency that worked.\n"); printf("PortAudio: Test finished.\n"); Pa_Terminate(); return 0; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return 1; }
//----------------------------------------------------------------------------- // Name: initialize_audio() // Desc: Initializes PortAudio With Globals //----------------------------------------------------------------------------- void initialize_audio(const char* inFile) { PaStreamParameters outputParameters; PaError err; /* Open the audio file */ if (( data.inFile = sf_open( inFile, SFM_READ, &data.sfinfo1 )) == NULL ) { printf("Error, Couldn't Open The File\n"); exit (1); } /* Check for Compatibility */ if (data.sfinfo1.channels > 2) { printf("Error, File Must be Stereo or Mono\n"); exit (1); } /* Print info about audio file */ printf("\nAudio File: %s\nFrames: %d\nSamples: %d\nChannels: %d\nSampleRate: %d\n", inFile, (int)data.sfinfo1.frames, (int)data.sfinfo1.frames * (int)data.sfinfo1.channels, (int)data.sfinfo1.channels, (int)data.sfinfo1.samplerate); /* Initialize PortAudio */ Pa_Initialize(); /* Set output stream parameters */ outputParameters.device = Pa_GetDefaultOutputDevice(); outputParameters.channelCount = data.sfinfo1.channels; outputParameters.sampleFormat = paFloat32; outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; /* Initialize SRC */ if ((data.src_state = src_new (data.src_converter_type, data.sfinfo1.channels, &data.src_error )) == NULL) { printf ("Error, SRC Initialization Failed\n"); exit (1); } /* Sets Up The SRC_DATA Struct */ initialize_SRC_DATA(); /* Sets Up Filters */ initialize_Filters(); /* Set Initial Amplitude */ data.amplitude = INITIAL_VOLUME; /* Open audio stream */ err = Pa_OpenStream( &g_stream, NULL, &outputParameters, data.sfinfo1.samplerate, FRAMES_PER_BUFFER, paNoFlag, paCallback, &data ); if (err != paNoError) { printf("PortAudio error: open stream: %s\n", Pa_GetErrorText(err)); } /* Start audio stream */ err = Pa_StartStream( g_stream ); if (err != paNoError) { printf( "PortAudio error: start stream: %s\n", Pa_GetErrorText(err)); } }
int main(void) { PaStreamParameters inputParameters, outputParameters; PaStream *stream = NULL; PaError err; char *sampleBlock; int i; int numBytes; printf("patest_read_write_wire.c\n"); fflush(stdout); numBytes = FRAMES_PER_BUFFER * NUM_CHANNELS * SAMPLE_SIZE ; sampleBlock = (char *) malloc( numBytes ); if( sampleBlock == NULL ) { printf("Could not allocate record array.\n"); exit(1); } CLEAR( sampleBlock ); err = Pa_Initialize(); if( err != paNoError ) goto error; inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */ printf( "Input device # %d.\n", inputParameters.device ); printf( "Input LL: %g s\n", Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency ); printf( "Input HL: %g s\n", Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency ); inputParameters.channelCount = NUM_CHANNELS; inputParameters.sampleFormat = PA_SAMPLE_TYPE; inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency ; inputParameters.hostApiSpecificStreamInfo = NULL; outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ printf( "Output device # %d.\n", outputParameters.device ); printf( "Output LL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency ); printf( "Output HL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency ); outputParameters.channelCount = NUM_CHANNELS; outputParameters.sampleFormat = PA_SAMPLE_TYPE; outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; /* -- setup -- */ err = Pa_OpenStream( &stream, &inputParameters, &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ NULL, /* no callback, use blocking API */ NULL ); /* no callback, so no callback userData */ if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Wire on. Will run %d seconds.\n", NUM_SECONDS); fflush(stdout); for( i=0; i<(NUM_SECONDS*SAMPLE_RATE)/FRAMES_PER_BUFFER; ++i ) { err = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER ); if( err && CHECK_UNDERFLOW ) goto xrun; err = Pa_ReadStream( stream, sampleBlock, FRAMES_PER_BUFFER ); if( err && CHECK_OVERFLOW ) goto xrun; } err = Pa_StopStream( stream ); if( err != paNoError ) goto error; CLEAR( sampleBlock ); /* err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Wire on. Interrupt to stop.\n"); fflush(stdout); while( 1 ) { err = Pa_WriteStream( stream, sampleBlock, FRAMES_PER_BUFFER ); if( err ) goto xrun; err = Pa_ReadStream( stream, sampleBlock, FRAMES_PER_BUFFER ); if( err ) goto xrun; } err = Pa_StopStream( stream ); if( err != paNoError ) goto error; Pa_CloseStream( stream ); */ free( sampleBlock ); Pa_Terminate(); return 0; xrun: if( stream ) { Pa_AbortStream( stream ); Pa_CloseStream( stream ); } free( sampleBlock ); Pa_Terminate(); if( err & paInputOverflow ) fprintf( stderr, "Input Overflow.\n" ); if( err & paOutputUnderflow ) fprintf( stderr, "Output Underflow.\n" ); return -2; error: if( stream ) { Pa_AbortStream( stream ); Pa_CloseStream( stream ); } free( sampleBlock ); Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return -1; }
int main(void) { PortAudioStream *stream; PaError err; paTestData DATA; int i; int totalSamps; printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); /* initialise sinusoidal wavetable */ for( i=0; i<TABLE_SIZE; i++ ) { DATA.sine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. ); } DATA.left_phase = DATA.right_phase = 0; DATA.framesToGo = totalSamps = NUM_SECONDS * SAMPLE_RATE; /* Play for a few seconds. */ err = Pa_Initialize(); if( err != paNoError ) goto error; err = Pa_OpenStream( &stream, paNoDevice,/* default input device */ 0, /* no input */ paFloat32, /* 32 bit floating point input */ NULL, Pa_GetDefaultOutputDeviceID(), /* default output device */ 2, /* stereo output */ paFloat32, /* 32 bit floating point output */ NULL, SAMPLE_RATE, FRAMES_PER_BUFFER, /* frames per buffer */ NUM_BUFFERS, /* number of buffers, if zero then use default minimum */ paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &DATA ); if( err != paNoError ) goto error; DATA.outTime = -1.0; // mark time for callback as undefined err = Pa_StartStream( stream ); if( err != paNoError ) goto error; /* Watch until sound is halfway finished. */ printf("Play for %d seconds.\n", NUM_SECONDS/2 ); fflush(stdout); do { ReportStreamTime( stream, &DATA ); Pa_Sleep(100); } while( Pa_StreamTime( stream ) < (totalSamps/2) ); /* Stop sound until ENTER hit. */ err = Pa_StopStream( stream ); if( err != paNoError ) goto error; printf("Pause for 2 seconds.\n"); fflush(stdout); Pa_Sleep( 2000 ); DATA.outTime = -1.0; // mark time for callback as undefined err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Play until sound is finished.\n"); fflush(stdout); do { ReportStreamTime( stream, &DATA ); Pa_Sleep(100); } while( Pa_StreamActive( stream ) ); err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); printf("Test finished.\n"); return err; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
int main(void) { PaStreamParameters inputParameters, outputParameters; PaStream* stream; PaError err = paNoError; paTestData data; int totalFrames; int numSamples; int numBytes; SAMPLE max, val; double average; struct sockaddr_in myaddr, remaddr; int fd, i, slen=sizeof(remaddr); char buf[BUFLEN]; /* message buffer */ int recvlen; /* # bytes in acknowledgement message */ char *server = "127.0.0.1"; /* change this to use a different server */ /* create a socket */ if ((fd=socket(AF_INET, SOCK_DGRAM, 0))==-1) printf("socket created\n"); /* bind it to all local addresses and pick any port number */ memset((char *)&myaddr, 0, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = htons(0); if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) { perror("bind failed"); return 0; } /* now define remaddr, the address to whom we want to send messages */ /* For convenience, the host address is expressed as a numeric IP address */ /* that we will convert to a binary format via inet_aton */ memset((char *) &remaddr, 0, sizeof(remaddr)); remaddr.sin_family = AF_INET; remaddr.sin_port = htons(SERVICE_PORT); if (inet_aton(server, &remaddr.sin_addr)==0) { fprintf(stderr, "inet_aton() failed\n"); exit(1); } data.fd = fd; data.remaddr = (struct sockaddr *) &remaddr; data.slen = slen; err = Pa_Initialize(); if( err != paNoError ) exit(1); inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */ if (inputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default input device.\n"); exit(1); } inputParameters.channelCount = 2; /* stereo input */ inputParameters.sampleFormat = PA_SAMPLE_TYPE; inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; inputParameters.hostApiSpecificStreamInfo = NULL; /* Record some audio. -------------------------------------------- */ err = Pa_OpenStream( &stream, &inputParameters, NULL, /* &outputParameters, */ SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ sendCallback, &data ); if( err != paNoError ) exit(1); err = Pa_StartStream( stream ); if( err != paNoError ) exit(1); printf("\n=== Now listenning!! Please speak into the microphone. ===\n"); fflush(stdout); while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) { Pa_Sleep(1000); printf("index = \n"); fflush(stdout); } if( err < 0 ) exit(1); err = Pa_CloseStream( stream ); if( err != paNoError ) exit(1); /* now let's send the messages */ //close(fd); return 0; }
int main(void) { PaStreamParameters inputParameters, outputParameters; PaStream *stream; PaError err; SAMPLE *recordedSamples; int i; int totalFrames; int numSamples; int numBytes; SAMPLE max, average, val; printf("patest_read_record.c\n"); fflush(stdout); totalFrames = NUM_SECONDS * SAMPLE_RATE; /* Record for a few seconds. */ numSamples = totalFrames * NUM_CHANNELS; numBytes = numSamples * sizeof(SAMPLE); recordedSamples = (SAMPLE *) malloc( numBytes ); if( recordedSamples == NULL ) { printf("Could not allocate record array.\n"); exit(1); } for( i=0; i<numSamples; i++ ) recordedSamples[i] = 0; err = Pa_Initialize(); if( err != paNoError ) goto error; inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */ inputParameters.channelCount = NUM_CHANNELS; inputParameters.sampleFormat = PA_SAMPLE_TYPE; inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; inputParameters.hostApiSpecificStreamInfo = NULL; /* Record some audio. -------------------------------------------- */ err = Pa_OpenStream( &stream, &inputParameters, NULL, /* &outputParameters, */ SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ NULL, /* no callback, use blocking API */ NULL ); /* no callback, so no callback userData */ if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Now recording!!\n"); fflush(stdout); err = Pa_ReadStream( stream, recordedSamples, totalFrames ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; /* Measure maximum peak amplitude. */ max = 0; average = 0; for( i=0; i<numSamples; i++ ) { val = recordedSamples[i]; if( val < 0 ) val = -val; /* ABS */ if( val > max ) { max = val; } average += val; } average = average / numSamples; printf("Sample max amplitude = "PRINTF_S_FORMAT"\n", max ); printf("Sample average = "PRINTF_S_FORMAT"\n", average ); /* Was as below. Better choose at compile time because this keeps generating compiler-warnings: if( PA_SAMPLE_TYPE == paFloat32 ) { printf("sample max amplitude = %f\n", max ); printf("sample average = %f\n", average ); } else { printf("sample max amplitude = %d\n", max ); printf("sample average = %d\n", average ); } */ /* Write recorded data to a file. */ #if 0 { FILE *fid; fid = fopen("recorded.raw", "wb"); if( fid == NULL ) { printf("Could not open file."); } else { fwrite( recordedSamples, NUM_CHANNELS * sizeof(SAMPLE), totalFrames, fid ); fclose( fid ); printf("Wrote data to 'recorded.raw'\n"); } } #endif /* Playback recorded data. -------------------------------------------- */ outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ outputParameters.channelCount = NUM_CHANNELS; outputParameters.sampleFormat = PA_SAMPLE_TYPE; outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; printf("Begin playback.\n"); fflush(stdout); err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ NULL, /* no callback, use blocking API */ NULL ); /* no callback, so no callback userData */ if( err != paNoError ) goto error; if( stream ) { err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Waiting for playback to finish.\n"); fflush(stdout); err = Pa_WriteStream( stream, recordedSamples, totalFrames ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; printf("Done.\n"); fflush(stdout); } free( recordedSamples ); Pa_Terminate(); return 0; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return -1; }
int main(void) { PaStream *stream; PaStreamParameters outputParameters; PaError err; paTestData data; int i; printf("Play different tone sine waves that alternate between left and right channel.\n"); printf("The low tone should be on the left channel.\n"); /* initialise sinusoidal wavetable */ for( i=0; i<TABLE_SIZE; i++ ) { data.sine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. ); } data.left_phase = data.right_phase = 0; data.currentBalance = 0.0; data.targetBalance = 0.0; err = Pa_Initialize(); if( err != paNoError ) goto error; outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ if (outputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default output device.\n"); goto error; } outputParameters.channelCount = 2; /* stereo output */ outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; err = Pa_OpenStream( &stream, NULL, /* No input. */ &outputParameters, /* As above. */ SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Play for several seconds.\n"); for( i=0; i<4; i++ ) { printf("Hear low sound on left side.\n"); data.targetBalance = 0.01; Pa_Sleep( 1000 ); printf("Hear high sound on right side.\n"); data.targetBalance = 0.99; Pa_Sleep( 1000 ); } err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); printf("Test finished.\n"); return err; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
int main(void) { PaStreamParameters outputParameters; PaStream *stream; PaError err; paTestData data; int i; printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); /* initialise sinusoidal wavetable */ for( i=0; i<TABLE_SIZE; i++ ) { data.sine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. ); } data.left_phase = data.right_phase = 0; err = Pa_Initialize(); if( err != paNoError ) goto error; outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ if (outputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default output device.\n"); goto error; } outputParameters.channelCount = 2; /* stereo output */ outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); if( err != paNoError ) goto error; sprintf( data.message, "No Message" ); err = Pa_SetStreamFinishedCallback( stream, &StreamFinished ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Play for %d seconds.\n", NUM_SECONDS ); Pa_Sleep( NUM_SECONDS * 1000 ); err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); printf("Test finished.\n"); return err; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
int main(int argc, char* argv[]) { PaStreamParameters outputParameters; PaWinMmeStreamInfo wmmeStreamInfo; PaStream *stream; PaError err; paTestData data; int deviceIndex; FILE *fp; const char *fileName = "c:\\test_48k.ac3.spdif"; data.buffer = NULL; printf("usage: patest_wmme_ac3 fileName [paDeviceIndex]\n"); printf("**IMPORTANT*** The provided file must include the spdif preamble at the start of every AC-3 frame. Using a normal ac3 file won't work.\n"); printf("PortAudio Test: output a raw spdif ac3 stream. SR = %d, BufSize = %d, Chans = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER, CHANNEL_COUNT); if( argc >= 2 ) fileName = argv[1]; printf( "reading spdif ac3 raw stream file %s\n", fileName ); fp = fopen( fileName, "rb" ); if( !fp ){ fprintf( stderr, "error opening spdif ac3 file.\n" ); return -1; } /* get file size */ fseek( fp, 0, SEEK_END ); data.bufferSampleCount = ftell( fp ) / sizeof(short); fseek( fp, 0, SEEK_SET ); /* allocate buffer, read the whole file into memory */ data.buffer = (short*)malloc( data.bufferSampleCount * sizeof(short) ); if( !data.buffer ){ fprintf( stderr, "error allocating buffer.\n" ); return -1; } fread( data.buffer, sizeof(short), data.bufferSampleCount, fp ); fclose( fp ); data.playbackIndex = 0; err = Pa_Initialize(); if( err != paNoError ) goto error; deviceIndex = Pa_GetHostApiInfo( Pa_HostApiTypeIdToHostApiIndex( paMME ) )->defaultOutputDevice; if( argc >= 3 ){ sscanf( argv[1], "%d", &deviceIndex ); } printf( "using device id %d (%s)\n", deviceIndex, Pa_GetDeviceInfo(deviceIndex)->name ); outputParameters.device = deviceIndex; outputParameters.channelCount = CHANNEL_COUNT; outputParameters.sampleFormat = paInt16; /* IMPORTANT must use paInt16 for WMME AC3 */ outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; wmmeStreamInfo.size = sizeof(PaWinMmeStreamInfo); wmmeStreamInfo.hostApiType = paMME; wmmeStreamInfo.version = 1; wmmeStreamInfo.flags = paWinMmeWaveFormatDolbyAc3Spdif; outputParameters.hostApiSpecificStreamInfo = &wmmeStreamInfo; if( Pa_IsFormatSupported( 0, &outputParameters, SAMPLE_RATE ) == paFormatIsSupported ){ printf( "Pa_IsFormatSupported reports device will support %d channels.\n", CHANNEL_COUNT ); }else{ printf( "Pa_IsFormatSupported reports device will not support %d channels.\n", CHANNEL_COUNT ); } err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, 0, patestCallback, &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Play for %d seconds.\n", NUM_SECONDS ); Pa_Sleep( NUM_SECONDS * 1000 ); err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); free( data.buffer ); printf("Test finished.\n"); return err; error: Pa_Terminate(); free( data.buffer ); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
Main() { mScale = 0.1f; mOffset = 1.0f; mDataOffset = 0; isClicked = false; screen = Vec2<unsigned int>(800, 600); std::setlocale(LC_ALL, "en_US.UTF-8"); glfwInit(); glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); //glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0); GLFWwindow* window = glfwCreateWindow(screen.x, screen.y, "test", nullptr, nullptr); if (window == nullptr) { printf("cant create window"); return; } glfwSetWindowSizeCallback(window, windowSizeCallback); glfwSetKeyCallback(window, keyCallback); glfwSetMouseButtonCallback(window, clickCallback); glfwSetCursorPosCallback(window, mouseCallback); glfwMakeContextCurrent(window); glewExperimental = true; glewInit(); int tmp; glGetIntegerv(GL_MAX_ELEMENTS_VERTICES , &tmp); std::cout << "GL_MAX_ELEMENTS_VERTICES: " << tmp << std::endl; int err = Pa_Initialize(); if (err != paNoError) printf("error"); int num = Pa_GetDeviceCount(); const PaDeviceInfo* devInfo; const PaHostApiInfo* apiInfo; for (int i = 0; i < num; ++i) { devInfo = Pa_GetDeviceInfo(i); apiInfo = Pa_GetHostApiInfo(devInfo->hostApi); printf("%i, %s on %s\n", i, devInfo->name, apiInfo->name); } float sampleRate = 44100.0f; double t = glfwGetTime(); Kern k(sampleRate, 12, 4 * 16.352f, sampleRate / 2); BlockMatrix<std::complex<double>> b(k.K, k.mN0, k.mB, 0.01); mAudioData = new double[b.getWidth()]; mAudioLength = b.getWidth(); for (unsigned int i = 0; i < mAudioLength; ++i) { mAudioData[i] = wave(55, sampleRate, i) + wave(110, sampleRate, i) + wave(220, sampleRate, i) + wave(440, sampleRate, i) + wave(880, sampleRate, i) + wave(1760, sampleRate, i) + wave(3520, sampleRate, i) + wave(7040, sampleRate, i); } printf("kernel time:%f\n", glfwGetTime() - t); float drawArray[k.mB * 2]; std::complex<double> out[k.mB]; CQT::transform(mAudioData, out, b, mAudioLength); t = glfwGetTime(); printf("transform time:%f\n", glfwGetTime() - t); //glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); glDebugMessageCallback(debugCallback, nullptr); //glEnable(GL_DEBUG_OUTPUT); printf("%s\n", glGetString(GL_VERSION)); Shader fs("res/shader/fragment.c", true, GL_FRAGMENT_SHADER); Shader vs("res/shader/vertex.c", true, GL_VERTEX_SHADER); Program* p = new Program(); p->attach(fs); p->attach(vs); p->build(); p->use(); Program p2; Shader fs2("res/shader/fragment2.c", true, GL_FRAGMENT_SHADER); Shader vs2("res/shader/vertex2.c", true, GL_VERTEX_SHADER); p2.attach(fs2); p2.attach(vs2); p2.build(); p2.use(); int uniformData = p2.getUniformLocation("data"); unsigned int waterfallSize = 512; tm = new TextureManager(); unsigned int waterfallTexture; unsigned int waterfallId = tm->getFreeTexture(); glGenTextures(1, &waterfallTexture); glActiveTexture(GL_TEXTURE0 + waterfallId); glBindTexture( GL_TEXTURE0, waterfallTexture ); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR); unsigned char* textureTmp = new unsigned char[waterfallSize * b.getWidth()]; glTexImage2D( GL_TEXTURE_2D_ARRAY, 0, GL_R8, b.getWidth(), waterfallSize, 0, GL_RED, GL_UNSIGNED_BYTE, textureTmp); delete textureTmp; float max = 0; for (unsigned int i = 0; i < k.mB; ++i) { drawArray[2 * i + 0] = (float)i / k.mB * 2.0f - 1.0f; float tmp = std::abs(out[i]); drawArray[2 * i + 1] = tmp; max = std::max(tmp, max); } font = new Font(512, "res/font/DroidSans.woff", 32, tm); print = new Print(font); //print.set(&font, "res/shader/fontVertex.c", "res/shader/fontFragment.c"); print->setScreenSize(screen); glm::vec2* vert = new glm::vec2[1024]; glm::vec2* debug = new glm::vec2[b.getWidth()]; for (unsigned int i = 0; i < b.getWidth(); ++i) { debug[i].x = (float)i / b.getWidth() * 2.0f - 1.0f; } uint32_t vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); uint32_t vbo[2]; glGenBuffers(1, vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glEnableVertexAttribArray(0); glBufferData(GL_ARRAY_BUFFER, k.mB * sizeof(glm::vec2), drawArray, GL_DYNAMIC_DRAW); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); glEnable(GL_BLEND); glfwSetWindowUserPointer(window, this); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); double time, timeo; glfwSwapInterval(1); PaStream* stream; PaStreamParameters params; params.device = 21; params.channelCount = 1; params.sampleFormat = paFloat32; params.hostApiSpecificStreamInfo = nullptr; params.suggestedLatency = 0.5; err = Pa_OpenStream(&stream, ¶ms, nullptr, sampleRate, paFramesPerBufferUnspecified, 0, paCallback, this); if (err != paNoError) printf("error %i", err); Pa_StartStream(stream); while(!glfwWindowShouldClose(window)) { timeo = time; time = glfwGetTime(); CQT::transform(mAudioData, out, b, mAudioLength); max = 0.0f; for (unsigned int i = 0; i < k.mB; ++i) { drawArray[2 * i + 0] = (float)i / k.mB * 2.0f - 1.0f; float tmp = std::abs(out[i]); drawArray[2 * i + 1] = tmp; max = std::max(tmp, max); } for (unsigned int i = 0; i < k.mB; ++i) { drawArray[2 * i + 1] = std::log(drawArray[2 * i +1]) * mScale + mOffset; } //printf("%f\n", drawArray[1]); glBindVertexArray(vao); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ARRAY_BUFFER, k.mB * sizeof(glm::vec2), drawArray, GL_DYNAMIC_DRAW); p->use(); glDrawArrays(GL_LINE_STRIP, 0, k.mB); for (unsigned int i = 0; i < b.getWidth(); ++i) { debug[i].y = mAudioData[i] / 15.0; } glBufferData(GL_ARRAY_BUFFER, b.getWidth() * sizeof(glm::vec2), debug, GL_DYNAMIC_DRAW); glDrawArrays(GL_LINE_STRIP, 0, b.getWidth()); print->printfAt(-300.0f, 100.0f, 16.0f, 16.0f, u8"Fps:%03.3f", 1/(time-timeo)); glfwSwapBuffers(window); glClear(GL_COLOR_BUFFER_BIT); glfwPollEvents(); } Pa_StopStream(stream); Pa_CloseStream(stream); Pa_Terminate(); std::cout << "Hello World. I'm Peach." << std::endl; }
int main(void) { int i; PaStream* stream; PaStreamParameters outputParameters; PaError err; paTestData data = {0}; double load; printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); /* initialise sinusoidal wavetable */ for( i=0; i<TABLE_SIZE; i++ ) { data.sine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. ); } data.sine[TABLE_SIZE] = data.sine[0]; /* set guard point */ err = Pa_Initialize(); if( err != paNoError ) goto error; outputParameters.device = Pa_GetDefaultOutputDevice(); /* Default output device. */ if (outputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default output device.\n"); goto error; } outputParameters.channelCount = 2; /* Stereo output. */ outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output. */ outputParameters.hostApiSpecificStreamInfo = NULL; outputParameters.suggestedLatency = Pa_GetDeviceInfo(outputParameters.device) ->defaultHighOutputLatency; err = Pa_OpenStream(&stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* No out of range samples should occur. */ patestCallback, &data); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; /* Play an increasing number of sine waves until we hit MAX_USAGE */ do { data.numSines++; Pa_Sleep(200); load = Pa_GetStreamCpuLoad(stream); printf("numSines = %d, CPU load = %f\n", data.numSines, load ); fflush(stdout); } while((load < MAX_USAGE) && (data.numSines < MAX_SINES)); Pa_Sleep(2000); /* Stay for 2 seconds around 80% CPU. */ err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); printf("Test finished.\n"); return err; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
int main(int argc, char* argv[]){ char* host = "127.0.0.1"; if (argc != 2){ std::cerr << "Usage: client <host>" << std::endl; return 1; }else{ host = argv[1]; } PaStreamParameters outputParameters; PaStream *stream; PaError err; sAudioBuffer* audiobuf; audiobuf = new sAudioBuffer(); audiobuf->dec = opus_decoder_create(SAMPLE_RATE, 2, &audiobuf->error); if(audiobuf->error != OPUS_OK){ std::cerr << "opus: could not create decoder" << std::endl; return 2; } printf("SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); audiobuf->readerIndex = 0; err = Pa_Initialize(); if( err != paNoError ) goto error; outputParameters.device = Pa_GetDefaultOutputDevice(); if (outputParameters.device == paNoDevice){ fprintf(stderr,"Error: No default output device.\n"); goto error; } outputParameters.channelCount = 2; outputParameters.sampleFormat = paFloat32; outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; err = Pa_OpenStream( &stream, NULL, &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, audioCallback, audiobuf); if( err != paNoError ) goto error; err = Pa_SetStreamFinishedCallback( stream, &StreamFinished ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; try{ serveClient(host, audiobuf); }catch (std::exception& e){ std::cerr << e.what() << std::endl; } err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); delete audiobuf; return 0; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
int main(int argc, char* argv[]) { PaStream *stream; PaError err; patest1data data; int i; PaStreamParameters inputParameters, outputParameters; const PaHostErrorInfo* herr; printf("patest1.c\n"); fflush(stdout); printf("Ring modulate input for 20 seconds.\n"); fflush(stdout); /* initialise sinusoidal wavetable */ for( i=0; i<100; i++ ) data.sine[i] = sin( ((double)i/100.) * M_PI * 2. ); data.phase = 0; data.sampsToGo = SAMPLE_RATE * 20; /* 20 seconds. */ /* initialise portaudio subsytem */ err = Pa_Initialize(); inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */ if (inputParameters.device == paNoDevice) { fprintf(stderr,"Error: No input default device.\n"); goto done; } inputParameters.channelCount = 2; /* stereo input */ inputParameters.sampleFormat = paFloat32; /* 32 bit floating point input */ inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; inputParameters.hostApiSpecificStreamInfo = NULL; outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ if (outputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default output device.\n"); goto done; } outputParameters.channelCount = 2; /* stereo output */ outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; err = Pa_OpenStream( &stream, &inputParameters, &outputParameters, (double)SAMPLE_RATE, /* Samplerate in Hertz. */ 512, /* Small buffers */ paClipOff, /* We won't output out of range samples so don't bother clipping them. */ patest1Callback, &data ); if( err != paNoError ) goto done; err = Pa_StartStream( stream ); if( err != paNoError ) goto done; printf( "Press any key to end.\n" ); fflush(stdout); getc( stdin ); /* wait for input before exiting */ err = Pa_AbortStream( stream ); if( err != paNoError ) goto done; printf( "Waiting for stream to complete...\n" ); /* sleep until playback has finished */ while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Pa_Sleep(1000); if( err < 0 ) goto done; err = Pa_CloseStream( stream ); if( err != paNoError ) goto done; done: Pa_Terminate(); if( err != paNoError ) { fprintf( stderr, "An error occured while using portaudio\n" ); if( err == paUnanticipatedHostError ) { fprintf( stderr, " unanticipated host error.\n"); herr = Pa_GetLastHostErrorInfo(); if (herr) { fprintf( stderr, " Error number: %ld\n", herr->errorCode ); if (herr->errorText) fprintf( stderr, " Error text: %s\n", herr->errorText ); } else fprintf( stderr, " Pa_GetLastHostErrorInfo() failed!\n" ); } else { fprintf( stderr, " Error number: %d\n", err ); fprintf( stderr, " Error text: %s\n", Pa_GetErrorText( err ) ); } err = 1; /* Always return 0 or 1, but no other return codes. */ } printf( "bye\n" ); return err; }
int main(void) { PaStreamParameters outputParameters; PaAsioStreamInfo asioOutputInfo; PaStream *stream; PaError err; paTestData data; int outputChannelSelectors[1]; int i; printf("PortAudio Test: output MONO sine wave. SR = %d, BufSize = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER); /* initialise sinusoidal wavetable */ for( i=0; i<TABLE_SIZE; i++ ) { data.sine[i] = (float) (AMPLITUDE * sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. )); } data.phase = 0; err = Pa_Initialize(); if( err != paNoError ) goto error; outputParameters.device = OUTPUT_DEVICE; outputParameters.channelCount = 1; /* MONO output */ outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; asioOutputInfo.size = sizeof(PaAsioStreamInfo); asioOutputInfo.hostApiType = paASIO; asioOutputInfo.version = 1; asioOutputInfo.flags = paAsioUseChannelSelectors; outputChannelSelectors[0] = 1; /* select the second (right) ASIO device channel */ asioOutputInfo.channelSelectors = outputChannelSelectors; outputParameters.hostApiSpecificStreamInfo = &asioOutputInfo; err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Play for %d seconds.\n", NUM_SECONDS ); fflush(stdout); Pa_Sleep( NUM_SECONDS * 1000 ); err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); printf("Test finished.\n"); return err; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
int main(void) { PortAudioStream *stream; PaError err; paTestData data; int i; int timeout; printf("Play different tone sine waves that alternate between left and right channel.\n"); printf("The low tone should be on the left channel.\n"); /* initialise sinusoidal wavetable */ for( i=0; i<TABLE_SIZE; i++ ) { data.sine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. ); } data.left_phase = data.right_phase = data.toggle = 0; data.countDown = SAMPLE_RATE; err = Pa_Initialize(); if( err != paNoError ) goto error; err = Pa_OpenStream( &stream, paNoDevice,/* default input device */ 0, /* no input */ paFloat32, /* 32 bit floating point input */ NULL, Pa_GetDefaultOutputDeviceID(), /* default output device */ 2, /* stereo output */ paFloat32, /* 32 bit floating point output */ NULL, SAMPLE_RATE, FRAMES_PER_BUFFER, /* frames per buffer */ 0, /* number of buffers, if zero then use default minimum */ paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Play for several seconds.\n"); timeout = NUM_SECONDS * 4; while( timeout > 0 ) { Pa_Sleep( 300 ); timeout -= 1; } err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); printf("Test finished.\n"); return err; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
int main(void) { PaStreamParameters outputParameters; PaStream *stream; PaError err; int numStress; paTestData data = {0}; double load; printf("PortAudio Test: output sine wave. SR = %d, BufSize = %d. MAX_LOAD = %f\n", SAMPLE_RATE, FRAMES_PER_BUFFER, MAX_LOAD ); err = Pa_Initialize(); if( err != paNoError ) goto error; outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ if (outputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default output device.\n"); goto error; } outputParameters.channelCount = 1; /* mono output */ outputParameters.sampleFormat = paFloat32; /* 32 bit floating point output */ outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; /* Determine number of sines required to get to 50% */ do { data.numSines++; Pa_Sleep( 100 ); load = Pa_GetStreamCpuLoad( stream ); printf("numSines = %d, CPU load = %f\n", data.numSines, load ); } while( load < 0.5 ); /* Calculate target stress value then ramp up to that level*/ numStress = (int) (2.0 * data.numSines * MAX_LOAD ); for( ; data.numSines < numStress; data.numSines++ ) { Pa_Sleep( 200 ); load = Pa_GetStreamCpuLoad( stream ); printf("STRESSING: numSines = %d, CPU load = %f\n", data.numSines, load ); } printf("Suffer for 5 seconds.\n"); Pa_Sleep( 5000 ); printf("Stop stream.\n"); err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); printf("Test finished.\n"); return err; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
int newChain(PaDeviceIndex inputDeviceIndex, PaDeviceIndex outputDeviceIndex) { PaError err; //malloc memory for new node Chain* newChain = malloc(sizeof(Chain)); //set new final node's next pointer to NULL newChain->nextChain = NULL; if(rootChain == NULL){ rootChain = newChain; } else{ Chain* iterator = rootChain; while(iterator->nextChain != NULL){ iterator = iterator->nextChain; } //set final node's next node pointer to new node iterator->nextChain = newChain; } newChain->inputParameters.device = inputDeviceIndex; if(newChain->inputParameters.device == paNoDevice){ fprintf(stderr,"Error: Input device is invalid.\n Maybe the device has been unplugged?"); goto error; } const PaDeviceInfo* inputDeviceInfo = Pa_GetDeviceInfo(inputDeviceIndex); const PaDeviceInfo* outputDeviceInfo = Pa_GetDeviceInfo(outputDeviceIndex); newChain->inputParameters.channelCount = inputDeviceInfo->maxInputChannels; newChain->inputParameters.sampleFormat = PA_SAMPLE_TYPE; newChain->inputParameters.suggestedLatency = inputDeviceInfo->defaultLowInputLatency; newChain->inputParameters.hostApiSpecificStreamInfo = NULL; newChain->outputParameters.device = outputDeviceIndex; if(newChain->outputParameters.device == paNoDevice){ fprintf(stderr,"Error: Output device is invalid.\n Maybe the device has been unplugged?"); goto error; } newChain->outputParameters.channelCount = outputDeviceInfo->maxOutputChannels; newChain->outputParameters.sampleFormat = PA_SAMPLE_TYPE; newChain->outputParameters.suggestedLatency = outputDeviceInfo->defaultLowOutputLatency; newChain->outputParameters.hostApiSpecificStreamInfo = NULL; //set root ChainLink to empty effect that does nothing, because it needs to be initialized //to something in order to be passed to the callback //should probably set this to be a gain adjustment; control output level and input level newChain->chainLink = malloc(sizeof(ChainLink)); newChain->chainLink->effectType = IO; newChain->chainLink->effectData = initIOEffect(); newChain->chainLink->effectFunction = &IOEffect; newChain->chainLink->nextLink = NULL; //set global number of input and output channels numInputChannels = newChain->inputParameters.channelCount; numOutputChannels = newChain->outputParameters.channelCount; //set the global sampleRate here sampleRate = inputDeviceInfo->defaultSampleRate; err = Pa_OpenStream( &(newChain->stream), &(newChain->inputParameters), &(newChain->outputParameters), inputDeviceInfo->defaultSampleRate, paFramesPerBufferUnspecified, paClipOff, audioCallback, newChain->chainLink); if(err != paNoError) goto error; err = Pa_StartStream(newChain->stream); if( err != paNoError ) goto error; return 0; error: fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return -1; }
int main(void) { PaStreamParameters inputParameters, outputParameters; PaStream* stream; PaError err = paNoError; paTestData data; int i; int totalFrames; int numSamples; int numBytes; SAMPLE max, val; double average; printf("patest_record.c\n"); fflush(stdout); data.maxFrameIndex = totalFrames = NUM_SECONDS * SAMPLE_RATE; /* Record for a few seconds. */ data.frameIndex = 0; numSamples = totalFrames * NUM_CHANNELS; numBytes = numSamples * sizeof(SAMPLE); data.recordedSamples = (SAMPLE *) malloc( numBytes ); /* From now on, recordedSamples is initialised. */ if( data.recordedSamples == NULL ) { printf("Could not allocate record array.\n"); ; } for( i=0; i<numSamples; i++ ) data.recordedSamples[i] = 0; err = Pa_Initialize(); if( err != paNoError ) {}; inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */ if (inputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default input device.\n"); ; } inputParameters.channelCount = NUM_CHANNELS; inputParameters.sampleFormat = PA_SAMPLE_TYPE; inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; inputParameters.hostApiSpecificStreamInfo = NULL; // /* Record some audio. -------------------------------------------- */ // err = Pa_OpenStream( // &stream, // &inputParameters, // NULL, /* &outputParameters, */ // SAMPLE_RATE, // FRAMES_PER_BUFFER, // paClipOff, /* we won't output out of range samples so don't bother clipping them */ // recordCallback, // &data ); // if( err != paNoError ) {}; // // err = Pa_StartStream( stream ); // if( err != paNoError ) {}; // printf("\n=== Sprawdzam poziom szumów. Nie mów nic. ===\n"); fflush(stdout); // // while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) // { // Pa_Sleep(1000); // printf("index = %d\n", data.frameIndex ); fflush(stdout); // } // if( err < 0 ){}; // // err = Pa_CloseStream( stream ); // if( err != paNoError ) {}; data.frameIndex = 0; err = Pa_OpenStream( &stream, &inputParameters, NULL, /* &outputParameters, */ SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ recordCallback, &data ); if( err != paNoError ) {}; err = Pa_StartStream( stream ); if( err != paNoError ) {}; printf("\n=== Teraz nagrywam powiedź coś. ===\n"); fflush(stdout); while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) { Pa_Sleep(1000); printf("index = %d\n", data.frameIndex ); fflush(stdout); } if( err < 0 ){}; err = Pa_CloseStream( stream ); if( err != paNoError ) {}; /* Measure maximum peak amplitude. */ max = 0; average = 0.0; for( i=0; i<numSamples; i++ ) { val = data.recordedSamples[i]; if( val < 0 ) val = -val; /* ABS */ if( val > max ) { max = val; } average += val; } average = average / (double)numSamples; printf("maksymalna amplituda = "PRINTF_S_FORMAT"\n", max ); printf("srednia = %lf\n", average ); zapiszWykres(numSamples, data); zapiszHistogram(numSamples, data); //przejsciaPrzezZero(numSamples, data, 0); przejsciaPrzezZero(numSamples, data, average); /* Playback recorded data. -------------------------------------------- */ data.frameIndex = 0; outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ if (outputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default output device.\n"); } outputParameters.channelCount = NUM_CHANNELS; /* stereo output */ outputParameters.sampleFormat = PA_SAMPLE_TYPE; outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; printf("\n=== Now playing back. ===\n"); fflush(stdout); err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ playCallback, &data ); if( err != paNoError ) {}; if( stream ) { err = Pa_StartStream( stream ); if( err != paNoError ) {}; printf("Waiting for playback to finish.\n"); fflush(stdout); while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Pa_Sleep(100); if( err < 0 ) {}; err = Pa_CloseStream( stream ); if( err != paNoError ) {}; printf("Done.\n"); fflush(stdout); } Pa_Terminate(); if( data.recordedSamples ) /* Sure it is NULL or valid. */ free( data.recordedSamples ); if( err != paNoError ) { fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); err = 1; /* Always return 0 or 1, but no other return codes. */ } return err; }
static void *output_thread(void *ptr) { int err; int output_buffer_size; #ifndef PORTAUDIO_DEV int num_mixers, nbVolumes, volumeIdx; #endif struct timeval now; struct timespec timeout; slimaudio_t *audio = (slimaudio_t *) ptr; audio->output_STMs = false; audio->output_STMu = false; err = Pa_Initialize(); if (err != paNoError) { printf("PortAudio error4: %s Could not open any audio devices.\n", Pa_GetErrorText(err) ); exit(-1); } if ( audio->renice ) if ( slimproto_renice_thread (-5) ) /* Increase priority */ fprintf(stderr, "output_thread: renice failed. Got Root?\n"); #ifndef PORTAUDIO_DEV DEBUGF("output_thread: output_device_id : %i\n", audio->output_device_id ); DEBUGF("output_thread: pa_framesPerBuffer: %lu\n", pa_framesPerBuffer ); DEBUGF("output_thread: pa_numberOfBuffers: %lu\n", pa_numberOfBuffers ); err = Pa_OpenStream( &audio->pa_stream, /* stream */ paNoDevice, /* input device */ 0, /* input channels */ 0, /* input sample format */ NULL, /* input driver info */ audio->output_device_id,/* output device */ 2, /* output channels */ paInt16, /* output sample format */ NULL, /* output driver info */ 44100.0, /* sample rate */ pa_framesPerBuffer, /* frames per buffer */ pa_numberOfBuffers, /* number of buffers */ paNoFlag, /* stream flags */ pa_callback, /* callback */ audio); /* user data */ #else PaStreamParameters outputParameters; const PaDeviceInfo * paDeviceInfo; float newLatency; #ifdef PADEV_WASAPI PaWasapiStreamInfo streamInfo; const PaHostApiInfo *paHostApiInfo; #endif paDeviceInfo = Pa_GetDeviceInfo(audio->output_device_id); /* Device is not stereo or better, abort */ if (paDeviceInfo->maxOutputChannels < 2) { printf("output_thread: PortAudio device does not support 44.1KHz, 16-bit, stereo audio.\n"); printf("output_thread: Use -L for a list of supported audio devices, then use -o followed\n"); printf("output_thread: by the device number listed before the colon. See -h for details.\n"); exit(-2); } outputParameters.device = audio->output_device_id; #ifdef SLIMPROTO_ZONES outputParameters.channelCount = 2 * audio->output_num_zones; #else outputParameters.channelCount = 2; #endif outputParameters.sampleFormat = paInt16; outputParameters.suggestedLatency = paDeviceInfo->defaultHighOutputLatency; if ( audio->modify_latency ) { newLatency = (float) audio->user_latency / 1000.0; if ( ( newLatency > 1.0 ) || ( newLatency <= paDeviceInfo->defaultLowOutputLatency ) ) { fprintf (stderr, "User defined latency %f out of range %f-1.0, using default.\n", newLatency, paDeviceInfo->defaultLowOutputLatency ); newLatency = paDeviceInfo->defaultHighOutputLatency; } outputParameters.suggestedLatency = newLatency ; } #ifdef PADEV_WASAPI /* Use exclusive mode for WASAPI device, default is shared */ paHostApiInfo = Pa_GetHostApiInfo ( paDeviceInfo->hostApi ); if ( paHostApiInfo != NULL ) { if ( paHostApiInfo->type == paWASAPI ) { /* Use exclusive mode for WasApi device, default is shared */ if (wasapi_exclusive) { streamInfo.size = sizeof(PaWasapiStreamInfo); streamInfo.hostApiType = paWASAPI; streamInfo.version = 1; streamInfo.flags = paWinWasapiExclusive; outputParameters.hostApiSpecificStreamInfo = &streamInfo; DEBUGF("WASAPI: Exclusive\n"); } else { outputParameters.hostApiSpecificStreamInfo = NULL; DEBUGF("WASAPI: Shared\n"); } } } #else outputParameters.hostApiSpecificStreamInfo = NULL; #endif DEBUGF("paDeviceInfo->deviceid %d\n", outputParameters.device); DEBUGF("paDeviceInfo->maxOutputChannels %i\n", paDeviceInfo->maxOutputChannels); DEBUGF("outputParameters.suggestedLatency %f\n", outputParameters.suggestedLatency); DEBUGF("paDeviceInfo->defaultHighOutputLatency %f\n", (float) paDeviceInfo->defaultHighOutputLatency); DEBUGF("paDeviceInfo->defaultLowOutputLatency %f\n", (float) paDeviceInfo->defaultLowOutputLatency); DEBUGF("paDeviceInfo->defaultSampleRate %f\n", paDeviceInfo->defaultSampleRate); err = Pa_OpenStream ( &audio->pa_stream, /* stream */ NULL, /* inputParameters */ &outputParameters, /* outputParameters */ 44100.0, /* sample rate */ paFramesPerBufferUnspecified, /* framesPerBuffer */ paPrimeOutputBuffersUsingStreamCallback, /* streamFlags */ pa_callback, /* streamCallback */ audio); /* userData */ #endif #ifdef BSD_THREAD_LOCKING pthread_mutex_lock(&audio->output_mutex); #endif if (err != paNoError) { printf("output_thread: PortAudio error1: %s\n", Pa_GetErrorText(err) ); exit(-1); } #ifndef PORTAUDIO_DEV num_mixers = Px_GetNumMixers(audio->pa_stream); while (--num_mixers >= 0) { DEBUGF("Mixer: %s\n", Px_GetMixerName(audio->pa_stream, num_mixers)); } if (audio->volume_control == VOLUME_DRIVER) { DEBUGF("Opening mixer.\n" ); audio->px_mixer = Px_OpenMixer(audio->pa_stream, 0); } if (audio->px_mixer != NULL) { DEBUGF("Px_mixer = %p\n", audio->px_mixer); DEBUGF("PCM volume supported: %d.\n", Px_SupportsPCMOutputVolume(audio->px_mixer)); nbVolumes = Px_GetNumOutputVolumes(audio->px_mixer); DEBUGF("Nb volumes supported: %d.\n", nbVolumes); for (volumeIdx=0; volumeIdx<nbVolumes; ++volumeIdx) { DEBUGF("Volume %d: %s\n", volumeIdx, Px_GetOutputVolumeName(audio->px_mixer, volumeIdx)); } } #endif while (audio->output_state != QUIT) { switch (audio->output_state) { case STOPPED: audio->decode_num_tracks_started = 0L; audio->stream_samples = 0UL; audio->pa_streamtime_offset = audio->stream_samples; DEBUGF("output_thread STOPPED: %llu\n",audio->pa_streamtime_offset); slimaudio_buffer_set_readopt(audio->output_buffer, BUFFER_BLOCKING); case PAUSED: /* We report ourselves to the server every few seconds ** as a keep-alive. This is required for Squeezebox Server ** v6.5.x although technically, "stat" is not a valid event ** code for the STAT Client->Server message. This was ** lifted by observing how a Squeezebox3 reports itself to ** the server using Squeezebox Server's d_slimproto and ** d_slimproto_v tracing services. Note that Squeezebox3 ** seems to report every 1 second or so, but the server only ** drops the connection after 15-20 seconds of inactivity. */ DEBUGF("output_thread PAUSED: %llu\n",audio->pa_streamtime_offset); if (audio->keepalive_interval <= 0) { pthread_cond_wait(&audio->output_cond, &audio->output_mutex); } else { gettimeofday(&now, NULL); timeout.tv_sec = now.tv_sec + audio->keepalive_interval; timeout.tv_nsec = now.tv_usec * 1000; err = pthread_cond_timedwait(&audio->output_cond, &audio->output_mutex, &timeout); if (err == ETIMEDOUT) { DEBUGF("Sending keepalive. Interval=%ds.\n", audio->keepalive_interval); output_thread_stat(audio, "stat"); } } break; case PLAY: audio->output_predelay_frames = audio->output_predelay_msec * 44.100; DEBUGF("output_thread PLAY: output_predelay_frames: %i\n", audio->output_predelay_frames); output_buffer_size = slimaudio_buffer_available(audio->output_buffer); DEBUGF("output_thread BUFFERING: output_buffer_size: %i output_threshold: %i", output_buffer_size, audio->output_threshold); DEBUGF(" buffering_timeout: %i\n", audio->buffering_timeout); if ( (output_buffer_size < audio->output_threshold) && (audio->buffering_timeout > 0) ) { pthread_mutex_unlock(&audio->output_mutex); pthread_cond_broadcast(&audio->output_cond); Pa_Sleep(100); pthread_mutex_lock(&audio->output_mutex); audio->buffering_timeout--; } else { DEBUGF("output_thread PLAY: start stream: %llu\n", audio->pa_streamtime_offset); audio->buffering_timeout = BUFFERING_TIMEOUT; err = Pa_StartStream(audio->pa_stream); if (err != paNoError) { printf("output_thread: PortAudio error2: %s\n", Pa_GetErrorText(err)); exit(-1); } audio->output_state = PLAYING; pthread_cond_broadcast(&audio->output_cond); } break; case BUFFERING: DEBUGF("output_thread BUFFERING: %llu\n",audio->pa_streamtime_offset); case PLAYING: gettimeofday(&now, NULL); timeout.tv_sec = now.tv_sec + 1; timeout.tv_nsec = now.tv_usec * 1000; err = pthread_cond_timedwait(&audio->output_cond, &audio->output_mutex, &timeout); if (err == ETIMEDOUT) { DEBUGF("output_thread ETIMEDOUT-PLAYING: %llu\n",audio->pa_streamtime_offset); output_thread_stat(audio, "STMt"); } /* Track started */ if (audio->output_STMs) { audio->output_STMs = false; audio->decode_num_tracks_started++; audio->replay_gain = audio->start_replay_gain; slimaudio_output_vol_adjust(audio); audio->pa_streamtime_offset = audio->stream_samples; DEBUGF("output_thread STMs-PLAYING: %llu\n",audio->pa_streamtime_offset); output_thread_stat(audio, "STMs"); } /* Data underrun ** On buffer underrun causes the server to switch to the next track. */ if (audio->output_STMu) { audio->output_STMu = false; audio->output_state = STOP; DEBUGF("output_thread STMu-PLAYING: %llu\n",audio->pa_streamtime_offset); output_thread_stat(audio, "STMu"); pthread_cond_broadcast(&audio->output_cond); } break; case STOP: #ifndef PORTAUDIO_DEV if ( (err = Pa_StreamActive(audio->pa_stream) ) > 0) { err = Pa_StopStream(audio->pa_stream); if (err != paNoError) { printf("output_thread: PortAudio error3: %s\n", Pa_GetErrorText(err) ); exit(-1); } } else { if ( err != paNoError) { printf("output_thread: PortAudio error9: %s\n", Pa_GetErrorText(err) ); exit(-1); } } #else if ( (err = Pa_IsStreamActive(audio->pa_stream)) > 0) { err = Pa_StopStream(audio->pa_stream); if (err != paNoError) { printf("output_thread[STOP]: PortAudio error3: %s\n", Pa_GetErrorText(err) ); exit(-1); } } else if ( err != paNoError) { printf("output_thread[STOP ISACTIVE]: PortAudio error3: %s\n", Pa_GetErrorText(err) ); exit(-1); } #endif audio->output_state = STOPPED; DEBUGF("output_thread STOP: %llu\n",audio->pa_streamtime_offset); pthread_cond_broadcast(&audio->output_cond); break; case PAUSE: #ifndef PORTAUDIO_DEV if ( (err = Pa_StreamActive(audio->pa_stream) ) > 0) { err = Pa_StopStream(audio->pa_stream); if (err != paNoError) { printf("output_thread: PortAudio error10: %s\n", Pa_GetErrorText(err)); exit(-1); } } else { if ( err != paNoError) { printf("output_thread: PortAudio error11: %s\n", Pa_GetErrorText(err) ); exit(-1); } } #else if ( (err = Pa_IsStreamActive(audio->pa_stream)) > 0) { err = Pa_StopStream(audio->pa_stream); if (err != paNoError) { printf("output_thread[PAUSE]: PortAudio error3: %s\n", Pa_GetErrorText(err) ); exit(-1); } } else if ( err != paNoError) { printf("output_thread[PAUSE ISACTIVE]: PortAudio error3: %s\n", Pa_GetErrorText(err) ); exit(-1); } #endif audio->output_state = PAUSED; DEBUGF("output_thread PAUSE: %llu\n",audio->pa_streamtime_offset); pthread_cond_broadcast(&audio->output_cond); break; case QUIT: DEBUGF("output_thread QUIT: %llu\n",audio->pa_streamtime_offset); break; } } pthread_mutex_unlock(&audio->output_mutex); #ifndef PORTAUDIO_DEV if (audio->px_mixer != NULL) { Px_CloseMixer(audio->px_mixer); audio->px_mixer = NULL; } #endif err = Pa_CloseStream(audio->pa_stream); if (err != paNoError) { printf("output_thread[exit]: PortAudio error3: %s\n", Pa_GetErrorText(err) ); exit(-1); } audio->pa_stream = NULL; Pa_Terminate(); DEBUGF("output_thread: PortAudio terminated\n"); return 0; }
bool Portaudio::init() { PaError err = Pa_Initialize(); if (err != paNoError) { qDebug("Portaudio initialize failed: %s", Pa_GetErrorText(err)); return false; } initialized = true; if (MScore::debugMode) qDebug("using PortAudio Version: %s", Pa_GetVersionText()); PaDeviceIndex idx = preferences.portaudioDevice; if (idx < 0) idx = Pa_GetDefaultOutputDevice(); const PaDeviceInfo* di = Pa_GetDeviceInfo(idx); _sampleRate = int(di->defaultSampleRate); /* Open an audio I/O stream. */ struct PaStreamParameters out; memset(&out, 0, sizeof(out)); out.device = idx; out.channelCount = 2; out.sampleFormat = paFloat32; #ifdef Q_OS_MAC out.suggestedLatency = 0.020; #else // on windows, this small latency causes some problem out.suggestedLatency = 0.100; #endif out.hostApiSpecificStreamInfo = 0; err = Pa_OpenStream(&stream, 0, &out, double(_sampleRate), 0, 0, paCallback, (void*)this); if (err != paNoError) { // fall back to default device: out.device = Pa_GetDefaultOutputDevice(); err = Pa_OpenStream(&stream, 0, &out, double(_sampleRate), 0, 0, paCallback, (void*)this); if (err != paNoError) { qDebug("Portaudio open stream %d failed: %s", idx, Pa_GetErrorText(err)); return false; } } const PaStreamInfo* si = Pa_GetStreamInfo(stream); if (si) _sampleRate = int(si->sampleRate); #ifdef USE_ALSA midiDriver = new AlsaMidiDriver(seq); #endif #ifdef USE_PORTMIDI midiDriver = new PortMidiDriver(seq); #endif if (midiDriver && !midiDriver->init()) { qDebug("Init midi driver failed"); delete midiDriver; midiDriver = 0; #ifdef USE_PORTMIDI return true; // return OK for audio driver; midi is only input #else return false; #endif } return true; }
static int open_output(void) { double rate; int n, nrates, include_enc, exclude_enc, ret; PaSampleFormat SampleFormat, nativeSampleFormats; if( dpm.name != NULL) ret = sscanf(dpm.name, "%d", &opt_pa_device_id); if (dpm.name == NULL || ret == 0 || ret == EOF) opt_pa_device_id = -2; #ifdef AU_PORTAUDIO_DLL #if PORTAUDIO_V19 { if(&dpm == &portaudio_asio_play_mode){ HostApiTypeId = paASIO; } else if(&dpm == &portaudio_win_ds_play_mode){ HostApiTypeId = paDirectSound; } else if(&dpm == &portaudio_win_wmme_play_mode){ HostApiTypeId = paMME; } else { return -1; } if(load_portaudio_dll(0)) return -1; } #else { if(&dpm == &portaudio_asio_play_mode){ if(load_portaudio_dll(PA_DLL_ASIO)) return -1; } else if(&dpm == &portaudio_win_ds_play_mode){ if(load_portaudio_dll(PA_DLL_WIN_DS)) return -1; } else if(&dpm == &portaudio_win_wmme_play_mode){ if(load_portaudio_dll(PA_DLL_WIN_WMME)) return -1; } else { return -1; } } #endif #endif /* if call twice Pa_OpenStream causes paDeviceUnavailable error */ if(pa_active == 1) return 0; if(pa_active == 0){ err = Pa_Initialize(); if( err != paNoError ) goto error; pa_active = 1; } if (opt_pa_device_id == -1){ print_device_list(); goto error2; } #ifdef PORTAUDIO_V19 #ifdef AU_PORTAUDIO_DLL { PaHostApiIndex i, ApiCount; i = 0; ApiCount = Pa_GetHostApiCount(); do{ HostApiInfo=Pa_GetHostApiInfo(i); if( HostApiInfo->type == HostApiTypeId ) break; i++; }while ( i < ApiCount ); if ( i == ApiCount ) goto error; DeviceIndex = HostApiInfo->defaultOutputDevice; if(DeviceIndex==paNoDevice) goto error; } #else DeviceIndex = Pa_GetDefaultOutputDevice(); if(DeviceIndex==paNoDevice) goto error; #endif DeviceInfo = Pa_GetDeviceInfo( DeviceIndex); if(DeviceInfo==NULL) goto error; if(opt_pa_device_id != -2){ const PaDeviceInfo *id_DeviceInfo; id_DeviceInfo=Pa_GetDeviceInfo((PaDeviceIndex)opt_pa_device_id); if(id_DeviceInfo==NULL) goto error; if( DeviceInfo->hostApi == id_DeviceInfo->hostApi){ DeviceIndex=(PaDeviceIndex)opt_pa_device_id; DeviceInfo = id_DeviceInfo; } } if (dpm.encoding & PE_24BIT) { SampleFormat = paInt24; }else if (dpm.encoding & PE_16BIT) { SampleFormat = paInt16; }else { SampleFormat = paInt8; } stereo = (dpm.encoding & PE_MONO) ? 1 : 2; data_nbyte = (dpm.encoding & PE_16BIT) ? 2 : 1; data_nbyte = (dpm.encoding & PE_24BIT) ? 3 : data_nbyte; pa_data.samplesToGo = 0; pa_data.bufpoint = pa_data.buf; pa_data.bufepoint = pa_data.buf; // firsttime = 1; numBuffers = 1; //Pa_GetMinNumBuffers( framesPerBuffer, dpm.rate ); framesPerInBuffer = numBuffers * framesPerBuffer; if (framesPerInBuffer < 4096) framesPerInBuffer = 4096; bytesPerInBuffer = framesPerInBuffer * data_nbyte * stereo; /* set StreamParameters */ StreamParameters.device = DeviceIndex; StreamParameters.channelCount = stereo; if(ctl->id_character != 'r' && ctl->id_character != 'A' && ctl->id_character != 'W' && ctl->id_character != 'P'){ StreamParameters.suggestedLatency = DeviceInfo->defaultHighOutputLatency; }else{ StreamParameters.suggestedLatency = DeviceInfo->defaultLowOutputLatency; } StreamParameters.hostApiSpecificStreamInfo = NULL; if( SampleFormat == paInt16){ StreamParameters.sampleFormat = paInt16; if( paFormatIsSupported != Pa_IsFormatSupported( NULL , &StreamParameters,(double) dpm.rate )){ StreamParameters.sampleFormat = paInt32; conv16_32 = 1; } else { StreamParameters.sampleFormat = paInt16; conv16_32 = 0; } }else{ StreamParameters.sampleFormat = SampleFormat; } err = Pa_IsFormatSupported( NULL , &StreamParameters, (double) dpm.rate ); if ( err != paNoError) goto error; err = Pa_OpenStream( & stream, /* passes back stream pointer */ NULL, /* inputStreamParameters */ &StreamParameters, /* outputStreamParameters */ (double) dpm.rate, /* sample rate */ paFramesPerBufferUnspecified, /* frames per buffer */ paFramesPerBufferUnspecified, /* PaStreamFlags */ paCallback, /* specify our custom callback */ &pa_data /* pass our data through to callback */ ); // Pa_Sleeep(1); if ( err != paNoError) goto error; return 0; #else if(opt_pa_device_id == -2){ DeviceID = Pa_GetDefaultOutputDeviceID(); if(DeviceID==paNoDevice) goto error2; }else{ DeviceID = opt_pa_device_id; } DeviceInfo = Pa_GetDeviceInfo( DeviceID); if(DeviceInfo==NULL) goto error2; nativeSampleFormats = DeviceInfo->nativeSampleFormats; exclude_enc = PE_ULAW | PE_ALAW | PE_BYTESWAP; include_enc = PE_SIGNED; if (!(nativeSampleFormats & paInt16) && !(nativeSampleFormats & paInt32)) {exclude_enc |= PE_16BIT;} if (!(nativeSampleFormats & paInt24)) {exclude_enc |= PE_24BIT;} dpm.encoding = validate_encoding(dpm.encoding, include_enc, exclude_enc); if (dpm.encoding & PE_24BIT) { SampleFormat = paInt24; }else if (dpm.encoding & PE_16BIT) { if(nativeSampleFormats & paInt16) SampleFormat = paInt16; else{ SampleFormat = paInt32; conv16_32 = 1; } }else { SampleFormat = paInt8; } stereo = (dpm.encoding & PE_MONO) ? 1 : 2; data_nbyte = (dpm.encoding & PE_16BIT) ? 2 : 1; data_nbyte = (dpm.encoding & PE_24BIT) ? 3 : data_nbyte; nrates = DeviceInfo->numSampleRates; if (nrates == -1) { /* range supported */ rate = dpm.rate; if (dpm.rate < DeviceInfo->sampleRates[0]) rate = DeviceInfo->sampleRates[0]; if (dpm.rate > DeviceInfo->sampleRates[1]) rate = DeviceInfo->sampleRates[1]; } else { rate = DeviceInfo->sampleRates[nrates-1]; for (n = nrates - 1; n >= 0; n--) { /* find nearest sample rate */ if (dpm.rate <= DeviceInfo->sampleRates[n]) rate=DeviceInfo->sampleRates[n]; } } dpm.rate = (int32)rate; pa_data.samplesToGo = 0; pa_data.bufpoint = pa_data.buf; pa_data.bufepoint = pa_data.buf; // firsttime = 1; numBuffers = Pa_GetMinNumBuffers( framesPerBuffer, dpm.rate ); framesPerInBuffer = numBuffers * framesPerBuffer; if (framesPerInBuffer < 4096) framesPerInBuffer = 4096; bytesPerInBuffer = framesPerInBuffer * data_nbyte * stereo; // printf("%d\n",framesPerInBuffer); // printf("%d\n",dpm.rate); err = Pa_OpenDefaultStream( &stream, /* passes back stream pointer */ 0, /* no input channels */ stereo, /* 2:stereo 1:mono output */ SampleFormat, /* 24bit 16bit 8bit output */ (double)dpm.rate, /* sample rate */ framesPerBuffer, /* frames per buffer */ numBuffers, /* number of buffers, if zero then use default minimum */ paCallback, /* specify our custom callback */ &pa_data); /* pass our data through to callback */ if ( err != paNoError && err != paHostError) goto error; return 0; #endif error: ctl->cmsg( CMSG_ERROR, VERB_NORMAL, "PortAudio error: %s\n", Pa_GetErrorText( err ) ); error2: Pa_Terminate(); pa_active = 0; #ifdef AU_PORTAUDIO_DLL #ifndef PORTAUDIO_V19 free_portaudio_dll(); #endif #endif return -1; }
int openPA(Synth* synth) { printf("PortAudio Test: output sawtooth wave.\n"); fflush(stdout); PaStreamParameters inputParameters, outputParameters; /* Initialize library before making any other calls. */ err = Pa_Initialize(); if( err != paNoError ) goto error; /* Set up input parameters */ inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */ if (inputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default input device.\n"); goto error; } printf( "Input device # %d.\n", inputParameters.device ); printf( "Input LL: %g s\n", Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency ); printf( "Input HL: %g s\n", Pa_GetDeviceInfo( inputParameters.device )->defaultHighInputLatency ); inputParameters.channelCount = NUM_INPUT; inputParameters.sampleFormat = FORMAT; inputParameters.suggestedLatency = Pa_GetDeviceInfo( inputParameters.device )->defaultLowInputLatency; inputParameters.hostApiSpecificStreamInfo = NULL; /* Set up output parameters */ outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ if (outputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default output device.\n"); goto error; } printf( "Output device # %d.\n", outputParameters.device ); printf( "Output LL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency ); printf( "Output HL: %g s\n", Pa_GetDeviceInfo( outputParameters.device )->defaultHighOutputLatency ); outputParameters.channelCount = NUM_OUTPUT; outputParameters.sampleFormat = FORMAT; outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; /* Open an audio I/O stream. */ err = Pa_OpenStream( &stream, &inputParameters, &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, paCallback, synth ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; return err; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); vc_free(vc); return err; }
int main(void) { char pad[256]; PortAudioStream *stream; PaError err; const PaDeviceInfo *pdi; paTestData data = {0}; printf("PortAudio Test: output sine wave on each channel.\n" ); err = Pa_Initialize(); if( err != paNoError ) goto error; pdi = Pa_GetDeviceInfo( OUTPUT_DEVICE ); data.numChannels = pdi->maxOutputChannels; if( data.numChannels > MAX_CHANNELS ) data.numChannels = MAX_CHANNELS; printf("Number of Channels = %d\n", data.numChannels ); data.amplitude = 1.0; err = Pa_OpenStream( &stream, paNoDevice, /* default input device */ 0, /* no input */ paFloat32, /* 32 bit floating point input */ NULL, OUTPUT_DEVICE, data.numChannels, paFloat32, /* 32 bit floating point output */ NULL, SAMPLE_RATE, FRAMES_PER_BUFFER, /* frames per buffer */ 0, /* number of buffers, if zero then use default minimum */ paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; do { printf("Current amplitude = %f\n", data.amplitude ); printf("Enter new amplitude or 'q' to quit.\n"); fflush(stdout); gets( pad ); if( pad[0] != 'q' ) { // I tried to use atof but it seems to be broken on Mac OS X 10.1 float amp; sscanf( pad, "%f", & ); data.amplitude = amp; } } while( pad[0] != 'q' ); err = Pa_StopStream( stream ); if( err != paNoError ) goto error; Pa_CloseStream( stream ); Pa_Terminate(); printf("Test finished.\n"); return err; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
void audio_thread(struct params * prm) { PaStream *stream; PaError err; PaStreamParameters ioparam; ioparam.device = dev; ioparam.channelCount = prm->channels; ioparam.sampleFormat = prm->sampleFormat; ioparam.suggestedLatency = Pa_GetDeviceInfo(dev)->defaultLowOutputLatency; ioparam.hostApiSpecificStreamInfo = NULL; pthread_mutex_lock(&queue_mutex); reset_queue_pointer = 1; pthread_mutex_unlock(&queue_mutex); struct udata ud; ud.prm = prm; ud.verbose = verbose; switch (prm->sampleFormat) { case paInt8: ud.bpFrame = 1; break; case paInt16: ud.bpFrame = 2; break; case paInt24: ud.bpFrame = 3; break; case paInt32: ud.bpFrame = 4; break; case paFloat32: ud.bpFrame = 4; break; default: break; } err = Pa_OpenStream(&stream, NULL, &ioparam, prm->sampleRate, prm->framesPerBuffer, 0, get_data, &ud ); if (err!=paNoError) { fprintf(stderr,"Can't open stream: %s\n",Pa_GetErrorText(err)); return; } err = Pa_StartStream(stream); if(err != paNoError) { fprintf(stderr,"Can't start stream: %s\n",Pa_GetErrorText(err)); Pa_CloseStream(stream); return; } const char * format = "unknown"; switch (prm->sampleFormat) { case paInt8: format = "8"; break; case paInt16: format = "16"; break; case paInt24: format = "24"; break; case paInt32: format = "32"; break; case paFloat32: format = "float32"; break; } fprintf(stderr,"Opened audio stream\n"); fprintf(stderr,"Number of channels: %d\n",prm->channels); fprintf(stderr,"Bit depth: %s\n",format); fprintf(stderr,"Sample rate: %.0fHz\n",prm->sampleRate); fprintf(stderr,"Buffer size: %lu frames\n",prm->framesPerBuffer); while (keep_going) Pa_Sleep(60); Pa_CloseStream(stream); fprintf(stderr,"Closed audio stream due to inactivity\n"); }
int run_filter(AudioOptions audio_options) { PaStreamParameters input_parameters, output_parameters; PaStream *input_stream = NULL, *output_stream = NULL; PaError err = paNoError; CircularBuffer * output_buffer = CircularBuffer_create(audio_options.buffer_size); CircularBuffer * input_buffer = NULL; CircularBuffer * decoder_input = NULL; DecodingBuffer * decoder_buffer = NULL; int live_stream = !audio_options.wav_path || !strlen(audio_options.wav_path); OSFilter * filter = OSFilter_create( audio_options.filters, audio_options.num_filters, 2, audio_options.filter_size, audio_options.conv_multiple * (audio_options.filter_size - 1), audio_options.input_scale ); if (!filter) { goto done; } if ((err = Pa_Initialize()) != paNoError) { goto done; } int step_size = audio_options.filter_size - 1; RecordCallbackMetadata record_data = { NULL, 0, 0, audio_options.number_of_channels, audio_options.enabled_channels, 0 }; { int num_enabled_channels = 0; for (int i = 0; i < audio_options.number_of_channels; ++i) { if (audio_options.enabled_channels & (1 << i)) { num_enabled_channels++; } } if (num_enabled_channels != audio_options.enabled_channels) { record_data.stripe_input = 1; } if (num_enabled_channels == 0) { record_data.stripe_input = 0; } } if (record_data.stripe_input) { printf("striping record_data: %d channels with %d enabled flag\n", record_data.number_of_channels, record_data.enabled_channels ); } else { printf("NOT striping record_data: %d channels with %d enabled flag\n", record_data.number_of_channels, record_data.enabled_channels ); } if (live_stream) { input_buffer = CircularBuffer_create(audio_options.buffer_size); if (audio_options.decode_input) { decoder_input = CircularBuffer_create(audio_options.buffer_size); decoder_buffer = Decoding_new(decoder_input, input_buffer); record_data.buffer = decoder_input; if (!Decoding_start_ac3(decoder_buffer)) { printf("Failed to start ac3 decoder thread.\n"); goto done; } } else { record_data.buffer = input_buffer; } input_parameters.device = audio_options.input_device; input_parameters.channelCount = 2; input_parameters.sampleFormat = PA_SAMPLE_TYPE; input_parameters.suggestedLatency = Pa_GetDeviceInfo(input_parameters.device)->defaultHighInputLatency; input_parameters.hostApiSpecificStreamInfo = NULL; err = Pa_OpenStream( &input_stream, &input_parameters, NULL, audio_options.sample_rate, step_size, paNoFlag, recordCallback, &record_data ); if (err != paNoError) { goto done; } record_data.start_time = currentTimeMillis(); #ifdef LINUX_ALSA PaAlsa_EnableRealtimeScheduling(input_stream, 1); #endif if ((err = Pa_StartStream(input_stream)) != paNoError) { goto done; } } else { input_buffer = __read_audio_file(audio_options); } output_parameters.device = audio_options.output_device; if (audio_options.output_channels >= 6) { output_parameters.channelCount = audio_options.output_channels + 2; } else { output_parameters.channelCount = audio_options.output_channels; } output_parameters.sampleFormat = PA_SAMPLE_TYPE; output_parameters.suggestedLatency = Pa_GetDeviceInfo(output_parameters.device)->defaultLowOutputLatency; output_parameters.hostApiSpecificStreamInfo = NULL; PlaybackCallbackData playback_data = { output_buffer, output_parameters.channelCount }; printf("output channels: %d\n", output_parameters.channelCount); err = Pa_OpenStream( &output_stream, NULL, &output_parameters, audio_options.sample_rate, step_size, paNoFlag, playCallback, &playback_data ); if (err != paNoError) { goto done; } #ifdef LINUX_ALSA PaAlsa_EnableRealtimeScheduling(output_stream, 1); #endif if ((err = Pa_StartStream(output_stream)) != paNoError) { goto done; } int output_scale = output_parameters.channelCount / 2; int frame_print_interval = DEBUG_PRINT_INTERVAL_MILLIS * audio_options.sample_rate / 1000; int current_frame = 0; while (true) { if ((err = Pa_IsStreamActive(output_stream)) != 1) { break; } if (input_stream && (err = Pa_IsStreamActive(input_stream)) != 1) { break; } current_frame += OSFilter_execute(filter, input_buffer, output_buffer); if (audio_options.print_debug && current_frame > frame_print_interval) { current_frame -= frame_print_interval; if (!is_parent_running(audio_options.parent_thread_ident)) { printf("Parent thread is dead. Shutting down now.\n"); fflush(stdout); goto done; } if (!audio_options.print_debug) { continue; } long frame_difference = (CircularBuffer_lag(input_buffer) + CircularBuffer_lag(output_buffer) / output_scale) / 2; float lag = (float)(frame_difference) / audio_options.sample_rate * 1000; printf("%lu\t%lu\t%lu\t%fms\n", input_buffer->offset_producer, output_buffer->offset_consumer / output_scale, frame_difference, lag ); if (live_stream && (lag > audio_options.lag_reset_limit * 1000)) { printf("Resetting to latest due to high lag.\n"); CircularBuffer_fastforward(input_buffer, audio_options.filter_size * 2); CircularBuffer_fastforward(output_buffer, 0); } fflush(stdout); } } if (err < 0) { goto done; } done: if (output_stream) { Pa_CloseStream(output_stream); } if (input_stream) { Pa_CloseStream(input_stream); } Pa_Terminate(); if (input_buffer) { CircularBuffer_destroy(input_buffer); } CircularBuffer_destroy(output_buffer); if (decoder_input) { CircularBuffer_destroy(decoder_input); } if (decoder_buffer) { Decoding_free(decoder_buffer); } OSFilter_destroy(filter); if (err != paNoError) { fprintf(stdout, "An error occured while using the portaudio stream\n"); fprintf(stdout, "Error number: %d\n", err); fprintf(stdout, "Error message: %s\n", Pa_GetErrorText(err)); fflush(stdout); err = 1; } return err; }
int main(int argc, char* argv[]) { PaStreamParameters outputParameters; PaWinDirectSoundStreamInfo directSoundStreamInfo; PaStream *stream; PaError err; paTestData data; int i; int deviceIndex; printf("PortAudio Test: output a sine blip on each channel. SR = %d, BufSize = %d, Chans = %d\n", SAMPLE_RATE, FRAMES_PER_BUFFER, CHANNEL_COUNT); err = Pa_Initialize(); if( err != paNoError ) goto error; deviceIndex = Pa_GetHostApiInfo( Pa_HostApiTypeIdToHostApiIndex( paDirectSound ) )->defaultOutputDevice; if( argc == 2 ){ sscanf( argv[1], "%d", &deviceIndex ); } printf( "using device id %d (%s)\n", deviceIndex, Pa_GetDeviceInfo(deviceIndex)->name ); /* initialise sinusoidal wavetable */ for( i=0; i<TABLE_SIZE; i++ ) { data.sine[i] = (float) sin( ((double)i/(double)TABLE_SIZE) * M_PI * 2. ); } data.phase = 0; data.currentChannel = 0; data.cycleCount = 0; outputParameters.device = deviceIndex; outputParameters.channelCount = CHANNEL_COUNT; outputParameters.sampleFormat = paFloat32; /* 32 bit floating point processing */ outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; /* it's not strictly necessary to provide a channelMask for surround sound output. But if you want to be sure which channel mask PortAudio will use then you should supply one */ directSoundStreamInfo.size = sizeof(PaWinDirectSoundStreamInfo); directSoundStreamInfo.hostApiType = paDirectSound; directSoundStreamInfo.version = 1; directSoundStreamInfo.flags = paWinDirectSoundUseChannelMask; directSoundStreamInfo.channelMask = PAWIN_SPEAKER_5POINT1; /* request 5.1 output format */ outputParameters.hostApiSpecificStreamInfo = &directSoundStreamInfo; if( Pa_IsFormatSupported( 0, &outputParameters, SAMPLE_RATE ) == paFormatIsSupported ){ printf( "Pa_IsFormatSupported reports device will support %d channels.\n", CHANNEL_COUNT ); }else{ printf( "Pa_IsFormatSupported reports device will not support %d channels.\n", CHANNEL_COUNT ); } err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ patestCallback, &data ); if( err != paNoError ) goto error; err = Pa_StartStream( stream ); if( err != paNoError ) goto error; printf("Play for %d seconds.\n", NUM_SECONDS ); Pa_Sleep( NUM_SECONDS * 1000 ); err = Pa_StopStream( stream ); if( err != paNoError ) goto error; err = Pa_CloseStream( stream ); if( err != paNoError ) goto error; Pa_Terminate(); printf("Test finished.\n"); return err; error: Pa_Terminate(); fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); return err; }
int main(void) { PaStreamParameters outputParameters; PaStream* stream; PaError err = paNoError; paTestData data; int totalFrames; int numSamples; int numBytes; data.maxFrameIndex = totalFrames = NUM_SECONDS * SAMPLE_RATE; /* Record for a few seconds. */ data.frameIndex = 0; numSamples = totalFrames * NUM_CHANNELS; numBytes = numSamples * sizeof(SAMPLE); data.recordedSamples = (SAMPLE *) malloc( numBytes ); /* From now on, recordedSamples is initialised. */ if( data.recordedSamples == NULL ) { printf("Could not allocate record array.\n"); goto done; } if( err != paNoError ) goto done; FILE * pFile; long lSize; size_t result; pFile = fopen ( "recorded.raw" , "rb" ); if (pFile==NULL) { fputs ("Error opening file!",stderr); exit (1); } // obtain file size: fseek (pFile , 0 , SEEK_END); lSize = ftell (pFile); rewind (pFile); // copy the file into the buffer: result = fread( data.recordedSamples, NUM_CHANNELS * sizeof(SAMPLE), lSize / (NUM_CHANNELS * sizeof(SAMPLE)), pFile ); if (result != lSize / (NUM_CHANNELS * sizeof(SAMPLE))) { fputs ("Reading error, file may be corrupted\n",stderr); exit (3); } fclose (pFile); /* Playback recorded data. -------------------------------------------- */ data.frameIndex = 0; outputParameters.device = Pa_GetDefaultOutputDevice(); /* default output device */ if (outputParameters.device == paNoDevice) { fprintf(stderr,"Error: No default output device.\n"); goto done; } outputParameters.channelCount = 2; /* stereo output */ outputParameters.sampleFormat = PA_SAMPLE_TYPE; outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency; outputParameters.hostApiSpecificStreamInfo = NULL; printf("\n=== Now playing back. ===\n"); fflush(stdout); err = Pa_OpenStream( &stream, NULL, /* no input */ &outputParameters, SAMPLE_RATE, FRAMES_PER_BUFFER, paClipOff, /* we won't output out of range samples so don't bother clipping them */ playCallback, &data ); if( err != paNoError ) goto done; if( stream ) { err = Pa_StartStream( stream ); if( err != paNoError ) goto done; printf("Waiting for playback to finish.\n"); fflush(stdout); while( ( err = Pa_IsStreamActive( stream ) ) == 1 ) Pa_Sleep(100); if( err < 0 ) goto done; err = Pa_CloseStream( stream ); if( err != paNoError ) goto done; printf("Done.\n"); fflush(stdout); } done: Pa_Terminate(); if( data.recordedSamples ) /* Sure it is NULL or valid. */ free( data.recordedSamples ); if( err != paNoError ) { fprintf( stderr, "An error occured while using the portaudio stream\n" ); fprintf( stderr, "Error number: %d\n", err ); fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); err = 1; /* Always return 0 or 1, but no other return codes. */ } return err; }