Beispiel #1
0
void
PortAudioLayer::initStream()
{
    dcblocker_.reset();

    RING_DBG("Open PortAudio Output Stream");
    PaStreamParameters outputParameters;
    outputParameters.device = indexOut_;

    if (outputParameters.device == paNoDevice) {
        RING_ERR("Error: No valid output device. There will be no sound.");
    } else {
        const auto outputDeviceInfo =
            Pa_GetDeviceInfo(outputParameters.device);
        outputParameters.channelCount =
            audioFormat_.nb_channels = outputDeviceInfo->maxOutputChannels;
        outputParameters.sampleFormat = paInt16;
        outputParameters.suggestedLatency = outputDeviceInfo->defaultLowOutputLatency;
        outputParameters.hostApiSpecificStreamInfo = NULL;

        auto err = Pa_OpenStream(
            &streams[Direction::Output],
            NULL,
            &outputParameters,
            outputDeviceInfo->defaultSampleRate,
            paFramesPerBufferUnspecified,
            paNoFlag,
            &PortAudioLayer::paOutputCallback,
            this);
        if(err != paNoError)
            this->handleError(err);
    }

    RING_DBG("Open PortAudio Input Stream");
    PaStreamParameters inputParameters;
    inputParameters.device = indexIn_;
    if (inputParameters.device == paNoDevice) {
        RING_ERR("Error: No valid input device. There will be no mic.");
    } else {
        const auto inputDeviceInfo =
            Pa_GetDeviceInfo(inputParameters.device);
        inputParameters.channelCount =
            audioInputFormat_.nb_channels = inputDeviceInfo->maxInputChannels;
        inputParameters.sampleFormat = paInt16;
        inputParameters.suggestedLatency = inputDeviceInfo->defaultLowInputLatency;
        inputParameters.hostApiSpecificStreamInfo = NULL;

        auto err = Pa_OpenStream(
            &streams[Direction::Input],
            &inputParameters,
            NULL,
            inputDeviceInfo->defaultSampleRate,
            paFramesPerBufferUnspecified,
            paNoFlag,
            &PortAudioLayer::paInputCallback,
            this);
        if(err != paNoError)
            this->handleError(err);
    }

    RING_DBG("Start PortAudio Streams");
    for (int i = 0; i < Direction::End; i++) {
        auto err = Pa_StartStream(streams[i]);
        if (err != paNoError)
            this->handleError(err);
    }

    flushUrgent();
    flushMain();
}
Beispiel #2
0
static int output_data(char *buf, int32 nbytes)
{
	unsigned int i;
	int32 samplesToGo;
	char *bufepoint;

    if(pa_active == 0) return -1; 
	
	while((pa_active==1) && (pa_data.samplesToGo > bytesPerInBuffer)){ Pa_Sleep(1);};
	
//	if(pa_data.samplesToGo > DATA_BLOCK_SIZE){ 
//		Sleep(  (pa_data.samplesToGo - DATA_BLOCK_SIZE)/dpm.rate/4  );
//	}
	samplesToGo=pa_data.samplesToGo;
	bufepoint=pa_data.bufepoint;

	if (pa_data.buf+bytesPerInBuffer*2 >= bufepoint + nbytes){
		memcpy(bufepoint, buf, nbytes);
		bufepoint += nbytes;
		//buf += nbytes;
	}else{
		int32 send = pa_data.buf+bytesPerInBuffer*2 - bufepoint;
		if (send != 0) memcpy(bufepoint, buf, send);
		buf += send;
		memcpy(pa_data.buf, buf, nbytes - send);
		bufepoint = pa_data.buf + nbytes - send;
		//buf += nbytes-send;
	}
	samplesToGo += nbytes;

	pa_data.samplesToGo=samplesToGo;
	pa_data.bufepoint=bufepoint;

/*
	if(firsttime==1){
		err = Pa_StartStream( stream );

		if( err != paNoError ) goto error;
		firsttime=0;
	}
*/
#if PORTAUDIO_V19
	if( 0==Pa_IsStreamActive(stream)){
#else
	if( 0==Pa_StreamActive(stream)){
#endif
		err = Pa_StartStream( stream );

		if( err != paNoError ) goto error;
	}
		
//	if(ctl->id_character != 'r' && ctl->id_character != 'A' && ctl->id_character != 'W' && ctl->id_character != 'P')
//	    while((pa_active==1) && (pa_data.samplesToGo > bytesPerInBuffer)){ Pa_Sleep(1);};
//	Pa_Sleep( (pa_data.samplesToGo - bytesPerInBuffer)/dpm.rate * 1000);
	return 0;

error:
	Pa_Terminate(); pa_active=0;
	ctl->cmsg(CMSG_ERROR, VERB_NORMAL, "PortAudio error: %s\n", Pa_GetErrorText( err ) );
	return -1;
}

static void close_output(void)
{	
	if( pa_active==0) return;
#ifdef PORTAUDIO_V19
	if(Pa_IsStreamActive(stream)){
#else
	if(Pa_StreamActive(stream)){
#endif
		Pa_Sleep(  bytesPerInBuffer/dpm.rate*1000  );
	}	
	err = Pa_AbortStream( stream );
    if( (err!=paStreamIsStopped) && (err!=paNoError) ) goto error;
	err = Pa_CloseStream( stream );
//	if( err != paNoError ) goto error;
	Pa_Terminate(); 
	pa_active=0;

#ifdef AU_PORTAUDIO_DLL
#ifndef PORTAUDIO_V19
  free_portaudio_dll();
#endif
#endif

	return;

error:
	Pa_Terminate(); pa_active=0;
#ifdef AU_PORTAUDIO_DLL
#ifndef PORTAUDIO_V19
  free_portaudio_dll();
#endif
#endif
	ctl->cmsg(  CMSG_ERROR, VERB_NORMAL, "PortAudio error: %s\n", Pa_GetErrorText( err ) );
	return;
}


static int acntl(int request, void *arg)
{
    switch(request)
    {
 
      case PM_REQ_GETQSIZ:
		 *(int *)arg = bytesPerInBuffer*2;
    	return 0;
		//break;
      case PM_REQ_GETFILLABLE:
		 *(int *)arg = bytesPerInBuffer*2-pa_data.samplesToGo;
    	return 0;
		//break;
      case PM_REQ_GETFILLED:
		 *(int *)arg = pa_data.samplesToGo;
    	return 0;
		//break;

    	
   	case PM_REQ_DISCARD:
    case PM_REQ_FLUSH:
    	pa_data.samplesToGo=0;
    	pa_data.bufpoint=pa_data.bufepoint;
    	err = Pa_AbortStream( stream );
    	if( (err!=paStreamIsStopped) && (err!=paNoError) ) goto error;
    	err = Pa_StartStream( stream );
    	if(err!=paNoError) goto error;
		return 0;

		//break;

    case PM_REQ_RATE:  
    	{
    		int i;
    		double sampleRateBack;
    		i = *(int *)arg; //* sample rate in and out *
    		close_output();
    		sampleRateBack=dpm.rate;
    		dpm.rate=i;
    		if(0==open_output()){
    			return 0;
    		}else{    		
    			dpm.rate=sampleRateBack;
    			open_output();
    			return -1;
    		}
    	}
    	//break;

//    case PM_REQ_RATE: 
//          return -1;
    	
    case PM_REQ_PLAY_START: //* Called just before playing *
    case PM_REQ_PLAY_END: //* Called just after playing *
        return 0;
      
	default:
    	return -1;

    }
	return -1;
error:
/*
	Pa_Terminate(); pa_active=0;
#ifdef AU_PORTAUDIO_DLL
  free_portaudio_dll();
#endif
*/
	ctl->cmsg(  CMSG_ERROR, VERB_NORMAL, "PortAudio error in acntl : %s\n", Pa_GetErrorText( err ) );
	return -1;
}


static void print_device_list(void){
	PaDeviceIndex maxDeviceIndex, i;
	PaHostApiIndex HostApiIndex;
	const PaDeviceInfo* DeviceInfo;

#if PORTAUDIO_V19
	HostApiIndex=Pa_HostApiTypeIdToHostApiIndex(HostApiTypeId);
#endif
	
	maxDeviceIndex=Pa_GetDeviceCount();
	
	for( i = 0; i < maxDeviceIndex; i++){
		DeviceInfo=Pa_GetDeviceInfo(i);
#if PORTAUDIO_V19
		if( DeviceInfo->hostApi == HostApiIndex){
#endif
			if( DeviceInfo->maxOutputChannels > 0){
				ctl->cmsg(  CMSG_ERROR, VERB_NORMAL, "%2d %s",i,DeviceInfo->name);
			}
#if PORTAUDIO_V19
		}
#endif
	}
}
Beispiel #3
0
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;
}
Beispiel #4
0
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;
}
Beispiel #5
0
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;
}
Beispiel #6
0
bool Initialize(VinoMemory* Mem)
{
    // Init values
    {
        float OrthoMtx[4][4] =
        {
            { 2.0f,   0.0f,   0.0f,   0.0f },
            { 0.0f,  -2.0f,   0.0f,   0.0f },
            { 0.0f,   0.0f,  -1.0f,   0.0f },
            { -1.0f,  1.0f,   0.0f,   1.0f },
        };
        memcpy(Mem->Window.ProjMtx, OrthoMtx, sizeof(OrthoMtx));
    }

#if 0
    // Initialize mpg123
    {
        if (Mem->Audio.Mpg_Init() != MPG123_OK)
        {
            // TODO: Log error
            return false;
        }

        int Error;
        Mem->Audio.MpgHandle = Mem->Audio.Mpg_New(0, &Error);
        if (Error)
        {
            // TODO: Log error
            return false;
        }

        Error = Mem->Audio.Mpg_Open(Mem->Audio.MpgHandle, "C:\\Users\\Apoorva\\Music\\foo.mp3");
        if (Error) { return false; }

        Error = Mem->Audio.Mpg_GetFormat(Mem->Audio.MpgHandle,
            (long*)&Mem->Audio.Rate, &Mem->Audio.Channels, &Mem->Audio.Encoding);
        if (Error) { return false; }
    }

    // Initialize PortAudio
    {
        PaError Error = Pa_Initialize();
        if (Error != paNoError)
        {
            // TODO: Log: Audio init failure
            return false;
        }

        PaStream* Stream;
        Error = Pa_OpenDefaultStream(
            &Stream,
            0,
            Mem->Audio.Channels,
            paInt16,
            Mem->Audio.Rate,
            0,
            AudioReadCallback,
            Mem);

        Error = Pa_SetStreamFinishedCallback(Stream, &AudioFinishedCallback);
        if (Error != paNoError) { return false; }

        Error = Pa_StartStream(Stream);
        if (Error != paNoError) { return false; }





        //Error = Pa_StopStream(Stream);
        //if (Error != paNoError) { return false; }

        //Error = Pa_CloseStream(Stream);
        //if (Error != paNoError) { return false; }

        //Pa_Terminate();
    }
#endif

    const char* Vert;
    // Vertex shader
    {
        Vert = 
        "   #version 330                                        \n"
        "   uniform mat4 ProjMtx;                               \n" // Uniforms[0]
        "                                                       \n"
        "   in vec2 Position;                                   \n" // Attributes[0]
        "   in vec2 UV;                                         \n" // Attributes[1]
        "   in vec4 Color;                                      \n" // Attributes[2]
        "                                                       \n"
        "   out vec2 Frag_UV;                                   \n"
        "   out vec4 Frag_Color;                                \n"
        "   void main()                                         \n"
        "   {                                                   \n"
        "       Frag_UV = UV;                                   \n"
        "       Frag_Color = Color;                             \n"
        "       gl_Position = ProjMtx * vec4(Position.xy,0,1);  \n"
        "   }                                                   \n";
    }

    // Default shader
    {
    const char* Frag =
"   #version 330                                                \n"
"   uniform sampler2D Texture;                                  \n" // Uniforms[1]
"                                                               \n"
"   in vec2 Frag_UV;                                            \n"
"   in vec4 Frag_Color;                                         \n"
"                                                               \n"
"   out vec4 Out_Color;                                         \n"
"   void main()                                                 \n"
"   {                                                           \n"
"       Out_Color = Frag_Color * texture( Texture, Frag_UV.st); \n"
"   }                                                           \n";

    CompileShader(Mem->Shaders[VinoShader_Default], Vert, Frag, 3, 2,
        "Position", "UV", "Color",
        "ProjMtx", "Texture");
    }

    // Setup for ImGui
    {
        glGenBuffers(1, &Mem->Meshes[VinoMesh_ImGui].VboHandle);
        glGenBuffers(1, &Mem->Meshes[VinoMesh_ImGui].ElementsHandle);

        glGenVertexArrays        (1, &Mem->Meshes[VinoMesh_ImGui].VaoHandle);
        glBindVertexArray        (Mem->Meshes[VinoMesh_ImGui].VaoHandle);
        glBindBuffer             (GL_ARRAY_BUFFER, Mem->Meshes[VinoMesh_ImGui].VboHandle);
        glEnableVertexAttribArray(Mem->Shaders[VinoShader_Default].Attributes[0]);
        glEnableVertexAttribArray(Mem->Shaders[VinoShader_Default].Attributes[1]);
        glEnableVertexAttribArray(Mem->Shaders[VinoShader_Default].Attributes[2]);

    #define OFFSETOF(TYPE, ELEMENT) ((size_t)&(((TYPE *)0)->ELEMENT))
        glVertexAttribPointer(Mem->Shaders[VinoShader_Default].Attributes[0], 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, pos));
        glVertexAttribPointer(Mem->Shaders[VinoShader_Default].Attributes[1], 2, GL_FLOAT, GL_FALSE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, uv));
        glVertexAttribPointer(Mem->Shaders[VinoShader_Default].Attributes[2], 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(ImDrawVert), (GLvoid*)OFFSETOF(ImDrawVert, col));
    #undef OFFSETOF
        glBindVertexArray(0);
        glBindBuffer(GL_ARRAY_BUFFER, 0);

        // Create fonts texture
        ImGuiIO& io = ImGui::GetIO();

        unsigned char* pixels;
        int width, height;
        //ImFont* my_font0 = io.Fonts->AddFontFromFileTTF("d:\\DroidSans.ttf", 15.0f);
        io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);

        glGenTextures  (1, &Mem->Textures[VinoTex_Font]);
        glBindTexture  (GL_TEXTURE_2D, Mem->Textures[VinoTex_Font]);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexImage2D   (GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);

        // Store our identifier
        io.Fonts->TexID = (void *)(intptr_t)Mem->Textures[VinoTex_Font];

        // Cleanup
        io.Fonts->ClearInputData();
        io.Fonts->ClearTexData();
    }

    // Load interface textures and colors
    {
        // Texture IDs
        Mem->Textures[VinoTex_TitleBarButtons] = LoadAndBindImage("../../img/win32_titlebar_buttons.png");
        Mem->Textures[VinoTex_TitleBarIcon]    = LoadAndBindImage("../../img/win32_titlebar_icon.png");
        Mem->Textures[VinoTex_InterfaceIcons]  = LoadAndBindImage("../../img/interface_icons.png");

        // Colors
#if 1
        Mem->Colors[VinoCol_Clear]         = Color(45,45,48); // Dark grey
#else
        Mem->Colors[VinoCol_Clear]         = Color(114,144,154); // Light blue
#endif
        Mem->Colors[VinoCol_Transparent]   = Color(0,0,0,0);
        Mem->Colors[VinoCol_Button]        = Color(92,92,94);
        Mem->Colors[VinoCol_ButtonHover]   = Color(64,64,64);
        Mem->Colors[VinoCol_ButtonActive]  = Color(0,122,204);
    }

    // ImGui Style Settings
    {
        ImGuiStyle& Style = ImGui::GetStyle();
        Style.WindowFillAlphaDefault = 1.0f;
        // TODO: Move repeated stuff here by setting global style
    }

    return true;
}
Beispiel #7
0
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;
}
void audiosource_portaudio::init() {
	err = Pa_Initialize();
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_Initialize");
	}

	PaHostApiIndex api_idx;

	const PaHostApiInfo* info = Pa_GetHostApiInfo(Pa_GetDefaultHostApi());

	std::cerr << "Default device: " << info->name << std::endl;

	for (api_idx = 0; api_idx < Pa_GetHostApiCount(); ++api_idx) {
		info = Pa_GetHostApiInfo(api_idx);
		std::cerr << "device " << api_idx << ": " << info->name << std::endl;
	}

	//int frames_per_buffer = get_sample_rate();
	int frames_per_buffer = paFramesPerBufferUnspecified;

	/*
	 * We have two separate streams for input and output to work-around a Debian specific
	 * bug on PortAudio.
	 */

    /* Open an audio I/O stream. */
    err = Pa_OpenDefaultStream( &stream_in,
    							get_in_channel_count(),          /* input channels */
                                0,          /* output */
                                paFloat32,  /* 32 bit floating point output */
                                get_sample_rate(),
                                frames_per_buffer, /* frames per buffer, i.e. the number
                                                   of sample frames that PortAudio will
                                                   request from the callback. Many apps
                                                   may want to use
                                                   paFramesPerBufferUnspecified, which
                                                   tells PortAudio to pick the best,
                                                   possibly changing, buffer size.*/
                                portaudio_in_callback, /* this is your callback function */
                                static_cast<void*>(this) ); /*This is a pointer that will be passed to
                                                   your callback*/
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_OpenDefaultStream");
	}

	err = Pa_StartStream( stream_in );
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_StartStream");
	}

    /* Open an audio I/O stream. */
    err = Pa_OpenDefaultStream( &stream_out,
    							0,          /* input channels */
    							get_out_channel_count(),          /* output */
                                paFloat32,  /* 32 bit floating point output */
                                get_sample_rate(),
                                frames_per_buffer, /* frames per buffer, i.e. the number
                                                   of sample frames that PortAudio will
                                                   request from the callback. Many apps
                                                   may want to use
                                                   paFramesPerBufferUnspecified, which
                                                   tells PortAudio to pick the best,
                                                   possibly changing, buffer size.*/
                                portaudio_out_callback, /* this is your callback function */
                                static_cast<void*>(this) ); /*This is a pointer that will be passed to
                                                   your callback*/
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_OpenDefaultStream");
	}

	err = Pa_StartStream( stream_out );
	if( err != paNoError ) {
		std::cerr << "PortAudio error: " << Pa_GetErrorText( err ) << std::endl;
		throw audiosourceexception("Pa_StartStream");
	}
}
Beispiel #9
0
/*!
   Start the audio device

 */
void AudioReaderPortAudio::initialize()
{
    initialized     = false;
    bpmax           = sizes.chunk_size / sizes.advance_size;
    inputParameters.device=settings->value(s_sdr_deviceindx,s_sdr_deviceindx_def).toInt();
    switch (settings->value(s_sdr_bits,s_sdr_bits_def).toInt()) {
    case 0:
        inputParameters.sampleFormat = paInt16;
        break;
    case 1:
        inputParameters.sampleFormat = paInt24;
        break;
    case 2:
        inputParameters.sampleFormat = paInt32;
        break;
    }
    inputParameters.channelCount=2;
    inputParameters.hostApiSpecificStreamInfo=NULL;

    if (buff) {
        delete [] buff;
    }
    buff = new unsigned char[sizes.chunk_size];
    for (unsigned long i = 0; i < sizes.chunk_size; i++) {
        buff[i] = 0;
    }
    stream = NULL;
    err    = Pa_Initialize();
    if (checkError(err)) {
        stop();
        return;
    }
    int numDevices = Pa_GetDeviceCount();
    if (numDevices < 0) {
        emit(error("ERROR: PortAudio found no audio devices"));
        return;
    }
    if (Pa_GetDeviceInfo(inputParameters.device)==NULL) {
        emit(error("ERROR: getdeviceinfo returned null pointer"));
        return;
    }
    if (Pa_GetDeviceInfo(inputParameters.device)->maxInputChannels < 2) {
        emit(error("ERROR: audio device does not support stereo"));
        return;
    }
    // set suggested latency
    inputParameters.suggestedLatency = Pa_GetDeviceInfo(inputParameters.device)->defaultLowInputLatency;
    periodSize=settings->value(s_sdr_fft,s_sdr_fft_def).toInt()/4;

    err = Pa_IsFormatSupported(&inputParameters, NULL,
                               settings->value(s_sdr_sound_sample_freq,s_sdr_sound_sample_freq_def).toInt());
    if (checkError(err)) {
        stop();
        return;
    }
    err = Pa_OpenStream(
                &stream,
                &inputParameters, NULL,
                settings->value(s_sdr_sound_sample_freq,s_sdr_sound_sample_freq_def).toInt(),
                periodSize,
                paClipOff | paDitherOff,
                callback,
                this);
    if (checkError(err)) {
        stop();
        return;
    }
    err = Pa_StartStream(stream);
    if (checkError(err)) {
        stop();
        return;
    }
    mutex.lock();
    initialized = true;
    running = true;
    mutex.unlock();
}
Beispiel #10
0
int main(void)
{
    PortAudioStream *stream;
    PaError err;
    paTestData data;
    int i;
    PaDeviceID inputDevice;
    const PaDeviceInfo *pdi;
    printf("PortAudio Test: input signal from each channel. %d buffers\n", NUM_BUFFERS );
    data.liveChannel = 0;
    err = Pa_Initialize();
    if( err != paNoError ) goto error;
#ifdef INPUT_DEVICE_NAME
    printf("Try to use device: %s\n", INPUT_DEVICE_NAME );
    inputDevice = PaFindDeviceByName(INPUT_DEVICE_NAME);
    if( inputDevice == paNoDevice )
    {
        printf("Could not find %s. Using default instead.\n", INPUT_DEVICE_NAME );
        inputDevice = Pa_GetDefaultInputDeviceID();
    }
#else
    printf("Using default input device.\n");
    inputDevice = Pa_GetDefaultInputDeviceID();
#endif
    pdi = Pa_GetDeviceInfo( inputDevice );
    if( pdi == NULL )
    {
        printf("Could not get device info!\n");
        goto error;
    }
    data.numChannels = pdi->maxInputChannels;
    printf("Input Device name is %s\n", pdi->name );
    printf("Input Device has %d channels.\n", pdi->maxInputChannels);
    err = Pa_OpenStream(
              &stream,
              inputDevice,
              pdi->maxInputChannels,
              paFloat32,  /* 32 bit floating point input */
              NULL,
              OUTPUT_DEVICE,
              2,
              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.liveChannel = 0;
    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;
    for( i=0; i<data.numChannels; i++ )
    {
        data.liveChannel = i;
        printf("Channel %d being sent to output. Hit ENTER for next channel.", i );
        fflush(stdout);
        getchar();
    }
    err = Pa_StopStream( stream );
    if( err != paNoError ) goto error;

    err = 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;
}
Beispiel #11
0
	void startStream(PaStream* stream) {
		if(!stream) return;
		PaError err = Pa_StartStream(stream);
		if (err != paNoError)
			Logger::logError("PortAudio error:") << Pa_GetErrorText(err) << endl;
	}
Beispiel #12
0
int main(void)
{
    
    /***************************************************************
     Set up the hardware parameters
     ****************************************************************/
    
    PaStreamParameters inputParameters, outputParameters;
    PaStream *stream;
    PaError err;
    
    err = Pa_Initialize();
    if( err != paNoError ) goto error;
    
    inputParameters.device = Pa_GetDefaultInputDevice(); /* default input device */
    if (inputParameters.device == paNoDevice) {
        fprintf(stderr,"Error: No default input device.\n");
        goto error;
    }
    inputParameters.channelCount = 1;       /* Single channel input */
    inputParameters.sampleFormat = PA_SAMPLE_TYPE;
    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 error;
    }
    outputParameters.channelCount = 1;       /* Single channel output */
    outputParameters.sampleFormat = PA_SAMPLE_TYPE;
    outputParameters.suggestedLatency = Pa_GetDeviceInfo( outputParameters.device )->defaultLowOutputLatency;
    outputParameters.hostApiSpecificStreamInfo = NULL;
    
    tempOutput =(float*)malloc(FRAMES_PER_BUFFER*sizeof(float));
    
    audioKernelSamples = (int16_t*)malloc(FRAMES_PER_BUFFER*sizeof(int16_t));
    
    
    /***************************************************************
     Initialize the effects from the soundbox!
     ****************************************************************/
    
    /////////////EQ///////////////
    gainL = 12.00f;
    gainM = 0.00f;
    gainH = 0.00f;
    fcL = 300.0f;
    fcM = 800.0f;
    fcH = 8000.0f;
    QL = 0.7f;
    QM =2.0f;
    QH =0.7f;
    /////////////////////////////
    
    /////////////delay///////////
    feedback_d = 100;
    time_d= 32;
    level_d = 127;
    /////////////////////////////
    
    ///////////Chorus///////////
    rate_c= 200;
    depth_c = 8;
    level_c = 127;
    type_c = LFO_SINE;
    delayLineSize_c =10000;
    ////////////////////////////
    
    /////////Flanger///////////
    rate_f = 32;
    depth_f = 16;
    delay_f = 255;
    level_f = 255;
    type_f = LFO_SINE;
    delayLineSize_f = 10000;
    //////////////////////////
    
    //////Tremolo////////////
    rate_t = 127;
    depth_t = 127;
    level_t = 255;
    type_t = LFO_SINE;
    
    ////////////////////////
    
    //////////Vibrato///////
    rate_v = 255;
    depth_v = 255;
    type_v = LFO_SINE;
    delayLineSize_v = 10000;
    ///////////////////
    
    /////// WAH WAH ///////
    rate_w = 127;
    depth_w = 255;
    res_w = 127;
    type_w = automatic;
    ///////////////////////
    
    /////// Phaser  ///////
    rate_p = 32;
    depth_p = 127;
    res_p = 255;
    ///////////////////////
    
    ///// Distortion /////
    pre_amp_d = 255;
    master_d = 160;
    tone_d = 180;
    //////////////////////
    
    
    initialize();
    
    

    /***************************************************************
     Open the stream (The communication to the sound card)
     ****************************************************************/
    
    err = Pa_OpenStream(
                        &stream,
                        &inputParameters,
                        &outputParameters,
                        SAMPLE_RATE,
                        FRAMES_PER_BUFFER,
                        0, /* paClipOff, */  /* we won't output out of range samples so don't bother clipping them */
                        processCallback,
                        NULL );
    
    /***************************************************************
     Error handling code below .......
     ****************************************************************/
    
    if( err != paNoError ) goto error;
    
    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;
    
    printf("Hit ENTER to stop program.\n");
    getchar();
    err = Pa_CloseStream( stream );
    if( err != paNoError ) goto error;
    
    printf("Finished. gNumNoInputs = %d\n", gNumNoInputs );
    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)
{
    PaStreamParameters outputParameters;
    PaStream *stream;
    PaError err;
    TestData data;
    int i, j;


    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. );
    }

    err = Pa_Initialize();
    if( err != paNoError ) goto error;

    outputParameters.device = OUTPUT_DEVICE;
    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,      /* output will be in-range, so no need to clip */
              TestCallback,
              &data );
    if( err != paNoError ) goto error;

    printf("Repeating test %d times.\n", NUM_LOOPS );

    for( i=0; i < NUM_LOOPS; ++i )
    {
        data.phase = 0;
        data.generatedFramesCount = 0;
        data.callbackReturnedPaComplete = 0;
        data.callbackInvokedAfterReturningPaComplete = 0;

        err = Pa_StartStream( stream );
        if( err != paNoError ) goto error;

        printf("Play for %d seconds.\n", NUM_SECONDS );

        /* wait for the callback to complete generating NUM_SECONDS of tone */

        do
        {
            Pa_Sleep( 500 );
        }
        while( !data.callbackReturnedPaComplete );

        printf( "Callback returned paComplete.\n" );
        printf( "Waiting for buffers to finish playing...\n" );

        /* wait for stream to become inactive,
           or for a timeout of approximately NUM_SECONDS
         */

        j = 0;
        while( Pa_IsStreamActive( stream ) && j < NUM_SECONDS * 2 )
        {
            printf(".\n" );
            Pa_Sleep( 500 );
            ++j;
        }

        if( Pa_IsStreamActive( stream ) )
        {
            printf( "TEST FAILED: Timed out waiting for buffers to finish playing.\n" );
        }
        else
        {
            printf("Buffers finished.\n" );
        }

        if( data.callbackInvokedAfterReturningPaComplete )
        {
            printf( "TEST FAILED: Callback was invoked after returning paComplete.\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 PlayerObject::setPlaying(bool playing) {
	PlayerObject* player = this;
	bool oldplayingstate = false;
	PyScopedGIL gil;
	{
		PyScopedGIUnlock gunlock;
		
		player->workerThread.start(); // if not running yet, start
		if(!player->outStream.get())
			player->outStream.reset(new OutStream(this));
		assert(player->outStream.get() != NULL);
		if(playing && !player->outStream->stream) {
			PaError ret;
			ret = Pa_OpenDefaultStream(
									   &player->outStream->stream,
									   0,
									   player->outNumChannels, // numOutputChannels
									   paInt16, // sampleFormat
									   player->outSamplerate, // sampleRate
									   AUDIO_BUFFER_SIZE / 2, // framesPerBuffer,
									   &paStreamCallback,
									   player //void *userData
									   );
			if(ret != paNoError) {
				PyErr_SetString(PyExc_RuntimeError, "Pa_OpenDefaultStream failed");
				if(player->outStream->stream)
					player->outStream->close();
				playing = 0;
			}
		}
		if(playing) {
			player->needRealtimeReset = 1;
			Pa_StartStream(player->outStream->stream);
		} else
			player->outStream->stop();
		oldplayingstate = player->playing;
		player->playing = playing;
	}
	
	if(!PyErr_Occurred() && player->dict) {
		Py_INCREF(player->dict);
		PyObject* onPlayingStateChange = PyDict_GetItemString(player->dict, "onPlayingStateChange");
		if(onPlayingStateChange && onPlayingStateChange != Py_None) {
			Py_INCREF(onPlayingStateChange);
			
			PyObject* kwargs = PyDict_New();
			assert(kwargs);
			PyDict_SetItemString_retain(kwargs, "oldState", PyBool_FromLong(oldplayingstate));
			PyDict_SetItemString_retain(kwargs, "newState", PyBool_FromLong(playing));
			
			PyObject* retObj = PyEval_CallObjectWithKeywords(onPlayingStateChange, NULL, kwargs);
			Py_XDECREF(retObj);
			
			// errors are not fatal from the callback, so handle it now and go on
			if(PyErr_Occurred())
				PyErr_Print();
			
			Py_DECREF(kwargs);
			Py_DECREF(onPlayingStateChange);
		}
		Py_DECREF(player->dict);
	}
	
	return PyErr_Occurred() ? -1 : 0;
}
Beispiel #15
0
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;
}
Beispiel #16
0
PaError pa_open_callback(double sampleRate, int inchannels, int outchannels,
    int framesperbuf, int nbuffers, int indeviceno, int outdeviceno, PaStreamCallback *callbackfn)
{
    long   bytesPerSample;
    PaError err;
    PaStreamParameters instreamparams, outstreamparams;
    PaStreamParameters*p_instreamparams=0, *p_outstreamparams=0;

    /* fprintf(stderr, "nchan %d, flags %d, bufs %d, framesperbuf %d\n",
            nchannels, flags, nbuffers, framesperbuf); */

    instreamparams.device = indeviceno;
    instreamparams.channelCount = inchannels;
    instreamparams.sampleFormat = paFloat32;
    instreamparams.suggestedLatency = 0;        /* was nbuffers*framesperbuf/sampleRate */
    instreamparams.hostApiSpecificStreamInfo = 0;
    
    outstreamparams.device = outdeviceno;
    outstreamparams.channelCount = outchannels;
    outstreamparams.sampleFormat = paFloat32;
    outstreamparams.suggestedLatency = 0;
    outstreamparams.hostApiSpecificStreamInfo = 0;

    if(inchannels>0 && indeviceno >= 0)
        p_instreamparams=&instreamparams;
    if(outchannels>0 && outdeviceno >= 0)
        p_outstreamparams=&outstreamparams;

    err=Pa_IsFormatSupported(p_instreamparams, p_outstreamparams, sampleRate);

    if (paFormatIsSupported != err)
    {
        /* check whether we have to change the numbers of channel and/or samplerate */
        const PaDeviceInfo* info = 0;
        double inRate=0, outRate=0;

        if (inchannels>0)
        {
            if (NULL != (info = Pa_GetDeviceInfo( instreamparams.device )))
            {
              inRate=info->defaultSampleRate;

              if(info->maxInputChannels<inchannels)
                instreamparams.channelCount=info->maxInputChannels;
            }
        }

        if (outchannels>0)
        {
            if (NULL != (info = Pa_GetDeviceInfo( outstreamparams.device )))
            {
              outRate=info->defaultSampleRate;

              if(info->maxOutputChannels<outchannels)
                outstreamparams.channelCount=info->maxOutputChannels;
            }
        }

        if (err == paInvalidSampleRate)
        {
            sampleRate=outRate;
        }

        err=Pa_IsFormatSupported(p_instreamparams, p_outstreamparams,
            sampleRate);
        if (paFormatIsSupported != err)
        goto error;
    }

    err = Pa_OpenStream(
              &pa_stream,
              p_instreamparams,
              p_outstreamparams,
              sampleRate,
              framesperbuf,
              paNoFlag,      /* portaudio will clip for us */
              callbackfn,
              0);
    if (err != paNoError)
        goto error;

    err = Pa_StartStream(pa_stream);
    if (err != paNoError)
    {
        fprintf(stderr, "Pa_StartStream failed; closing audio stream...\n");
        pa_close_audio();
        goto error;
    }
    sys_dacsr=sampleRate;
    return paNoError;
error:
    pa_stream = NULL;
    return err;
}
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
    {        
        Pa_Sleep( 100 );

        load = Pa_GetStreamCpuLoad( stream );
        printf("sineCount = %d, CPU load = %f\n", data.sineCount, load );
		
		if( load < 0.3 )
		{
			data.sineCount += 10;
    }
		else if( load < 0.4 )
		{
			data.sineCount += 2;
		}
		else
		{
			data.sineCount += 1;
		}
		
    }
    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+=4 )
    {
        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;
}
Beispiel #18
0
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);

    data.phase = 0;
    for (i = 0 ; i < 12 ; i++) {
      data.amplitudes[i] = 0;
      data.states[i] = DECAY;
    }

    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;

    sprintf( data.message, "No Message" );
    err = Pa_SetStreamFinishedCallback( stream, &StreamFinished );
    if( err != paNoError ) goto error;

    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;

    /* set up unbuffered reading */
    struct termios tio;
    tcgetattr(1,&tio);
    tio.c_lflag &=(~ICANON & ~ECHO);
    tcsetattr(1,TCSANOW,&tio);

    int pressed = -1;
    while(1) {
      switch (getc(stdin)) {
      case 'C':
        pressed = 0;
        break;
      case 'd':
        pressed = 1;
        break;
      case 'D':
        pressed = 2;
        break;
      case 'e':
        pressed = 3;
        break;
      case 'E':
        pressed = 4;
        break;
      case 'F':
        pressed = 5;
        break;
      case 'g':
        pressed = 6;
        break;
      case 'G':
        pressed = 7;
        break;
      case 'a':
        pressed = 8;
        break;
      case 'A':
        pressed = 9;
        break;
      case 'b':
        pressed = 10;
        break;
      case 'B':
        pressed = 11;
        break;
      }

      if (pressed != -1) {
        data.states[pressed] = ATTACK;
      }
    }

    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;
}
Beispiel #19
0
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;
}
static PaCtx *
pa_phone_setup(void) {
  PaCtx		*ctx;
  int		err, i, srcerr;
  PaError	err2;

  err = paNoError;
  err2 = 0;
  
  if ((ctx = calloc(1, sizeof(PaCtx))) == NULL) {
    WHY("Unable to allocate PA context");
    err2 = 1;
    goto error;
  }

  /* Init mutex */
  if (pthread_mutex_init(&ctx->mtx, NULL) != 0) {
    WHYF("Unable to init mutex: %s\n", strerror(errno));
    err2 = 1;
    goto error;
  }
  
  /* Allocate FIFOs */
  i = IN_FRAMES * 10 * sizeof(int16_t);
  printf("Allocating %d byte FIFOs\n", i);
    
  if ((ctx->incoming = fifo_alloc(i)) == NULL) {
    WHY("Unable to allocate incoming FIFO\n");
    err2 = 1;
    goto error;    
  }

  if ((ctx->incrate = fifo_alloc(i)) == NULL) {
    WHY("Unable to allocate incoming SRC FIFO\n");
    err2 = 1;
    goto error;
  }

  if ((ctx->outgoing = fifo_alloc(i)) == NULL) {
    WHY("Unable to allocate outgoing FIFO\n");
    err2 = 1;
    goto error;
  }    


  /* Init sample rate converter */
  if ((ctx->src = src_new(SRC_SINC_BEST_QUALITY, 1, &srcerr)) == NULL) {
    WHYF("Unable to init sample rate converter: %d\n", srcerr);
    err2 = 1;
    goto error;
  }

  /* Init echo canceller */
  if ((ctx->echocan = echo_can_init(ECHO_LEN, ADAPT_MODE)) == NULL) {
    WHY("Unable to init echo canceller\n");
    err2 = 1;
    goto error;
  }

  /* Init codec2 */
  if ((ctx->codec2 = codec2_create()) == NULL) {
    WHY("Unable to init codec2\n");
    err2 = 1;
    goto error;
  }
    
  /* Initialize Port Audio library */
  if ((err = Pa_Initialize()) != paNoError)
    goto error;
     
  /* Open an audio I/O stream. */
  if ((err = Pa_OpenDefaultStream(&ctx->stream,
				  1,          /* input channels */
				  1,          /* output channels */
				  paInt16,
				  SAMPLE_RATE,
				  IN_FRAMES, /* frames per buffer */
				  patestCallback,
				  &ctx)) != paNoError)
    goto error;
 
  /* Start stream */
  if ((err = Pa_StartStream(ctx->stream)) != paNoError)
    goto error;

  /* Close down stream, PA, etc */
/* XXX: hangs in pthread_join on Ubuntu 10.04 */
#ifndef linux
  if ((err = Pa_StopStream(ctx->stream)) != paNoError)
    goto error;
#endif

  /* Do stuff */

  if ((err = Pa_CloseStream(ctx->stream)) != paNoError)
    goto error;

  error:
  Pa_Terminate();
    
  /* Free things */
  freectx(ctx);
    
  if (err != paNoError)
    WHYF("Port audio error: %s\n", Pa_GetErrorText(err));

  return NULL;
}
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;
}
Beispiel #22
0
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;
}
Beispiel #23
0
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;
}
Beispiel #24
0
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;
}
Beispiel #25
0
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;
}
Beispiel #26
0
        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, &params, 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;

        }
Beispiel #27
0
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", &amp );
            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;
}
Beispiel #28
0
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;
}
Beispiel #29
0
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;
}
Beispiel #30
0
PaError TestRecording( paTestData *dataPtr )
{
    PortAudioStream *stream;
    PaError    err;
    int        i;

    /* Record some audio. */
    err = Pa_OpenStream(
              &stream,
              Pa_GetDefaultInputDeviceID(),
              dataPtr->samplesPerFrame,               /* stereo input */
              PA_SAMPLE_TYPE,
              NULL,
              paNoDevice,
              0,
              PA_SAMPLE_TYPE,
              NULL,
              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,
              dataPtr );
    if( err != paNoError ) goto error;
    err = Pa_StartStream( stream );
    if( err != paNoError ) goto error;

    printf("Now recording!\n"); fflush(stdout);
    for( i=0; i<(NUM_SECONDS*1000/SLEEP_DUR_MSEC); i++ )
    {
        if( Pa_StreamActive( stream ) <= 0)
        {
            printf("Stream inactive!\n");
            break;
        }
        if( dataPtr->maxFrameIndex <= dataPtr->frameIndex )
        {
            printf("Buffer recording complete.\n");
            break;
        }
        Pa_Sleep(100);
        printf("index = %d\n", dataPtr->frameIndex ); fflush(stdout);
    }

    printf("Finished loop. Close stream.\n"); fflush(stdout);

    err = Pa_CloseStream( stream );
    if( err != paNoError ) goto error;

    printf("Done.\n"); fflush(stdout);
    {
        SAMPLE max = 0;
        SAMPLE posVal;
        int i;
        for( i=0; i<dataPtr->numSamples; i++ )
        {
            posVal = dataPtr->recordedSamples[i];
            if( posVal < 0 ) posVal = -posVal;
            if( posVal > max ) max = posVal;
        }
        printf("Largest recorded sample = %d\n", max );
    }
    /* 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( dataPtr->recordedSamples, dataPtr->samplesPerFrame * sizeof(SAMPLE), totalFrames, fid );
            fclose( fid );
            printf("Wrote data to 'recorded.raw'\n");
        }
    }
#endif

error:
    return err;
}